text stringlengths 2 1.04M | meta dict |
|---|---|
#import <Foundation/Foundation.h>
#import "VLCMediaList.h"
@class VLCLibrary;
@class VLCMediaList;
@class VLCMediaDiscoverer;
typedef NS_ENUM(unsigned, VLCMediaDiscovererCategoryType)
{
VLCMediaDiscovererCategoryTypeDevices = 0,
VLCMediaDiscovererCategoryTypeLAN,
VLCMediaDiscovererCategoryTypePodcasts,
VLCMediaDiscovererCategoryTypeLocalDirectories
};
/* discoverer keys */
extern NSString *const VLCMediaDiscovererName;
extern NSString *const VLCMediaDiscovererLongName;
extern NSString *const VLCMediaDiscovererCategory;
/**
* VLCMediaDiscoverer
*/
@interface VLCMediaDiscoverer : NSObject
/**
* The library instance used by the discoverers
* \note unless for debug, you are wrong if you want to use this selector
*/
@property (nonatomic, readonly) VLCLibrary *libraryInstance;
/**
* The full list of available media discoverers
* \return returns an empty array for binary compatibility, will be removed in subsequent releases
* \deprecated use availableMediaDiscovererForCategoryType instead
*/
+ (NSArray *)availableMediaDiscoverer __attribute__((deprecated));
/**
* \param categoryType VLCMediaDiscovererCategory you are looking for
* \return an array of dictionaries describing the available discoverers for the requested type
*/
+ (NSArray *)availableMediaDiscovererForCategoryType:(VLCMediaDiscovererCategoryType)categoryType;
/* Initializers */
/**
* Initializes new object with specified name.
* \param aServiceName Name of the service for this VLCMediaDiscoverer object.
* \returns Newly created media discoverer.
* \note with VLCKit 3.0 and above, you need to start the discoverer explicitly after creation
*/
- (instancetype)initWithName:(NSString *)aServiceName;
/**
* same as above but with a custom VLCLibrary instance
* \note Using this mode can lead to a significant performance impact - use only if you know what you are doing
*/
- (instancetype)initWithName:(NSString *)aServiceName libraryInstance:(VLCLibrary *)libraryInstance;
/**
* start media discovery
* \returns -1 if start failed, otherwise 0
*/
- (int)startDiscoverer;
/**
* stop media discovery
*/
- (void)stopDiscoverer;
/**
* a read-only property to retrieve the list of discovered media items
*/
@property (weak, readonly) VLCMediaList *discoveredMedia;
/**
* localized name of the discovery module if available, otherwise in US English
* \deprecated Will be removed in the next major release, may return an empty string for binary compatibility
*/
@property (readonly, copy) NSString *localizedName __attribute__((deprecated));
/**
* read-only property to check if the discovery service is active
* \return boolean value
*/
@property (readonly) BOOL isRunning;
@end
| {
"content_hash": "ec208f8adbc9edbebe442549a21e4b4f",
"timestamp": "",
"source": "github",
"line_count": 91,
"max_line_length": 111,
"avg_line_length": 29.87912087912088,
"alnum_prop": 0.7723427730783377,
"repo_name": "lpniuniu/LifePlayer",
"id": "e4bf8ffa06449ad919eb47150e7dd977416d635f",
"size": "4026",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "LifePlayer/LifePlayer/MobileVLCKit/MobileVLCKit/VLCMediaDiscoverer.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Objective-C",
"bytes": "127718"
},
{
"name": "Objective-C++",
"bytes": "1920"
},
{
"name": "Ruby",
"bytes": "538"
}
],
"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.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.cloudidentity.v1.model;
/**
* Request message for cancelling an unfinished user account wipe.
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the Cloud Identity API. For a detailed explanation see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class GoogleAppsCloudidentityDevicesV1CancelWipeDeviceUserRequest extends com.google.api.client.json.GenericJson {
/**
* Required. [Resource name](https://cloud.google.com/apis/design/resource_names) of the customer.
* If you're using this API for your own organization, use `customers/my_customer` If you're using
* this API to manage another organization, use `customers/{customer_id}`, where customer_id is
* the customer to whom the device belongs.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String customer;
/**
* Required. [Resource name](https://cloud.google.com/apis/design/resource_names) of the customer.
* If you're using this API for your own organization, use `customers/my_customer` If you're using
* this API to manage another organization, use `customers/{customer_id}`, where customer_id is
* the customer to whom the device belongs.
* @return value or {@code null} for none
*/
public java.lang.String getCustomer() {
return customer;
}
/**
* Required. [Resource name](https://cloud.google.com/apis/design/resource_names) of the customer.
* If you're using this API for your own organization, use `customers/my_customer` If you're using
* this API to manage another organization, use `customers/{customer_id}`, where customer_id is
* the customer to whom the device belongs.
* @param customer customer or {@code null} for none
*/
public GoogleAppsCloudidentityDevicesV1CancelWipeDeviceUserRequest setCustomer(java.lang.String customer) {
this.customer = customer;
return this;
}
@Override
public GoogleAppsCloudidentityDevicesV1CancelWipeDeviceUserRequest set(String fieldName, Object value) {
return (GoogleAppsCloudidentityDevicesV1CancelWipeDeviceUserRequest) super.set(fieldName, value);
}
@Override
public GoogleAppsCloudidentityDevicesV1CancelWipeDeviceUserRequest clone() {
return (GoogleAppsCloudidentityDevicesV1CancelWipeDeviceUserRequest) super.clone();
}
}
| {
"content_hash": "8f4d0e6dfcb231d02b31c68f465ad209",
"timestamp": "",
"source": "github",
"line_count": 75,
"max_line_length": 182,
"avg_line_length": 44.2,
"alnum_prop": 0.7496229260935143,
"repo_name": "googleapis/google-api-java-client-services",
"id": "a53c041e95891b151961295c0972bd96e9ac6a1e",
"size": "3315",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "clients/google-api-services-cloudidentity/v1/1.30.1/com/google/api/services/cloudidentity/v1/model/GoogleAppsCloudidentityDevicesV1CancelWipeDeviceUserRequest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<?php
require_once 'bootstrap.inc';
$fixture = new Sync_Fixture();
$action_string = $argv[1];
if ($action_string) {
$actions = explode('+', $action_string);
foreach($actions as $action){
$fixture->{$action}();
}
}
print "\n"; | {
"content_hash": "96a1cfc261eeed3b9c136cab00fa6886",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 42,
"avg_line_length": 19.153846153846153,
"alnum_prop": 0.5823293172690763,
"repo_name": "silentorb/drupal-vineyard-sync-test",
"id": "25360f242ec1fe86675679249b7dd29208d4ee18",
"size": "249",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "api.php",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "5218"
},
{
"name": "PHP",
"bytes": "478"
}
],
"symlink_target": ""
} |
disylee来翻译
How to Remove Music Players from Ubuntu Sound Menu
================================================================================

**Since its introduction back in 2010, the Ubuntu Sound Menu has proven to be one of the most popular and unique features of the Unity desktop.**
Allowing music players to integrate with the volume applet – i.e., where one would expect to find sound-related tomfoolery – through a standard interface is inspired. One wonders why other operating systems haven’t followed suit!
#### Overstuffed ####
Handy though it may be there is a “problem” with the applet as it currently exists: pretty much anything that so much as looks at an MP3 can, should it want, lodge itself inside. While useful, an omnipresent listing for apps you have installed but don’t use that often is annoying and unsightly.
I’m going to wager that the screenshot above looks familiar to a great many of you reading this! Never fear, **dconf-editor** is here.
### Remove Players from Ubuntu Sound Menu ###
#### Part One: Basics ####
The quickest and easiest way to remove entries from the Sound Menu is to uninstall the apps afflicting it. But that’s extreme; as I said, you may want the app, just not the integration.
To remove players without ditching the apps we need to use a scary looking tool called dconf-editor.
You may have it installed already, but if you don’t you’ll find it in the Ubuntu Software Center waiting.
- [Click to Install Dconf-Editor in Ubuntu][1]
Once installed, head to the Unity Dash to open it. Don’t panic when it opens; you’ve not been shunted back to the 2002, it’s supposed to look like that.
Using the left-hand sidebar you need to navigate to com > canonical > indicator > sound. The following pane will appear.

Double click on the closed brackets next to interested-media-players and delete the players you wish to remove from the Sound Menu, but leave in the square brackets and don’t delete any commas or apostrophes from items you wish to keep.
For example, I removed ‘**rhythmbox.desktop**’, ‘**pithos.desktop**’, ‘**clementine.desktop**’, to leave a line that reads:
['tomahawk.desktop']
Now, when I open the Sound menu I only see Tomahawk:

#### Part Two: Blacklisting ####
Wait! Don’t close dconf-editor yet. While the steps above makes things look nice and tidy some players will instantly re-add themselves to the sound menu when opened. To avoid having to repeat the process add them to the **blacklisted-media-player** section.
Remember to enclose each player in apostrophes with a comma separating multiple entries. They must also be inside the square brackets — so double check before exiting.
The net result:

--------------------------------------------------------------------------------
via: http://www.omgubuntu.co.uk/2014/11/remove-players-ubuntu-sound-menu
作者:[Joey-Elijah Sneddon][a]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创翻译,[Linux中国](http://linux.cn/) 荣誉推出
[a]:https://plus.google.com/117485690627814051450/?rel=author
[1]:apt://dconf-editor
| {
"content_hash": "678803e25489aae2370032016b57e0c6",
"timestamp": "",
"source": "github",
"line_count": 65,
"max_line_length": 295,
"avg_line_length": 52.87692307692308,
"alnum_prop": 0.7235961594413733,
"repo_name": "leozhang2018/TranslateProject",
"id": "d42bd88065fc858794076475ec3da43c0d9683dd",
"size": "3553",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "sources/tech/20141112 How to Remove Music Players from Ubuntu Sound Menu.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
from django.shortcuts import render
from datetime import date
from ticketing.models import Ticket, Performance
from django.contrib.auth.decorators import login_required, user_passes_test
from django.utils.translation import ugettext_lazy as _
from datetime import date, datetime
from pytz import utc
from pprint import pformat
from core.models import User
from core.views import notapproved
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from ticketing.models import ( Order, Ticket, Performance, PriceCategory,
StandardMarketingPollAnswer, GivenPaperTickets )
from django.forms import ( Form, ChoiceField, IntegerField, NullBooleanField,
CharField, DateTimeField)
from django.contrib import messages
import django.utils.timezone as django_tz
from django.db.models import Q
from django.conf import settings #needed for automatisation, with settings.CURRENT_PRODUCTION
@login_required
@user_passes_test(lambda u:u.approved,login_url='/accessrestricted')
def promo_dashboard(request):
#AUTOMATISATION NEEDED, see comment at imports
concert1 = Performance.objects.get(short_name__contains="lente2016_1")
concert2 = Performance.objects.get(short_name__contains="lente2016_2")
data = {
'num_do' : Ticket.objects.filter(order__performance=concert1).count(),
'num_zo' : Ticket.objects.filter(order__performance=concert2).count(),
# 'num_by_musician_do' : Ticket.objects.filter(order__performance=do, order__standardmarketingpollanswer__referred_member=request.user).count(),
# 'num_by_musician_vr' : Ticket.objects.filter(order__performance=vr, order__standardmarketingpollanswer__referred_member=request.user).count(),
}
total_graph, concert1_graph, concert2_graph = [], [], []
total_tickets, concert1_tickets, concert2_tickets = 0, 0, 0
for order in sorted(Order.objects.filter(performance__in=(concert1,concert2)),key=lambda o: o.creation_date):
total_tickets += order.num_tickets()
total_graph.append({
'timestamp': to_timestamp(order.creation_date),
'num_new_tickets': order.num_tickets(),
'total_tickets': total_tickets,
'order': order,
})
if order.performance == concert1:
concert1_tickets += order.num_tickets()
concert1_graph.append({
'timestamp': to_timestamp(order.creation_date),
'num_new_tickets': order.num_tickets(),
'total_tickets': concert1_tickets,
'order': order,
})
elif order.performance == concert2:
concert2_tickets += order.num_tickets()
concert2_graph.append({
'timestamp': to_timestamp(order.creation_date),
'num_new_tickets': order.num_tickets(),
'total_tickets': concert2_tickets,
'order': order,
})
data['total_graph'] = total_graph
data['concert1_graph'] = concert1_graph
data['concert2_graph'] = concert2_graph
user_totals = []
for user in User.objects.all():
user_totals.append({
'user': user,
#only get tickets of the two current productions, UNTESTED
'num_tickets': Ticket.objects.filter(Q(order__performance=concert1)&(Q(order__seller=user)|Q(order__standardmarketingpollanswer__referred_member=user))).count()
+ Ticket.objects.filter(Q(order__performance=concert2)&(Q(order__seller=user)|Q(order__standardmarketingpollanswer__referred_member=user))).count()
})
data['user_totals'] = sorted(user_totals, key=lambda obj: -obj['num_tickets'])[0:5]
return render(request, 'internal/promo_dashboard.html', data)
def to_timestamp(dt):
epoch = django_tz.make_aware(datetime(1970,1,1), django_tz.get_default_timezone())
return int((dt - epoch).total_seconds()*1000)
@login_required
@user_passes_test(lambda u:u.approved,login_url='/accessrestricted')
def facebook_pictures(request):
return render(request, 'internal/pictures.html', {})
@login_required
@user_passes_test(lambda u:u.approved,login_url='/accessrestricted')
def my_tickets_dashboard(request):
data = {}
data['ticket_distributions'] = \
GivenPaperTickets.objects.filter(given_to=request.user)
data['total_tickets_given'] = \
sum([ts.count for ts in GivenPaperTickets.objects.filter(given_to=request.user)])
data['registered_sales'] = \
Order.objects.filter(online=False, seller=request.user)
data['total_tickets_registered_sales'] = \
Ticket.objects.filter(order__online=False, order__seller=request.user).count()
data['total_price_registered_sales'] = \
sum([o.total_price() for o in Order.objects.filter(online=False, seller=request.user)])
data['online_order_mentioneds'] = \
Order.objects.filter(online=True, standardmarketingpollanswer__referred_member=request.user)
data['total_tickets_online_order_mentioneds'] = \
Ticket.objects.filter(order__online=True, order__standardmarketingpollanswer__referred_member=request.user).count()
return render(request, 'internal/my_tickets_dashboard.html', data)
performances = (
('do', _('Donderdag 5 mei')),
('zo', _('Zondag 8 mei')),
)
class ReportedSaleForm(Form):
performance = ChoiceField(required=True, choices=performances)
num_student_tickets = IntegerField(required=False, min_value=0, initial=0)
num_non_student_tickets = IntegerField(required=False, min_value=0, initial=0)
num_culture_card_tickets = IntegerField(required=False, min_value=0, initial=0)
payment_method = ChoiceField(required=False, choices=Order.payment_method_choices)
marketing_feedback = CharField(required=False)
first_concert = NullBooleanField(required=False)
sale_date = DateTimeField(required=False)
remarks = CharField(required=False)
@login_required
@user_passes_test(lambda u:u.approved,login_url='/accessrestricted')
def register_sold_tickets(request):
if request.method == 'POST':
form = ReportedSaleForm(request.POST)
if form.is_valid():
persist_data(parse_form_data(form.cleaned_data), request.user)
messages.success(request, _('Je verkochte tickets zijn geregistreerd.'))
return HttpResponseRedirect(reverse('space_ticketing:my_tickets_dashboard'))
else:
form = ReportedSaleForm(initial={'sale_date': datetime.now().strftime('%Y-%m-%d %H:%M')})
return render(request, 'internal/register_sold_tickets.html', {'form': form})
def parse_form_data(form):
data = {}
data['performance'] = form.get('performance', '')
data['performance_full'] = dict(performances).get(data['performance'], '')
data['num_culture_card_tickets'] = int(form.get('num_culture_card_tickets', 0))
data['num_student_tickets'] = int(form.get('num_student_tickets', 0))
data['num_non_student_tickets'] = int(form.get('num_non_student_tickets', 0))
data['marketing_feedback'] = form.get('marketing_feedback', '')
data['first_concert'] = form.get('first_concert', None)
data['sale_date'] = form.get('sale_date', None)
data['remarks'] = form.get('remarks', '')
return data
def persist_data(data, user):
short_name_mapping = {'do': lente2016_1, 'zo': lente2016_2}
performance = Performance.objects.get(short_name__contains=short_name_mapping['performance'])
order = Order.objects.create(
performance = performance,
seller = user,
sale_date = data['sale_date'],
payment_method = None,
date = datetime.now(utc),
user_remarks = data['remarks'],
online = False,
)
marketing_poll_answers = StandardMarketingPollAnswer.objects.create(
associated_order = order,
marketing_feedback = data['marketing_feedback'],
first_concert = data['first_concert'],
)
for i in range(data['num_student_tickets']):
Ticket.objects.create(
order = order,
price_category = PriceCategory.objects.get(full_name="Student VVK (vanaf winter 2015)", price=5),
)
for i in range(data['num_non_student_tickets']):
Ticket.objects.create(
order = order,
price_category = PriceCategory.objects.get(full_name="Niet-student in VVK (vanaf winter 2015)", price=9),
)
for i in range(data['num_culture_card_tickets']):
Ticket.objects.create(
order = order,
price_category = PriceCategory.objects.get(full_name="KU Leuven Cultuurkaart in VVK (vanaf winter 2015)", price=4),
) | {
"content_hash": "0359cbe2d48a64a8348f37194be18bff",
"timestamp": "",
"source": "github",
"line_count": 186,
"max_line_length": 163,
"avg_line_length": 42.865591397849464,
"alnum_prop": 0.7327229399222376,
"repo_name": "tfiers/arenberg-online",
"id": "7d7d37fb60523d1c93ffaeed6c5b628b57c0b38e",
"size": "7973",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "ticketing/views/internal.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "62"
},
{
"name": "CSS",
"bytes": "31305"
},
{
"name": "HTML",
"bytes": "230598"
},
{
"name": "JavaScript",
"bytes": "96170"
},
{
"name": "Python",
"bytes": "178246"
}
],
"symlink_target": ""
} |
task main()
{
//Motor power level range -127 to 127 (Full Power)
// 3/4 Power - 96
// 1/2 Power - 63
// Full Power - 127
//Manual straightening for left motor. SLM (Straight Left Motor).
int SLM
void changeValue()
{
SLM = 60;
}
//Resetting encoder values.
SensorValue[rightEncoder] = 0;
SensorValue[leftEncoder] = 0;
//First forward movement.
while(SensorValue[leftEncoder] < 1850)
{
if(SensorValue[leftEncoder] > SensorValue[rightEncoder])
{
motor[rightMotor] = 96;
motor[leftMotor] = 80;
}
if(SensorValue[leftEncoder] < SensorValue[rightEncoder])
{
motor[rightMotor] = 96;
motor[leftMotor] = 80;
}
else(SensorValue[leftEncoder] == SensorValue[rightEncoder])
{
motor[rightMotor] = 96;
motor[leftMotor] = SLM;
}
}
//Resetting encoder values.
SensorValue[rightEncoder] = 0;
SensorValue[leftEncoder] = 0;
//First left turn.
while(SensorValue[rightEncoder] <= 230)
{
motor[rightMotor] = 96;
motor[leftMotor] = -96;
}
//Resetting encoder values.
SensorValue[rightEncoder] = 0;
SensorValue[leftEncoder] = 0;
//Second forward movement.
while(SensorValue[leftEncoder] < 1850)
{
if(SensorValue[leftEncoder] > SensorValue[rightEncoder])
{
motor[rightMotor] = 96;
motor[leftMotor] = 80;
}
if(SensorValue[leftEncoder] < SensorValue[rightEncoder])
{
motor[rightMotor] = 80;
motor[leftMotor] = 96;
}
else(SensorValue[leftEncoder] == SensorValue[rightEncoder])
{
motor[rightMotor] = 96;
motor[leftMotor] = SLM;
}
}
//Resetting encoder values.
SensorValue[rightEncoder] = 0;
SensorValue[leftEncoder] = 0;
//Second right turn.
while(SensorValue[rightEncoder] <= 230)
{
motor[rightMotor] = -96;
motor[leftMotor] = 96;
}
//Third forward movement.
while(SensorValue[leftEncoder] < 1850)
{
if(SensorValue[leftEncoder] > SensorValue[rightEncoder])
{
motor[rightMotor] = 96;
motor[leftMotor] = 80;
}
if(SensorValue[leftEncoder] < SensorValue[rightEncoder])
{
motor[rightMotor] = 80;
motor[leftMotor] = 96;
}
else(SensorValue[leftEncoder] == SensorValue[rightEncoder])
{
motor[rightMotor] = 96;
motor[leftMotor] = SLM;
}
}
//Resetting encoder values.
SensorValue[rightEncoder] = 0;
SensorValue[leftEncoder] = 0;
//Thrid right turn.
while(SensorValue[rightEncoder] <= 230)
{
motor[rightMotor] = -96;
motor[leftMotor] = 96;
}
}
| {
"content_hash": "47b53467f6950cac15b2f8457c34abf3",
"timestamp": "",
"source": "github",
"line_count": 120,
"max_line_length": 67,
"avg_line_length": 23.841666666666665,
"alnum_prop": 0.564138413142258,
"repo_name": "MarcWoodyard/Vex-Cortex-RobotC-Scripts",
"id": "6a2c57ec7d04b91ec42d4c5b95f637823d76aba4",
"size": "3461",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Programs/Labyrinth-Challenge.c",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "9188"
}
],
"symlink_target": ""
} |
struct SampleKey
{
bool mEnabled;
const char* mName;
bool matchesPattern( const char* pattern )
{
U32 indexInName = 0;
U32 indexInPattern = 0;
while( mName[ indexInName ] != '\0' )
{
if( pattern[ indexInPattern ] == '\0' )
break;
else if( dToupper( mName[ indexInName ] ) == dToupper( pattern[ indexInPattern ] ) )
{
indexInName ++;
indexInPattern ++;
}
else if( pattern[ indexInPattern ] == '*' )
{
// Handle senseless concatenation of wildcards.
while( pattern[ indexInPattern ] == '*' )
indexInPattern ++;
// Skip to next slash in name.
while( mName[ indexInName ] && mName[ indexInName ] != '/' )
indexInName ++;
}
else
return false;
}
return ( pattern[ indexInPattern ] == '\0'
|| ( indexInPattern > 0 && pattern[ indexInPattern ] == '*' ) );
}
};
/// A sampler backend is responsible for storing the actual sampling data.
struct ISamplerBackend
{
virtual ~ISamplerBackend() {}
virtual bool init( const char* location ) = 0;
virtual void beginFrame() = 0;
virtual void endFrame() = 0;
virtual void sample( U32 key, bool value ) = 0;
virtual void sample( U32 key, S32 value ) = 0;
virtual void sample( U32 key, F32 value ) = 0;
virtual void sample( U32 key, const char* value ) = 0;
};
static bool gSamplerRunning;
static S32 gSamplingFrequency = 1; ///< Frequency = samples taken every nth frame.
static U32 gCurrentFrameDelta;
static Vector< SampleKey > gSampleKeys( __FILE__, __LINE__ );
static ISamplerBackend* gSamplerBackend;
//--------------------------------------------------------------------------------
// CSV Backend.
//--------------------------------------------------------------------------------
/// A sampler backend that outputs samples to a CSV file.
class CSVSamplerBackend : public ISamplerBackend
{
/// Value holder for an individual sample. Unfortunately, since the
/// order in which samples arrive at the sampler may vary from frame to
/// frame, we cannot emit data immediately but rather have to buffer
/// it in these sample records and then flush them to disk once we receive
/// the endFrame call.
struct SampleRecord
{
U32 mKey;
U32 mType; //< Console type code.
bool mSet;
union
{
bool mBool;
S32 mS32;
F32 mF32;
const char* mString;
} mValue;
SampleRecord() : mKey(0), mSet(false), mType(TypeBool) { mValue.mBool = false; }
SampleRecord( U32 key )
: mKey( key ), mSet( false ), mType(TypeBool) { mValue.mBool = false; }
void set( bool value )
{
mType = TypeBool;
mValue.mBool = value;
mSet = true;
}
void set( S32 value )
{
mType = TypeS32;
mValue.mS32 = value;
mSet = true;
}
void set( F32 value )
{
mType = TypeF32;
mValue.mF32 = value;
mSet = true;
}
void set( const char* str )
{
mType = TypeString;
mValue.mString = dStrdup( str );
mSet = true;
}
void clean()
{
if( mType == TypeString )
dFree( ( void* ) mValue.mString );
mSet = false;
}
};
FileStream mStream;
Vector< SampleRecord > mRecords;
~CSVSamplerBackend()
{
mStream.close();
}
/// Open the file and emit a row with the names of all enabled keys.
virtual bool init( const char* fileName )
{
if( !mStream.open( fileName, Torque::FS::File::Write ) )
{
Con::errorf( "CSVSamplerBackend::init -- could not open '%s' for writing", fileName );
return false;
}
Con::printf( "CSVSamplerBackend::init -- writing samples to '%s'", fileName );
bool first = true;
for( U32 i = 0; i < gSampleKeys.size(); ++ i )
{
SampleKey& key = gSampleKeys[ i ];
if( key.mEnabled )
{
if( !first )
mStream.write( 1, "," );
mRecords.push_back( SampleRecord( i + 1 ) );
mStream.write( dStrlen( key.mName ), key.mName );
first = false;
}
}
newline();
return true;
}
virtual void beginFrame()
{
}
virtual void endFrame()
{
char buffer[ 256 ];
for( U32 i = 0; i < mRecords.size(); ++ i )
{
if( i != 0 )
mStream.write( 1, "," );
SampleRecord& record = mRecords[ i ];
if( record.mSet )
{
if( record.mType == TypeBool )
{
if( record.mValue.mBool )
mStream.write( 4, "true" );
else
mStream.write( 5, "false" );
}
else if( record.mType == TypeS32 )
{
dSprintf( buffer, sizeof( buffer ), "%d", record.mValue.mS32 );
mStream.write( dStrlen( buffer ), buffer );
}
else if( record.mType == TypeF32 )
{
dSprintf( buffer, sizeof( buffer ), "%f", record.mValue.mF32 );
mStream.write( dStrlen( buffer ), buffer );
}
else if( record.mType == TypeString )
{
//FIXME: does not do doubling of double quotes in the string at the moment
mStream.write( 1, "\"" );
mStream.write( dStrlen( record.mValue.mString ), record.mValue.mString );
mStream.write( 1, "\"" );
}
else
AssertWarn( false, "CSVSamplerBackend::endFrame - bug: invalid sample type" );
}
record.clean();
}
newline();
}
void newline()
{
mStream.write( 1, "\n" );
}
SampleRecord* lookup( U32 key )
{
//TODO: do this properly with a binary search (the mRecords array is already sorted by key)
for( U32 i = 0; i < mRecords.size(); ++ i )
if( mRecords[ i ].mKey == key )
return &mRecords[ i ];
AssertFatal( false, "CSVSamplerBackend::lookup - internal error: sample key not found" );
return NULL; // silence compiler
}
virtual void sample( U32 key, bool value )
{
lookup( key )->set( value );
}
virtual void sample( U32 key, S32 value )
{
lookup( key )->set( value );
}
virtual void sample( U32 key, F32 value )
{
lookup( key )->set( value );
}
virtual void sample( U32 key, const char* value )
{
lookup( key )->set( value );
}
};
//--------------------------------------------------------------------------------
// Internal Functions.
//--------------------------------------------------------------------------------
static void stopSampling()
{
if( gSamplerRunning )
{
SAFE_DELETE( gSamplerBackend );
gSamplerRunning = false;
}
}
static void beginSampling( const char* location, const char* backend )
{
if( gSamplerRunning )
stopSampling();
if( dStricmp( backend, "CSV" ) == 0 )
gSamplerBackend = new CSVSamplerBackend;
else
{
Con::errorf( "beginSampling -- No backend called '%s'", backend );
return;
}
if( !gSamplerBackend->init( location ) )
{
SAFE_DELETE( gSamplerBackend );
}
else
{
gSamplerRunning = true;
gCurrentFrameDelta = 0;
}
}
//--------------------------------------------------------------------------------
// Sampler Functions.
//--------------------------------------------------------------------------------
void Sampler::init()
{
Con::addVariable( "Sampler::frequency", TypeS32, &gSamplingFrequency, "Samples taken every nth frame.\n"
"@ingroup Rendering");
}
void Sampler::beginFrame()
{
gCurrentFrameDelta ++;
if( gSamplerBackend && gCurrentFrameDelta == gSamplingFrequency )
gSamplerBackend->beginFrame();
}
void Sampler::endFrame()
{
if( gSamplerBackend && gCurrentFrameDelta == gSamplingFrequency )
{
gSamplerBackend->endFrame();
gCurrentFrameDelta = 0;
}
}
void Sampler::destroy()
{
if( gSamplerBackend )
SAFE_DELETE( gSamplerBackend );
}
U32 Sampler::registerKey( const char* name )
{
gSampleKeys.push_back( SampleKey() );
U32 index = gSampleKeys.size();
SampleKey& key = gSampleKeys.last();
key.mName = name;
key.mEnabled = false;
return index;
}
void Sampler::enableKeys( const char* pattern, bool state )
{
if( gSamplerRunning )
{
Con::errorf( "Sampler::enableKeys -- cannot change key states while sampling" );
return;
}
for( U32 i = 0; i < gSampleKeys.size(); ++ i )
if( gSampleKeys[ i ].matchesPattern( pattern ) )
{
gSampleKeys[ i ].mEnabled = state;
Con::printf( "Sampler::enableKeys -- %s %s", state ? "enabling" : "disabling",
gSampleKeys[ i ].mName );
}
}
#define SAMPLE_FUNC( type ) \
void Sampler::sample( U32 key, type value ) \
{ \
if( gSamplerRunning \
&& gCurrentFrameDelta == gSamplingFrequency \
&& gSampleKeys[ key - 1 ].mEnabled ) \
gSamplerBackend->sample( key, value ); \
}
SAMPLE_FUNC( bool );
SAMPLE_FUNC( S32 );
SAMPLE_FUNC( F32 );
SAMPLE_FUNC( const char* );
//--------------------------------------------------------------------------------
// Console Functions.
//--------------------------------------------------------------------------------
DefineEngineFunction( beginSampling, void, (const char * location, const char * backend), ("CSV"), "(location, [backend]) -"
"@brief Takes a string informing the backend where to store "
"sample data and optionally a name of the specific logging "
"backend to use. The default is the CSV backend. In most "
"cases, the logging store will be a file name."
"@tsexample\n"
"beginSampling( \"mysamples.csv\" );\n"
"@endtsexample\n\n"
"@ingroup Rendering")
{
beginSampling( location, backend );
}
DefineEngineFunction( stopSampling, void, (), , "()"
"@brief Stops the rendering sampler\n\n"
"@ingroup Rendering\n")
{
stopSampling();
}
DefineEngineFunction( enableSamples, void, (const char * pattern, bool state), (true), "(pattern, [state]) -"
"@brief Enable sampling for all keys that match the given name "
"pattern. Slashes are treated as separators.\n\n"
"@ingroup Rendering")
{
Sampler::enableKeys( pattern, state );
}
| {
"content_hash": "5fd921a4ffdb6ee9d0d60138a578d048",
"timestamp": "",
"source": "github",
"line_count": 391,
"max_line_length": 124,
"avg_line_length": 27.40920716112532,
"alnum_prop": 0.5221610525333582,
"repo_name": "chaigler/Torque3D",
"id": "405a8180046b283d4a53a3d9bc2895ec4563f5b6",
"size": "12303",
"binary": false,
"copies": "3",
"ref": "refs/heads/development",
"path": "Engine/source/util/sampler.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ada",
"bytes": "89079"
},
{
"name": "Assembly",
"bytes": "199191"
},
{
"name": "Awk",
"bytes": "42982"
},
{
"name": "Batchfile",
"bytes": "68732"
},
{
"name": "C",
"bytes": "44024765"
},
{
"name": "C#",
"bytes": "54021"
},
{
"name": "C++",
"bytes": "59643860"
},
{
"name": "CMake",
"bytes": "988394"
},
{
"name": "CSS",
"bytes": "55472"
},
{
"name": "D",
"bytes": "101732"
},
{
"name": "DIGITAL Command Language",
"bytes": "240259"
},
{
"name": "Dockerfile",
"bytes": "988"
},
{
"name": "GLSL",
"bytes": "515671"
},
{
"name": "HLSL",
"bytes": "501593"
},
{
"name": "HTML",
"bytes": "1664814"
},
{
"name": "Java",
"bytes": "192558"
},
{
"name": "JavaScript",
"bytes": "73468"
},
{
"name": "Lex",
"bytes": "18784"
},
{
"name": "Lua",
"bytes": "1288"
},
{
"name": "M4",
"bytes": "885777"
},
{
"name": "Makefile",
"bytes": "4069931"
},
{
"name": "Metal",
"bytes": "3691"
},
{
"name": "Module Management System",
"bytes": "15326"
},
{
"name": "NSIS",
"bytes": "1193756"
},
{
"name": "Objective-C",
"bytes": "685452"
},
{
"name": "Objective-C++",
"bytes": "119396"
},
{
"name": "Pascal",
"bytes": "48918"
},
{
"name": "Perl",
"bytes": "720596"
},
{
"name": "PowerShell",
"bytes": "12518"
},
{
"name": "Python",
"bytes": "298716"
},
{
"name": "Raku",
"bytes": "7894"
},
{
"name": "Rich Text Format",
"bytes": "4380"
},
{
"name": "Roff",
"bytes": "2152001"
},
{
"name": "SAS",
"bytes": "13756"
},
{
"name": "Shell",
"bytes": "1392232"
},
{
"name": "Smalltalk",
"bytes": "6201"
},
{
"name": "StringTemplate",
"bytes": "4329"
},
{
"name": "WebAssembly",
"bytes": "13560"
},
{
"name": "Yacc",
"bytes": "19731"
}
],
"symlink_target": ""
} |
/* ** GENEREATED FILE - DO NOT MODIFY ** */
package com.wilutions.mslib.outlook.impl;
import com.wilutions.com.*;
@SuppressWarnings("all")
@CoClass(guid="{C091A9ED-A463-DB41-5DAE-69E7A5F7FCBC}")
public class SyncObjectsImpl extends Dispatch implements com.wilutions.mslib.outlook.SyncObjects {
@DeclDISPID(61440) public com.wilutions.mslib.outlook._Application getApplication() throws ComException {
final Object obj = this._dispatchCall(61440,"Application", DISPATCH_PROPERTYGET,null);
if (obj == null) return null;
return Dispatch.as(obj, com.wilutions.mslib.outlook.impl._ApplicationImpl.class);
}
@DeclDISPID(61450) public com.wilutions.mslib.outlook.OlObjectClass getClass_() throws ComException {
final Object obj = this._dispatchCall(61450,"Class", DISPATCH_PROPERTYGET,null);
if (obj == null) return null;
return com.wilutions.mslib.outlook.OlObjectClass.valueOf((Integer)obj);
}
@DeclDISPID(61451) public com.wilutions.mslib.outlook._NameSpace getSession() throws ComException {
final Object obj = this._dispatchCall(61451,"Session", DISPATCH_PROPERTYGET,null);
if (obj == null) return null;
return Dispatch.as(obj, com.wilutions.mslib.outlook.impl._NameSpaceImpl.class);
}
@DeclDISPID(61441) public IDispatch getParent() throws ComException {
final Object obj = this._dispatchCall(61441,"Parent", DISPATCH_PROPERTYGET,null);
if (obj == null) return null;
return (IDispatch)obj;
}
@DeclDISPID(80) public Integer getCount() throws ComException {
final Object obj = this._dispatchCall(80,"Count", DISPATCH_PROPERTYGET,null);
if (obj == null) return null;
return (Integer)obj;
}
@DeclDISPID(81) public com.wilutions.mslib.outlook.SyncObject Item(final Object Index) throws ComException {
assert(Index != null);
final Object obj = this._dispatchCall(81,"Item", DISPATCH_METHOD,null,Index);
if (obj == null) return null;
final Dispatch disp = (Dispatch)obj;
return disp.as(com.wilutions.mslib.outlook.SyncObject.class);
}
@DeclDISPID(64074) public com.wilutions.mslib.outlook._SyncObject getAppFolders() throws ComException {
final Object obj = this._dispatchCall(64074,"AppFolders", DISPATCH_PROPERTYGET,null);
if (obj == null) return null;
return Dispatch.as(obj, com.wilutions.mslib.outlook.impl._SyncObjectImpl.class);
}
public SyncObjectsImpl(String progId) throws ComException {
super(progId, "{00063086-0000-0000-C000-000000000046}");
}
protected SyncObjectsImpl(long ndisp) {
super(ndisp);
}
public String toString() {
return "[SyncObjectsImpl" + super.toString() + "]";
}
}
| {
"content_hash": "3e36f258fd531d7b6be1350b70065e7f",
"timestamp": "",
"source": "github",
"line_count": 54,
"max_line_length": 111,
"avg_line_length": 49.870370370370374,
"alnum_prop": 0.7148161901225399,
"repo_name": "wolfgangimig/joa",
"id": "1c1de4529f219167e34634bd941887f09a741ea2",
"size": "2693",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "java/joa/src-gen/com/wilutions/mslib/outlook/impl/SyncObjectsImpl.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "1296"
},
{
"name": "CSS",
"bytes": "792"
},
{
"name": "HTML",
"bytes": "1337"
},
{
"name": "Java",
"bytes": "9952275"
},
{
"name": "VBScript",
"bytes": "338"
}
],
"symlink_target": ""
} |
The MIT License (MIT)
Coptright (c) 2020 FriendOfFlarum
Copyright (c) Flagrow, Connor Davis (davis@produes.co), Matteo Pompili (matpompili@gmail.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE. | {
"content_hash": "28ef0f5d16bce9ae903d7626a313414a",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 93,
"avg_line_length": 53.36363636363637,
"alnum_prop": 0.803236797274276,
"repo_name": "flagrow/flarum-ext-split",
"id": "e70eb3d76b15d9087af6361a1c1469ed90214233",
"size": "1174",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "LICENSE.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "23557"
},
{
"name": "PHP",
"bytes": "15935"
}
],
"symlink_target": ""
} |
#pragma once
#if ENABLE(INTL)
#include "IntlNumberFormat.h"
#include "JSObject.h"
namespace JSC {
class IntlNumberFormatPrototype : public IntlNumberFormat {
public:
typedef IntlNumberFormat Base;
static const unsigned StructureFlags = Base::StructureFlags | HasStaticPropertyTable;
static IntlNumberFormatPrototype* create(VM&, JSGlobalObject*, Structure*);
static Structure* createStructure(VM&, JSGlobalObject*, JSValue);
DECLARE_INFO;
protected:
void finishCreation(VM&, Structure*);
private:
IntlNumberFormatPrototype(VM&, Structure*);
};
} // namespace JSC
#endif // ENABLE(INTL)
| {
"content_hash": "4333d4a9cade76d06febf559288d9595",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 89,
"avg_line_length": 20.833333333333332,
"alnum_prop": 0.7456,
"repo_name": "acton393/incubator-weex",
"id": "285aa86bc061581b9388a30157f54bb61872f3f3",
"size": "1433",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "weex_core/Source/include/JavaScriptCore/runtime/IntlNumberFormatPrototype.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Awk",
"bytes": "1100"
},
{
"name": "C",
"bytes": "60699"
},
{
"name": "C++",
"bytes": "1854783"
},
{
"name": "CMake",
"bytes": "10554"
},
{
"name": "HTML",
"bytes": "2550"
},
{
"name": "Java",
"bytes": "3880410"
},
{
"name": "JavaScript",
"bytes": "4869113"
},
{
"name": "Objective-C",
"bytes": "1424241"
},
{
"name": "Objective-C++",
"bytes": "624134"
},
{
"name": "Python",
"bytes": "53148"
},
{
"name": "Ruby",
"bytes": "10196"
},
{
"name": "Shell",
"bytes": "30067"
},
{
"name": "Vue",
"bytes": "111308"
}
],
"symlink_target": ""
} |
using DragonSpark.Compose;
using DragonSpark.Model.Selection;
using DragonSpark.Model.Selection.Alterations;
using DragonSpark.Runtime.Execution;
namespace DragonSpark.Runtime.Objects;
sealed class OnlyOnceAlteration<TIn, TOut> : IAlteration<ISelect<TIn, TOut>>
{
public static OnlyOnceAlteration<TIn, TOut> Default { get; } = new OnlyOnceAlteration<TIn, TOut>();
OnlyOnceAlteration() {}
public ISelect<TIn, TOut> Get(ISelect<TIn, TOut> parameter)
=> A.Condition(new ThreadAwareFirst())
.Then()
.Bind()
.Accept<TIn>()
.Return()
.To(parameter.Then().OrDefault)
.Get();
} | {
"content_hash": "296f8dfc6c9b40951d050aa25cbf54f4",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 100,
"avg_line_length": 27.954545454545453,
"alnum_prop": 0.7138211382113822,
"repo_name": "DragonSpark/Framework",
"id": "68be20a81669c119853042ac8748e21db8277f6a",
"size": "617",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "DragonSpark/Runtime/Objects/OnlyOnceAlteration.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "2079497"
},
{
"name": "CSS",
"bytes": "673"
},
{
"name": "HTML",
"bytes": "103546"
},
{
"name": "JavaScript",
"bytes": "1311"
},
{
"name": "TypeScript",
"bytes": "2495"
}
],
"symlink_target": ""
} |
title: Sudo
group: applications
---
FreeAgent's internal management platform.
<div class="BlockGrid">
<div class="BlockGrid-item">
<img alt="One FreeAgent" src="{{ site.baseurl }}/assets/img/applications_sudo.png" />
</div>
</div>
## Overview
Brief summary of the product
## Target Audience
Who is the target audience for this product?
## Principle Actions
What are the key targets for using this product?
| {
"content_hash": "30985041f4de41aeacf011b47b7bef66",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 89,
"avg_line_length": 20,
"alnum_prop": 0.7214285714285714,
"repo_name": "fac/origin",
"id": "b791f9cdb2ab207d10e792e93c58545dd791bc00",
"size": "424",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/_team/applications/sudo.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "233426"
},
{
"name": "JavaScript",
"bytes": "3781"
},
{
"name": "Ruby",
"bytes": "8845"
}
],
"symlink_target": ""
} |
/*
* Changes for SnappyData data platform.
*
* Portions Copyright (c) 2017-2019 TIBCO Software Inc. 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. See accompanying
* LICENSE file.
*/
/**
* Result.h
*
* This class encapsulates the result of execution of a statement or prepared
* statement.
*/
#ifndef RESULT_H_
#define RESULT_H_
#include "Types.h"
#include "PreparedStatement.h"
#include <memory>
using namespace io::snappydata::client::impl;
namespace io {
namespace snappydata {
namespace client {
class Result {
private:
std::shared_ptr<ClientService> m_service;
StatementAttributes m_attrs;
thrift::StatementResult m_result;
Result(const std::shared_ptr<ClientService>& service,
const StatementAttributes& attrs);
Result(const Result&) = delete; // no copy constructor
Result operator=(const Result&) = delete; // no assignment operator
friend class Connection;
friend class PreparedStatement;
static void getResultSetArgs(const StatementAttributes& attrs,
int32_t& batchSize, bool& updatable, bool& scrollable) noexcept;
ResultSet* newResultSet(thrift::RowSet& rowSet);
public:
~Result();
std::unique_ptr<ResultSet> getResultSet();
int32_t getUpdateCount() const noexcept;
inline bool hasBatchUpdateCounts() const noexcept {
return m_result.__isset.batchUpdateCounts
&& m_result.batchUpdateCounts.size() > 0;
}
const std::vector<int32_t>& getBatchUpdateCounts() const noexcept;
const std::map<int32_t, thrift::ColumnValue>& getOutputParameters()
const noexcept;
std::unique_ptr<ResultSet> getGeneratedKeys();
const StatementAttributes& getAttributes() const noexcept {
return m_attrs;
}
inline bool hasWarnings() const noexcept {
return m_result.__isset.warnings || (m_result.__isset.resultSet &&
m_result.resultSet.__isset.warnings);
}
std::unique_ptr<SQLWarning> getWarnings() const;
std::unique_ptr<PreparedStatement> getPreparedStatement() const;
};
} /* namespace client */
} /* namespace snappydata */
} /* namespace io */
#endif /* RESULT_H_ */
| {
"content_hash": "0620194ec865db388b9edaba0174f16c",
"timestamp": "",
"source": "github",
"line_count": 99,
"max_line_length": 77,
"avg_line_length": 27.141414141414142,
"alnum_prop": 0.7041310011164867,
"repo_name": "SnappyDataInc/snappy-store",
"id": "b7cbdb2f78f14e142b15c4dd52030cbfc075011b",
"size": "3352",
"binary": false,
"copies": "1",
"ref": "refs/heads/snappy/master",
"path": "native/src/snappyclient/headers/Result.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "AGS Script",
"bytes": "90653"
},
{
"name": "Assembly",
"bytes": "738033"
},
{
"name": "Batchfile",
"bytes": "23509"
},
{
"name": "C",
"bytes": "298655"
},
{
"name": "C#",
"bytes": "1338285"
},
{
"name": "C++",
"bytes": "784695"
},
{
"name": "CSS",
"bytes": "54987"
},
{
"name": "Gnuplot",
"bytes": "3125"
},
{
"name": "HTML",
"bytes": "8595527"
},
{
"name": "Java",
"bytes": "117988027"
},
{
"name": "JavaScript",
"bytes": "33027"
},
{
"name": "Makefile",
"bytes": "9359"
},
{
"name": "Mathematica",
"bytes": "92588"
},
{
"name": "PHP",
"bytes": "869892"
},
{
"name": "PLSQL",
"bytes": "80858"
},
{
"name": "PLpgSQL",
"bytes": "205179"
},
{
"name": "Pascal",
"bytes": "3707"
},
{
"name": "Pawn",
"bytes": "93609"
},
{
"name": "Perl",
"bytes": "196843"
},
{
"name": "Python",
"bytes": "131049"
},
{
"name": "Ruby",
"bytes": "26443"
},
{
"name": "SQLPL",
"bytes": "47702"
},
{
"name": "Shell",
"bytes": "550962"
},
{
"name": "SourcePawn",
"bytes": "15059"
},
{
"name": "TSQL",
"bytes": "5461819"
},
{
"name": "Thrift",
"bytes": "55057"
},
{
"name": "XSLT",
"bytes": "67112"
},
{
"name": "sed",
"bytes": "6411"
}
],
"symlink_target": ""
} |
/* Licensed under the BSD. See License.txt for full text. */
$(document).ready(function() {
// If Do later is ever pressed send to profile
$("#step_three_later_2").click(function() {
window.location.href = "profile.php";
});
$("#step_three_submit_2_2").click(function() {
$("#step_three_alert_success_2").html("").slideUp();
$("#step_three_alert_danger_2").html("").slideUp();
$posted_values = "";
$("#checkbox_input :input").each(function() {
if ($(this).is(':checked')) {
$posted_values = $posted_values + $(this).attr("name") + ",";
}
});
stepThreePartTwo($posted_values);
});
// Handle submits
$("#step_three_submit_2").click(function() {
// Scroll to top
$('html, body').animate({ scrollTop: 0 }, 'fast');
// Reset alerts
$("#step_three_alert_success_2").html("").slideUp();
$("#step_three_alert_danger_2").html("").slideUp();
// Get all values selected
$posted_values = "";
$("#radio_input :input").each(function() {
if ($(this).is(':checked')) {
$posted_values = $posted_values + $(this).val() + ",";
}
});
// Send to appropriate area
$status = $("#step_three_status_2").val();
if ($status == "part_one") {
stepThreePartOne_2($posted_values);
} else if ($status == "part_two") {
stepThreePartTwo_3($posted_values);
}
});
});
function stepThreePartTwo_3($posted_values) {
// Get slot_id out of junk
$slot_id = $posted_values.split(',')[0];
// POST slot_id to PHP
$.ajax({
type : "POST",
url : "php/timeformone_2.php",
data : {
slot_id : $slot_id
}
}).done(function($msg) {
// Get results from POST
$response = parseResponse($msg);
// If success
if (inArray("true", $response)) {
// Set status to two
$("#step_three_status_2").val("part_three");
// Display success message to user
setTimeout(function() {
displayAlert($("#step_three_alert_success_2"), "Thank you for your information. Please wait...");
}, 500);
setTimeout(function() {
$("#step_three_departure").val($slot_id);
$inbetween = false;
$("#checkbox_input :input").each(function() {
if ($(this).attr("type") == "checkbox") {
if ($(this).attr("name") == ("ts" + $("#step_three_arrival").val())) {
$inbetween = true;
}
if ($inbetween) {
$(this).prop("checked", true);
} else {
$(this).parent("p").wrap("<strike>");
$(this).prop('disabled', true);
}
if ($(this).attr("name") == ("ts" + $("#step_three_departure").val())) {
$inbetween = false;
}
}
});
// Reset warnings and show step_two instructions
$("#step_three_alert_success_2").html("").slideUp();
$("#step_three_alert_danger_2").html("").slideUp();
$("#step_three_part_two_inst_2").slideUp();
$("#step_three_part_three_inst_2").slideDown();
$("#radio_input").slideUp();
$("#checkbox_input").slideDown();
}, 3000);
} else {
$html = "<p>The following errors occured:</p><ul>";
if (inArray("err1", $response)) {
$html = createError($html, "Not enough time between first and last time slot.");
}
if (inArray("err2", $response)) {
$html = createError($html, "Not enough time in between time slots selected.");
}
$html = $html + "</ul>"
setTimeout(function() {
displayAlert($('#step_three_alert_danger_2'), $html);
}, 500);
}
});
}
// Function to set arrival time slot
function stepThreePartOne_2($posted_values) {
// Get slot_id out of junk
$slot_id = $posted_values.split(',')[0];
// POST slot_id to PHP
$.ajax({
type : "POST",
url : "php/arrival.php",
data : {
slot_id : $slot_id
}
}).done(function($msg) {
// Get results from POST
$response = parseResponse($msg);
// If success
if (inArray("true", $response)) {
// Set status to two
$("#step_three_status_2").val("part_two");
// Display success message to user
setTimeout(function() {
displayAlert($("#step_three_alert_success_2"), "Thank you for your information. Please wait...");
}, 500);
setTimeout(function() {
// Strikout/Disable time slots before and including arrival slot.
$before = true;
$("#radio_input :input").each(function() {
$(this).prop("checked", false);
if ($before) {
$(this).prop('disabled', true);
$(this).parent("label").wrap("<strike>");
}
if ($slot_id == $(this).val()) {
$before = false;
}
});
// Reset warnings and show step_two instructions
$("#step_three_alert_success_2").html("").slideUp();
$("#step_three_alert_danger_2").html("").slideUp();
$("#step_three_part_one_inst_2").slideUp();
$("#step_three_part_two_inst_2").slideDown();
$("#step_three_arrival").val($slot_id);
}, 3000);
// If failure
} else if (inArray("false", $response)) {
$html = "<p>The following errors occured:</p><ul>";
if (inArray("err1", $response)) {
$html = createError($html, "Please mark a time slot.");
}
$html = $html + "</ul>"
setTimeout(function() {
displayAlert($('#step_three_alert_danger_2'), $html);
}, 500);
}
});
}
| {
"content_hash": "4aeb0039e533da96738ff40cb90c1327",
"timestamp": "",
"source": "github",
"line_count": 222,
"max_line_length": 114,
"avg_line_length": 29.346846846846848,
"alnum_prop": 0.44850345356868765,
"repo_name": "beloitcollegecomputerscience/SIGCSE-live",
"id": "75ce6b94d247a27a5a2b3b9a431a6c27cfcd5b10",
"size": "6515",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "user/js/register_2.js",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "237327"
},
{
"name": "HTML",
"bytes": "659"
},
{
"name": "JavaScript",
"bytes": "112764"
},
{
"name": "PHP",
"bytes": "306463"
}
],
"symlink_target": ""
} |
'use strict';
const path = require('path');
const _ = require('lodash');
const logger = require('../utils/logger');
const parseOptions = require('./options');
const defaults = require('./defaults');
const BrowserConfig = require('./browser-config');
module.exports = class Config {
static create(config) {
return new Config(config);
}
static read(configPath) {
try {
return require(path.resolve(process.cwd(), configPath));
} catch (e) {
logger.error(`Unable to read config from path ${configPath}`);
throw e;
}
}
constructor(config = defaults.config) {
let options;
if (_.isObjectLike(config)) {
options = config;
} else {
this.configPath = config;
options = Config.read(config);
}
if (_.isFunction(options.prepareEnvironment)) {
options.prepareEnvironment();
}
_.extend(this, parseOptions({
options,
env: process.env,
argv: process.argv
}));
this.browsers = _.mapValues(this.browsers, (browser, id) => {
const browserOptions = _.extend({},
browser,
{
id: id,
system: this.system
}
);
return new BrowserConfig(browserOptions);
});
}
forBrowser(id) {
return this.browsers[id];
}
getBrowserIds() {
return _.keys(this.browsers);
}
serialize() {
return _.extend({}, this, {
browsers: _.mapValues(this.browsers, (broConf) => broConf.serialize())
});
}
/**
* This method is used in subrocesses to merge a created config
* in a subrocess with a config from the main process
*/
mergeWith(config) {
_.mergeWith(this, config, (l, r) => {
if (_.isObjectLike(l)) {
return;
}
// When passing stringified config from the master to workers
// all functions are transformed to strings and all regular expressions to empty objects
return typeof l === typeof r ? r : l;
});
}
};
| {
"content_hash": "523b064c44080464eb32b9c31e4bcdfd",
"timestamp": "",
"source": "github",
"line_count": 85,
"max_line_length": 100,
"avg_line_length": 26.376470588235293,
"alnum_prop": 0.5214094558429974,
"repo_name": "gemini-testing/hermione",
"id": "5fb45820a3b00142baee21a61b7f269dce8341c8",
"size": "2242",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/config/index.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "934711"
}
],
"symlink_target": ""
} |
package com.google.android.exoplayer2.source.smoothstreaming.manifest;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Pair;
import androidx.annotation.Nullable;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.Format;
import com.google.android.exoplayer2.ParserException;
import com.google.android.exoplayer2.audio.AacUtil;
import com.google.android.exoplayer2.drm.DrmInitData;
import com.google.android.exoplayer2.drm.DrmInitData.SchemeData;
import com.google.android.exoplayer2.extractor.mp4.PsshAtomUtil;
import com.google.android.exoplayer2.extractor.mp4.TrackEncryptionBox;
import com.google.android.exoplayer2.source.smoothstreaming.manifest.SsManifest.ProtectionElement;
import com.google.android.exoplayer2.source.smoothstreaming.manifest.SsManifest.StreamElement;
import com.google.android.exoplayer2.upstream.ParsingLoadable;
import com.google.android.exoplayer2.util.Assertions;
import com.google.android.exoplayer2.util.CodecSpecificDataUtil;
import com.google.android.exoplayer2.util.MimeTypes;
import com.google.android.exoplayer2.util.Util;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.UUID;
import org.checkerframework.checker.nullness.compatqual.NullableType;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
/**
* Parses SmoothStreaming client manifests.
*
* @see <a href="http://msdn.microsoft.com/en-us/library/ee673436(v=vs.90).aspx">IIS Smooth
* Streaming Client Manifest Format</a>
*/
public class SsManifestParser implements ParsingLoadable.Parser<SsManifest> {
private final XmlPullParserFactory xmlParserFactory;
public SsManifestParser() {
try {
xmlParserFactory = XmlPullParserFactory.newInstance();
} catch (XmlPullParserException e) {
throw new RuntimeException("Couldn't create XmlPullParserFactory instance", e);
}
}
@Override
public SsManifest parse(Uri uri, InputStream inputStream) throws IOException {
try {
XmlPullParser xmlParser = xmlParserFactory.newPullParser();
xmlParser.setInput(inputStream, null);
SmoothStreamingMediaParser smoothStreamingMediaParser =
new SmoothStreamingMediaParser(null, uri.toString());
return (SsManifest) smoothStreamingMediaParser.parse(xmlParser);
} catch (XmlPullParserException e) {
throw ParserException.createForMalformedManifest(/* message= */ null, /* cause= */ e);
}
}
/** Thrown if a required field is missing. */
public static class MissingFieldException extends ParserException {
public MissingFieldException(String fieldName) {
super(
"Missing required field: " + fieldName,
/* cause= */ null,
/* contentIsMalformed= */ true,
C.DATA_TYPE_MANIFEST);
}
}
/** A base class for parsers that parse components of a smooth streaming manifest. */
private abstract static class ElementParser {
private final String baseUri;
private final String tag;
@Nullable private final ElementParser parent;
private final List<Pair<String, @NullableType Object>> normalizedAttributes;
public ElementParser(@Nullable ElementParser parent, String baseUri, String tag) {
this.parent = parent;
this.baseUri = baseUri;
this.tag = tag;
this.normalizedAttributes = new LinkedList<>();
}
public final Object parse(XmlPullParser xmlParser) throws XmlPullParserException, IOException {
String tagName;
boolean foundStartTag = false;
int skippingElementDepth = 0;
while (true) {
int eventType = xmlParser.getEventType();
switch (eventType) {
case XmlPullParser.START_TAG:
tagName = xmlParser.getName();
if (tag.equals(tagName)) {
foundStartTag = true;
parseStartTag(xmlParser);
} else if (foundStartTag) {
if (skippingElementDepth > 0) {
skippingElementDepth++;
} else if (handleChildInline(tagName)) {
parseStartTag(xmlParser);
} else {
ElementParser childElementParser = newChildParser(this, tagName, baseUri);
if (childElementParser == null) {
skippingElementDepth = 1;
} else {
addChild(childElementParser.parse(xmlParser));
}
}
}
break;
case XmlPullParser.TEXT:
if (foundStartTag && skippingElementDepth == 0) {
parseText(xmlParser);
}
break;
case XmlPullParser.END_TAG:
if (foundStartTag) {
if (skippingElementDepth > 0) {
skippingElementDepth--;
} else {
tagName = xmlParser.getName();
parseEndTag(xmlParser);
if (!handleChildInline(tagName)) {
return build();
}
}
}
break;
case XmlPullParser.END_DOCUMENT:
return null;
default:
// Do nothing.
break;
}
xmlParser.next();
}
}
private ElementParser newChildParser(ElementParser parent, String name, String baseUri) {
if (QualityLevelParser.TAG.equals(name)) {
return new QualityLevelParser(parent, baseUri);
} else if (ProtectionParser.TAG.equals(name)) {
return new ProtectionParser(parent, baseUri);
} else if (StreamIndexParser.TAG.equals(name)) {
return new StreamIndexParser(parent, baseUri);
}
return null;
}
/**
* Stash an attribute that may be normalized at this level. In other words, an attribute that
* may have been pulled up from the child elements because its value was the same in all
* children.
*
* <p>Stashing an attribute allows child element parsers to retrieve the values of normalized
* attributes using {@link #getNormalizedAttribute(String)}.
*
* @param key The name of the attribute.
* @param value The value of the attribute.
*/
protected final void putNormalizedAttribute(String key, @Nullable Object value) {
normalizedAttributes.add(Pair.create(key, value));
}
/**
* Attempt to retrieve a stashed normalized attribute. If there is no stashed attribute with the
* provided name, the parent element parser will be queried, and so on up the chain.
*
* @param key The name of the attribute.
* @return The stashed value, or null if the attribute was not found.
*/
@Nullable
protected final Object getNormalizedAttribute(String key) {
for (int i = 0; i < normalizedAttributes.size(); i++) {
Pair<String, Object> pair = normalizedAttributes.get(i);
if (pair.first.equals(key)) {
return pair.second;
}
}
return parent == null ? null : parent.getNormalizedAttribute(key);
}
/**
* Whether this {@link ElementParser} parses a child element inline.
*
* @param tagName The name of the child element.
* @return Whether the child is parsed inline.
*/
protected boolean handleChildInline(String tagName) {
return false;
}
/**
* @param xmlParser The underlying {@link XmlPullParser}
* @throws ParserException If a parsing error occurs.
*/
protected void parseStartTag(XmlPullParser xmlParser) throws ParserException {
// Do nothing.
}
/** @param xmlParser The underlying {@link XmlPullParser} */
protected void parseText(XmlPullParser xmlParser) {
// Do nothing.
}
/** @param xmlParser The underlying {@link XmlPullParser} */
protected void parseEndTag(XmlPullParser xmlParser) {
// Do nothing.
}
/** @param parsedChild A parsed child object. */
protected void addChild(Object parsedChild) {
// Do nothing.
}
protected abstract Object build();
protected final String parseRequiredString(XmlPullParser parser, String key)
throws MissingFieldException {
String value = parser.getAttributeValue(null, key);
if (value != null) {
return value;
} else {
throw new MissingFieldException(key);
}
}
protected final int parseInt(XmlPullParser parser, String key, int defaultValue)
throws ParserException {
String value = parser.getAttributeValue(null, key);
if (value != null) {
try {
return Integer.parseInt(value);
} catch (NumberFormatException e) {
throw ParserException.createForMalformedManifest(/* message= */ null, /* cause= */ e);
}
} else {
return defaultValue;
}
}
protected final int parseRequiredInt(XmlPullParser parser, String key) throws ParserException {
String value = parser.getAttributeValue(null, key);
if (value != null) {
try {
return Integer.parseInt(value);
} catch (NumberFormatException e) {
throw ParserException.createForMalformedManifest(/* message= */ null, /* cause= */ e);
}
} else {
throw new MissingFieldException(key);
}
}
protected final long parseLong(XmlPullParser parser, String key, long defaultValue)
throws ParserException {
String value = parser.getAttributeValue(null, key);
if (value != null) {
try {
return Long.parseLong(value);
} catch (NumberFormatException e) {
throw ParserException.createForMalformedManifest(/* message= */ null, /* cause= */ e);
}
} else {
return defaultValue;
}
}
protected final long parseRequiredLong(XmlPullParser parser, String key)
throws ParserException {
String value = parser.getAttributeValue(null, key);
if (value != null) {
try {
return Long.parseLong(value);
} catch (NumberFormatException e) {
throw ParserException.createForMalformedManifest(/* message= */ null, /* cause= */ e);
}
} else {
throw new MissingFieldException(key);
}
}
protected final boolean parseBoolean(XmlPullParser parser, String key, boolean defaultValue) {
String value = parser.getAttributeValue(null, key);
if (value != null) {
return Boolean.parseBoolean(value);
} else {
return defaultValue;
}
}
}
private static class SmoothStreamingMediaParser extends ElementParser {
public static final String TAG = "SmoothStreamingMedia";
private static final String KEY_MAJOR_VERSION = "MajorVersion";
private static final String KEY_MINOR_VERSION = "MinorVersion";
private static final String KEY_TIME_SCALE = "TimeScale";
private static final String KEY_DVR_WINDOW_LENGTH = "DVRWindowLength";
private static final String KEY_DURATION = "Duration";
private static final String KEY_LOOKAHEAD_COUNT = "LookaheadCount";
private static final String KEY_IS_LIVE = "IsLive";
private final List<StreamElement> streamElements;
private int majorVersion;
private int minorVersion;
private long timescale;
private long duration;
private long dvrWindowLength;
private int lookAheadCount;
private boolean isLive;
@Nullable private ProtectionElement protectionElement;
public SmoothStreamingMediaParser(ElementParser parent, String baseUri) {
super(parent, baseUri, TAG);
lookAheadCount = SsManifest.UNSET_LOOKAHEAD;
protectionElement = null;
streamElements = new LinkedList<>();
}
@Override
public void parseStartTag(XmlPullParser parser) throws ParserException {
majorVersion = parseRequiredInt(parser, KEY_MAJOR_VERSION);
minorVersion = parseRequiredInt(parser, KEY_MINOR_VERSION);
timescale = parseLong(parser, KEY_TIME_SCALE, 10000000L);
duration = parseRequiredLong(parser, KEY_DURATION);
dvrWindowLength = parseLong(parser, KEY_DVR_WINDOW_LENGTH, 0);
lookAheadCount = parseInt(parser, KEY_LOOKAHEAD_COUNT, SsManifest.UNSET_LOOKAHEAD);
isLive = parseBoolean(parser, KEY_IS_LIVE, false);
putNormalizedAttribute(KEY_TIME_SCALE, timescale);
}
@Override
public void addChild(Object child) {
if (child instanceof StreamElement) {
streamElements.add((StreamElement) child);
} else if (child instanceof ProtectionElement) {
Assertions.checkState(protectionElement == null);
protectionElement = (ProtectionElement) child;
}
}
@Override
public Object build() {
StreamElement[] streamElementArray = new StreamElement[streamElements.size()];
streamElements.toArray(streamElementArray);
if (protectionElement != null) {
DrmInitData drmInitData =
new DrmInitData(
new SchemeData(
protectionElement.uuid, MimeTypes.VIDEO_MP4, protectionElement.data));
for (StreamElement streamElement : streamElementArray) {
int type = streamElement.type;
if (type == C.TRACK_TYPE_VIDEO || type == C.TRACK_TYPE_AUDIO) {
Format[] formats = streamElement.formats;
for (int i = 0; i < formats.length; i++) {
formats[i] = formats[i].buildUpon().setDrmInitData(drmInitData).build();
}
}
}
}
return new SsManifest(
majorVersion,
minorVersion,
timescale,
duration,
dvrWindowLength,
lookAheadCount,
isLive,
protectionElement,
streamElementArray);
}
}
private static class ProtectionParser extends ElementParser {
public static final String TAG = "Protection";
public static final String TAG_PROTECTION_HEADER = "ProtectionHeader";
public static final String KEY_SYSTEM_ID = "SystemID";
private static final int INITIALIZATION_VECTOR_SIZE = 8;
private boolean inProtectionHeader;
private UUID uuid;
private byte[] initData;
public ProtectionParser(ElementParser parent, String baseUri) {
super(parent, baseUri, TAG);
}
@Override
public boolean handleChildInline(String tag) {
return TAG_PROTECTION_HEADER.equals(tag);
}
@Override
public void parseStartTag(XmlPullParser parser) {
if (TAG_PROTECTION_HEADER.equals(parser.getName())) {
inProtectionHeader = true;
String uuidString = parser.getAttributeValue(null, KEY_SYSTEM_ID);
uuidString = stripCurlyBraces(uuidString);
uuid = UUID.fromString(uuidString);
}
}
@Override
public void parseText(XmlPullParser parser) {
if (inProtectionHeader) {
initData = Base64.decode(parser.getText(), Base64.DEFAULT);
}
}
@Override
public void parseEndTag(XmlPullParser parser) {
if (TAG_PROTECTION_HEADER.equals(parser.getName())) {
inProtectionHeader = false;
}
}
@Override
public Object build() {
return new ProtectionElement(
uuid, PsshAtomUtil.buildPsshAtom(uuid, initData), buildTrackEncryptionBoxes(initData));
}
private static TrackEncryptionBox[] buildTrackEncryptionBoxes(byte[] initData) {
return new TrackEncryptionBox[] {
new TrackEncryptionBox(
/* isEncrypted= */ true,
/* schemeType= */ null,
INITIALIZATION_VECTOR_SIZE,
getProtectionElementKeyId(initData),
/* defaultEncryptedBlocks= */ 0,
/* defaultClearBlocks= */ 0,
/* defaultInitializationVector= */ null)
};
}
private static byte[] getProtectionElementKeyId(byte[] initData) {
StringBuilder initDataStringBuilder = new StringBuilder();
for (int i = 0; i < initData.length; i += 2) {
initDataStringBuilder.append((char) initData[i]);
}
String initDataString = initDataStringBuilder.toString();
String keyIdString =
initDataString.substring(
initDataString.indexOf("<KID>") + 5, initDataString.indexOf("</KID>"));
byte[] keyId = Base64.decode(keyIdString, Base64.DEFAULT);
swap(keyId, 0, 3);
swap(keyId, 1, 2);
swap(keyId, 4, 5);
swap(keyId, 6, 7);
return keyId;
}
private static void swap(byte[] data, int firstPosition, int secondPosition) {
byte temp = data[firstPosition];
data[firstPosition] = data[secondPosition];
data[secondPosition] = temp;
}
private static String stripCurlyBraces(String uuidString) {
if (uuidString.charAt(0) == '{' && uuidString.charAt(uuidString.length() - 1) == '}') {
uuidString = uuidString.substring(1, uuidString.length() - 1);
}
return uuidString;
}
}
private static class StreamIndexParser extends ElementParser {
public static final String TAG = "StreamIndex";
private static final String TAG_STREAM_FRAGMENT = "c";
private static final String KEY_TYPE = "Type";
private static final String KEY_TYPE_AUDIO = "audio";
private static final String KEY_TYPE_VIDEO = "video";
private static final String KEY_TYPE_TEXT = "text";
private static final String KEY_SUB_TYPE = "Subtype";
private static final String KEY_NAME = "Name";
private static final String KEY_URL = "Url";
private static final String KEY_MAX_WIDTH = "MaxWidth";
private static final String KEY_MAX_HEIGHT = "MaxHeight";
private static final String KEY_DISPLAY_WIDTH = "DisplayWidth";
private static final String KEY_DISPLAY_HEIGHT = "DisplayHeight";
private static final String KEY_LANGUAGE = "Language";
private static final String KEY_TIME_SCALE = "TimeScale";
private static final String KEY_FRAGMENT_DURATION = "d";
private static final String KEY_FRAGMENT_START_TIME = "t";
private static final String KEY_FRAGMENT_REPEAT_COUNT = "r";
private final String baseUri;
private final List<Format> formats;
private int type;
private String subType;
private long timescale;
private String name;
private String url;
private int maxWidth;
private int maxHeight;
private int displayWidth;
private int displayHeight;
private String language;
private ArrayList<Long> startTimes;
private long lastChunkDuration;
public StreamIndexParser(ElementParser parent, String baseUri) {
super(parent, baseUri, TAG);
this.baseUri = baseUri;
formats = new LinkedList<>();
}
@Override
public boolean handleChildInline(String tag) {
return TAG_STREAM_FRAGMENT.equals(tag);
}
@Override
public void parseStartTag(XmlPullParser parser) throws ParserException {
if (TAG_STREAM_FRAGMENT.equals(parser.getName())) {
parseStreamFragmentStartTag(parser);
} else {
parseStreamElementStartTag(parser);
}
}
private void parseStreamFragmentStartTag(XmlPullParser parser) throws ParserException {
int chunkIndex = startTimes.size();
long startTime = parseLong(parser, KEY_FRAGMENT_START_TIME, C.TIME_UNSET);
if (startTime == C.TIME_UNSET) {
if (chunkIndex == 0) {
// Assume the track starts at t = 0.
startTime = 0;
} else if (lastChunkDuration != C.INDEX_UNSET) {
// Infer the start time from the previous chunk's start time and duration.
startTime = startTimes.get(chunkIndex - 1) + lastChunkDuration;
} else {
// We don't have the start time, and we're unable to infer it.
throw ParserException.createForMalformedManifest(
"Unable to infer start time", /* cause= */ null);
}
}
chunkIndex++;
startTimes.add(startTime);
lastChunkDuration = parseLong(parser, KEY_FRAGMENT_DURATION, C.TIME_UNSET);
// Handle repeated chunks.
long repeatCount = parseLong(parser, KEY_FRAGMENT_REPEAT_COUNT, 1L);
if (repeatCount > 1 && lastChunkDuration == C.TIME_UNSET) {
throw ParserException.createForMalformedManifest(
"Repeated chunk with unspecified duration", /* cause= */ null);
}
for (int i = 1; i < repeatCount; i++) {
chunkIndex++;
startTimes.add(startTime + (lastChunkDuration * i));
}
}
private void parseStreamElementStartTag(XmlPullParser parser) throws ParserException {
type = parseType(parser);
putNormalizedAttribute(KEY_TYPE, type);
if (type == C.TRACK_TYPE_TEXT) {
subType = parseRequiredString(parser, KEY_SUB_TYPE);
} else {
subType = parser.getAttributeValue(null, KEY_SUB_TYPE);
}
putNormalizedAttribute(KEY_SUB_TYPE, subType);
name = parser.getAttributeValue(null, KEY_NAME);
putNormalizedAttribute(KEY_NAME, name);
url = parseRequiredString(parser, KEY_URL);
maxWidth = parseInt(parser, KEY_MAX_WIDTH, Format.NO_VALUE);
maxHeight = parseInt(parser, KEY_MAX_HEIGHT, Format.NO_VALUE);
displayWidth = parseInt(parser, KEY_DISPLAY_WIDTH, Format.NO_VALUE);
displayHeight = parseInt(parser, KEY_DISPLAY_HEIGHT, Format.NO_VALUE);
language = parser.getAttributeValue(null, KEY_LANGUAGE);
putNormalizedAttribute(KEY_LANGUAGE, language);
timescale = parseInt(parser, KEY_TIME_SCALE, -1);
if (timescale == -1) {
timescale = (Long) getNormalizedAttribute(KEY_TIME_SCALE);
}
startTimes = new ArrayList<>();
}
private int parseType(XmlPullParser parser) throws ParserException {
String value = parser.getAttributeValue(null, KEY_TYPE);
if (value != null) {
if (KEY_TYPE_AUDIO.equalsIgnoreCase(value)) {
return C.TRACK_TYPE_AUDIO;
} else if (KEY_TYPE_VIDEO.equalsIgnoreCase(value)) {
return C.TRACK_TYPE_VIDEO;
} else if (KEY_TYPE_TEXT.equalsIgnoreCase(value)) {
return C.TRACK_TYPE_TEXT;
} else {
throw ParserException.createForMalformedManifest(
"Invalid key value[" + value + "]", /* cause= */ null);
}
}
throw new MissingFieldException(KEY_TYPE);
}
@Override
public void addChild(Object child) {
if (child instanceof Format) {
formats.add((Format) child);
}
}
@Override
public Object build() {
Format[] formatArray = new Format[formats.size()];
formats.toArray(formatArray);
return new StreamElement(
baseUri,
url,
type,
subType,
timescale,
name,
maxWidth,
maxHeight,
displayWidth,
displayHeight,
language,
formatArray,
startTimes,
lastChunkDuration);
}
}
private static class QualityLevelParser extends ElementParser {
public static final String TAG = "QualityLevel";
private static final String KEY_INDEX = "Index";
private static final String KEY_BITRATE = "Bitrate";
private static final String KEY_CODEC_PRIVATE_DATA = "CodecPrivateData";
private static final String KEY_SAMPLING_RATE = "SamplingRate";
private static final String KEY_CHANNELS = "Channels";
private static final String KEY_FOUR_CC = "FourCC";
private static final String KEY_TYPE = "Type";
private static final String KEY_SUB_TYPE = "Subtype";
private static final String KEY_LANGUAGE = "Language";
private static final String KEY_NAME = "Name";
private static final String KEY_MAX_WIDTH = "MaxWidth";
private static final String KEY_MAX_HEIGHT = "MaxHeight";
private Format format;
public QualityLevelParser(ElementParser parent, String baseUri) {
super(parent, baseUri, TAG);
}
@Override
public void parseStartTag(XmlPullParser parser) throws ParserException {
Format.Builder formatBuilder = new Format.Builder();
@Nullable String sampleMimeType = fourCCToMimeType(parseRequiredString(parser, KEY_FOUR_CC));
int type = (Integer) getNormalizedAttribute(KEY_TYPE);
if (type == C.TRACK_TYPE_VIDEO) {
List<byte[]> codecSpecificData =
buildCodecSpecificData(parser.getAttributeValue(null, KEY_CODEC_PRIVATE_DATA));
formatBuilder
.setContainerMimeType(MimeTypes.VIDEO_MP4)
.setWidth(parseRequiredInt(parser, KEY_MAX_WIDTH))
.setHeight(parseRequiredInt(parser, KEY_MAX_HEIGHT))
.setInitializationData(codecSpecificData);
} else if (type == C.TRACK_TYPE_AUDIO) {
if (sampleMimeType == null) {
// If we don't know the MIME type, assume AAC.
sampleMimeType = MimeTypes.AUDIO_AAC;
}
int channelCount = parseRequiredInt(parser, KEY_CHANNELS);
int sampleRate = parseRequiredInt(parser, KEY_SAMPLING_RATE);
List<byte[]> codecSpecificData =
buildCodecSpecificData(parser.getAttributeValue(null, KEY_CODEC_PRIVATE_DATA));
if (codecSpecificData.isEmpty() && MimeTypes.AUDIO_AAC.equals(sampleMimeType)) {
codecSpecificData =
Collections.singletonList(
AacUtil.buildAacLcAudioSpecificConfig(sampleRate, channelCount));
}
formatBuilder
.setContainerMimeType(MimeTypes.AUDIO_MP4)
.setChannelCount(channelCount)
.setSampleRate(sampleRate)
.setInitializationData(codecSpecificData);
} else if (type == C.TRACK_TYPE_TEXT) {
@C.RoleFlags int roleFlags = 0;
@Nullable String subType = (String) getNormalizedAttribute(KEY_SUB_TYPE);
if (subType != null) {
switch (subType) {
case "CAPT":
roleFlags = C.ROLE_FLAG_CAPTION;
break;
case "DESC":
roleFlags = C.ROLE_FLAG_DESCRIBES_MUSIC_AND_SOUND;
break;
default:
break;
}
}
formatBuilder.setContainerMimeType(MimeTypes.APPLICATION_MP4).setRoleFlags(roleFlags);
} else {
formatBuilder.setContainerMimeType(MimeTypes.APPLICATION_MP4);
}
format =
formatBuilder
.setId(parser.getAttributeValue(null, KEY_INDEX))
.setLabel((String) getNormalizedAttribute(KEY_NAME))
.setSampleMimeType(sampleMimeType)
.setAverageBitrate(parseRequiredInt(parser, KEY_BITRATE))
.setLanguage((String) getNormalizedAttribute(KEY_LANGUAGE))
.build();
}
@Override
public Object build() {
return format;
}
private static List<byte[]> buildCodecSpecificData(String codecSpecificDataString) {
ArrayList<byte[]> csd = new ArrayList<>();
if (!TextUtils.isEmpty(codecSpecificDataString)) {
byte[] codecPrivateData = Util.getBytesFromHexString(codecSpecificDataString);
@Nullable byte[][] split = CodecSpecificDataUtil.splitNalUnits(codecPrivateData);
if (split == null) {
csd.add(codecPrivateData);
} else {
Collections.addAll(csd, split);
}
}
return csd;
}
@Nullable
private static String fourCCToMimeType(String fourCC) {
if (fourCC.equalsIgnoreCase("H264")
|| fourCC.equalsIgnoreCase("X264")
|| fourCC.equalsIgnoreCase("AVC1")
|| fourCC.equalsIgnoreCase("DAVC")) {
return MimeTypes.VIDEO_H264;
} else if (fourCC.equalsIgnoreCase("AAC")
|| fourCC.equalsIgnoreCase("AACL")
|| fourCC.equalsIgnoreCase("AACH")
|| fourCC.equalsIgnoreCase("AACP")) {
return MimeTypes.AUDIO_AAC;
} else if (fourCC.equalsIgnoreCase("TTML") || fourCC.equalsIgnoreCase("DFXP")) {
return MimeTypes.APPLICATION_TTML;
} else if (fourCC.equalsIgnoreCase("ac-3") || fourCC.equalsIgnoreCase("dac3")) {
return MimeTypes.AUDIO_AC3;
} else if (fourCC.equalsIgnoreCase("ec-3") || fourCC.equalsIgnoreCase("dec3")) {
return MimeTypes.AUDIO_E_AC3;
} else if (fourCC.equalsIgnoreCase("dtsc")) {
return MimeTypes.AUDIO_DTS;
} else if (fourCC.equalsIgnoreCase("dtsh") || fourCC.equalsIgnoreCase("dtsl")) {
return MimeTypes.AUDIO_DTS_HD;
} else if (fourCC.equalsIgnoreCase("dtse")) {
return MimeTypes.AUDIO_DTS_EXPRESS;
} else if (fourCC.equalsIgnoreCase("opus")) {
return MimeTypes.AUDIO_OPUS;
}
return null;
}
}
}
| {
"content_hash": "8f28fe819b90cad423311ba19a7b396d",
"timestamp": "",
"source": "github",
"line_count": 780,
"max_line_length": 100,
"avg_line_length": 36.77820512820513,
"alnum_prop": 0.6518632133021927,
"repo_name": "amzn/exoplayer-amazon-port",
"id": "b26e2d41d8d1789cbdea43b16ede37191c59e33f",
"size": "29306",
"binary": false,
"copies": "2",
"ref": "refs/heads/amazon/r2.17.1",
"path": "library/smoothstreaming/src/main/java/com/google/android/exoplayer2/source/smoothstreaming/manifest/SsManifestParser.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C++",
"bytes": "60500"
},
{
"name": "Java",
"bytes": "6311191"
},
{
"name": "Makefile",
"bytes": "13718"
},
{
"name": "Shell",
"bytes": "5784"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle">
<!--apply button background transparent, full opacity-->
<solid android:color="#00ffffff"/>
<!--make button border solid color, nontransparent-->
<stroke android:color="#ffffff" android:width="1dp"/>
<corners android:radius="75dp"/>
</shape>
</item>
</selector> | {
"content_hash": "a28c403e6bde594f3d05a587dd436dfa",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 69,
"avg_line_length": 35.5,
"alnum_prop": 0.5955734406438632,
"repo_name": "neeharmb/Twitter_App",
"id": "8847eb91ddede504bea0061eaca273aebef24f1d",
"size": "497",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/res/drawable/button_login.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "61225"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<ServiceConfiguration xmlns="http://www.cagrid.org/1/grape-service-configuration"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<ServiceGroupDescription>Dorian</ServiceGroupDescription>
<Services>
<ServiceDescriptor>
<DisplayName>Training</DisplayName>
<ServiceURL>https://dorian.training.cagrid.org:8443/wsrf/services/cagrid/Dorian</ServiceURL>
<ServiceIdentity>/O=caBIG/OU=caGrid/OU=Training/OU=Services/CN=dorian.training.cagrid.org</ServiceIdentity>
</ServiceDescriptor>
</Services>
</ServiceConfiguration>
| {
"content_hash": "2b9f627b8ced945e703342fc213cdacf",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 119,
"avg_line_length": 53.25,
"alnum_prop": 0.702660406885759,
"repo_name": "NCIP/cagrid",
"id": "1b56e467601850840c4650cd402b5af855c71680",
"size": "639",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "cagrid/Software/core/caGrid/repository/caGrid/target_grid/training-1.4/dorian-services-configuration.xml",
"mode": "33261",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "438360"
},
{
"name": "Java",
"bytes": "25536538"
},
{
"name": "JavaScript",
"bytes": "265984"
},
{
"name": "Perl",
"bytes": "115674"
},
{
"name": "Scala",
"bytes": "405"
},
{
"name": "Shell",
"bytes": "85928"
},
{
"name": "XSLT",
"bytes": "75865"
}
],
"symlink_target": ""
} |
using System;
namespace DataGenerator.Commands.IntegrationTest.DbContextAssembly
{
public class DataGenerator
{
public void Generate(AppDbContext dbContext, string argument)
{
Console.WriteLine("DataGenerator.Commands.IntegrationTest.DbContextAssembly.DataGenerator.Generate");
Console.WriteLine($"argument: {argument}");
dbContext.Users.Add(new User { Name = "User1" });
dbContext.Users.Add(new User { Name = "User2" });
dbContext.SaveChanges();
Console.WriteLine("DataGenerator.Commands.IntegrationTest.DbContextAssembly.DataGenerator.Generate-DONE");
}
}
} | {
"content_hash": "00dc90240d5c5f14884ddbfcdef93b26",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 118,
"avg_line_length": 40.294117647058826,
"alnum_prop": 0.6598540145985401,
"repo_name": "ST-Software/DataGenerator.Commands",
"id": "dfbd32042cfabc1f33c369b219c9042bc2274c50",
"size": "687",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/DataGenerator.Commands.IntegrationTest.DbContextAssembly/DataGenerator.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "17045"
},
{
"name": "PowerShell",
"bytes": "212"
}
],
"symlink_target": ""
} |
require 'test_helper'
require_relative 'thing'
require_relative 'foo/bar'
module Dibber
class SeederTest < Minitest::Test
def setup
Seeder.seeds_path = File.join(File.dirname(__FILE__), 'seeds')
end
def teardown
Thing.clear_all
Foo::Bar.clear_all
end
def test_process_log
assert_kind_of(ProcessLog, Seeder.process_log)
end
def test_process_log_start
@log = Seeder.process_log
assert(@log.raw.keys.include?(:time), 'time should be logged')
end
def test_report
test_process_log_start
assert_equal(@log.report, Seeder.report)
end
def test_monitor
Seeder.clear_process_log
Seeder.monitor(Thing)
assert_equal({command: 'Thing.count', start: Thing.count}, Seeder.process_log.raw[:things])
end
def test_clear_process_log
test_monitor
Seeder.clear_process_log
assert_nil Seeder.process_log.raw[:things], "Log should be empty"
end
def test_seeds_path
assert_match(/test\/dibber\/seeds\/$/, Seeder.seeds_path)
end
def test_objects_from
content = YAML.load_file(thing_file_path)
assert_equal(content, Seeder.objects_from('things.yml'))
end
def test_start_log
thing_seeder.start_log
assert(Seeder.process_log.raw.keys.include?(:things), 'Things should be logged')
end
def test_objects
content = YAML.load_file(thing_file_path)
assert_equal(content, thing_seeder.objects)
end
def test_build_with_no_objects
thing_seeder = Seeder.new(Thing, 'empty.yml')
assert_raises RuntimeError do
thing_seeder.build
end
end
def test_build
assert_equal(0, Thing.count)
thing_seeder.build
assert_equal(2, Thing.count)
foo = Thing.find_or_initialize_by(name: :foo)
bar = Thing.find_or_initialize_by(name: :bar)
assert_equal([foo, bar], Thing.saved)
assert_equal({'title' => 'one'}, foo.attributes)
end
def test_build_with_block
other = 'other'
thing_seeder.build { |t| t.other_method = other }
foo = Thing.find_or_initialize_by(name: :foo)
bar = Thing.find_or_initialize_by(name: :bar)
assert_equal([foo, bar], Thing.where(other_method: other))
end
def test_rebuilding_does_not_overwrite
test_build
attributes = {'title' => 'something else'}
foo = Thing.find_or_initialize_by(name: :foo)
foo.attributes = attributes
foo.save
thing_seeder.build
assert_equal(2, Thing.count)
foo = Thing.find_or_initialize_by(name: :foo)
assert_equal(attributes, foo.attributes)
end
def test_rebuilding_does_overwrite_if_set_to
test_build
attributes = {'title' => 'something else'}
foo = Thing.find_or_initialize_by(name: :foo)
foo.attributes = attributes
foo.save
thing_seeder(:overwrite => true).build
assert_equal(2, Thing.count)
foo = Thing.find_or_initialize_by(name: :foo)
assert_equal({'title' => 'one'}, foo.attributes)
end
def test_other_method_instead_of_attributes
thing_seeder('other_method').build
foo = Thing.find_or_initialize_by(name: :foo)
bar = Thing.find_or_initialize_by(name: :bar)
assert_equal([foo, bar], Thing.saved)
assert_equal({:name=>"foo"}, foo.attributes)
assert_equal({'title' => 'one'}, foo.other_method)
end
def test_other_method_replacing_attributes_via_args
thing_seeder(:attributes_method => 'other_method').build
foo = Thing.find_or_initialize_by(name: :foo)
bar = Thing.find_or_initialize_by(name: :bar)
assert_equal([foo, bar], Thing.saved)
assert_equal({:name=>"foo"}, foo.attributes)
assert_equal({'title' => 'one'}, foo.other_method)
end
def test_alternative_name_method
thing_seeder(:name_method => 'other_method').build
assert_equal(2, Thing.count)
foo = Thing.find_or_initialize_by(other_method: :foo)
bar = Thing.find_or_initialize_by(other_method: :bar)
assert_equal([foo, bar], Thing.saved)
assert_equal({'title' => 'one'}, foo.attributes)
end
def test_seed
assert_equal(0, Thing.count)
Seeder.seed(:things)
assert_equal(2, Thing.count)
foo = Thing.find_or_initialize_by(name: :foo)
bar = Thing.find_or_initialize_by(name: :bar)
assert_equal([foo, bar], Thing.saved)
assert_equal({'title' => 'one'}, foo.attributes)
end
def test_seed_with_block
other = 'other'
Seeder.seed(:things) { |thing| thing.other_method = other }
foo = Thing.find_or_initialize_by(name: :foo)
bar = Thing.find_or_initialize_by(name: :bar)
assert_equal([foo, bar], Thing.where(other_method: other))
end
def test_seed_with_block_using_attributes
other = 'other'
Seeder.seed(:things) { |thing| thing.other_method = thing.attributes['title'] }
foo = Thing.find_or_initialize_by(name: :foo)
assert_equal('one', foo.other_method)
end
def test_seed_with_alternative_name_method
Seeder.seed(:things, :name_method => 'other_method')
assert_equal(2, Thing.count)
foo = Thing.find_or_initialize_by(other_method: :foo)
bar = Thing.find_or_initialize_by(other_method: :bar)
assert_equal([foo, bar], Thing.saved)
assert_equal({'title' => 'one'}, foo.attributes)
end
def test_seed_with_non_existent_class
assert_raises NameError do
Seeder.seed(:non_existent_class)
end
end
def test_seed_with_non_existent_seed_file
no_file_found_error = Errno::ENOENT
assert_raises no_file_found_error do
Seeder.seed(:array)
end
end
def test_seed_with_sub_class_string
assert_equal(0, Foo::Bar.count)
Seeder.seed('foo/bar')
assert_equal(1, Foo::Bar.count)
bar = Foo::Bar.find_or_initialize_by(name: :some)
assert_equal([bar], Foo::Bar.saved)
assert_equal({'title' => 'thing'}, bar.attributes)
end
def test_seed_with_class
assert_equal(0, Thing.count)
Seeder.seed(Thing)
assert_equal(2, Thing.count)
foo = Thing.find_or_initialize_by(name: :foo)
bar = Thing.find_or_initialize_by(name: :bar)
assert_equal([foo, bar], Thing.saved)
assert_equal({'title' => 'one'}, foo.attributes)
end
def test_seed_with_class_name
assert_equal(0, Thing.count)
Seeder.seed('Thing')
assert_equal(2, Thing.count)
foo = Thing.find_or_initialize_by(name: :foo)
bar = Thing.find_or_initialize_by(name: :bar)
assert_equal([foo, bar], Thing.saved)
assert_equal({'title' => 'one'}, foo.attributes)
end
def test_seed_with_class_with_alternative_name_method
Seeder.seed(Thing, :name_method => 'other_method')
assert_equal(2, Thing.count)
foo = Thing.find_or_initialize_by(other_method: :foo)
bar = Thing.find_or_initialize_by(other_method: :bar)
assert_equal([foo, bar], Thing.saved)
assert_equal({'title' => 'one'}, foo.attributes)
end
def test_seed_with_class_that_does_not_exist
assert_raises NameError do
Seeder.seed(NonExistentClass)
end
end
def test_seed_with_class_with_non_existent_seed_file
no_file_found_error = Errno::ENOENT
assert_raises no_file_found_error do
Seeder.seed(Array)
end
end
def test_seed_with_sub_class
assert_equal(0, Foo::Bar.count)
Seeder.seed(Foo::Bar)
assert_equal(1, Foo::Bar.count)
bar = Foo::Bar.find_or_initialize_by(name: :some)
assert_equal([bar], Foo::Bar.saved)
assert_equal({'title' => 'thing'}, bar.attributes)
end
def test_seeds_path_with_none_set
Seeder.seeds_path = nil
assert_raises RuntimeError do
Seeder.seeds_path
end
end
def test_process_log_not_reset_by_second_seed_process_on_same_class
Seeder.seed(:things)
original_start = Seeder.process_log.raw[:things][:start]
Seeder.seed(:things)
assert_equal original_start, Seeder.process_log.raw[:things][:start]
end
module DummyRails
def self.root
'/some/path'
end
end
def test_seeds_path_if_Rails_exists
Dibber.const_set :Rails, DummyRails
Seeder.seeds_path = nil
assert_equal '/some/path/db/seeds/', Seeder.seeds_path
Dibber.send(:remove_const, :Rails)
end
private
def thing_seeder(method = 'attributes')
@thing_seeder = Seeder.new(Thing, 'things.yml', method)
end
def thing_file_path
File.join(File.dirname(__FILE__), 'seeds', 'things.yml')
end
end
end
| {
"content_hash": "c6f6f98e96a7317a39c6c6722f187e49",
"timestamp": "",
"source": "github",
"line_count": 284,
"max_line_length": 97,
"avg_line_length": 30.552816901408452,
"alnum_prop": 0.6332833928777227,
"repo_name": "reggieb/Dibber",
"id": "6bfcd6ed15309c97c4b80748259860f542a60fdd",
"size": "8677",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/dibber/seeder_test.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "24217"
},
{
"name": "Shell",
"bytes": "75"
}
],
"symlink_target": ""
} |
/**
*
*/
package ca.eandb.jmist.framework.geometry.mesh;
import ca.eandb.jmist.math.Point2;
public enum Point2Format {
DOUBLE_XY(new DoublePoint2Reader());
private final MeshElementReader<Point2> reader;
private Point2Format(MeshElementReader<Point2> reader) {
this.reader = reader;
}
public MeshElementReader<Point2> createReader(int offset) {
return offset == 0
? reader : new OffsetMeshElementReader<>(offset, reader);
}
}
| {
"content_hash": "2ccd59d0d8149a7ff53b3b9a74dd97a0",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 65,
"avg_line_length": 21.952380952380953,
"alnum_prop": 0.7180043383947939,
"repo_name": "bwkimmel/jmist",
"id": "ac38cc5c1fb9570462cc3868e2be084f19fa9a81",
"size": "461",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "jmist-core/src/main/java/ca/eandb/jmist/framework/geometry/mesh/Point2Format.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "3161361"
}
],
"symlink_target": ""
} |
rem do the call in one place
call %~dp0pdf_envcall.bat
@echo on
rem otherwise do it here
rem call ....\WPy64-...\scripts\env.bat
%python% %~dp0pdf_concat.py %*
| {
"content_hash": "804c6640c68f487817d9596763d7813e",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 39,
"avg_line_length": 18.11111111111111,
"alnum_prop": 0.6932515337423313,
"repo_name": "winpython/winpython_afterdoc",
"id": "0a9bbb5e21652977023f276a02e1fb5fbd7c974e",
"size": "163",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "docs/drag_and_drop_concat_and_rotate_pdf/pdf_concat.bat",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
package org.apache.tez.dag.api.client;
import javax.annotation.Nullable;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import com.google.common.annotations.VisibleForTesting;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.tez.common.CachedEntity;
import org.apache.tez.common.Preconditions;
import org.apache.hadoop.yarn.exceptions.ApplicationNotFoundException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.hadoop.classification.InterfaceAudience.Private;
import org.apache.hadoop.yarn.api.records.ApplicationId;
import org.apache.hadoop.yarn.api.records.ApplicationReport;
import org.apache.hadoop.yarn.api.records.FinalApplicationStatus;
import org.apache.hadoop.yarn.api.records.YarnApplicationState;
import org.apache.hadoop.yarn.exceptions.YarnException;
import org.apache.tez.client.FrameworkClient;
import org.apache.tez.common.counters.TezCounters;
import org.apache.tez.dag.api.DAGNotRunningException;
import org.apache.tez.dag.api.TezConfiguration;
import org.apache.tez.dag.api.TezException;
import org.apache.tez.dag.api.TezUncheckedException;
import org.apache.tez.dag.api.client.rpc.DAGClientRPCImpl;
import org.apache.tez.dag.api.records.DAGProtos;
@Private
public class DAGClientImpl extends DAGClient {
private static final Logger LOG = LoggerFactory.getLogger(DAGClientImpl.class);
private final ApplicationId appId;
private final String dagId;
private final TezConfiguration conf;
private final FrameworkClient frameworkClient;
/**
* Container to cache the last {@link DAGStatus}.
*/
private final CachedEntity<DAGStatus> cachedDAGStatusRef;
@VisibleForTesting
protected DAGClientInternal realClient;
private volatile boolean dagCompleted = false;
@VisibleForTesting
protected boolean isATSEnabled = false;
Map<String, VertexStatus> cachedVertexStatus = new HashMap<String, VertexStatus>();
private static final long SLEEP_FOR_COMPLETION = 500;
private static final long PRINT_STATUS_INTERVAL_MILLIS = 5000;
private final DecimalFormat formatter = new DecimalFormat("###.##%");
private long lastPrintStatusTimeMillis;
private EnumSet<VertexStatus.State> vertexCompletionStates = EnumSet.of(
VertexStatus.State.SUCCEEDED, VertexStatus.State.FAILED, VertexStatus.State.KILLED,
VertexStatus.State.ERROR);
private long statusPollInterval;
private long diagnoticsWaitTimeout;
private boolean cleanupFrameworkClient;
public DAGClientImpl(ApplicationId appId, String dagId, TezConfiguration conf,
@Nullable FrameworkClient frameworkClient, UserGroupInformation ugi) {
this.appId = appId;
this.dagId = dagId;
this.conf = conf;
if (frameworkClient != null) {
this.frameworkClient = frameworkClient;
} else {
this.frameworkClient = FrameworkClient.createFrameworkClient(conf);
this.frameworkClient.init(conf);
this.frameworkClient.start();
cleanupFrameworkClient = true;
}
isATSEnabled = conf.get(TezConfiguration.TEZ_HISTORY_LOGGING_SERVICE_CLASS, "")
.equals("org.apache.tez.dag.history.logging.ats.ATSHistoryLoggingService") &&
conf.getBoolean(TezConfiguration.TEZ_DAG_HISTORY_LOGGING_ENABLED,
TezConfiguration.TEZ_DAG_HISTORY_LOGGING_ENABLED_DEFAULT) &&
conf.getBoolean(TezConfiguration.TEZ_AM_HISTORY_LOGGING_ENABLED,
TezConfiguration.TEZ_AM_HISTORY_LOGGING_ENABLED_DEFAULT) &&
DAGClientTimelineImpl.isSupported();
realClient = new DAGClientRPCImpl(appId, dagId, conf, this.frameworkClient, ugi);
statusPollInterval = conf.getLong(
TezConfiguration.TEZ_DAG_STATUS_POLLINTERVAL_MS,
TezConfiguration.TEZ_DAG_STATUS_POLLINTERVAL_MS_DEFAULT);
if(statusPollInterval < 0) {
LOG.error("DAG Status poll interval cannot be negative and setting to default value.");
statusPollInterval = TezConfiguration.TEZ_DAG_STATUS_POLLINTERVAL_MS_DEFAULT;
}
this.diagnoticsWaitTimeout = conf.getLong(
TezConfiguration.TEZ_CLIENT_DIAGNOSTICS_WAIT_TIMEOUT_MS,
TezConfiguration.TEZ_CLIENT_DIAGNOSTICS_WAIT_TIMEOUT_MS_DEFAULT);
cachedDAGStatusRef = initCacheDAGRefFromConf(conf);
}
/**
* Constructs a new {@link CachedEntity} for {@link DAGStatus}.
* @param tezConf TEZ configuration parameters.
* @return a caching entry to hold the {@link DAGStatus}.
*/
protected CachedEntity<DAGStatus> initCacheDAGRefFromConf(TezConfiguration tezConf) {
long clientDAGStatusCacheTimeOut = tezConf.getLong(
TezConfiguration.TEZ_CLIENT_DAG_STATUS_CACHE_TIMEOUT_SECS,
TezConfiguration.TEZ_CLIENT_DAG_STATUS_CACHE_TIMEOUT_SECS_DEFAULT);
if (clientDAGStatusCacheTimeOut <= 0) {
LOG.error("DAG Status cache timeout interval should be positive. Enforcing default value.");
clientDAGStatusCacheTimeOut =
TezConfiguration.TEZ_CLIENT_DAG_STATUS_CACHE_TIMEOUT_SECS_DEFAULT;
}
return new CachedEntity<>(TimeUnit.SECONDS, clientDAGStatusCacheTimeOut);
}
protected CachedEntity<DAGStatus> getCachedDAGStatusRef() {
return cachedDAGStatusRef;
}
@Override
public String getExecutionContext() {
return realClient.getExecutionContext();
}
@Override
protected ApplicationReport getApplicationReportInternal() {
return realClient.getApplicationReportInternal();
}
@Override
public DAGStatus getDAGStatus(@Nullable Set<StatusGetOpts> statusOptions,
final long timeout) throws TezException, IOException {
Preconditions.checkArgument(timeout >= -1, "Timeout must be >= -1");
// Short circuit a timeout of 0.
if (timeout == 0) {
return getDAGStatusInternal(statusOptions, timeout);
}
long startTime = System.currentTimeMillis();
DAGStatus dagStatus = cachedDAGStatusRef.getValue();
boolean refreshStatus = true;
if (dagStatus == null) {
// the first lookup only or when the cachedDAG has expired
dagStatus = getDAGStatus(statusOptions);
refreshStatus = false;
}
// Handling when client dag status init or submitted. This really implies that the RM was
// contacted to get status. INITING is never used. DAG_INITING implies a DagState of RUNNING.
if (dagStatus.getState() == DAGStatus.State.INITING
|| dagStatus.getState() == DAGStatus.State.SUBMITTED) {
long timeoutAbsolute = startTime + timeout;
while (timeout < 0
|| (timeout > 0 && timeoutAbsolute > System.currentTimeMillis())) {
if (refreshStatus) {
// Try fetching the state with a timeout, in case the AM is already up.
dagStatus = getDAGStatusInternal(statusOptions, timeout);
}
refreshStatus = true; // For the next iteration of the loop.
if (dagStatus.getState() == DAGStatus.State.RUNNING) {
// Refreshed status indicates that the DAG is running.
// This status could have come from the AM or the RM - client sleep if RM, otherwise send request to the AM.
if (dagStatus.getSource() == DagStatusSource.AM) {
// RUNNING + AM should only happen if timeout is > -1.
// Otherwise the AM ignored the -1 value, or the AM source in the DAGStatus is invalid.
Preconditions.checkState(timeout > -1, "Should not reach here with a timeout of -1. File a bug");
return dagStatus;
} else {
// From the RM. Fall through to the Sleep.
}
} else if(dagStatus.getState() == DAGStatus.State.SUCCEEDED
|| dagStatus.getState() == DAGStatus.State.FAILED
|| dagStatus.getState() == DAGStatus.State.KILLED
|| dagStatus.getState() == DAGStatus.State.ERROR) {
// Again, check if this was from the RM. If it was, try getting it from a more informative source.
if (dagStatus.getSource() == DagStatusSource.RM) {
return getDAGStatusInternal(statusOptions, 0);
} else {
return dagStatus;
}
}
// Sleep before checking again.
long currentStatusPollInterval;
if (timeout < 0) {
currentStatusPollInterval = statusPollInterval;
} else {
long remainingTimeout = timeoutAbsolute - System.currentTimeMillis();
if (remainingTimeout < 0) {
// Timeout expired. Return the latest known dag status.
return dagStatus;
} else {
currentStatusPollInterval = remainingTimeout < statusPollInterval ? remainingTimeout : statusPollInterval;
}
}
try {
Thread.sleep(currentStatusPollInterval);
} catch (InterruptedException e) {
throw new TezException(e);
}
}// End of while
// Timeout may have expired before a single refresh
if (refreshStatus) {
return getDAGStatus(statusOptions);
} else {
return dagStatus;
}
} else { // Already running, or complete. Fallback to regular dagStatus with a timeout.
return getDAGStatusInternal(statusOptions, timeout);
}
}
protected DAGStatus getDAGStatusInternal(@Nullable Set<StatusGetOpts> statusOptions,
long timeout) throws TezException, IOException {
if (!dagCompleted) {
// fetch from AM. on Error and while DAG is still not completed (could not reach AM, AM got
// killed). return cached status. This prevents the progress being reset (for ex fetching from
// RM does not give status).
// dagCompleted may be reset within getDagStatusViaAM
final DAGStatus dagStatus = getDAGStatusViaAM(statusOptions, timeout);
if (!dagCompleted) {
if (dagStatus != null) { // update the cached DAGStatus
cachedDAGStatusRef.setValue(dagStatus);
return dagStatus;
}
DAGStatus cachedDAG = cachedDAGStatusRef.getValue();
if (cachedDAG != null) {
// could not get from AM (not reachable/ was killed). return cached status.
return cachedDAG;
}
}
if (isATSEnabled && dagCompleted) {
switchToTimelineClient();
}
}
if (isATSEnabled && dagCompleted) {
try {
// fetch from ATS and return only if status is completed.
DAGStatus dagStatus = realClient.getDAGStatus(statusOptions);
if (dagStatus.isCompleted()) {
return dagStatus;
}
} catch (ApplicationNotFoundException e) {
LOG.info("Failed to fetch DAG data for completed DAG from YARN Timeline"
+ " - Application not found by YARN", e);
} catch (TezException e) {
LOG.debug("DAGStatus fetch failed", e);
}
}
// dag completed and Timeline service is either not enabled or does not have completion status
// return cached status if completion info is present.
if (dagCompleted) {
DAGStatus cachedDag = cachedDAGStatusRef.getValue();
if (cachedDag != null && cachedDag.isCompleted()) {
return cachedDag;
}
}
// everything else fails rely on RM.
return getDAGStatusViaRM();
}
@Override
public DAGStatus getDAGStatus(@Nullable Set<StatusGetOpts> statusOptions) throws
TezException, IOException {
return getDAGStatusInternal(statusOptions, 0);
}
@Override
public VertexStatus getVertexStatus(String vertexName, Set<StatusGetOpts> statusOptions)
throws IOException, TezException {
return getVertexStatusInternal(statusOptions, vertexName);
}
protected VertexStatus getVertexStatusInternal(Set<StatusGetOpts> statusOptions, String vertexName)
throws IOException, TezException {
if (!dagCompleted) {
VertexStatus vertexStatus = getVertexStatusViaAM(vertexName, statusOptions);
if (!dagCompleted) {
if (vertexStatus != null) {
cachedVertexStatus.put(vertexName, vertexStatus);
return vertexStatus;
}
if (cachedVertexStatus.containsKey(vertexName)) {
return cachedVertexStatus.get(vertexName);
}
}
if (isATSEnabled && dagCompleted) {
switchToTimelineClient();
}
}
if (isATSEnabled && dagCompleted) {
try {
final VertexStatus vertexStatus = realClient.getVertexStatus(vertexName, statusOptions);
if (vertexCompletionStates.contains(vertexStatus.getState())) {
return vertexStatus;
}
} catch (ApplicationNotFoundException e) {
LOG.info("Failed to fetch Vertex data for completed DAG from YARN Timeline"
+ " - Application not found by YARN", e);
return null;
} catch (TezException e) {
LOG.debug("ERROR fetching vertex data from Yarn Timeline", e);
}
}
if (cachedVertexStatus.containsKey(vertexName)) {
final VertexStatus vertexStatus = cachedVertexStatus.get(vertexName);
if (vertexCompletionStates.contains(vertexStatus.getState())) {
return vertexStatus;
}
}
return null;
}
@Override
public String getDagIdentifierString() {
return realClient.getDagIdentifierString();
}
@Override
public String getSessionIdentifierString() {
return realClient.getSessionIdentifierString();
}
@Override
public void tryKillDAG() throws IOException, TezException {
if (!dagCompleted) {
realClient.tryKillDAG();
} else {
LOG.info("TryKill for app: " + appId + " dag:" + dagId + " dag already completed.");
}
}
@Override
public DAGStatus waitForCompletion(long timeMs) throws IOException, TezException, InterruptedException {
return _waitForCompletionWithStatusUpdates(timeMs, false, EnumSet.noneOf(StatusGetOpts.class));
}
@Override
public DAGStatus waitForCompletion() throws IOException, TezException, InterruptedException {
return _waitForCompletionWithStatusUpdates(-1, false, EnumSet.noneOf(StatusGetOpts.class));
}
@Override
public DAGStatus waitForCompletionWithStatusUpdates(
@Nullable Set<StatusGetOpts> statusGetOpts) throws IOException, TezException,
InterruptedException {
return _waitForCompletionWithStatusUpdates(-1, true, statusGetOpts);
}
@Override
public void close() throws IOException {
realClient.close();
if (frameworkClient != null && cleanupFrameworkClient) {
frameworkClient.stop();
}
}
/**
* Get the DAG status via the AM
* @param statusOptions
* @param timeout
* @return null if the AM cannot be contacted, otherwise the DAGstatus
* @throws IOException
*/
private DAGStatus getDAGStatusViaAM(@Nullable Set<StatusGetOpts> statusOptions,
long timeout) throws IOException {
DAGStatus dagStatus = null;
try {
dagStatus = realClient.getDAGStatus(statusOptions, timeout);
} catch (DAGNotRunningException e) {
LOG.info("DAG is no longer running", e);
dagCompleted = true;
} catch (ApplicationNotFoundException e) {
LOG.info("DAG is no longer running - application not found by YARN", e);
dagCompleted = true;
} catch (TezException e) {
// can be either due to a n/w issue or due to AM completed.
LOG.info("Cannot retrieve DAG Status due to TezException: {}", e.getMessage());
} catch (IOException e) {
// can be either due to a n/w issue or due to AM completed.
LOG.info("Cannot retrieve DAG Status due to IOException: {}", e.getMessage());
}
if (dagStatus == null && !dagCompleted) {
checkAndSetDagCompletionStatus();
}
return dagStatus;
}
private VertexStatus getVertexStatusViaAM(String vertexName, Set<StatusGetOpts> statusOptions) throws
IOException {
VertexStatus vertexStatus = null;
try {
vertexStatus = realClient.getVertexStatus(vertexName, statusOptions);
} catch (DAGNotRunningException e) {
LOG.info("DAG is no longer running", e);
dagCompleted = true;
} catch (ApplicationNotFoundException e) {
LOG.info("DAG is no longer running - application not found by YARN", e);
dagCompleted = true;
} catch (TezException e) {
// can be either due to a n/w issue of due to AM completed.
} catch (IOException e) {
// can be either due to a n/w issue of due to AM completed.
}
if (vertexStatus == null && !dagCompleted) {
checkAndSetDagCompletionStatus();
}
return vertexStatus;
}
/**
* Get the DAG status via the YARN ResourceManager
* @return the dag status, inferred from the RM App state. Does not return null.
* @throws TezException
* @throws IOException
*/
@VisibleForTesting
protected DAGStatus getDAGStatusViaRM() throws TezException, IOException {
LOG.debug("GetDAGStatus via AM for app: {} dag:{}", appId, dagId);
ApplicationReport appReport;
try {
appReport = frameworkClient.getApplicationReport(appId);
} catch (ApplicationNotFoundException e) {
LOG.info("DAG is no longer running - application not found by YARN", e);
throw new DAGNotRunningException(e);
} catch (YarnException e) {
throw new TezException(e);
}
if(appReport == null) {
throw new TezException("Unknown/Invalid appId: " + appId);
}
DAGProtos.DAGStatusProto.Builder builder = DAGProtos.DAGStatusProto.newBuilder();
DAGStatus dagStatus = new DAGStatus(builder, DagStatusSource.RM);
DAGProtos.DAGStatusStateProto dagState;
switch (appReport.getYarnApplicationState()) {
case NEW:
case NEW_SAVING:
case SUBMITTED:
case ACCEPTED:
dagState = DAGProtos.DAGStatusStateProto.DAG_SUBMITTED;
break;
case RUNNING:
dagState = DAGProtos.DAGStatusStateProto.DAG_RUNNING;
break;
case FAILED:
dagState = DAGProtos.DAGStatusStateProto.DAG_FAILED;
break;
case KILLED:
dagState = DAGProtos.DAGStatusStateProto.DAG_KILLED;
break;
case FINISHED:
switch(appReport.getFinalApplicationStatus()) {
case UNDEFINED:
case FAILED:
dagState = DAGProtos.DAGStatusStateProto.DAG_FAILED;
break;
case KILLED:
dagState = DAGProtos.DAGStatusStateProto.DAG_KILLED;
break;
case SUCCEEDED:
dagState = DAGProtos.DAGStatusStateProto.DAG_SUCCEEDED;
break;
default:
throw new TezUncheckedException("Encountered unknown final application"
+ " status from YARN"
+ ", appState=" + appReport.getYarnApplicationState()
+ ", finalStatus=" + appReport.getFinalApplicationStatus());
}
break;
default:
throw new TezUncheckedException("Encountered unknown application state"
+ " from YARN, appState=" + appReport.getYarnApplicationState());
}
builder.setState(dagState);
// workaround before YARN-2560 is fixed
if (appReport.getFinalApplicationStatus() == FinalApplicationStatus.FAILED
|| appReport.getFinalApplicationStatus() == FinalApplicationStatus.KILLED) {
long startTime = System.currentTimeMillis();
while((appReport.getDiagnostics() == null
|| appReport.getDiagnostics().isEmpty())
&& (System.currentTimeMillis() - startTime) < diagnoticsWaitTimeout) {
try {
Thread.sleep(100);
appReport = frameworkClient.getApplicationReport(appId);
} catch (YarnException e) {
throw new TezException(e);
} catch (InterruptedException e) {
throw new TezException(e);
}
}
}
if (appReport.getDiagnostics() != null) {
builder.addAllDiagnostics(Collections.singleton(appReport.getDiagnostics()));
}
return dagStatus;
}
private DAGStatus _waitForCompletionWithStatusUpdates(long timeMs,
boolean vertexUpdates,
@Nullable Set<StatusGetOpts> statusGetOpts) throws IOException, TezException, InterruptedException {
DAGStatus dagStatus;
boolean initPrinted = false;
boolean runningPrinted = false;
double dagProgress = -1.0; // Print the first one
// monitoring
Long maxNs = timeMs >= 0 ? (System.nanoTime() + (timeMs * 1000000L)) : null;
while (true) {
try {
dagStatus = getDAGStatus(statusGetOpts, SLEEP_FOR_COMPLETION);
} catch (DAGNotRunningException ex) {
return null;
}
if (!initPrinted
&& (dagStatus.getState() == DAGStatus.State.INITING || dagStatus.getState() == DAGStatus.State.SUBMITTED)) {
initPrinted = true; // Print once
log("Waiting for DAG to start running");
}
if (dagStatus.getState() == DAGStatus.State.RUNNING
|| dagStatus.getState() == DAGStatus.State.SUCCEEDED
|| dagStatus.getState() == DAGStatus.State.FAILED
|| dagStatus.getState() == DAGStatus.State.KILLED
|| dagStatus.getState() == DAGStatus.State.ERROR) {
break;
}
if (maxNs != null && System.nanoTime() > maxNs) {
return null;
}
}// End of while(true)
Set<String> vertexNames = Collections.emptySet();
while (!dagStatus.isCompleted()) {
if (!runningPrinted) {
log("DAG initialized: CurrentState=Running");
runningPrinted = true;
}
if (vertexUpdates && vertexNames.isEmpty()) {
vertexNames = getDAGStatus(statusGetOpts).getVertexProgress().keySet();
}
dagProgress = monitorProgress(vertexNames, dagProgress, null, dagStatus);
try {
dagStatus = getDAGStatus(statusGetOpts, SLEEP_FOR_COMPLETION);
} catch (DAGNotRunningException ex) {
return null;
}
if (maxNs != null && System.nanoTime() > maxNs) {
return null;
}
}// end of while
// Always print the last status irrespective of progress change
monitorProgress(vertexNames, -1.0, statusGetOpts, dagStatus);
log("DAG completed. " + "FinalState=" + dagStatus.getState());
return dagStatus;
}
private double monitorProgress(Set<String> vertexNames, double prevDagProgress,
Set<StatusGetOpts> opts, DAGStatus dagStatus) throws IOException, TezException {
Progress progress = dagStatus.getDAGProgress();
double dagProgress = prevDagProgress;
if (progress != null) {
dagProgress = getProgress(progress);
boolean progressChanged = dagProgress > prevDagProgress;
long currentTimeMillis = System.currentTimeMillis();
long timeSinceLastPrintStatus = currentTimeMillis - lastPrintStatusTimeMillis;
boolean printIntervalExpired = timeSinceLastPrintStatus > PRINT_STATUS_INTERVAL_MILLIS;
if (progressChanged || printIntervalExpired) {
lastPrintStatusTimeMillis = currentTimeMillis;
printDAGStatus(vertexNames, opts, dagStatus, progress);
}
}
return dagProgress;
}
private void printDAGStatus(Set<String> vertexNames, Set<StatusGetOpts> opts,
DAGStatus dagStatus, Progress dagProgress) throws IOException, TezException {
double vProgressFloat = 0.0f;
log("DAG: State: " + dagStatus.getState() + " Progress: "
+ formatter.format(getProgress(dagProgress)) + " " + dagProgress);
boolean displayCounter = opts != null && opts.contains(StatusGetOpts.GET_COUNTERS);
if (displayCounter) {
TezCounters counters = dagStatus.getDAGCounters();
if (counters != null) {
log("DAG Counters:\n" + counters);
}
}
for (String vertex : vertexNames) {
VertexStatus vStatus = getVertexStatus(vertex, opts);
if (vStatus == null) {
log("Could not retrieve status for vertex: " + vertex);
continue;
}
Progress vProgress = vStatus.getProgress();
if (vProgress != null) {
vProgressFloat = 0.0f;
if (vProgress.getTotalTaskCount() == 0) {
vProgressFloat = 1.0f;
} else if (vProgress.getTotalTaskCount() > 0) {
vProgressFloat = getProgress(vProgress);
}
log("\tVertexStatus:" + " VertexName: " + vertex + " Progress: "
+ formatter.format(vProgressFloat) + " " + vProgress);
}
if (displayCounter) {
TezCounters counters = vStatus.getVertexCounters();
if (counters != null) {
log("Vertex Counters for " + vertex + ":\n" + counters);
}
}
} // end of for loop
}
private void checkAndSetDagCompletionStatus() {
ApplicationReport appReport = realClient.getApplicationReportInternal();
if (appReport != null) {
final YarnApplicationState appState = appReport.getYarnApplicationState();
if (appState == YarnApplicationState.FINISHED || appState == YarnApplicationState.FAILED ||
appState == YarnApplicationState.KILLED) {
dagCompleted = true;
}
}
}
private void switchToTimelineClient() throws IOException, TezException {
realClient.close();
realClient = new DAGClientTimelineImpl(appId, dagId, conf, frameworkClient,
(int) (2 * PRINT_STATUS_INTERVAL_MILLIS));
LOG.debug("dag completed switching to DAGClientTimelineImpl");
}
@VisibleForTesting
public DAGClientInternal getRealClient() {
return realClient;
}
@Override
public String getWebUIAddress() throws IOException, TezException {
return realClient.getWebUIAddress();
}
private double getProgress(Progress progress) {
return (progress.getTotalTaskCount() == 0 ? 0.0 : (double) (progress.getSucceededTaskCount())
/ progress.getTotalTaskCount());
}
private void log(String message) {
LOG.info(message);
}
}
| {
"content_hash": "08f77df06efb614e913fc8f7a82cb020",
"timestamp": "",
"source": "github",
"line_count": 674,
"max_line_length": 156,
"avg_line_length": 38.311572700296736,
"alnum_prop": 0.6774843156997908,
"repo_name": "apache/tez",
"id": "95dd85f3888905ec336320ed476dff7b2c441b8d",
"size": "26628",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "tez-api/src/main/java/org/apache/tez/dag/api/client/DAGClientImpl.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "8183"
},
{
"name": "HTML",
"bytes": "3369"
},
{
"name": "Handlebars",
"bytes": "121430"
},
{
"name": "Java",
"bytes": "10755550"
},
{
"name": "JavaScript",
"bytes": "926614"
},
{
"name": "Less",
"bytes": "63464"
},
{
"name": "Python",
"bytes": "28200"
},
{
"name": "Roff",
"bytes": "8256"
},
{
"name": "Shell",
"bytes": "36346"
}
],
"symlink_target": ""
} |
package com.texttalk.distrib.storm;
import backtype.storm.task.OutputCollector;
import backtype.storm.task.TopologyContext;
import backtype.storm.topology.OutputFieldsDeclarer;
import backtype.storm.topology.base.BaseRichBolt;
import backtype.storm.tuple.Fields;
import backtype.storm.tuple.Tuple;
import backtype.storm.tuple.Values;
import com.texttalk.common.Utils;
import com.texttalk.common.command.CommandExecutor;
import com.texttalk.common.model.Message;
import com.texttalk.core.transcriber.PSOLATranscriber;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.Map;
/**
* Created by Andrew on 16/06/2014.
*/
public class TextTranscriptionBolt extends BaseRichBolt {
private static Logger logger = LoggerFactory.getLogger(TextTranscriptionBolt.class);
private OutputCollector collector;
private String transcriberPath = "";
private Integer timeout = 0;
public void prepare(Map config, TopologyContext context, OutputCollector collector) {
this.collector = collector;
transcriberPath = (String)config.get("transcribers.psola.execPath");
timeout = ((Long)config.get("transcribers.psola.timeout")).intValue();
}
public void execute(Tuple tuple) {
Message msg = Message.getMessage(tuple.getStringByField("textChunk"));
String textChunk = msg.getText();
String inputText = Utils.convertFromUTF8(textChunk, "Windows-1257");
String transcribedText = "";
logger.info("Running Transcription bolt...");
try {
ByteArrayInputStream in = new ByteArrayInputStream(inputText.getBytes("Windows-1257"));
ByteArrayOutputStream out = new ByteArrayOutputStream();
ByteArrayOutputStream error = new ByteArrayOutputStream();
new PSOLATranscriber()
.setSpeed(Integer.parseInt(msg.getSpeed()))
.setTone(Integer.parseInt(msg.getTone()))
.setCmd(new CommandExecutor().setTimeoutSecs(timeout).setErrorStream(error))
.setPSOLATranscribeCmd(transcriberPath)
.setInputStream(in)
.setOutputStream(out)
.process();
transcribedText = out.toString("UTF-8");
} catch(Exception e) {
// TODO: deal with exception
e.printStackTrace();
}
msg.setTranscript(transcribedText);
this.collector.emit(msg.getSynth(), new Values(Message.getJSON(msg)));
}
public void declareOutputFields(OutputFieldsDeclarer declarer) {
declarer.declareStream("psola", new Fields("transcribedText"));
}
}
| {
"content_hash": "28e36fd7d11509af50aef3d71300df6a",
"timestamp": "",
"source": "github",
"line_count": 79,
"max_line_length": 99,
"avg_line_length": 34.70886075949367,
"alnum_prop": 0.6907366885485048,
"repo_name": "andrewboss/texttalk-backend",
"id": "b89a65424eaa6d6d397661757fcaccf93fdae02d",
"size": "2742",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/texttalk/distrib/storm/TextTranscriptionBolt.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ApacheConf",
"bytes": "22808"
},
{
"name": "HTML",
"bytes": "19384"
},
{
"name": "Java",
"bytes": "93470"
},
{
"name": "Pascal",
"bytes": "1164"
},
{
"name": "Perl",
"bytes": "7252"
},
{
"name": "Puppet",
"bytes": "39026"
},
{
"name": "Ruby",
"bytes": "214200"
},
{
"name": "Shell",
"bytes": "10711"
}
],
"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_32) on Tue Jun 18 11:08:54 PDT 2013 -->
<TITLE>
DescribeWorkflowTypeRequest (AWS SDK for Java - 1.4.7)
</TITLE>
<META NAME="date" CONTENT="2013-06-18">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../JavaDoc.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="DescribeWorkflowTypeRequest (AWS SDK for Java - 1.4.7)";
}
}
</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="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </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>
<span id="feedback_section"><h3>Did this page help you?</h3> <a id="feedback_yes" target="_blank">Yes</a> <a id="feedback_no" target="_blank">No</a> <a id="go_cti" target="_blank">Tell us about it...</a></span>
<script type="text/javascript">
var javadoc_root_name = "/javadoc/";
var javadoc_path = location.href.substring(0, location.href.lastIndexOf(javadoc_root_name) + javadoc_root_name.length);
var file_path = location.href.substring(location.href.lastIndexOf(javadoc_root_name) + javadoc_root_name.length);
var feedback_yes_url = javadoc_path + "javadoc-resources/feedbackyes.html?topic_id=";
var feedback_no_url = javadoc_path + "javadoc-resources/feedbackno.html?topic_id=";
var feedback_tellmore_url = "https://aws-portal.amazon.com/gp/aws/html-forms-controller/documentation/aws_doc_feedback_04?service_name=Java-Ref&file_name=";
if(file_path != "overview-frame.html") {
var file_name = file_path.replace(/[/.]/g, '_');
document.getElementById("feedback_yes").setAttribute("href", feedback_yes_url + file_name);
document.getElementById("feedback_no").setAttribute("href", feedback_no_url + file_name);
document.getElementById("go_cti").setAttribute("href", feedback_tellmore_url + file_name);
} else {
// hide the header in overview-frame page
document.getElementById("feedback_section").innerHTML = "";
}
</script>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../com/amazonaws/services/simpleworkflow/model/DescribeWorkflowExecutionRequest.html" title="class in com.amazonaws.services.simpleworkflow.model"><B>PREV CLASS</B></A>
<A HREF="../../../../../com/amazonaws/services/simpleworkflow/model/DomainAlreadyExistsException.html" title="class in com.amazonaws.services.simpleworkflow.model"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?com/amazonaws/services/simpleworkflow/model/DescribeWorkflowTypeRequest.html" target="_top"><B>FRAMES</B></A>
<A HREF="DescribeWorkflowTypeRequest.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | FIELD | <A HREF="#constructor_summary">CONSTR</A> | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: FIELD | <A HREF="#constructor_detail">CONSTR</A> | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<!-- ======== START OF CLASS DATA ======== -->
<H2>
<FONT SIZE="-1">
com.amazonaws.services.simpleworkflow.model</FONT>
<BR>
Class DescribeWorkflowTypeRequest</H2>
<PRE>
<A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">java.lang.Object</A>
<IMG SRC="../../../../../resources/inherit.gif" ALT="extended by "><A HREF="../../../../../com/amazonaws/AmazonWebServiceRequest.html" title="class in com.amazonaws">com.amazonaws.AmazonWebServiceRequest</A>
<IMG SRC="../../../../../resources/inherit.gif" ALT="extended by "><B>com.amazonaws.services.simpleworkflow.model.DescribeWorkflowTypeRequest</B>
</PRE>
<DL>
<DT><B>All Implemented Interfaces:</B> <DD><A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/io/Serializable.html?is-external=true" title="class or interface in java.io">Serializable</A></DD>
</DL>
<HR>
<DL>
<DT><PRE>public class <B>DescribeWorkflowTypeRequest</B><DT>extends <A HREF="../../../../../com/amazonaws/AmazonWebServiceRequest.html" title="class in com.amazonaws">AmazonWebServiceRequest</A><DT>implements <A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/io/Serializable.html?is-external=true" title="class or interface in java.io">Serializable</A></DL>
</PRE>
<P>
Container for the parameters to the <A HREF="../../../../../com/amazonaws/services/simpleworkflow/AmazonSimpleWorkflow.html#describeWorkflowType(com.amazonaws.services.simpleworkflow.model.DescribeWorkflowTypeRequest)"><CODE>DescribeWorkflowType operation</CODE></A>.
<p>
Returns information about the specified <i>workflow type</i> . This includes configuration settings specified when the type was registered and other
information such as creation date, current status, etc.
</p>
<p>
<b>Access Control</b>
</p>
<p>
You can use IAM policies to control this action's access to Amazon SWF resources as follows:
</p>
<ul>
<li>Use a <code>Resource</code> element with the domain name to limit the action to only specified domains.</li>
<li>Use an <code>Action</code> element to allow or deny permission to call this action.</li>
<li>Constrain the following parameters by using a <code>Condition</code> element with the appropriate keys.
<ul>
<li> <code>workflowType.name</code> : String constraint. The key is <code>swf:workflowType.name</code> .</li>
<li> <code>workflowType.version</code> : String constraint. The key is <code>swf:workflowType.version</code> .</li>
</ul>
</li>
</ul>
<p>
If the caller does not have sufficient permissions to invoke the action, or the parameter values fall outside the specified constraints, the action
fails by throwing <code>OperationNotPermitted</code> . For details and example IAM policies, see <a
href="http://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dev-iam.html"> Using IAM to Manage Access to Amazon SWF Workflows </a> .
</p>
<P>
<P>
<DL>
<DT><B>See Also:</B><DD><A HREF="../../../../../com/amazonaws/services/simpleworkflow/AmazonSimpleWorkflow.html#describeWorkflowType(com.amazonaws.services.simpleworkflow.model.DescribeWorkflowTypeRequest)"><CODE>AmazonSimpleWorkflow.describeWorkflowType(DescribeWorkflowTypeRequest)</CODE></A>,
<A HREF="../../../../../serialized-form.html#com.amazonaws.services.simpleworkflow.model.DescribeWorkflowTypeRequest">Serialized Form</A></DL>
<HR>
<P>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<A NAME="constructor_summary"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Constructor Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../../../com/amazonaws/services/simpleworkflow/model/DescribeWorkflowTypeRequest.html#DescribeWorkflowTypeRequest()">DescribeWorkflowTypeRequest</A></B>()</CODE>
<BR>
</TD>
</TR>
</TABLE>
<!-- ========== METHOD SUMMARY =========== -->
<A NAME="method_summary"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Method Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> boolean</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../com/amazonaws/services/simpleworkflow/model/DescribeWorkflowTypeRequest.html#equals(java.lang.Object)">equals</A></B>(<A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</A> obj)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</A></CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../com/amazonaws/services/simpleworkflow/model/DescribeWorkflowTypeRequest.html#getDomain()">getDomain</A></B>()</CODE>
<BR>
The name of the domain in which this workflow type is registered.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../../com/amazonaws/services/simpleworkflow/model/WorkflowType.html" title="class in com.amazonaws.services.simpleworkflow.model">WorkflowType</A></CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../com/amazonaws/services/simpleworkflow/model/DescribeWorkflowTypeRequest.html#getWorkflowType()">getWorkflowType</A></B>()</CODE>
<BR>
The workflow type to describe.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> int</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../com/amazonaws/services/simpleworkflow/model/DescribeWorkflowTypeRequest.html#hashCode()">hashCode</A></B>()</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../com/amazonaws/services/simpleworkflow/model/DescribeWorkflowTypeRequest.html#setDomain(java.lang.String)">setDomain</A></B>(<A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</A> domain)</CODE>
<BR>
The name of the domain in which this workflow type is registered.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../com/amazonaws/services/simpleworkflow/model/DescribeWorkflowTypeRequest.html#setWorkflowType(com.amazonaws.services.simpleworkflow.model.WorkflowType)">setWorkflowType</A></B>(<A HREF="../../../../../com/amazonaws/services/simpleworkflow/model/WorkflowType.html" title="class in com.amazonaws.services.simpleworkflow.model">WorkflowType</A> workflowType)</CODE>
<BR>
The workflow type to describe.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</A></CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../com/amazonaws/services/simpleworkflow/model/DescribeWorkflowTypeRequest.html#toString()">toString</A></B>()</CODE>
<BR>
Returns a string representation of this object; useful for testing and
debugging.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../../com/amazonaws/services/simpleworkflow/model/DescribeWorkflowTypeRequest.html" title="class in com.amazonaws.services.simpleworkflow.model">DescribeWorkflowTypeRequest</A></CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../com/amazonaws/services/simpleworkflow/model/DescribeWorkflowTypeRequest.html#withDomain(java.lang.String)">withDomain</A></B>(<A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</A> domain)</CODE>
<BR>
The name of the domain in which this workflow type is registered.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../../com/amazonaws/services/simpleworkflow/model/DescribeWorkflowTypeRequest.html" title="class in com.amazonaws.services.simpleworkflow.model">DescribeWorkflowTypeRequest</A></CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../com/amazonaws/services/simpleworkflow/model/DescribeWorkflowTypeRequest.html#withWorkflowType(com.amazonaws.services.simpleworkflow.model.WorkflowType)">withWorkflowType</A></B>(<A HREF="../../../../../com/amazonaws/services/simpleworkflow/model/WorkflowType.html" title="class in com.amazonaws.services.simpleworkflow.model">WorkflowType</A> workflowType)</CODE>
<BR>
The workflow type to describe.</TD>
</TR>
</TABLE>
<A NAME="methods_inherited_from_class_com.amazonaws.AmazonWebServiceRequest"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left"><B>Methods inherited from class com.amazonaws.<A HREF="../../../../../com/amazonaws/AmazonWebServiceRequest.html" title="class in com.amazonaws">AmazonWebServiceRequest</A></B></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><A HREF="../../../../../com/amazonaws/AmazonWebServiceRequest.html#copyPrivateRequestParameters()">copyPrivateRequestParameters</A>, <A HREF="../../../../../com/amazonaws/AmazonWebServiceRequest.html#getRequestClientOptions()">getRequestClientOptions</A>, <A HREF="../../../../../com/amazonaws/AmazonWebServiceRequest.html#getRequestCredentials()">getRequestCredentials</A>, <A HREF="../../../../../com/amazonaws/AmazonWebServiceRequest.html#setRequestCredentials(com.amazonaws.auth.AWSCredentials)">setRequestCredentials</A></CODE></TD>
</TR>
</TABLE>
<A NAME="methods_inherited_from_class_java.lang.Object"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left"><B>Methods inherited from class java.lang.<A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</A></B></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html?is-external=true#getClass()" title="class or interface in java.lang">getClass</A>, <A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html?is-external=true#notify()" title="class or interface in java.lang">notify</A>, <A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html?is-external=true#notifyAll()" title="class or interface in java.lang">notifyAll</A>, <A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html?is-external=true#wait()" title="class or interface in java.lang">wait</A>, <A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html?is-external=true#wait(long)" title="class or interface in java.lang">wait</A>, <A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html?is-external=true#wait(long, int)" title="class or interface in java.lang">wait</A></CODE></TD>
</TR>
</TABLE>
<P>
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<A NAME="constructor_detail"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Constructor Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="DescribeWorkflowTypeRequest()"><!-- --></A><H3>
DescribeWorkflowTypeRequest</H3>
<PRE>
public <B>DescribeWorkflowTypeRequest</B>()</PRE>
<DL>
</DL>
<!-- ============ METHOD DETAIL ========== -->
<A NAME="method_detail"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Method Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="getDomain()"><!-- --></A><H3>
getDomain</H3>
<PRE>
public <A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</A> <B>getDomain</B>()</PRE>
<DL>
<DD>The name of the domain in which this workflow type is registered.
<p>
<b>Constraints:</b><br/>
<b>Length: </b>1 - 256<br/>
<P>
<DD><DL>
</DL>
</DD>
<DD><DL>
<DT><B>Returns:</B><DD>The name of the domain in which this workflow type is registered.</DL>
</DD>
</DL>
<HR>
<A NAME="setDomain(java.lang.String)"><!-- --></A><H3>
setDomain</H3>
<PRE>
public void <B>setDomain</B>(<A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</A> domain)</PRE>
<DL>
<DD>The name of the domain in which this workflow type is registered.
<p>
<b>Constraints:</b><br/>
<b>Length: </b>1 - 256<br/>
<P>
<DD><DL>
</DL>
</DD>
<DD><DL>
<DT><B>Parameters:</B><DD><CODE>domain</CODE> - The name of the domain in which this workflow type is registered.</DL>
</DD>
</DL>
<HR>
<A NAME="withDomain(java.lang.String)"><!-- --></A><H3>
withDomain</H3>
<PRE>
public <A HREF="../../../../../com/amazonaws/services/simpleworkflow/model/DescribeWorkflowTypeRequest.html" title="class in com.amazonaws.services.simpleworkflow.model">DescribeWorkflowTypeRequest</A> <B>withDomain</B>(<A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</A> domain)</PRE>
<DL>
<DD>The name of the domain in which this workflow type is registered.
<p>
Returns a reference to this object so that method calls can be chained together.
<p>
<b>Constraints:</b><br/>
<b>Length: </b>1 - 256<br/>
<P>
<DD><DL>
</DL>
</DD>
<DD><DL>
<DT><B>Parameters:</B><DD><CODE>domain</CODE> - The name of the domain in which this workflow type is registered.
<DT><B>Returns:</B><DD>A reference to this updated object so that method calls can be chained
together.</DL>
</DD>
</DL>
<HR>
<A NAME="getWorkflowType()"><!-- --></A><H3>
getWorkflowType</H3>
<PRE>
public <A HREF="../../../../../com/amazonaws/services/simpleworkflow/model/WorkflowType.html" title="class in com.amazonaws.services.simpleworkflow.model">WorkflowType</A> <B>getWorkflowType</B>()</PRE>
<DL>
<DD>The workflow type to describe.
<P>
<DD><DL>
</DL>
</DD>
<DD><DL>
<DT><B>Returns:</B><DD>The workflow type to describe.</DL>
</DD>
</DL>
<HR>
<A NAME="setWorkflowType(com.amazonaws.services.simpleworkflow.model.WorkflowType)"><!-- --></A><H3>
setWorkflowType</H3>
<PRE>
public void <B>setWorkflowType</B>(<A HREF="../../../../../com/amazonaws/services/simpleworkflow/model/WorkflowType.html" title="class in com.amazonaws.services.simpleworkflow.model">WorkflowType</A> workflowType)</PRE>
<DL>
<DD>The workflow type to describe.
<P>
<DD><DL>
</DL>
</DD>
<DD><DL>
<DT><B>Parameters:</B><DD><CODE>workflowType</CODE> - The workflow type to describe.</DL>
</DD>
</DL>
<HR>
<A NAME="withWorkflowType(com.amazonaws.services.simpleworkflow.model.WorkflowType)"><!-- --></A><H3>
withWorkflowType</H3>
<PRE>
public <A HREF="../../../../../com/amazonaws/services/simpleworkflow/model/DescribeWorkflowTypeRequest.html" title="class in com.amazonaws.services.simpleworkflow.model">DescribeWorkflowTypeRequest</A> <B>withWorkflowType</B>(<A HREF="../../../../../com/amazonaws/services/simpleworkflow/model/WorkflowType.html" title="class in com.amazonaws.services.simpleworkflow.model">WorkflowType</A> workflowType)</PRE>
<DL>
<DD>The workflow type to describe.
<p>
Returns a reference to this object so that method calls can be chained together.
<P>
<DD><DL>
</DL>
</DD>
<DD><DL>
<DT><B>Parameters:</B><DD><CODE>workflowType</CODE> - The workflow type to describe.
<DT><B>Returns:</B><DD>A reference to this updated object so that method calls can be chained
together.</DL>
</DD>
</DL>
<HR>
<A NAME="toString()"><!-- --></A><H3>
toString</H3>
<PRE>
public <A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</A> <B>toString</B>()</PRE>
<DL>
<DD>Returns a string representation of this object; useful for testing and
debugging.
<P>
<DD><DL>
<DT><B>Overrides:</B><DD><CODE><A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html?is-external=true#toString()" title="class or interface in java.lang">toString</A></CODE> in class <CODE><A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</A></CODE></DL>
</DD>
<DD><DL>
<DT><B>Returns:</B><DD>A string representation of this object.<DT><B>See Also:</B><DD><A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html?is-external=true#toString()" title="class or interface in java.lang"><CODE>Object.toString()</CODE></A></DL>
</DD>
</DL>
<HR>
<A NAME="hashCode()"><!-- --></A><H3>
hashCode</H3>
<PRE>
public int <B>hashCode</B>()</PRE>
<DL>
<DD><DL>
<DT><B>Overrides:</B><DD><CODE><A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html?is-external=true#hashCode()" title="class or interface in java.lang">hashCode</A></CODE> in class <CODE><A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</A></CODE></DL>
</DD>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="equals(java.lang.Object)"><!-- --></A><H3>
equals</H3>
<PRE>
public boolean <B>equals</B>(<A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</A> obj)</PRE>
<DL>
<DD><DL>
<DT><B>Overrides:</B><DD><CODE><A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html?is-external=true#equals(java.lang.Object)" title="class or interface in java.lang">equals</A></CODE> in class <CODE><A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</A></CODE></DL>
</DD>
<DD><DL>
</DL>
</DD>
</DL>
<!-- ========= END OF CLASS DATA ========= -->
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../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>
<script src="http://aws.amazon.com/js/urchin.js" type="text/javascript"></script>
<script type="text/javascript">urchinTracker();</script>
<!-- SiteCatalyst code version: H.25.2. Copyright 1996-2012 Adobe, Inc. All Rights Reserved.
More info available at http://www.omniture.com -->
<script language="JavaScript" type="text/javascript" src="https://d36cz9buwru1tt.cloudfront.net/js/sitecatalyst/s_code.min.js (view-source:https://d36cz9buwru1tt.cloudfront.net/js/sitecatalyst/s_code.min.js)" />
<script language="JavaScript" type="text/javascript">
<!--
// Documentation Service Name
s.prop66='AWS SDK for Java';
s.eVar66='D=c66';
// Documentation Guide Name
s.prop65='API Reference';
s.eVar65='D=c65';
var s_code=s.t();if(s_code)document.write(s_code)
//-->
</script>
<script language="JavaScript" type="text/javascript">
<!--if(navigator.appVersion.indexOf('MSIE')>=0)document.write(unescape('%3C')+'\!-'+'-')
//-->
</script>
<noscript>
<img src="http://amazonwebservices.d2.sc.omtrdc.net/b/ss/awsamazondev/1/H.25.2--NS/0" height="1" width="1" border="0" alt="" />
</noscript>
<!--/DO NOT REMOVE/-->
<!-- End SiteCatalyst code version: H.25.2. -->
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../com/amazonaws/services/simpleworkflow/model/DescribeWorkflowExecutionRequest.html" title="class in com.amazonaws.services.simpleworkflow.model"><B>PREV CLASS</B></A>
<A HREF="../../../../../com/amazonaws/services/simpleworkflow/model/DomainAlreadyExistsException.html" title="class in com.amazonaws.services.simpleworkflow.model"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?com/amazonaws/services/simpleworkflow/model/DescribeWorkflowTypeRequest.html" target="_top"><B>FRAMES</B></A>
<A HREF="DescribeWorkflowTypeRequest.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | FIELD | <A HREF="#constructor_summary">CONSTR</A> | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: FIELD | <A HREF="#constructor_detail">CONSTR</A> | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
Copyright © 2010 Amazon Web Services, Inc. All Rights Reserved.
</BODY>
</HTML>
| {
"content_hash": "86204ef2dbf099f366ff975039407469",
"timestamp": "",
"source": "github",
"line_count": 563,
"max_line_length": 931,
"avg_line_length": 51.53285968028419,
"alnum_prop": 0.6643573570468411,
"repo_name": "hobinyoon/aws-java-sdk-1.4.7",
"id": "1014f2998f6a4d4441ecad1699a628880374f5f6",
"size": "29013",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "documentation/javadoc/com/amazonaws/services/simpleworkflow/model/DescribeWorkflowTypeRequest.html",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
@interface EXGLGPUImageObject () <GPUImageTextureOutputDelegate>
@property (nonatomic, strong) GPUImageOutput *gpuImageOutput;
@property (nonatomic, strong) GPUImageTextureOutput *gpuImageTextureOutput;
@end
@implementation EXGLGPUImageObject
- (instancetype)initWithConfig:(NSDictionary *)config
{
if ((self = [super initWithConfig:config])) {
_gpuImageOutput = nil;
_gpuImageTextureOutput = nil;
// Construct the right kind of `GPUImageOutput` for `config`
if (config[@"texture"][@"camera"]) {
NSString *sessionPreset = AVCaptureSessionPreset640x480; // TODO: Read this from `config`
AVCaptureDevicePosition position = ([config[@"texture"][@"camera"][@"position"] isEqualToString:@"front"] ?
AVCaptureDevicePositionFront : AVCaptureDevicePositionBack);
GPUImageVideoCamera *gpuImageVideoCamera = [[GPUImageVideoCamera alloc]
initWithSessionPreset:sessionPreset cameraPosition:position];
gpuImageVideoCamera.outputImageOrientation = UIInterfaceOrientationPortrait; // You can rotate it in GL yourself ¯\_(ツ)_/¯
[gpuImageVideoCamera startCameraCapture]; // TODO: Don't start yet, allow updating config with `playing` as property
_gpuImageOutput = gpuImageVideoCamera;
}
if (_gpuImageOutput) {
_gpuImageTextureOutput = [[GPUImageTextureOutput alloc] init];
[_gpuImageOutput addTarget:_gpuImageTextureOutput];
_gpuImageTextureOutput.delegate = self;
} else {
return nil;
}
}
return self;
}
- (void)newFrameReadyFromTextureOutput:(GPUImageTextureOutput *)callbackTextureOutput
{
// Remember that `UEXGLContextMapObject(...)` needs to run on the GL thread
dispatch_async(dispatch_get_main_queue(), ^{
UEXGLContextMapObject(self.exglCtxId, self.exglObjId, callbackTextureOutput.texture);
// Some times a refCount > 0 assertion fails so just guard this
@try {
[callbackTextureOutput doneWithTexture];
} @catch (NSException *exception) {
// ¯\_(ツ)_/¯
}
});
}
@end
| {
"content_hash": "796cf0462d77d05aebdcc5dc9bf9f36f",
"timestamp": "",
"source": "github",
"line_count": 53,
"max_line_length": 128,
"avg_line_length": 39.490566037735846,
"alnum_prop": 0.6975633062589585,
"repo_name": "NewSpring/Apollos",
"id": "29d3fbfd7c6995e45d7754bfeed0f70039438d8a",
"size": "2155",
"binary": false,
"copies": "1",
"ref": "refs/heads/alpha",
"path": "ios/Pods/ExpoKit/ios/Exponent/Versioned/Core/Api/GL/EXGLGPUImageObject.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "130"
},
{
"name": "CSS",
"bytes": "4867"
},
{
"name": "HTML",
"bytes": "3112"
},
{
"name": "Java",
"bytes": "4564"
},
{
"name": "JavaScript",
"bytes": "1018775"
},
{
"name": "Objective-C",
"bytes": "2381"
},
{
"name": "Python",
"bytes": "3416"
},
{
"name": "Ruby",
"bytes": "2498"
},
{
"name": "Shell",
"bytes": "1801"
}
],
"symlink_target": ""
} |
[kakao](../../index.md) / [com.agoda.kakao.common.matchers](../index.md) / [SpinnerPopupMatcher](index.md) / [describeTo](./describe-to.md)
# describeTo
`fun describeTo(description: Description?): `[`Unit`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-unit/index.html) | {
"content_hash": "b48970a0b83b8d5d27fee39744a6540e",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 139,
"avg_line_length": 55.6,
"alnum_prop": 0.7122302158273381,
"repo_name": "agoda-com/Kakao",
"id": "77d5680bba4cfaedb7da8670aa003c968e232eca",
"size": "278",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/kakao/com.agoda.kakao.common.matchers/-spinner-popup-matcher/describe-to.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Kotlin",
"bytes": "228879"
}
],
"symlink_target": ""
} |
#ifndef _CRAM_STRUCTS_H_
#define _CRAM_STRUCTS_H_
/*
* Defines in-memory structs for the basic file-format objects in the
* CRAM format.
*
* The basic file format is:
* File-def SAM-hdr Container Container ...
*
* Container:
* Service-block data-block data-block ...
*
* Multiple blocks in a container are grouped together as slices,
* also sometimes referred to as landmarks in the spec.
*/
#include <stdint.h>
#include "cram/thread_pool.h"
#include "cram/string_alloc.h"
#include "cram/mFILE.h"
#include "htslib/khash.h"
#ifdef __cplusplus
extern "C" {
#endif
// Generic hash-map integer -> integer
KHASH_MAP_INIT_INT(m_i2i, int)
// Generic hash-set integer -> (existance)
KHASH_SET_INIT_INT(s_i2i)
// For brevity
typedef unsigned char uc;
/*
* A union for the preservation map. Required for khash.
*/
typedef union {
int i;
char *p;
} pmap_t;
// Generates static functions here which isn't ideal, but we have no way
// currently to declare the kh_map_t structure here without also declaring a
// duplicate in the .c files due to the nature of the KHASH macros.
KHASH_MAP_INIT_STR(map, pmap_t)
struct hFILE;
#define SEQS_PER_SLICE 10000
#define SLICE_PER_CNT 1
#define CRAM_SUBST_MATRIX "CGTNAGTNACTNACGNACGT"
#define MAX_STAT_VAL 1024
//#define MAX_STAT_VAL 16
typedef struct cram_stats {
int freqs[MAX_STAT_VAL];
khash_t(m_i2i) *h;
int nsamp; // total number of values added
int nvals; // total number of unique values added
} cram_stats;
/* NB: matches java impl, not the spec */
enum cram_encoding {
E_NULL = 0,
E_EXTERNAL = 1,
E_GOLOMB = 2,
E_HUFFMAN = 3,
E_BYTE_ARRAY_LEN = 4,
E_BYTE_ARRAY_STOP = 5,
E_BETA = 6,
E_SUBEXP = 7,
E_GOLOMB_RICE = 8,
E_GAMMA = 9,
E_NUM_CODECS = 10, /* Number of codecs, not a real one. */
};
enum cram_external_type {
E_INT = 1,
E_LONG = 2,
E_BYTE = 3,
E_BYTE_ARRAY = 4,
E_BYTE_ARRAY_BLOCK = 5,
};
/* External IDs used by this implementation (only assumed during writing) */
enum cram_DS_ID {
DS_CORE = 0,
DS_aux = 1, // aux_blk
DS_aux_OQ = 2,
DS_aux_BQ = 3,
DS_aux_BD = 4,
DS_aux_BI = 5,
DS_aux_FZ = 6, // also ZM:B
DS_aux_oq = 7, // other qualities
DS_aux_os = 8, // other sequences
DS_aux_oz = 9, // other strings
DS_ref,
DS_RN, // name_blk
DS_QS, // qual_blk
DS_IN, // base_blk
DS_SC, // soft_blk
DS_BF, // start loop
DS_CF,
DS_AP,
DS_RG,
DS_MQ,
DS_NS,
DS_MF,
DS_TS,
DS_NP,
DS_NF,
DS_RL,
DS_FN,
DS_FC,
DS_FP,
DS_DL,
DS_BA,
DS_BS,
DS_TL,
DS_RI,
DS_RS,
DS_PD,
DS_HC,
DS_BB,
DS_QQ,
DS_TN, // end loop
DS_RN_len,
DS_SC_len,
DS_BB_len,
DS_QQ_len,
DS_TC, // CRAM v1.0 tags
DS_TM, // test
DS_TV, // test
DS_END,
};
/* "File Definition Structure" */
typedef struct cram_file_def {
char magic[4];
uint8_t major_version;
uint8_t minor_version;
char file_id[20]; // Filename or SHA1 checksum
} cram_file_def;
#define CRAM_MAJOR_VERS(v) ((v) >> 8)
#define CRAM_MINOR_VERS(v) ((v) & 0xff)
struct cram_slice;
enum cram_block_method {
ERROR = -1,
RAW = 0,
GZIP = 1,
BZIP2 = 2,
LZMA = 3,
RANS = 4, // Generic; either order
RANS0 = 4,
RANS1 = 10, // Not externalised; stored as RANS (generic)
GZIP_RLE = 11, // NB: not externalised in CRAM
};
enum cram_content_type {
CT_ERROR = -1,
FILE_HEADER = 0,
COMPRESSION_HEADER = 1,
MAPPED_SLICE = 2,
UNMAPPED_SLICE = 3, // CRAM V1.0 only
EXTERNAL = 4,
CORE = 5,
};
/* Compression metrics */
typedef struct {
// number of trials and time to next trial
int trial;
int next_trial;
// aggregate sizes during trials
int sz_gz_rle;
int sz_gz_def;
int sz_rans0;
int sz_rans1;
int sz_bzip2;
int sz_lzma;
// resultant method from trials
int method;
int strat;
// Revisions of method, to allow culling of continually failing ones.
int gz_rle_cnt;
int gz_def_cnt;
int rans0_cnt;
int rans1_cnt;
int bzip2_cnt;
int lzma_cnt;
int revised_method;
double gz_rle_extra;
double gz_def_extra;
double rans0_extra;
double rans1_extra;
double bzip2_extra;
double lzma_extra;
} cram_metrics;
/* Block */
typedef struct cram_block {
enum cram_block_method method, orig_method;
enum cram_content_type content_type;
int32_t content_id;
int32_t comp_size;
int32_t uncomp_size;
uint32_t crc32;
int32_t idx; /* offset into data */
unsigned char *data;
// For bit I/O
size_t alloc;
size_t byte;
int bit;
} cram_block;
struct cram_codec; /* defined in cram_codecs.h */
struct cram_map;
#define CRAM_MAP_HASH 32
#define CRAM_MAP(a,b) (((a)*3+(b))&(CRAM_MAP_HASH-1))
/* Compression header block */
typedef struct cram_block_compression_hdr {
int32_t ref_seq_id;
int32_t ref_seq_start;
int32_t ref_seq_span;
int32_t num_records;
int32_t num_landmarks;
int32_t *landmark;
/* Flags from preservation map */
int mapped_qs_included;
int unmapped_qs_included;
int unmapped_placed;
int qs_included;
int read_names_included;
int AP_delta;
// indexed by ref-base and subst. code
char substitution_matrix[5][4];
// TD Dictionary as a concatenated block
cram_block *TD_blk; // Tag Dictionary
int nTL; // number of TL entries in TD
unsigned char **TL; // array of size nTL, pointer into TD_blk.
khash_t(m_s2i) *TD_hash; // Keyed on TD strings, map to TL[] indices
string_alloc_t *TD_keys; // Pooled keys for TD hash.
khash_t(map) *preservation_map;
struct cram_map *rec_encoding_map[CRAM_MAP_HASH];
struct cram_map *tag_encoding_map[CRAM_MAP_HASH];
struct cram_codec *codecs[DS_END];
char *uncomp; // A single block of uncompressed data
size_t uncomp_size, uncomp_alloc;
unsigned int data_series; // See cram_fields enum below
} cram_block_compression_hdr;
typedef struct cram_map {
int key; /* 0xe0 + 3 bytes */
enum cram_encoding encoding;
int offset; /* Offset into a single block of memory */
int size; /* Size */
struct cram_codec *codec;
struct cram_map *next; // for noddy internal hash
} cram_map;
/* Mapped or unmapped slice header block */
typedef struct cram_block_slice_hdr {
enum cram_content_type content_type;
int32_t ref_seq_id; /* if content_type == MAPPED_SLICE */
int32_t ref_seq_start; /* if content_type == MAPPED_SLICE */
int32_t ref_seq_span; /* if content_type == MAPPED_SLICE */
int32_t num_records;
int64_t record_counter;
int32_t num_blocks;
int32_t num_content_ids;
int32_t *block_content_ids;
int32_t ref_base_id; /* if content_type == MAPPED_SLICE */
unsigned char md5[16];
} cram_block_slice_hdr;
struct ref_entry;
/*
* Container.
*
* Conceptually a container is split into slices, and slices into blocks.
* However on disk it's just a list of blocks and we need to query the
* block types to identify the start/end points of the slices.
*
* OR... are landmarks the start/end points of slices?
*/
typedef struct cram_container {
int32_t length;
int32_t ref_seq_id;
int32_t ref_seq_start;
int32_t ref_seq_span;
int64_t record_counter;
int64_t num_bases;
int32_t num_records;
int32_t num_blocks;
int32_t num_landmarks;
int32_t *landmark;
/* Size of container header above */
size_t offset;
/* Compression header is always the first block? */
cram_block_compression_hdr *comp_hdr;
cram_block *comp_hdr_block;
/* For construction purposes */
int max_slice, curr_slice; // maximum number of slices
int max_rec, curr_rec; // current and max recs per slice
int max_c_rec, curr_c_rec; // current and max recs per container
int slice_rec; // rec no. for start of this slice
int curr_ref; // current ref ID. -2 for no previous
int last_pos; // last record position
struct cram_slice **slices, *slice;
int pos_sorted; // boolean, 1=>position sorted data
int max_apos; // maximum position, used if pos_sorted==0
int last_slice; // number of reads in last slice (0 for 1st)
int multi_seq; // true if packing multi seqs per cont/slice
int unsorted; // true is AP_delta is 0.
/* Copied from fd before encoding, to allow multi-threading */
int ref_start, first_base, last_base, ref_id, ref_end;
char *ref;
//struct ref_entry *ref;
/* For multi-threading */
bam_seq_t **bams;
/* Statistics for encoding */
cram_stats *stats[DS_END];
khash_t(s_i2i) *tags_used; // set of tag types in use, for tag encoding map
int *refs_used; // array of frequency of ref seq IDs
uint32_t crc32; // CRC32
} cram_container;
/*
* A single cram record
*/
typedef struct cram_record {
struct cram_slice *s; // Filled out by cram_decode only
int32_t ref_id; // fixed for all recs in slice?
int32_t flags; // BF
int32_t cram_flags; // CF
int32_t len; // RL
int32_t apos; // AP
int32_t rg; // RG
int32_t name; // RN; idx to s->names_blk
int32_t name_len;
int32_t mate_line; // index to another cram_record
int32_t mate_ref_id;
int32_t mate_pos; // NP
int32_t tlen; // TS
// Auxiliary data
int32_t ntags; // TC
int32_t aux; // idx to s->aux_blk
int32_t aux_size; // total size of packed ntags in aux_blk
#ifndef TN_external
int32_t TN_idx; // TN; idx to s->TN;
#else
int32_t tn; // idx to s->tn_blk
#endif
int TL;
int32_t seq; // idx to s->seqs_blk
int32_t qual; // idx to s->qual_blk
int32_t cigar; // idx to s->cigar
int32_t ncigar;
int32_t aend; // alignment end
int32_t mqual; // MQ
int32_t feature; // idx to s->feature
int32_t nfeature; // number of features
int32_t mate_flags; // MF
} cram_record;
// Accessor macros as an analogue of the bam ones
#define cram_qname(c) (&(c)->s->name_blk->data[(c)->name])
#define cram_seq(c) (&(c)->s->seqs_blk->data[(c)->seq])
#define cram_qual(c) (&(c)->s->qual_blk->data[(c)->qual])
#define cram_aux(c) (&(c)->s->aux_blk->data[(c)->aux])
#define cram_seqi(c,i) (cram_seq((c))[(i)])
#define cram_name_len(c) ((c)->name_len)
#define cram_strand(c) (((c)->flags & BAM_FREVERSE) != 0)
#define cram_mstrand(c) (((c)->flags & BAM_FMREVERSE) != 0)
#define cram_cigar(c) (&((cr)->s->cigar)[(c)->cigar])
/*
* A feature is a base difference, used for the sequence reference encoding.
* (We generate these internally when writing CRAM.)
*/
typedef struct cram_feature {
union {
struct {
int pos;
int code;
int base; // substitution code
} X;
struct {
int pos;
int code;
int base; // actual base & qual
int qual;
} B;
struct {
int pos;
int code;
int seq_idx; // index to s->seqs_blk
int len;
} b;
struct {
int pos;
int code;
int qual;
} Q;
struct {
int pos;
int code;
int len;
int seq_idx; // soft-clip multiple bases
} S;
struct {
int pos;
int code;
int len;
int seq_idx; // insertion multiple bases
} I;
struct {
int pos;
int code;
int base; // insertion single base
} i;
struct {
int pos;
int code;
int len;
} D;
struct {
int pos;
int code;
int len;
} N;
struct {
int pos;
int code;
int len;
} P;
struct {
int pos;
int code;
int len;
} H;
};
} cram_feature;
/*
* A slice is really just a set of blocks, but it
* is the logical unit for decoding a number of
* sequences.
*/
typedef struct cram_slice {
cram_block_slice_hdr *hdr;
cram_block *hdr_block;
cram_block **block;
cram_block **block_by_id;
/* State used during encoding/decoding */
int last_apos, max_apos;
/* Array of decoded cram records */
cram_record *crecs;
/* An dynamically growing buffers for data pointed
* to by crecs[] array.
*/
uint32_t *cigar;
uint32_t cigar_alloc;
uint32_t ncigar;
cram_feature *features;
int nfeatures;
int afeatures; // allocated size of features
#ifndef TN_external
// TN field (Tag Name)
uint32_t *TN;
int nTN, aTN; // used and allocated size for TN[]
#else
cram_block *tn_blk;
int tn_id;
#endif
// For variable sized elements which are always external blocks.
cram_block *name_blk;
cram_block *seqs_blk;
cram_block *qual_blk;
cram_block *base_blk;
cram_block *soft_blk;
cram_block *aux_blk;
cram_block *aux_OQ_blk;
cram_block *aux_BQ_blk;
cram_block *aux_BD_blk;
cram_block *aux_BI_blk;
cram_block *aux_FZ_blk;
cram_block *aux_oq_blk;
cram_block *aux_os_blk;
cram_block *aux_oz_blk;
string_alloc_t *pair_keys; // Pooled keys for pair hash.
khash_t(m_s2i) *pair[2]; // for identifying read-pairs in this slice.
char *ref; // slice of current reference
int ref_start; // start position of current reference;
int ref_end; // end position of current reference;
int ref_id;
} cram_slice;
/*-----------------------------------------------------------------------------
* Consider moving reference handling to cram_refs.[ch]
*/
// from fa.fai / samtools faidx files
typedef struct ref_entry {
char *name;
char *fn;
int64_t length;
int64_t offset;
int bases_per_line;
int line_length;
int64_t count; // for shared references so we know to dealloc seq
char *seq;
mFILE *mf;
int is_md5; // Reference comes from a raw seq found by MD5
} ref_entry;
KHASH_MAP_INIT_STR(refs, ref_entry*)
// References structure.
typedef struct {
string_alloc_t *pool; // String pool for holding filenames and SN vals
khash_t(refs) *h_meta; // ref_entry*, index by name
ref_entry **ref_id; // ref_entry*, index by ID
int nref; // number of ref_entry
char *fn; // current file opened
BGZF *fp; // and the hFILE* to go with it.
int count; // how many cram_fd sharing this refs struct
pthread_mutex_t lock; // Mutex for multi-threaded updating
ref_entry *last; // Last queried sequence
int last_id; // Used in cram_ref_decr_locked to delay free
} refs_t;
/*-----------------------------------------------------------------------------
* CRAM index
*
* Detect format by number of entries per line.
* 5 => 1.0 (refid, start, nseq, C offset, slice)
* 6 => 1.1 (refid, start, span, C offset, S offset, S size)
*
* Indices are stored in a nested containment list, which is trivial to set
* up as the indices are on sorted data so we're appending to the nclist
* in sorted order. Basically if a slice entirely fits within a previous
* slice then we append to that slices list. This is done recursively.
*
* Lists are sorted on two dimensions: ref id + slice coords.
*/
typedef struct cram_index {
int nslice, nalloc; // total number of slices
struct cram_index *e; // array of size nslice
int refid; // 1.0 1.1
int start; // 1.0 1.1
int end; // 1.1
int nseq; // 1.0 - undocumented
int slice; // 1.0 landmark index, 1.1 landmark value
int len; // 1.1 - size of slice in bytes
int64_t offset; // 1.0 1.1
} cram_index;
typedef struct {
int refid;
int start;
int end;
} cram_range;
/*-----------------------------------------------------------------------------
*/
/* CRAM File handle */
typedef struct spare_bams {
bam_seq_t **bams;
struct spare_bams *next;
} spare_bams;
typedef struct cram_fd {
struct hFILE *fp;
int mode; // 'r' or 'w'
int version;
cram_file_def *file_def;
SAM_hdr *header;
char *prefix;
int64_t record_counter;
int err;
// Most recent compression header decoded
//cram_block_compression_hdr *comp_hdr;
//cram_block_slice_hdr *slice_hdr;
// Current container being processed.
cram_container *ctr;
// positions for encoding or decoding
int first_base, last_base;
// cached reference portion
refs_t *refs; // ref meta-data structure
char *ref, *ref_free; // current portion held in memory
int ref_id;
int ref_start;
int ref_end;
char *ref_fn; // reference fasta filename
// compression level and metrics
int level;
cram_metrics *m[DS_END];
// options
int decode_md; // Whether to export MD and NM tags
int verbose;
int seqs_per_slice;
int slices_per_container;
int embed_ref;
int no_ref;
int ignore_md5;
int use_bz2;
int use_rans;
int use_lzma;
int shared_ref;
unsigned int required_fields;
cram_range range;
// lookup tables, stored here so we can be trivially multi-threaded
unsigned int bam_flag_swap[0x1000]; // cram -> bam flags
unsigned int cram_flag_swap[0x1000];// bam -> cram flags
unsigned char L1[256]; // ACGT{*} ->0123{4}
unsigned char L2[256]; // ACGTN{*}->01234{5}
char cram_sub_matrix[32][32]; // base substituion codes
int index_sz;
cram_index *index; // array, sizeof index_sz
off_t first_container;
int eof;
int last_slice; // number of recs encoded in last slice
int multi_seq;
int unsorted;
int empty_container; // Marker for EOF block
// thread pool
int own_pool;
t_pool *pool;
t_results_queue *rqueue;
pthread_mutex_t metrics_lock;
pthread_mutex_t ref_lock;
spare_bams *bl;
pthread_mutex_t bam_list_lock;
void *job_pending;
int ooc; // out of containers.
char cacheDir[1024]; // directory with cached reference
char refUrl[4096]; // URL from which to grab reference
char md5Ref[128]; // MD5 sum of reference sequence
} cram_fd;
// Translation of required fields to cram data series
enum cram_fields {
CRAM_BF = 0x00000001,
CRAM_AP = 0x00000002,
CRAM_FP = 0x00000004,
CRAM_RL = 0x00000008,
CRAM_DL = 0x00000010,
CRAM_NF = 0x00000020,
CRAM_BA = 0x00000040,
CRAM_QS = 0x00000080,
CRAM_FC = 0x00000100,
CRAM_FN = 0x00000200,
CRAM_BS = 0x00000400,
CRAM_IN = 0x00000800,
CRAM_RG = 0x00001000,
CRAM_MQ = 0x00002000,
CRAM_TL = 0x00004000,
CRAM_RN = 0x00008000,
CRAM_NS = 0x00010000,
CRAM_NP = 0x00020000,
CRAM_TS = 0x00040000,
CRAM_MF = 0x00080000,
CRAM_CF = 0x00100000,
CRAM_RI = 0x00200000,
CRAM_RS = 0x00400000,
CRAM_PD = 0x00800000,
CRAM_HC = 0x01000000,
CRAM_SC = 0x02000000,
CRAM_BB = 0x04000000,
CRAM_BB_len = 0x08000000,
CRAM_QQ = 0x10000000,
CRAM_QQ_len = 0x20000000,
CRAM_aux= 0x40000000,
CRAM_ALL= 0x7fffffff,
};
// A CIGAR opcode, but not necessarily the implications of it. Eg FC/FP may
// encode a base difference, but we don't need to know what it is for CIGAR.
// If we have a soft-clip or insertion, we do need SC/IN though to know how
// long that array is.
#define CRAM_CIGAR (CRAM_FN | CRAM_FP | CRAM_FC | CRAM_DL | CRAM_IN | \
CRAM_SC | CRAM_HC | CRAM_PD | CRAM_RS | CRAM_RL | CRAM_BF)
#define CRAM_SEQ (CRAM_CIGAR | CRAM_BA | CRAM_BS | \
CRAM_RL | CRAM_AP | CRAM_BB)
#define CRAM_QUAL (CRAM_CIGAR | CRAM_RL | CRAM_AP | CRAM_QS | CRAM_QQ)
/* BF bitfields */
/* Corrected in 1.1. Use bam_flag_swap[bf] and BAM_* macros for 1.0 & 1.1 */
#define CRAM_FPAIRED 256
#define CRAM_FPROPER_PAIR 128
#define CRAM_FUNMAP 64
#define CRAM_FREVERSE 32
#define CRAM_FREAD1 16
#define CRAM_FREAD2 8
#define CRAM_FSECONDARY 4
#define CRAM_FQCFAIL 2
#define CRAM_FDUP 1
#define DS_aux_S "\001"
#define DS_aux_OQ_S "\002"
#define DS_aux_BQ_S "\003"
#define DS_aux_BD_S "\004"
#define DS_aux_BI_S "\005"
#define DS_aux_FZ_S "\006"
#define DS_aux_oq_S "\007"
#define DS_aux_os_S "\010"
#define DS_aux_oz_S "\011"
#define CRAM_M_REVERSE 1
#define CRAM_M_UNMAP 2
/* CF bitfields */
#define CRAM_FLAG_PRESERVE_QUAL_SCORES (1<<0)
#define CRAM_FLAG_DETACHED (1<<1)
#define CRAM_FLAG_MATE_DOWNSTREAM (1<<2)
#define CRAM_FLAG_NO_SEQ (1<<3)
#ifdef __cplusplus
}
#endif
#endif /* _CRAM_STRUCTS_H_ */
| {
"content_hash": "58f6dccfa0800a65cba01f5727a2c80c",
"timestamp": "",
"source": "github",
"line_count": 791,
"max_line_length": 79,
"avg_line_length": 26.943109987357776,
"alnum_prop": 0.5862424924924925,
"repo_name": "hillerlab/GenomeAlignmentTools",
"id": "7c52deb5411fe960b95fddf959de76717b365128",
"size": "22879",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "kent/src/htslib/cram/cram_structs.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ActionScript",
"bytes": "1224"
},
{
"name": "AngelScript",
"bytes": "434284"
},
{
"name": "C",
"bytes": "14825208"
},
{
"name": "C++",
"bytes": "81839"
},
{
"name": "CAP CDS",
"bytes": "475"
},
{
"name": "Gnuplot",
"bytes": "36237"
},
{
"name": "HTML",
"bytes": "11954"
},
{
"name": "M4",
"bytes": "7552"
},
{
"name": "Makefile",
"bytes": "111088"
},
{
"name": "Perl",
"bytes": "80546"
},
{
"name": "PostScript",
"bytes": "2595"
},
{
"name": "Python",
"bytes": "37076"
},
{
"name": "Roff",
"bytes": "20366"
},
{
"name": "Shell",
"bytes": "34162"
},
{
"name": "TSQL",
"bytes": "2442"
},
{
"name": "q",
"bytes": "218"
}
],
"symlink_target": ""
} |
<?php
namespace Admin\Service;
use DateTime;
use Core\Test\ServiceTestCase;
use Admin\Model\User;
use Core\Model\EntityException;
use Zend\Authentication\AuthenticationService;
/**
* Testes do serviço Auth
* @category Admin
* @package Service
* @author Elton Minetto<eminetto@coderockr.com>
*/
/**
* @group Service
*/
class AuthTest extends ServiceTestCase {
/**
* Authenticação sem parâmetros
* @expectedException \Exception
* @return void
*/
public function testAuthenticateWithoutParams() {
$authService = $this->serviceManager->get('Admin\Service\Auth');
$authService->authenticate();
}
/**
* Authenticação sem parâmetros
* @expectedException \Exception
* @expectedExceptionMessage Parâmetros inválidos
* @return void
*/
public function testAuthenticateEmptyParams() {
$authService = $this->serviceManager->get('Admin\Service\Auth');
$authService->authenticate(array());
}
/**
* Teste da autenticação inválida
* @expectedException \Exception
* @expectedExceptionMessage Login ou senha inválidos
* @return void
*/
public function testAuthenticateInvalidParameters() {
$authService = $this->serviceManager->get('Admin\Service\Auth');
$authService->authenticate(array('username' => 'invalid', 'password' => 'invalid'));
}
/**
* Teste da autenticação Inválida
* @expectedException \Exception
* @expectedExceptionMessage Login ou senha inválidos
* @return void
*/
public function testAuthenticateInvalidPassord() {
$authService = $this->serviceManager->get('Admin\Service\Auth');
$user = $this->addUser();
$authService->authenticate(array('username' => $user->username, 'password' => 'invalida'));
}
/**
* Teste da autenticação Válida
* @return void
*/
public function testAuthenticateValidParams() {
$authService = $this->serviceManager->get('Admin\Service\Auth');
$user = $this->addUser();
$result = $authService->authenticate(
array('username' => $user->username, 'password' => 'apple')
);
$this->assertTrue($result);
//testar a se a authenticação foi criada
$auth = new AuthenticationService();
$this->assertEquals($auth->getIdentity(), $user->username);
//verica se o usuário foi salvo na sessão
$session = $this->serviceManager->get('Session');
$savedUser = $session->offsetGet('user');
$this->assertEquals($user->id, $savedUser->id);
}
/**
* Limpa a autenticação depois de cada teste
* @return void
*/
public function tearDown() {
parent::tearDown();
$auth = new AuthenticationService();
$auth->clearIdentity();
}
/**
* Teste do logout
* @return void
*/
public function testLogout() {
$authService = $this->serviceManager->get('Admin\Service\Auth');
$user = $this->addUser();
$result = $authService->authenticate(
array('username' => $user->username, 'password' => 'apple')
);
$this->assertTrue($result);
$result = $authService->logout();
$this->assertTrue($result);
//verifica se removeu a identidade da autenticação
$auth = new AuthenticationService();
$this->assertNull($auth->getIdentity());
//verifica se o usuário foi removido da sessão
$session = $this->serviceManager->get('Session');
$savedUser = $session->offsetGet('user');
$this->assertNull($savedUser);
}
private function addUser() {
$user = new User();
$user->username = 'steve';
$user->password = md5('apple');
$user->name = 'Steve <b>Jobs</b>';
$user->valid = 1;
$user->role = 'admin';
$saved = $this->getTable('Admin\Model\User')->save($user);
return $saved;
}
/**
* Teste da autorização
* @return void
*/
public function testAuthorize() {
$authService = $this->getService('Admin\Service\Auth');
$result = $authService->authorize();
$this->assertFalse($result);
$user = $this->addUser();
$result = $authService->authenticate(
array('username' => $user->username, 'password' => 'apple')
);
$this->assertTrue($result);
$result = $authService->authorize();
$this->assertTrue($result);
}
}
| {
"content_hash": "e30a48c42009f7f052ae3424e322ac9d",
"timestamp": "",
"source": "github",
"line_count": 163,
"max_line_length": 99,
"avg_line_length": 28.87730061349693,
"alnum_prop": 0.5770129594221373,
"repo_name": "Echenique/zf2-project",
"id": "abc24ed8f6ae418055c454d47eba95497fa6c2b9",
"size": "4739",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "module/Admin/tests/src/Admin/Service/AuthTest.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "1045"
},
{
"name": "PHP",
"bytes": "126046"
}
],
"symlink_target": ""
} |
<?php
namespace Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection;
use Symfony\Bundle\FrameworkBundle\Tests\TestCase;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\FrameworkExtension;
use Symfony\Component\Cache\Adapter\ApcuAdapter;
use Symfony\Component\Cache\Adapter\ChainAdapter;
use Symfony\Component\Cache\Adapter\DoctrineAdapter;
use Symfony\Component\Cache\Adapter\FilesystemAdapter;
use Symfony\Component\Cache\Adapter\ProxyAdapter;
use Symfony\Component\Cache\Adapter\RedisAdapter;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\DefinitionDecorator;
use Symfony\Component\DependencyInjection\Loader\ClosureLoader;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\Serializer\Normalizer\DataUriNormalizer;
use Symfony\Component\Serializer\Normalizer\DateTimeNormalizer;
use Symfony\Component\Serializer\Normalizer\JsonSerializableNormalizer;
abstract class FrameworkExtensionTest extends TestCase
{
private static $containerCache = array();
abstract protected function loadFromFile(ContainerBuilder $container, $file);
public function testFormCsrfProtection()
{
$container = $this->createContainerFromFile('full');
$def = $container->getDefinition('form.type_extension.csrf');
$this->assertTrue($container->getParameter('form.type_extension.csrf.enabled'));
$this->assertEquals('%form.type_extension.csrf.enabled%', $def->getArgument(1));
$this->assertEquals('_csrf', $container->getParameter('form.type_extension.csrf.field_name'));
$this->assertEquals('%form.type_extension.csrf.field_name%', $def->getArgument(2));
}
public function testPropertyAccessWithDefaultValue()
{
$container = $this->createContainerFromFile('full');
$def = $container->getDefinition('property_accessor');
$this->assertFalse($def->getArgument(0));
$this->assertFalse($def->getArgument(1));
}
public function testPropertyAccessWithOverriddenValues()
{
$container = $this->createContainerFromFile('property_accessor');
$def = $container->getDefinition('property_accessor');
$this->assertTrue($def->getArgument(0));
$this->assertTrue($def->getArgument(1));
}
/**
* @expectedException \LogicException
* @expectedExceptionMessage CSRF protection needs sessions to be enabled.
*/
public function testCsrfProtectionNeedsSessionToBeEnabled()
{
$this->createContainerFromFile('csrf_needs_session');
}
public function testCsrfProtectionForFormsEnablesCsrfProtectionAutomatically()
{
$container = $this->createContainerFromFile('csrf');
$this->assertTrue($container->hasDefinition('security.csrf.token_manager'));
}
public function testProxies()
{
$container = $this->createContainerFromFile('full');
$this->assertEquals(array('127.0.0.1', '10.0.0.1'), $container->getParameter('kernel.trusted_proxies'));
}
public function testHttpMethodOverride()
{
$container = $this->createContainerFromFile('full');
$this->assertFalse($container->getParameter('kernel.http_method_override'));
}
public function testEsi()
{
$container = $this->createContainerFromFile('full');
$this->assertTrue($container->hasDefinition('esi'), '->registerEsiConfiguration() loads esi.xml');
}
public function testEnabledProfiler()
{
$container = $this->createContainerFromFile('profiler');
$this->assertTrue($container->hasDefinition('profiler'), '->registerProfilerConfiguration() loads profiling.xml');
$this->assertTrue($container->hasDefinition('data_collector.config'), '->registerProfilerConfiguration() loads collectors.xml');
}
public function testDisabledProfiler()
{
$container = $this->createContainerFromFile('full');
$this->assertFalse($container->hasDefinition('profiler'), '->registerProfilerConfiguration() does not load profiling.xml');
$this->assertFalse($container->hasDefinition('data_collector.config'), '->registerProfilerConfiguration() does not load collectors.xml');
}
public function testRouter()
{
$container = $this->createContainerFromFile('full');
$this->assertTrue($container->has('router'), '->registerRouterConfiguration() loads routing.xml');
$arguments = $container->findDefinition('router')->getArguments();
$this->assertEquals($container->getParameter('kernel.root_dir').'/config/routing.xml', $container->getParameter('router.resource'), '->registerRouterConfiguration() sets routing resource');
$this->assertEquals('%router.resource%', $arguments[1], '->registerRouterConfiguration() sets routing resource');
$this->assertEquals('xml', $arguments[2]['resource_type'], '->registerRouterConfiguration() sets routing resource type');
}
/**
* @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException
*/
public function testRouterRequiresResourceOption()
{
$container = $this->createContainer();
$loader = new FrameworkExtension();
$loader->load(array(array('router' => true)), $container);
}
public function testSession()
{
$container = $this->createContainerFromFile('full');
$this->assertTrue($container->hasDefinition('session'), '->registerSessionConfiguration() loads session.xml');
$this->assertEquals('fr', $container->getParameter('kernel.default_locale'));
$this->assertEquals('session.storage.native', (string) $container->getAlias('session.storage'));
$this->assertEquals('session.handler.native_file', (string) $container->getAlias('session.handler'));
$options = $container->getParameter('session.storage.options');
$this->assertEquals('_SYMFONY', $options['name']);
$this->assertEquals(86400, $options['cookie_lifetime']);
$this->assertEquals('/', $options['cookie_path']);
$this->assertEquals('example.com', $options['cookie_domain']);
$this->assertTrue($options['cookie_secure']);
$this->assertFalse($options['cookie_httponly']);
$this->assertTrue($options['use_cookies']);
$this->assertEquals(108, $options['gc_divisor']);
$this->assertEquals(1, $options['gc_probability']);
$this->assertEquals(90000, $options['gc_maxlifetime']);
$this->assertEquals('/path/to/sessions', $container->getParameter('session.save_path'));
}
public function testNullSessionHandler()
{
$container = $this->createContainerFromFile('session');
$this->assertTrue($container->hasDefinition('session'), '->registerSessionConfiguration() loads session.xml');
$this->assertNull($container->getDefinition('session.storage.native')->getArgument(1));
$this->assertNull($container->getDefinition('session.storage.php_bridge')->getArgument(0));
}
public function testRequest()
{
$container = $this->createContainerFromFile('full');
$this->assertTrue($container->hasDefinition('request.add_request_formats_listener'), '->registerRequestConfiguration() loads request.xml');
$listenerDef = $container->getDefinition('request.add_request_formats_listener');
$this->assertEquals(array('csv' => array('text/csv', 'text/plain'), 'pdf' => array('application/pdf')), $listenerDef->getArgument(0));
}
public function testEmptyRequestFormats()
{
$container = $this->createContainerFromFile('request');
$this->assertFalse($container->hasDefinition('request.add_request_formats_listener'), '->registerRequestConfiguration() does not load request.xml when no request formats are defined');
}
public function testTemplating()
{
$container = $this->createContainerFromFile('full');
$this->assertTrue($container->hasDefinition('templating.name_parser'), '->registerTemplatingConfiguration() loads templating.xml');
$this->assertEquals('templating.engine.delegating', (string) $container->getAlias('templating'), '->registerTemplatingConfiguration() configures delegating loader if multiple engines are provided');
$this->assertEquals($container->getDefinition('templating.loader.chain'), $container->getDefinition('templating.loader.wrapped'), '->registerTemplatingConfiguration() configures loader chain if multiple loaders are provided');
$this->assertEquals($container->getDefinition('templating.loader'), $container->getDefinition('templating.loader.cache'), '->registerTemplatingConfiguration() configures the loader to use cache');
$this->assertEquals('%templating.loader.cache.path%', $container->getDefinition('templating.loader.cache')->getArgument(1));
$this->assertEquals('/path/to/cache', $container->getParameter('templating.loader.cache.path'));
$this->assertEquals(array('php', 'twig'), $container->getParameter('templating.engines'), '->registerTemplatingConfiguration() sets a templating.engines parameter');
$this->assertEquals(array('FrameworkBundle:Form', 'theme1', 'theme2'), $container->getParameter('templating.helper.form.resources'), '->registerTemplatingConfiguration() registers the theme and adds the base theme');
$this->assertEquals('global_hinclude_template', $container->getParameter('fragment.renderer.hinclude.global_template'), '->registerTemplatingConfiguration() registers the global hinclude.js template');
}
public function testTemplatingCanBeDisabled()
{
$container = $this->createContainerFromFile('templating_disabled');
$this->assertFalse($container->hasParameter('templating.engines'), '"templating.engines" container parameter is not registered when templating is disabled.');
}
public function testAssets()
{
$container = $this->createContainerFromFile('assets');
$packages = $container->getDefinition('assets.packages');
// default package
$defaultPackage = $container->getDefinition($packages->getArgument(0));
$this->assertUrlPackage($container, $defaultPackage, array('http://cdn.example.com'), 'SomeVersionScheme', '%%s?version=%%s');
// packages
$packages = $packages->getArgument(1);
$this->assertCount(5, $packages);
$package = $container->getDefinition($packages['images_path']);
$this->assertPathPackage($container, $package, '/foo', 'SomeVersionScheme', '%%s?version=%%s');
$package = $container->getDefinition($packages['images']);
$this->assertUrlPackage($container, $package, array('http://images1.example.com', 'http://images2.example.com'), '1.0.0', '%%s?version=%%s');
$package = $container->getDefinition($packages['foo']);
$this->assertPathPackage($container, $package, '', '1.0.0', '%%s-%%s');
$package = $container->getDefinition($packages['bar']);
$this->assertUrlPackage($container, $package, array('https://bar2.example.com'), 'SomeVersionScheme', '%%s?version=%%s');
$package = $container->getDefinition($packages['bar_version_strategy']);
$this->assertEquals('assets.custom_version_strategy', (string) $package->getArgument(1));
}
public function testAssetsDefaultVersionStrategyAsService()
{
$container = $this->createContainerFromFile('assets_version_strategy_as_service');
$packages = $container->getDefinition('assets.packages');
// default package
$defaultPackage = $container->getDefinition($packages->getArgument(0));
$this->assertEquals('assets.custom_version_strategy', (string) $defaultPackage->getArgument(1));
}
public function testTranslator()
{
$container = $this->createContainerFromFile('full');
$this->assertTrue($container->hasDefinition('translator.default'), '->registerTranslatorConfiguration() loads translation.xml');
$this->assertEquals('translator.default', (string) $container->getAlias('translator'), '->registerTranslatorConfiguration() redefines translator service from identity to real translator');
$options = $container->getDefinition('translator.default')->getArgument(3);
$files = array_map(function ($resource) { return realpath($resource); }, $options['resource_files']['en']);
$ref = new \ReflectionClass('Symfony\Component\Validator\Validation');
$this->assertContains(
strtr(dirname($ref->getFileName()).'/Resources/translations/validators.en.xlf', '/', DIRECTORY_SEPARATOR),
$files,
'->registerTranslatorConfiguration() finds Validator translation resources'
);
$ref = new \ReflectionClass('Symfony\Component\Form\Form');
$this->assertContains(
strtr(dirname($ref->getFileName()).'/Resources/translations/validators.en.xlf', '/', DIRECTORY_SEPARATOR),
$files,
'->registerTranslatorConfiguration() finds Form translation resources'
);
$ref = new \ReflectionClass('Symfony\Component\Security\Core\Security');
$this->assertContains(
strtr(dirname($ref->getFileName()).'/Resources/translations/security.en.xlf', '/', DIRECTORY_SEPARATOR),
$files,
'->registerTranslatorConfiguration() finds Security translation resources'
);
$this->assertContains(
strtr(__DIR__.'/Fixtures/translations/test_paths.en.yml', '/', DIRECTORY_SEPARATOR),
$files,
'->registerTranslatorConfiguration() finds translation resources in custom paths'
);
$calls = $container->getDefinition('translator.default')->getMethodCalls();
$this->assertEquals(array('fr'), $calls[1][1][0]);
}
public function testTranslatorMultipleFallbacks()
{
$container = $this->createContainerFromFile('translator_fallbacks');
$calls = $container->getDefinition('translator.default')->getMethodCalls();
$this->assertEquals(array('en', 'fr'), $calls[1][1][0]);
}
/**
* @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException
*/
public function testTemplatingRequiresAtLeastOneEngine()
{
$container = $this->createContainer();
$loader = new FrameworkExtension();
$loader->load(array(array('templating' => null)), $container);
}
public function testValidation()
{
$container = $this->createContainerFromFile('full');
$ref = new \ReflectionClass('Symfony\Component\Form\Form');
$xmlMappings = array(dirname($ref->getFileName()).'/Resources/config/validation.xml');
$calls = $container->getDefinition('validator.builder')->getMethodCalls();
$this->assertCount(6, $calls);
$this->assertSame('setConstraintValidatorFactory', $calls[0][0]);
$this->assertEquals(array(new Reference('validator.validator_factory')), $calls[0][1]);
$this->assertSame('setTranslator', $calls[1][0]);
$this->assertEquals(array(new Reference('translator')), $calls[1][1]);
$this->assertSame('setTranslationDomain', $calls[2][0]);
$this->assertSame(array('%validator.translation_domain%'), $calls[2][1]);
$this->assertSame('addXmlMappings', $calls[3][0]);
$this->assertSame(array($xmlMappings), $calls[3][1]);
$this->assertSame('addMethodMapping', $calls[4][0]);
$this->assertSame(array('loadValidatorMetadata'), $calls[4][1]);
$this->assertSame('setMetadataCache', $calls[5][0]);
$this->assertEquals(array(new Reference('validator.mapping.cache.doctrine.apc')), $calls[5][1]);
}
public function testValidationService()
{
$container = $this->createContainerFromFile('validation_annotations', array('kernel.charset' => 'UTF-8'), false);
$this->assertInstanceOf('Symfony\Component\Validator\Validator\ValidatorInterface', $container->get('validator'));
}
public function testAnnotations()
{
$container = $this->createContainerFromFile('full');
$this->assertEquals($container->getParameter('kernel.cache_dir').'/annotations', $container->getDefinition('annotations.filesystem_cache')->getArgument(0));
$this->assertSame('annotations.cached_reader', (string) $container->getAlias('annotation_reader'));
$this->assertSame('annotations.filesystem_cache', (string) $container->getDefinition('annotations.cached_reader')->getArgument(1));
}
public function testFileLinkFormat()
{
$container = $this->createContainerFromFile('full');
$this->assertEquals('file%link%format', $container->getParameter('templating.helper.code.file_link_format'));
}
public function testValidationAnnotations()
{
$container = $this->createContainerFromFile('validation_annotations');
$calls = $container->getDefinition('validator.builder')->getMethodCalls();
$this->assertCount(7, $calls);
$this->assertSame('enableAnnotationMapping', $calls[4][0]);
$this->assertEquals(array(new Reference('annotation_reader')), $calls[4][1]);
$this->assertSame('addMethodMapping', $calls[5][0]);
$this->assertSame(array('loadValidatorMetadata'), $calls[5][1]);
$this->assertSame('setMetadataCache', $calls[6][0]);
$this->assertEquals(array(new Reference('validator.mapping.cache.symfony')), $calls[6][1]);
// no cache this time
}
public function testValidationPaths()
{
require_once __DIR__.'/Fixtures/TestBundle/TestBundle.php';
$container = $this->createContainerFromFile('validation_annotations', array(
'kernel.bundles' => array('TestBundle' => 'Symfony\Bundle\FrameworkBundle\Tests\TestBundle'),
));
$calls = $container->getDefinition('validator.builder')->getMethodCalls();
$this->assertCount(8, $calls);
$this->assertSame('addXmlMappings', $calls[3][0]);
$this->assertSame('addYamlMappings', $calls[4][0]);
$this->assertSame('enableAnnotationMapping', $calls[5][0]);
$this->assertSame('addMethodMapping', $calls[6][0]);
$this->assertSame(array('loadValidatorMetadata'), $calls[6][1]);
$this->assertSame('setMetadataCache', $calls[7][0]);
$this->assertEquals(array(new Reference('validator.mapping.cache.symfony')), $calls[7][1]);
$xmlMappings = $calls[3][1][0];
$this->assertCount(2, $xmlMappings);
try {
// Testing symfony/symfony
$this->assertStringEndsWith('Component'.DIRECTORY_SEPARATOR.'Form/Resources/config/validation.xml', $xmlMappings[0]);
} catch (\Exception $e) {
// Testing symfony/framework-bundle with deps=high
$this->assertStringEndsWith('symfony'.DIRECTORY_SEPARATOR.'form/Resources/config/validation.xml', $xmlMappings[0]);
}
$this->assertStringEndsWith('TestBundle/Resources/config/validation.xml', $xmlMappings[1]);
$yamlMappings = $calls[4][1][0];
$this->assertCount(1, $yamlMappings);
$this->assertStringEndsWith('TestBundle/Resources/config/validation.yml', $yamlMappings[0]);
}
public function testValidationNoStaticMethod()
{
$container = $this->createContainerFromFile('validation_no_static_method');
$calls = $container->getDefinition('validator.builder')->getMethodCalls();
$this->assertCount(5, $calls);
$this->assertSame('addXmlMappings', $calls[3][0]);
$this->assertSame('setMetadataCache', $calls[4][0]);
$this->assertEquals(array(new Reference('validator.mapping.cache.symfony')), $calls[4][1]);
// no cache, no annotations, no static methods
}
public function testFormsCanBeEnabledWithoutCsrfProtection()
{
$container = $this->createContainerFromFile('form_no_csrf');
$this->assertFalse($container->getParameter('form.type_extension.csrf.enabled'));
}
public function testStopwatchEnabledWithDebugModeEnabled()
{
$container = $this->createContainerFromFile('default_config', array(
'kernel.container_class' => 'foo',
'kernel.debug' => true,
));
$this->assertTrue($container->has('debug.stopwatch'));
}
public function testStopwatchEnabledWithDebugModeDisabled()
{
$container = $this->createContainerFromFile('default_config', array(
'kernel.container_class' => 'foo',
));
$this->assertTrue($container->has('debug.stopwatch'));
}
public function testSerializerDisabled()
{
$container = $this->createContainerFromFile('default_config');
$this->assertFalse($container->has('serializer'));
}
public function testSerializerEnabled()
{
$container = $this->createContainerFromFile('full');
$this->assertTrue($container->has('serializer'));
$argument = $container->getDefinition('serializer.mapping.chain_loader')->getArgument(0);
$this->assertCount(1, $argument);
$this->assertEquals('Symfony\Component\Serializer\Mapping\Loader\AnnotationLoader', $argument[0]->getClass());
$this->assertNull($container->getDefinition('serializer.mapping.class_metadata_factory')->getArgument(1));
$this->assertEquals(new Reference('serializer.name_converter.camel_case_to_snake_case'), $container->getDefinition('serializer.normalizer.object')->getArgument(1));
$this->assertEquals(new Reference('property_info', ContainerBuilder::IGNORE_ON_INVALID_REFERENCE), $container->getDefinition('serializer.normalizer.object')->getArgument(3));
}
public function testRegisterSerializerExtractor()
{
$container = $this->createContainerFromFile('full');
$serializerExtractorDefinition = $container->getDefinition('property_info.serializer_extractor');
$this->assertEquals('serializer.mapping.class_metadata_factory', $serializerExtractorDefinition->getArgument(0)->__toString());
$this->assertFalse($serializerExtractorDefinition->isPublic());
$tag = $serializerExtractorDefinition->getTag('property_info.list_extractor');
$this->assertEquals(array('priority' => -999), $tag[0]);
}
public function testDataUriNormalizerRegistered()
{
if (!class_exists('Symfony\Component\Serializer\Normalizer\DataUriNormalizer')) {
$this->markTestSkipped('The DataUriNormalizer has been introduced in the Serializer Component version 3.1.');
}
$container = $this->createContainerFromFile('full');
$definition = $container->getDefinition('serializer.normalizer.data_uri');
$tag = $definition->getTag('serializer.normalizer');
$this->assertEquals(DataUriNormalizer::class, $definition->getClass());
$this->assertEquals(-920, $tag[0]['priority']);
}
public function testDateTimeNormalizerRegistered()
{
if (!class_exists('Symfony\Component\Serializer\Normalizer\DateTimeNormalizer')) {
$this->markTestSkipped('The DateTimeNormalizer has been introduced in the Serializer Component version 3.1.');
}
$container = $this->createContainerFromFile('full');
$definition = $container->getDefinition('serializer.normalizer.datetime');
$tag = $definition->getTag('serializer.normalizer');
$this->assertEquals(DateTimeNormalizer::class, $definition->getClass());
$this->assertEquals(-910, $tag[0]['priority']);
}
public function testJsonSerializableNormalizerRegistered()
{
if (!class_exists('Symfony\Component\Serializer\Normalizer\JsonSerializableNormalizer')) {
$this->markTestSkipped('The JsonSerializableNormalizer has been introduced in the Serializer Component version 3.1.');
}
$container = $this->createContainerFromFile('full');
$definition = $container->getDefinition('serializer.normalizer.json_serializable');
$tag = $definition->getTag('serializer.normalizer');
$this->assertEquals(JsonSerializableNormalizer::class, $definition->getClass());
$this->assertEquals(-900, $tag[0]['priority']);
}
public function testObjectNormalizerRegistered()
{
$container = $this->createContainerFromFile('full');
$definition = $container->getDefinition('serializer.normalizer.object');
$tag = $definition->getTag('serializer.normalizer');
$this->assertEquals('Symfony\Component\Serializer\Normalizer\ObjectNormalizer', $definition->getClass());
$this->assertEquals(-1000, $tag[0]['priority']);
}
public function testSerializerCacheActivated()
{
$container = $this->createContainerFromFile('serializer_enabled');
$this->assertTrue($container->hasDefinition('serializer.mapping.cache_class_metadata_factory'));
}
public function testSerializerCacheDisabled()
{
$container = $this->createContainerFromFile('serializer_enabled', array('kernel.debug' => true, 'kernel.container_class' => __CLASS__));
$this->assertFalse($container->hasDefinition('serializer.mapping.cache_class_metadata_factory'));
}
/**
* @group legacy
* @expectedDeprecation The "framework.serializer.cache" option is deprecated %s.
*/
public function testDeprecatedSerializerCacheOption()
{
$container = $this->createContainerFromFile('serializer_legacy_cache', array('kernel.debug' => true, 'kernel.container_class' => __CLASS__));
$this->assertFalse($container->hasDefinition('serializer.mapping.cache_class_metadata_factory'));
$this->assertTrue($container->hasDefinition('serializer.mapping.class_metadata_factory'));
$cache = $container->getDefinition('serializer.mapping.class_metadata_factory')->getArgument(1);
$this->assertEquals(new Reference('foo'), $cache);
}
public function testAssetHelperWhenAssetsAreEnabled()
{
$container = $this->createContainerFromFile('full');
$packages = $container->getDefinition('templating.helper.assets')->getArgument(0);
$this->assertSame('assets.packages', (string) $packages);
}
public function testAssetHelperWhenTemplatesAreEnabledAndNoAssetsConfiguration()
{
$container = $this->createContainerFromFile('templating_no_assets');
$packages = $container->getDefinition('templating.helper.assets')->getArgument(0);
$this->assertSame('assets.packages', (string) $packages);
}
public function testAssetsHelperIsRemovedWhenPhpTemplatingEngineIsEnabledAndAssetsAreDisabled()
{
$container = $this->createContainerFromFile('templating_php_assets_disabled');
$this->assertTrue(!$container->has('templating.helper.assets'), 'The templating.helper.assets helper service is removed when assets are disabled.');
}
public function testAssetHelperWhenAssetsAndTemplatesAreDisabled()
{
$container = $this->createContainerFromFile('default_config');
$this->assertFalse($container->hasDefinition('templating.helper.assets'));
}
public function testSerializerServiceIsRegisteredWhenEnabled()
{
$container = $this->createContainerFromFile('serializer_enabled');
$this->assertTrue($container->hasDefinition('serializer'));
}
public function testSerializerServiceIsNotRegisteredWhenDisabled()
{
$container = $this->createContainerFromFile('serializer_disabled');
$this->assertFalse($container->hasDefinition('serializer'));
}
public function testPropertyInfoDisabled()
{
$container = $this->createContainerFromFile('default_config');
$this->assertFalse($container->has('property_info'));
}
public function testPropertyInfoEnabled()
{
$container = $this->createContainerFromFile('property_info');
$this->assertTrue($container->has('property_info'));
}
public function testCachePoolServices()
{
$container = $this->createContainerFromFile('cache');
$this->assertCachePoolServiceDefinitionIsCreated($container, 'cache.foo', 'cache.adapter.apcu', 30);
$this->assertCachePoolServiceDefinitionIsCreated($container, 'cache.bar', 'cache.adapter.doctrine', 5);
$this->assertCachePoolServiceDefinitionIsCreated($container, 'cache.baz', 'cache.adapter.filesystem', 7);
$this->assertCachePoolServiceDefinitionIsCreated($container, 'cache.foobar', 'cache.adapter.psr6', 10);
$this->assertCachePoolServiceDefinitionIsCreated($container, 'cache.def', 'cache.app', 11);
}
protected function createContainer(array $data = array())
{
return new ContainerBuilder(new ParameterBag(array_merge(array(
'kernel.bundles' => array('FrameworkBundle' => 'Symfony\\Bundle\\FrameworkBundle\\FrameworkBundle'),
'kernel.cache_dir' => __DIR__,
'kernel.debug' => false,
'kernel.environment' => 'test',
'kernel.name' => 'kernel',
'kernel.root_dir' => __DIR__,
'kernel.container_class' => 'testContainer',
), $data)));
}
protected function createContainerFromFile($file, $data = array(), $resetCompilerPasses = true)
{
$cacheKey = md5(get_class($this).$file.serialize($data));
if (isset(self::$containerCache[$cacheKey])) {
return self::$containerCache[$cacheKey];
}
$container = $this->createContainer($data);
$container->registerExtension(new FrameworkExtension());
$this->loadFromFile($container, $file);
if ($resetCompilerPasses) {
$container->getCompilerPassConfig()->setOptimizationPasses(array());
$container->getCompilerPassConfig()->setRemovingPasses(array());
}
$container->compile();
return self::$containerCache[$cacheKey] = $container;
}
protected function createContainerFromClosure($closure, $data = array())
{
$container = $this->createContainer($data);
$container->registerExtension(new FrameworkExtension());
$loader = new ClosureLoader($container);
$loader->load($closure);
$container->getCompilerPassConfig()->setOptimizationPasses(array());
$container->getCompilerPassConfig()->setRemovingPasses(array());
$container->compile();
return $container;
}
private function assertPathPackage(ContainerBuilder $container, DefinitionDecorator $package, $basePath, $version, $format)
{
$this->assertEquals('assets.path_package', $package->getParent());
$this->assertEquals($basePath, $package->getArgument(0));
$this->assertVersionStrategy($container, $package->getArgument(1), $version, $format);
}
private function assertUrlPackage(ContainerBuilder $container, DefinitionDecorator $package, $baseUrls, $version, $format)
{
$this->assertEquals('assets.url_package', $package->getParent());
$this->assertEquals($baseUrls, $package->getArgument(0));
$this->assertVersionStrategy($container, $package->getArgument(1), $version, $format);
}
private function assertVersionStrategy(ContainerBuilder $container, Reference $reference, $version, $format)
{
$versionStrategy = $container->getDefinition($reference);
if (null === $version) {
$this->assertEquals('assets.empty_version_strategy', (string) $reference);
} else {
$this->assertEquals('assets.static_version_strategy', $versionStrategy->getParent());
$this->assertEquals($version, $versionStrategy->getArgument(0));
$this->assertEquals($format, $versionStrategy->getArgument(1));
}
}
private function assertCachePoolServiceDefinitionIsCreated(ContainerBuilder $container, $id, $adapter, $defaultLifetime)
{
$this->assertTrue($container->has($id), sprintf('Service definition "%s" for cache pool of type "%s" is registered', $id, $adapter));
$poolDefinition = $container->getDefinition($id);
$this->assertInstanceOf(DefinitionDecorator::class, $poolDefinition, sprintf('Cache pool "%s" is based on an abstract cache pool.', $id));
$this->assertTrue($poolDefinition->hasTag('cache.pool'), sprintf('Service definition "%s" is tagged with the "cache.pool" tag.', $id));
$this->assertFalse($poolDefinition->isAbstract(), sprintf('Service definition "%s" is not abstract.', $id));
$tag = $poolDefinition->getTag('cache.pool');
$this->assertTrue(isset($tag[0]['default_lifetime']), 'The default lifetime is stored as an attribute of the "cache.pool" tag.');
$this->assertSame($defaultLifetime, $tag[0]['default_lifetime'], 'The default lifetime is stored as an attribute of the "cache.pool" tag.');
$parentDefinition = $poolDefinition;
do {
$parentId = $parentDefinition->getParent();
$parentDefinition = $container->findDefinition($parentId);
} while ($parentDefinition instanceof DefinitionDecorator);
switch ($adapter) {
case 'cache.adapter.apcu':
$this->assertSame(ApcuAdapter::class, $parentDefinition->getClass());
break;
case 'cache.adapter.doctrine':
$this->assertSame(DoctrineAdapter::class, $parentDefinition->getClass());
break;
case 'cache.app':
if (ChainAdapter::class === $parentDefinition->getClass()) {
break;
}
case 'cache.adapter.filesystem':
$this->assertSame(FilesystemAdapter::class, $parentDefinition->getClass());
break;
case 'cache.adapter.psr6':
$this->assertSame(ProxyAdapter::class, $parentDefinition->getClass());
break;
case 'cache.adapter.redis':
$this->assertSame(RedisAdapter::class, $parentDefinition->getClass());
break;
default:
$this->fail('Unresolved adapter: '.$adapter);
}
}
}
| {
"content_hash": "e319bcb8b337d1c25c6d1aacd8668aaa",
"timestamp": "",
"source": "github",
"line_count": 739,
"max_line_length": 234,
"avg_line_length": 46.54127198917456,
"alnum_prop": 0.6736930860033726,
"repo_name": "ngantran1991/quanlycafe",
"id": "4e93a0e4f424ce85a2c57c61d8776c3cb675b846",
"size": "34623",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/FrameworkExtensionTest.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "3605"
},
{
"name": "CSS",
"bytes": "232740"
},
{
"name": "HTML",
"bytes": "683014"
},
{
"name": "JavaScript",
"bytes": "197471"
},
{
"name": "PHP",
"bytes": "139014"
}
],
"symlink_target": ""
} |
/* Lzma86.h -- LZMA + x86 (BCJ) Filter
2013-01-18 : Igor Pavlov : Public domain */
#ifndef __LZMA86_H
#define __LZMA86_H
#include <LZMA/7zTypes.h>
EXTERN_C_BEGIN
#define LZMA86_SIZE_OFFSET (1 + 5)
#define LZMA86_HEADER_SIZE (LZMA86_SIZE_OFFSET + 8)
/*
It's an example for LZMA + x86 Filter use.
You can use .lzma86 extension, if you write that stream to file.
.lzma86 header adds one additional byte to standard .lzma header.
.lzma86 header (14 bytes):
Offset Size Description
0 1 = 0 - no filter, pure LZMA
= 1 - x86 filter + LZMA
1 1 lc, lp and pb in encoded form
2 4 dictSize (little endian)
6 8 uncompressed size (little endian)
Lzma86_Encode
-------------
level - compression level: 0 <= level <= 9, the default value for "level" is 5.
dictSize - The dictionary size in bytes. The maximum value is
128 MB = (1 << 27) bytes for 32-bit version
1 GB = (1 << 30) bytes for 64-bit version
The default value is 16 MB = (1 << 24) bytes, for level = 5.
It's recommended to use the dictionary that is larger than 4 KB and
that can be calculated as (1 << N) or (3 << N) sizes.
For better compression ratio dictSize must be >= inSize.
filterMode:
SZ_FILTER_NO - no Filter
SZ_FILTER_YES - x86 Filter
SZ_FILTER_AUTO - it tries both alternatives to select best.
Encoder will use 2 or 3 passes:
2 passes when FILTER_NO provides better compression.
3 passes when FILTER_YES provides better compression.
Lzma86Encode allocates Data with MyAlloc functions.
RAM Requirements for compressing:
RamSize = dictionarySize * 11.5 + 6MB + FilterBlockSize
filterMode FilterBlockSize
SZ_FILTER_NO 0
SZ_FILTER_YES inSize
SZ_FILTER_AUTO inSize
Return code:
SZ_OK - OK
SZ_ERROR_MEM - Memory allocation error
SZ_ERROR_PARAM - Incorrect paramater
SZ_ERROR_OUTPUT_EOF - output buffer overflow
SZ_ERROR_THREAD - errors in multithreading functions (only for Mt version)
*/
enum ESzFilterMode
{
SZ_FILTER_NO,
SZ_FILTER_YES,
SZ_FILTER_AUTO
};
SRes Lzma86_Encode(Byte *dest, size_t *destLen, const Byte *src, size_t srcLen,
int level, UInt32 dictSize, int filterMode);
/*
Lzma86_GetUnpackSize:
In:
src - input data
srcLen - input data size
Out:
unpackSize - size of uncompressed stream
Return code:
SZ_OK - OK
SZ_ERROR_INPUT_EOF - Error in headers
*/
SRes Lzma86_GetUnpackSize(const Byte *src, SizeT srcLen, UInt64 *unpackSize);
/*
Lzma86_Decode:
In:
dest - output data
destLen - output data size
src - input data
srcLen - input data size
Out:
destLen - processed output size
srcLen - processed input size
Return code:
SZ_OK - OK
SZ_ERROR_DATA - Data error
SZ_ERROR_MEM - Memory allocation error
SZ_ERROR_UNSUPPORTED - unsupported file
SZ_ERROR_INPUT_EOF - it needs more bytes in input buffer
*/
SRes Lzma86_Decode(Byte *dest, SizeT *destLen, const Byte *src, SizeT *srcLen);
EXTERN_C_END
#endif
| {
"content_hash": "635e156028b25ea59034239095638ccb",
"timestamp": "",
"source": "github",
"line_count": 111,
"max_line_length": 80,
"avg_line_length": 28.46846846846847,
"alnum_prop": 0.6496835443037975,
"repo_name": "NeroReflex/SeaDragon",
"id": "c934eb33d1d0deeb5343fac4295613d0c6f1432a",
"size": "3160",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "include/LZMA/Lzma86.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "7046563"
},
{
"name": "C++",
"bytes": "3297920"
},
{
"name": "CMake",
"bytes": "14057"
},
{
"name": "Objective-C",
"bytes": "416508"
}
],
"symlink_target": ""
} |
package org.axonframework.integrationtests.utils;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.io.Serializable;
/**
* Stub Domain Event, used for testing purposes.
*
* @author Allard Buijze
*/
public class StubDomainEvent implements Serializable {
private static final long serialVersionUID = 834667054977749990L;
private final String name;
public StubDomainEvent() {
this("name");
}
@JsonCreator
public StubDomainEvent(@JsonProperty("name") String name) {
this.name = name;
}
public String getName() {
return name;
}
@Override
public String toString() {
return "StubDomainEvent";
}
}
| {
"content_hash": "e301933969bff02bc88ced04c2012b43",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 69,
"avg_line_length": 19.842105263157894,
"alnum_prop": 0.6896551724137931,
"repo_name": "krosenvold/AxonFramework",
"id": "e068e0a6b2322f0e35a33e6ceb913cd8f1843076",
"size": "1360",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "integrationtests/src/test/java/org/axonframework/integrationtests/utils/StubDomainEvent.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "4501913"
}
],
"symlink_target": ""
} |
var Fluxer = require('fluxerjs');
var EndpointStore = module.exports = Fluxer.createStore('Endpoint');
Fluxer.on('Endpoint.New', function() {
EndpointStore.emit('OpenNewModal');
});
Fluxer.on('Endpoint.Open', function(endpoint) {
EndpointStore.emit('OpenEditModal', endpoint);
});
Fluxer.on('Endpoint.Updated', function(endpoints) {
EndpointStore.emit('EndpointsUpdated', endpoints);
});
Fluxer.on('Endpoint.Manage', function() {
EndpointStore.emit('OpenManagement');
});
Fluxer.on('Endpoint.Blur', function() {
EndpointStore.emit('CloseManagement');
});
| {
"content_hash": "121289c7d5a8f5583cda307dfdfc5a8d",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 68,
"avg_line_length": 24.608695652173914,
"alnum_prop": 0.726148409893993,
"repo_name": "cfsghost/DarkNight",
"id": "190065e6f0d1377ce7eb458bc8737102847d6145",
"size": "566",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/libs/stores/Endpoint.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "32850"
},
{
"name": "HTML",
"bytes": "1733"
},
{
"name": "JavaScript",
"bytes": "5602336"
}
],
"symlink_target": ""
} |
1. php composer.phar self-update
2. php composer.phar update
3. init.bat
4. common\config\main.php - прписать подключение к БД
5. yii.bat migrate - выполнить все миграции | {
"content_hash": "3d22a7050161b2b64a3d5f7cbd8b4e8b",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 53,
"avg_line_length": 34.2,
"alnum_prop": 0.7719298245614035,
"repo_name": "DarkAngel36/testtask",
"id": "8e5f8fdc60af6f0efa449156df04a0f42edbe47b",
"size": "215",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "deploy.md",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ApacheConf",
"bytes": "436"
},
{
"name": "Batchfile",
"bytes": "1026"
},
{
"name": "CSS",
"bytes": "2989"
},
{
"name": "PHP",
"bytes": "138658"
}
],
"symlink_target": ""
} |
#ifndef ROPUFU_SETTLERS_ONLINE_BATTLE_SKILL_HPP_INCLUDED
#define ROPUFU_SETTLERS_ONLINE_BATTLE_SKILL_HPP_INCLUDED
#include <ropufu/enum_array.hpp>
#include <cstddef> // std::size_t
#include <string> // std::string, std::to_string
#include <type_traits> // std::underlying_type_t
namespace ropufu::settlers_online
{
/** @brief Traits that some units may have that modify the course of the entire battle.
* @remark Used internally as an indexer for \c enum_array, so don't go too high or negative.
**/
enum struct battle_skill : char
{
none = 0,
juggernaut = 1, // Increases the general's (faction: general) attack damage by 20/40/60. These attacks have a 33/66/100% chance of dealing splash damage.
garrison_annex = 2, // Increases the unit capacity (faction: general) by 5/10/15.
lightning_slash = 3, // The general (faction: general) attacks twice per round. That second attack's initiative is \c last_strike.
unstoppable_charge = 4, // Increases the maximum attack damage of your swift units (faction: cavalry) by 1/2/3 and their attacks have a 33/66/100% chance of dealing splash damage.
weekly_maintenance = 5, // Increases the attack damage of your heavy units (faction: artillery) by 10/20/30.
master_planner = 6, // Adds 10% to this army's accuracy.
battle_frenzy = 7, // Increases the attack damage of this army by 10/20/30% for every combat round past the first.
rapid_fire = 8, // Increases the maximum attack damage of your Bowmen by 5/10/15.
sniper_training = 9, // Increases your Longbowmen's and regular Marksmen's minimum attack damage by 45/85/130% and the maximum by 5/10/15%.
cleave = 10, // Increases the attack damage of Elite Soldiers by 4/8/12 and their attacks have a 33/66/100% chance of dealing splash damage.
fast_learner = 11, // Increases the XP gained from enemy units defeated by this army by 10/20/30%.
overrun = 12 // Decreases the HP of enemy bosses by 8/16/25%.
}; // struct battle_skill
} // namespace ropufu::settlers_online
namespace std
{
std::string to_string(ropufu::settlers_online::battle_skill x) noexcept
{
using argument_type = ropufu::settlers_online::battle_skill;
switch (x)
{
case argument_type::none: return "none";
case argument_type::juggernaut: return "juggernaut";
case argument_type::garrison_annex: return "garrison annex";
case argument_type::lightning_slash: return "lightning slash";
case argument_type::unstoppable_charge: return "unstoppable charge";
case argument_type::weekly_maintenance: return "weekly maintenance";
case argument_type::master_planner: return "master planner";
case argument_type::battle_frenzy: return "battle frenzy";
case argument_type::rapid_fire: return "rapid fire";
case argument_type::sniper_training: return "sniper training";
case argument_type::cleave: return "cleave";
case argument_type::fast_learner: return "fast learner";
case argument_type::overrun: return "overrun";
default: return "unknown <battle_skill> " + std::to_string(static_cast<std::size_t>(x));
} // switch (...)
} // to_string(...)
} // namespace std
namespace ropufu::aftermath::detail
{
/** Mark \c battle_skill as suitable for \c enum_array storage. */
template <>
struct enum_array_keys<ropufu::settlers_online::battle_skill>
{
using underlying_type = std::underlying_type_t<ropufu::settlers_online::battle_skill>;
static constexpr underlying_type first_index = 0;
static constexpr underlying_type past_the_last_index = 13;
}; // struct enum_array_keys<...>
template <>
struct enum_parser<ropufu::settlers_online::battle_skill>
{
using enum_type = ropufu::settlers_online::battle_skill;
static std::string to_string(const enum_type& from) noexcept { return std::to_string(from); }
static bool try_parse(const std::string& from, enum_type& to) noexcept
{
if (from == "none") { to = enum_type::none; return true; }
if (from == "juggernaut") { to = enum_type::juggernaut; return true; }
if (from == "garrison annex") { to = enum_type::garrison_annex; return true; }
if (from == "lightning slash") { to = enum_type::lightning_slash; return true; }
if (from == "unstoppable charge") { to = enum_type::unstoppable_charge; return true; }
if (from == "weekly maintenance") { to = enum_type::weekly_maintenance; return true; }
if (from == "master planner") { to = enum_type::master_planner; return true; }
if (from == "battle frenzy") { to = enum_type::battle_frenzy; return true; }
if (from == "rapid fire") { to = enum_type::rapid_fire; return true; }
if (from == "sniper training") { to = enum_type::sniper_training; return true; }
if (from == "cleave") { to = enum_type::cleave; return true; }
if (from == "fast learner") { to = enum_type::fast_learner; return true; }
if (from == "overrun") { to = enum_type::overrun; return true; }
return false;
} // try_parse(...)
}; // struct enum_parser<...>
} // namespace ropufu::aftermath::detail
#endif // ROPUFU_SETTLERS_ONLINE_BATTLE_SKILL_HPP_INCLUDED
| {
"content_hash": "4d4eb56b3addf17934b1f2967c39053a",
"timestamp": "",
"source": "github",
"line_count": 97,
"max_line_length": 187,
"avg_line_length": 57.22680412371134,
"alnum_prop": 0.6350207169879301,
"repo_name": "ropufu/settlers_online",
"id": "25f1c519048800cf32ab6ca05dcc6b6f6555e7f7",
"size": "5551",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/settlers_online/enums/battle_skill.hpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "684"
},
{
"name": "C#",
"bytes": "284336"
},
{
"name": "C++",
"bytes": "437094"
},
{
"name": "Makefile",
"bytes": "801"
}
],
"symlink_target": ""
} |
%% test_surrogate
% lf_file = '/home-new/chrapkpk/Documents/projects/brain-modelling/analysis/pdc-analysis/output/std-s03-10/aal-coarse-19-outer-nocer-plus2/lf-sources-ch12-trials100-samplesall-normallchannels-envno/MCMTLOCCD_TWL4-T60-C12-P3-lambda=0.9900-gamma=1.000e-03.mat';
nchannels = 12;
norder = 3;
order_est = norder;
lambda = 0.99;
gamma = 1;
process_version = 3;
switch process_version
case 2
nsamples = 3000;
ntrials = 40;
vrc_type_params = {'time',nsamples,'order',norder};
case 3
nsamples = 358;
ntrials = 5;
vrc_type_params = {};
end
%% set up vrc
vrc_type = 'vrc-cp-ch2-coupling2-rnd';
vrc_gen = VARGenerator(vrc_type, nchannels, 'version', process_version);
if ~vrc_gen.hasprocess
vrc_gen.configure(vrc_type_params{:});
end
data_vrc = vrc_gen.generate('ntrials',ntrials);
check_data = true;
if check_data
figure;
for i=1:ntrials
hold off
plot(data_vrc.signal(:,:,i)');
prompt = 'hit any key to continue, q to quit';
resp = input(prompt,'s');
if isequal(lower(resp),'q')
break;
end
end
end
% vrc_data = loadfile(vrc_gen.get_file());
vrc_data_file = vrc_gen.get_file();
%% set up data
[~,exp_name,~] = fileparts(vrc_data_file);
outdir = 'output';
file_data = fullfile(outdir,exp_name,'source_data.mat');
if ~exist(file_data,'file')
vrc_data = loadfile(vrc_data_file);
save_parfor(file_data, vrc_data.signal);
end
%% set up filter
filter = MCMTLOCCD_TWL4(nchannels,norder,ntrials,...
'lambda',lambda,'gamma',gamma);
% filter results are dependent on all input file parameters
lf_files = run_lattice_filter(...
file_data,...
'basedir',outdir,...
'outdir',exp_name,...
'filters', {filter},...
'warmup',{'noise','data'},...
'force',false,...
'verbosity',0,...
'tracefields',{'Kf','Kb','Rf','ferror'},...
'plot_pdc', false);
% select pdc params
downsample_by = 4;
pdc_params = {...
'metric','diag',...
'downsample',downsample_by,...
};
pdc_files = rc2pdc_dynamic_from_lf_files(lf_files,'params',pdc_params);
%% pdc_surrogate
file_pdc_sig = pdc_surrogate(lf_files{1},...
'null_mode','estimate_ind_channels',...
'data_file',file_data,...
'nresamples',10,'alpha',0.05,'pdc_params',pdc_params);
% temp = loadfile(file_pdc_sig);
% temp2 = [];
% temp2.pdc = temp;
% save_parfor(file_pdc_sig,temp2);
%% plot significance
view_sig_obj = ViewPDC('fs',1,'outdir','data','w',[0 0.5]);
view_sig_obj.file_pdc = file_pdc_sig;
directions = {'outgoing','incoming'};
for direc=1:length(directions)
for ch=1:nchannels
created = view_sig_obj.plot_seed(ch,...
'direction',directions{direc},...
'threshold_mode','numeric',...
'threshold',0.01,...
'vertlines',[0 0.5]);
if created
view_sig_obj.save_plot('save',true,'engine','matlab');
end
close(gcf);
end
end
%%
params_plot_seed = {};
% params_plot_seed{1} = {'threshold',0.2};
params_plot_seed{1} = {'threshold_mode','significance'};
% params_plot_seed{2} = {'threshold_mode','significance_alpha'};
view_obj = ViewPDC('fs',1,'outdir','data','w',[0 0.5]);
view_obj.file_pdc = pdc_files{1};
view_obj.file_pdc_sig = file_pdc_sig;
directions = {'outgoing','incoming'};
for direc=1:length(directions)
for ch=1:nchannels
for idx_param=1:length(params_plot_seed)
params_plot_seed_cur = params_plot_seed{idx_param};
created = view_obj.plot_seed(ch,...
'direction',directions{direc},...
params_plot_seed_cur{:},...
'vertlines',[0 0.5]);
if created
view_obj.save_plot('save',true,'engine','matlab');
end
close(gcf);
end
end
end
| {
"content_hash": "9d5da27005250adcd2e1af4f85617745",
"timestamp": "",
"source": "github",
"line_count": 145,
"max_line_length": 259,
"avg_line_length": 26.813793103448276,
"alnum_prop": 0.5938786008230452,
"repo_name": "pchrapka/brain-modelling",
"id": "f203163c326303e821a19a8203261f6ba64bdd13",
"size": "3888",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "analysis/pdc-analysis/test_bootstrap.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Jupyter Notebook",
"bytes": "2265630"
},
{
"name": "M",
"bytes": "2270"
},
{
"name": "MATLAB",
"bytes": "1750479"
},
{
"name": "Makefile",
"bytes": "305"
},
{
"name": "Objective-C",
"bytes": "1122"
},
{
"name": "Shell",
"bytes": "45091"
}
],
"symlink_target": ""
} |
package com.datastax.oss.driver.core.cql;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.timeout;
import static org.mockito.Mockito.verify;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.Appender;
import com.datastax.oss.driver.api.core.CqlSession;
import com.datastax.oss.driver.api.core.config.DefaultDriverOption;
import com.datastax.oss.driver.api.core.cql.ExecutionInfo;
import com.datastax.oss.driver.api.core.cql.ResultSet;
import com.datastax.oss.driver.api.core.cql.SimpleStatement;
import com.datastax.oss.driver.api.core.cql.Statement;
import com.datastax.oss.driver.api.testinfra.CassandraRequirement;
import com.datastax.oss.driver.api.testinfra.ccm.CustomCcmRule;
import com.datastax.oss.driver.api.testinfra.session.SessionRule;
import com.datastax.oss.driver.api.testinfra.session.SessionUtils;
import com.datastax.oss.driver.internal.core.cql.CqlRequestHandler;
import com.datastax.oss.driver.internal.core.tracker.RequestLogger;
import com.google.common.base.Strings;
import java.util.List;
import java.util.stream.Collectors;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.RuleChain;
import org.junit.rules.TestRule;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.slf4j.LoggerFactory;
@RunWith(MockitoJUnitRunner.class)
public class ExecutionInfoWarningsIT {
private static final String KEY = "test";
private CustomCcmRule ccmRule =
new CustomCcmRule.Builder()
// set the warn threshold to 5Kb (default is 64Kb in newer versions)
.withCassandraConfiguration("batch_size_warn_threshold_in_kb", "5")
.build();
private SessionRule<CqlSession> sessionRule =
SessionRule.builder(ccmRule)
.withConfigLoader(
SessionUtils.configLoaderBuilder()
.withInt(DefaultDriverOption.REQUEST_PAGE_SIZE, 20)
.withInt(
DefaultDriverOption.REQUEST_LOGGER_MAX_QUERY_LENGTH,
RequestLogger.DEFAULT_REQUEST_LOGGER_MAX_QUERY_LENGTH)
.startProfile("log-disabled")
.withString(DefaultDriverOption.REQUEST_LOG_WARNINGS, "false")
.build())
.build();
@Rule public TestRule chain = RuleChain.outerRule(ccmRule).around(sessionRule);
@Mock private Appender<ILoggingEvent> appender;
@Captor private ArgumentCaptor<ILoggingEvent> loggingEventCaptor;
private Logger logger;
private Level originalLoggerLevel;
@Before
public void createSchema() {
// table with simple primary key, single cell.
sessionRule
.session()
.execute(
SimpleStatement.builder("CREATE TABLE IF NOT EXISTS test (k int primary key, v text)")
.setExecutionProfile(sessionRule.slowProfile())
.build());
for (int i = 0; i < 100; i++) {
sessionRule
.session()
.execute(
SimpleStatement.builder("INSERT INTO test (k, v) VALUES (?, ?)")
.addPositionalValues(KEY, i)
.build());
}
}
@Before
public void setupLogger() {
logger = (Logger) LoggerFactory.getLogger(CqlRequestHandler.class);
originalLoggerLevel = logger.getLevel();
logger.setLevel(Level.WARN);
logger.addAppender(appender);
}
@After
public void cleanupLogger() {
logger.setLevel(originalLoggerLevel);
logger.detachAppender(appender);
}
@Test
@CassandraRequirement(min = "3.0")
public void should_execute_query_and_log_server_side_warnings() {
final String query = "SELECT count(*) FROM test;";
Statement<?> st = SimpleStatement.builder(query).build();
ResultSet result = sessionRule.session().execute(st);
ExecutionInfo executionInfo = result.getExecutionInfo();
assertThat(executionInfo).isNotNull();
List<String> warnings = executionInfo.getWarnings();
assertThat(warnings).isNotEmpty();
String warning = warnings.get(0);
assertThat(warning).isEqualTo("Aggregation query used without partition key");
// verify the log was generated
verify(appender, timeout(500).times(1)).doAppend(loggingEventCaptor.capture());
assertThat(loggingEventCaptor.getValue().getMessage()).isNotNull();
String logMessage = loggingEventCaptor.getValue().getFormattedMessage();
assertThat(logMessage)
.startsWith(
"Query '[0 values] "
+ query
+ "' generated server side warning(s): Aggregation query used without partition key");
}
@Test
@CassandraRequirement(min = "3.0")
public void should_execute_query_and_not_log_server_side_warnings() {
final String query = "SELECT count(*) FROM test;";
Statement<?> st =
SimpleStatement.builder(query).setExecutionProfileName("log-disabled").build();
ResultSet result = sessionRule.session().execute(st);
ExecutionInfo executionInfo = result.getExecutionInfo();
assertThat(executionInfo).isNotNull();
List<String> warnings = executionInfo.getWarnings();
assertThat(warnings).isNotEmpty();
String warning = warnings.get(0);
assertThat(warning).isEqualTo("Aggregation query used without partition key");
// verify the log was NOT generated
verify(appender, timeout(500).times(0)).doAppend(loggingEventCaptor.capture());
}
@Test
@CassandraRequirement(min = "2.2")
public void should_expose_warnings_on_execution_info() {
// the default batch size warn threshold is 5 * 1024 bytes, but after CASSANDRA-10876 there must
// be multiple mutations in a batch to trigger this warning so the batch includes 2 different
// inserts.
final String query =
String.format(
"BEGIN UNLOGGED BATCH\n"
+ "INSERT INTO test (k, v) VALUES (1, '%s')\n"
+ "INSERT INTO test (k, v) VALUES (2, '%s')\n"
+ "APPLY BATCH",
Strings.repeat("1", 2 * 1024), Strings.repeat("1", 3 * 1024));
Statement<?> st = SimpleStatement.builder(query).build();
ResultSet result = sessionRule.session().execute(st);
ExecutionInfo executionInfo = result.getExecutionInfo();
assertThat(executionInfo).isNotNull();
List<String> warnings = executionInfo.getWarnings();
assertThat(warnings).isNotEmpty();
// verify the log was generated
verify(appender, timeout(500).atLeast(1)).doAppend(loggingEventCaptor.capture());
List<String> logMessages =
loggingEventCaptor.getAllValues().stream()
.map(ILoggingEvent::getFormattedMessage)
.collect(Collectors.toList());
assertThat(logMessages)
.anySatisfy(
logMessage ->
assertThat(logMessage)
.startsWith("Query '")
// different versiosns of Cassandra produce slightly different formated logs
// the .contains() below verify the common bits
.contains(
query.substring(0, RequestLogger.DEFAULT_REQUEST_LOGGER_MAX_QUERY_LENGTH))
.contains("' generated server side warning(s): ")
.contains("Batch")
.contains("for")
.contains(String.format("%s.test", sessionRule.keyspace().asCql(true)))
.contains("is of size")
.containsPattern("exceeding specified .*threshold"));
}
}
| {
"content_hash": "9af1a37c5ab2e72d240e5a07dfa2f65f",
"timestamp": "",
"source": "github",
"line_count": 187,
"max_line_length": 102,
"avg_line_length": 41.07486631016043,
"alnum_prop": 0.6795990105455019,
"repo_name": "datastax/java-driver",
"id": "e3648c93424639f688b5b830f4bda7c2547ca8de",
"size": "8269",
"binary": false,
"copies": "1",
"ref": "refs/heads/4.x",
"path": "integration-tests/src/test/java/com/datastax/oss/driver/core/cql/ExecutionInfoWarningsIT.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "9423701"
},
{
"name": "Scala",
"bytes": "1509"
},
{
"name": "Shell",
"bytes": "10722"
}
],
"symlink_target": ""
} |
<header class="banner navbar" role="banner">
<div class="wrapper wrapper--wide">
<div class="banner__inner">
<div class="navbar__header">
<label class="navbar__toggle" for="nav__toggle"><i class="ion ion-navicon"></i></label>
<a class="navbar__brand" href="<?php echo esc_url(home_url('/')); ?>"><?php bloginfo('name'); ?></a>
<div class="headaside">
<?php dynamic_sidebar('sidebar-header'); ?>
</div>
</div>
<input type="checkbox" id="nav__toggle">
<nav class="navbar__navigation" role="navigation">
<?php
if (has_nav_menu('primary_navigation')) :
wp_nav_menu(array('theme_location' => 'primary_navigation', 'walker' => new Roots_Nav_Walker(), 'menu_class' => 'nav nav--main'));
endif;
?>
</nav>
</div>
</div>
</header> | {
"content_hash": "785b287e4571bbc67b15716a8936bbb9",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 140,
"avg_line_length": 44.57142857142857,
"alnum_prop": 0.5032051282051282,
"repo_name": "ceto/nielstorp",
"id": "862c34fb0f5d0ce403cbb230f9a9750feda198b3",
"size": "936",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "templates/header.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "297892"
},
{
"name": "JavaScript",
"bytes": "450563"
},
{
"name": "PHP",
"bytes": "375023"
}
],
"symlink_target": ""
} |
package org.spdx.rdfparser.model;
import java.util.List;
import java.util.Map;
import com.google.common.collect.ImmutableMap;
import org.spdx.rdfparser.IModelContainer;
import org.spdx.rdfparser.InvalidSPDXAnalysisException;
import org.spdx.rdfparser.SpdxRdfConstants;
import org.spdx.rdfparser.SpdxVerificationHelper;
import com.google.common.base.Objects;
import com.google.common.collect.Lists;
import org.apache.jena.graph.Node;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* An Annotation is a comment on an SpdxItem by an agent.
* @author Gary O'Neall
*
*/
public class Annotation extends RdfModelObject implements Comparable<Annotation> {
static final Logger logger = LoggerFactory.getLogger(RdfModelObject.class.getName());
public enum AnnotationType {
annotationType_other,
annotationType_review;
public String getTag(){
return ANNOTATION_TYPE_TO_TAG.get(this);
}
public static AnnotationType fromTag(String tag){
return TAG_TO_ANNOTATION_TYPE.get(tag);
}
};
@Deprecated
public static final Map<AnnotationType, String> ANNOTATION_TYPE_TO_TAG;
@Deprecated
public static final Map<String, AnnotationType> TAG_TO_ANNOTATION_TYPE;
static {
ImmutableMap.Builder<String, AnnotationType> tagToAnnotationTypeBuilder = ImmutableMap.builder();
ImmutableMap.Builder<AnnotationType, String> annoationTypeToTagBuilder = ImmutableMap.builder();
annoationTypeToTagBuilder.put(AnnotationType.annotationType_other, "OTHER");
tagToAnnotationTypeBuilder.put("OTHER", AnnotationType.annotationType_other);
annoationTypeToTagBuilder.put(AnnotationType.annotationType_review, "REVIEW");
tagToAnnotationTypeBuilder.put("REVIEW", AnnotationType.annotationType_review);
TAG_TO_ANNOTATION_TYPE = tagToAnnotationTypeBuilder.build();
ANNOTATION_TYPE_TO_TAG = annoationTypeToTagBuilder.build();
}
AnnotationType annotationType;
String annotator;
String comment;
String annotationDate;
public Annotation(String annotator, AnnotationType annotationType, String date,
String comment) {
super();
this.annotator = annotator;
this.annotationType = annotationType;
this.annotationDate = date;
this.comment = comment;
}
public Annotation(IModelContainer modelContainer, Node annotationNode) throws InvalidSPDXAnalysisException {
super(modelContainer, annotationNode);
getPropertiesFromModel();
}
/* (non-Javadoc)
* @see org.spdx.rdfparser.model.RdfModelObject#getPropertiesFromModel()
*/
@Override
public void getPropertiesFromModel() throws InvalidSPDXAnalysisException {
//annotator
this.annotator = findSinglePropertyValue(SpdxRdfConstants.SPDX_NAMESPACE, SpdxRdfConstants.PROP_ANNOTATOR);
//Date
this.annotationDate = findSinglePropertyValue(SpdxRdfConstants.SPDX_NAMESPACE, SpdxRdfConstants.PROP_ANNOTATION_DATE);
//Comment
this.comment = findSinglePropertyValue(SpdxRdfConstants.RDFS_NAMESPACE, SpdxRdfConstants.RDFS_PROP_COMMENT);
//Annotation type
String annotationTypeUri = findUriPropertyValue(SpdxRdfConstants.SPDX_NAMESPACE,
SpdxRdfConstants.PROP_ANNOTATION_TYPE);
if (annotationTypeUri != null) {
String sAnnotationType = annotationTypeUri.substring(SpdxRdfConstants.SPDX_NAMESPACE.length());
try {
this.annotationType = AnnotationType.valueOf(sAnnotationType);
} catch (Exception ex) {
logger.error("Invalid annotation type found in the model: "+sAnnotationType);
throw(new InvalidSPDXAnalysisException("Invalid annotation type: "+sAnnotationType));
}
}
}
@Override
public Resource getType(Model model) {
return model.createResource(SpdxRdfConstants.SPDX_NAMESPACE + SpdxRdfConstants.CLASS_ANNOTATION);
}
/**
* Populate the model from the properties
* @throws InvalidSPDXAnalysisException
*/
@Override
public void populateModel() throws InvalidSPDXAnalysisException {
if (annotationType != null) {
setPropertyUriValue(SpdxRdfConstants.SPDX_NAMESPACE,
SpdxRdfConstants.PROP_ANNOTATION_TYPE,
SpdxRdfConstants.SPDX_NAMESPACE + this.annotationType.toString());
}
if (annotator != null) {
setPropertyValue(SpdxRdfConstants.SPDX_NAMESPACE, SpdxRdfConstants.PROP_ANNOTATOR, annotator);
}
if (comment != null) {
setPropertyValue(SpdxRdfConstants.RDFS_NAMESPACE, SpdxRdfConstants.RDFS_PROP_COMMENT, comment);
}
if (annotationDate != null) {
setPropertyValue(SpdxRdfConstants.SPDX_NAMESPACE, SpdxRdfConstants.PROP_ANNOTATION_DATE, annotationDate);
}
}
/* (non-Javadoc)
* @see org.spdx.rdfparser.model.IRdfModel#verify()
*/
@Override
public List<String> verify() {
List<String> retval = Lists.newArrayList();
if (annotationType == null) {
retval.add("Missing annotationtype for Annotation");
}
if (annotator == null) {
retval.add("Missing annotator for Annotation");
} else {
String v = SpdxVerificationHelper.verifyAnnotator(this.annotator);
if (v != null && !v.isEmpty()) {
retval.add(v + ":" + this.annotator);
}
}
if (comment == null) {
retval.add("Missing comment for Annotation");
}
if (annotationDate == null) {
retval.add("Missing date for Annotation");
} else {
String dateVerify = SpdxVerificationHelper.verifyDate(annotationDate);
if (dateVerify != null && !dateVerify.isEmpty()) {
retval.add(dateVerify);
}
}
return retval;
}
/**
* @return the annotationType
*/
public AnnotationType getAnnotationType() {
if (this.resource != null && this.refreshOnGet) {
String annotationTypeUri = findUriPropertyValue(SpdxRdfConstants.SPDX_NAMESPACE,
SpdxRdfConstants.PROP_ANNOTATION_TYPE);
if (annotationTypeUri != null) {
String sAnnotationType = annotationTypeUri.substring(SpdxRdfConstants.SPDX_NAMESPACE.length());
try {
this.annotationType = AnnotationType.valueOf(sAnnotationType);
} catch (Exception ex) {
logger.error("Invalid annotation type found in the model - "+sAnnotationType);
}
}
}
return annotationType;
}
/**
* @param annotationType the annotationType to set
* @throws InvalidSPDXAnalysisException
*/
public void setAnnotationType(AnnotationType annotationType) throws InvalidSPDXAnalysisException {
this.annotationType = annotationType;
if (annotationType != null) {
setPropertyUriValue(SpdxRdfConstants.SPDX_NAMESPACE,
SpdxRdfConstants.PROP_ANNOTATION_TYPE,
SpdxRdfConstants.SPDX_NAMESPACE + annotationType.toString());
} else {
removePropertyValue(SpdxRdfConstants.SPDX_NAMESPACE, SpdxRdfConstants.PROP_ANNOTATION_TYPE);
}
}
/**
* @return the annotator
*/
public String getAnnotator() {
if (this.resource != null && this.refreshOnGet) {
this.annotator = findSinglePropertyValue(SpdxRdfConstants.SPDX_NAMESPACE, SpdxRdfConstants.PROP_ANNOTATOR);
}
return annotator;
}
/**
* @param annotator the annotator to set
*/
public void setAnnotator(String annotator) {
this.annotator = annotator;
setPropertyValue(SpdxRdfConstants.SPDX_NAMESPACE, SpdxRdfConstants.PROP_ANNOTATOR, annotator);
}
/**
* @return the comment
*/
public String getComment() {
if (this.resource != null && this.refreshOnGet) {
this.comment = findSinglePropertyValue(SpdxRdfConstants.RDFS_NAMESPACE, SpdxRdfConstants.RDFS_PROP_COMMENT);
}
return comment;
}
/**
* @param comment the comment to set
*/
public void setComment(String comment) {
this.comment = comment;
setPropertyValue(SpdxRdfConstants.RDFS_NAMESPACE, SpdxRdfConstants.RDFS_PROP_COMMENT, comment);
}
/**
* @return the date
*/
public String getAnnotationDate() {
if (this.resource != null && this.refreshOnGet) {
annotationDate = findSinglePropertyValue(SpdxRdfConstants.SPDX_NAMESPACE, SpdxRdfConstants.PROP_ANNOTATION_DATE);
}
return annotationDate;
}
/**
* @param date the date to set
* @throws InvalidSPDXAnalysisException
*/
public void setAnnotationDate(String date) throws InvalidSPDXAnalysisException {
this.annotationDate = date;
if (date != null) {
String dateVerify = SpdxVerificationHelper.verifyDate(date);
if (dateVerify != null && !dateVerify.isEmpty()) {
throw(new InvalidSPDXAnalysisException("Invalid date format: "+dateVerify));
}
setPropertyValue(SpdxRdfConstants.SPDX_NAMESPACE, SpdxRdfConstants.PROP_ANNOTATION_DATE, date);
} else {
removePropertyValue(SpdxRdfConstants.SPDX_NAMESPACE, SpdxRdfConstants.PROP_ANNOTATION_DATE);
}
}
/* (non-Javadoc)
* @see org.spdx.rdfparser.model.RdfModelObject#getUri(org.spdx.rdfparser.IModelContainer)
*/
@Override
public String getUri(IModelContainer modelContainer) {
// We will just use anonymous nodes for Annotations
return null;
}
@Override
public Annotation clone() {
return new Annotation(this.annotator, this.annotationType, this.annotationDate,
this.comment);
}
/* (non-Javadoc)
* @see org.spdx.rdfparser.model.RdfModelObject#equivalent(org.spdx.rdfparser.model.RdfModelObject)
*/
@Override
public boolean equivalent(IRdfModel o) {
if (o == this) {
return true;
}
if (!(o instanceof Annotation)) {
return false;
}
Annotation comp = (Annotation)o;
return (Objects.equal(getAnnotator(), comp.getAnnotator()) &&
Objects.equal(getAnnotationType(), comp.getAnnotationType()) &&
Objects.equal(getComment(), comp.getComment()) &&
Objects.equal(getAnnotationDate(), comp.getAnnotationDate()));
}
/**
* @return The tag value of the annotation type
*/
public String getAnnotationTypeTag() {
return this.annotationType.getTag();
}
/* (non-Javadoc)
* @see java.lang.Comparable#compareTo(java.lang.Object)
*/
@Override
public int compareTo(Annotation o) {
if (o == null) {
return 1;
}
if (o.getAnnotationDate() == null) {
if (this.annotationDate != null) {
return 1;
}
}
if (this.annotationDate == null) {
return -1;
}
int retval = this.annotationDate.compareTo(o.getAnnotationDate());
if (retval != 0) {
return retval;
}
if (o.getAnnotator() == null) {
if (this.annotator != null) {
return 1;
}
}
if (this.annotator == null) {
return -1;
}
retval = this.annotator.compareToIgnoreCase(o.getAnnotator());
if (retval != 0) {
return retval;
}
if (o.getAnnotationType() == null) {
if (this.annotationType != null) {
return 1;
}
}
if (this.annotationType == null) {
return -1;
}
return this.annotationType.compareTo(o.getAnnotationType());
}
}
| {
"content_hash": "350a23c61dfd8115cf328081287157bb",
"timestamp": "",
"source": "github",
"line_count": 346,
"max_line_length": 120,
"avg_line_length": 30.358381502890172,
"alnum_prop": 0.7351485148514851,
"repo_name": "spdx/tools",
"id": "aae69d1cadca101e22b9df81e43e94bf65a66e17",
"size": "11131",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/org/spdx/rdfparser/model/Annotation.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "GAP",
"bytes": "2056"
},
{
"name": "HTML",
"bytes": "24821"
},
{
"name": "Java",
"bytes": "3412310"
}
],
"symlink_target": ""
} |
<!doctype html>
<html ng-app="cjd-countries">
<head>
<title>Countries</title>
<link href="app.css" rel="stylesheet">
</head>
<body>
<div ng-controller="CountryController as country">
<header>
<h1>List of Countries</h1>
<label class="filter-country"><input ng-model="searchText.name.common" type="text" placeholder="Filter by country..."></label>
<label>Landlocked
<select class="filter-landlocked" ng-model="filterItem.landlocked"
ng-options="item.value for item in filterOptions.landlocked"></select>
</label>
</header>
<div class="container">
<div class="country" ng-class="{'landlocked' : country.landlocked}" ng-repeat="country in countries | filter:searchText | filter:isLandlocked">
<country-block></country-block>
</div>
</div>
</div>
<script src="lib/angular.min.js"></script>
<script src="app.js"></script>
</body>
</html> | {
"content_hash": "0ae335fe4eef20d3648b78a02dee2022",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 149,
"avg_line_length": 36.61538461538461,
"alnum_prop": 0.6334033613445378,
"repo_name": "cdaley78/countries-angular-demo",
"id": "242cacdb5cc0a6e245a2c3509b770b2972fdc82e",
"size": "952",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "dist/index.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2322"
},
{
"name": "HTML",
"bytes": "1684"
},
{
"name": "JavaScript",
"bytes": "1927"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_72) on Wed May 13 11:47:54 EDT 2015 -->
<title>Uses of Class org.apache.cassandra.db.AtomicSortedColumns (apache-cassandra API)</title>
<meta name="date" content="2015-05-13">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.apache.cassandra.db.AtomicSortedColumns (apache-cassandra API)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../org/apache/cassandra/db/AtomicSortedColumns.html" title="class in org.apache.cassandra.db">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/apache/cassandra/db/class-use/AtomicSortedColumns.html" target="_top">Frames</a></li>
<li><a href="AtomicSortedColumns.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class org.apache.cassandra.db.AtomicSortedColumns" class="title">Uses of Class<br>org.apache.cassandra.db.AtomicSortedColumns</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../org/apache/cassandra/db/AtomicSortedColumns.html" title="class in org.apache.cassandra.db">AtomicSortedColumns</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#org.apache.cassandra.db">org.apache.cassandra.db</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="org.apache.cassandra.db">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../org/apache/cassandra/db/AtomicSortedColumns.html" title="class in org.apache.cassandra.db">AtomicSortedColumns</a> in <a href="../../../../../org/apache/cassandra/db/package-summary.html">org.apache.cassandra.db</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing fields, and an explanation">
<caption><span>Fields in <a href="../../../../../org/apache/cassandra/db/package-summary.html">org.apache.cassandra.db</a> with type parameters of type <a href="../../../../../org/apache/cassandra/db/AtomicSortedColumns.html" title="class in org.apache.cassandra.db">AtomicSortedColumns</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Field and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>static <a href="../../../../../org/apache/cassandra/db/ColumnFamily.Factory.html" title="class in org.apache.cassandra.db">ColumnFamily.Factory</a><<a href="../../../../../org/apache/cassandra/db/AtomicSortedColumns.html" title="class in org.apache.cassandra.db">AtomicSortedColumns</a>></code></td>
<td class="colLast"><span class="strong">AtomicSortedColumns.</span><code><strong><a href="../../../../../org/apache/cassandra/db/AtomicSortedColumns.html#factory">factory</a></strong></code> </td>
</tr>
</tbody>
</table>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../org/apache/cassandra/db/package-summary.html">org.apache.cassandra.db</a> that return types with arguments of type <a href="../../../../../org/apache/cassandra/db/AtomicSortedColumns.html" title="class in org.apache.cassandra.db">AtomicSortedColumns</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>java.util.Iterator<java.util.Map.Entry<<a href="../../../../../org/apache/cassandra/db/DecoratedKey.html" title="class in org.apache.cassandra.db">DecoratedKey</a>,<a href="../../../../../org/apache/cassandra/db/AtomicSortedColumns.html" title="class in org.apache.cassandra.db">AtomicSortedColumns</a>>></code></td>
<td class="colLast"><span class="strong">Memtable.</span><code><strong><a href="../../../../../org/apache/cassandra/db/Memtable.html#getEntryIterator(org.apache.cassandra.db.RowPosition,%20org.apache.cassandra.db.RowPosition)">getEntryIterator</a></strong>(<a href="../../../../../org/apache/cassandra/db/RowPosition.html" title="class in org.apache.cassandra.db">RowPosition</a> startWith,
<a href="../../../../../org/apache/cassandra/db/RowPosition.html" title="class in org.apache.cassandra.db">RowPosition</a> stopAt)</code> </td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../org/apache/cassandra/db/AtomicSortedColumns.html" title="class in org.apache.cassandra.db">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/apache/cassandra/db/class-use/AtomicSortedColumns.html" target="_top">Frames</a></li>
<li><a href="AtomicSortedColumns.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2015 The Apache Software Foundation</small></p>
</body>
</html>
| {
"content_hash": "4baf69574222c1ab0b9088495981c963",
"timestamp": "",
"source": "github",
"line_count": 170,
"max_line_length": 395,
"avg_line_length": 47.6764705882353,
"alnum_prop": 0.6521900061690314,
"repo_name": "anuragkapur/cassandra-2.1.2-ak-skynet",
"id": "804850a618f8c0748844da35c5d02021d766d59c",
"size": "8105",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "apache-cassandra-2.0.15/javadoc/org/apache/cassandra/db/class-use/AtomicSortedColumns.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "59670"
},
{
"name": "PowerShell",
"bytes": "37758"
},
{
"name": "Python",
"bytes": "622552"
},
{
"name": "Shell",
"bytes": "100474"
},
{
"name": "Thrift",
"bytes": "78926"
}
],
"symlink_target": ""
} |
using System.Collections;
using System.Collections.Specialized;
using System.Windows.Input;
using Xamarin.Forms;
namespace XFExtensions.Controls.Abstractions
{
public class SimpleList : StackLayout
{
public SimpleList()
{
// default values
TextColor = Color.Black;
ItemHeightRequest = 22;
}
public static readonly BindableProperty ItemsSourceProperty = BindableProperty.Create<SimpleList, IEnumerable>(
p => p.ItemsSource,
default(IEnumerable),
BindingMode.TwoWay,
propertyChanged: ItemsSourceChanged);
public IEnumerable ItemsSource
{
get { return (IEnumerable) GetValue(ItemsSourceProperty); }
set { SetValue(ItemsSourceProperty, value); }
}
private static void ItemsSourceChanged(BindableObject bindable, IEnumerable oldvalue, IEnumerable newvalue)
{
var list = (SimpleList) bindable;
list.Repopulate();
var colChange = list.ItemsSource as INotifyCollectionChanged;
if (colChange != null)
colChange.CollectionChanged += list.colChange_CollectionChanged;
}
public static readonly BindableProperty ItemTemplateProperty = BindableProperty.Create<SimpleList, DataTemplate>(
p => p.ItemTemplate,
default(DataTemplate),
BindingMode.Default,
propertyChanged: ItemTemplateChanged);
public DataTemplate ItemTemplate
{
get { return (DataTemplate)GetValue(ItemTemplateProperty); }
set { SetValue(ItemTemplateProperty, value); }
}
private static void ItemTemplateChanged(BindableObject bindable, DataTemplate oldvalue, DataTemplate newvalue)
{
var list = (SimpleList)bindable;
list.Repopulate();
}
public static readonly BindableProperty ItemSelectedCommandProperty = BindableProperty
.Create<SimpleList, ICommand>(
p => p.ItemSelectedCommand,
default(ICommand),
BindingMode.Default);
public ICommand ItemSelectedCommand
{
get { return (ICommand) GetValue(ItemSelectedCommandProperty); }
set { SetValue(ItemSelectedCommandProperty, value); }
}
public string DisplayMember { get; set; }
public Color TextColor { get; set; }
public int ItemHeightRequest { get; set; }
private void Repopulate()
{
Children.Clear();
if (ItemsSource == null)
return;
// build our own internal command so that we can respond to selected events
// correctly even if the command was set after the items were rendered
var selectedCommand = new Command<object>(o =>
{
if (ItemSelectedCommand != null && ItemSelectedCommand.CanExecute(o))
ItemSelectedCommand.Execute(o);
});
View child;
foreach (var item in ItemsSource)
{
if (ItemTemplate != null)
{
child = ItemTemplate.CreateContent() as View;
if (child == null)
continue;
child.BindingContext = item;
}
else if (!string.IsNullOrEmpty(DisplayMember))
{
child = new Label { BindingContext = item, TextColor = TextColor, HeightRequest = ItemHeightRequest };
child.SetBinding(Label.TextProperty, DisplayMember);
}
else
{
child = new Label { Text = item.ToString(), TextColor = TextColor, HeightRequest = ItemHeightRequest };
}
// add an internal tapped handler
var itemTapped = new TapGestureRecognizer {Command = selectedCommand, CommandParameter = item};
child.GestureRecognizers.Add(itemTapped);
Children.Add(child);
}
}
void colChange_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
Repopulate();
}
}
}
| {
"content_hash": "b8bd17e3975dc01b9f642e8c185511cd",
"timestamp": "",
"source": "github",
"line_count": 122,
"max_line_length": 123,
"avg_line_length": 36.622950819672134,
"alnum_prop": 0.5593106535362579,
"repo_name": "JC-Chris/XFExtensions",
"id": "cbce94835ba77be63d848d1ae5941eac7b73c0f3",
"size": "4470",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "XFExtensions.Controls/XFExtensions.Controls.Abstractions/SimpleList.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "154775"
}
],
"symlink_target": ""
} |
package org.dita.dost.writer;
import org.dita.dost.TestUtils;
import org.dita.dost.util.XMLUtils;
import org.junit.Test;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import static javax.xml.XMLConstants.NULL_NS_URI;
import static org.dita.dost.util.Constants.*;
import static org.junit.Assert.assertEquals;
public class NormalizeFilterTest {
@Test
public void testCascade() throws Exception {
final NormalizeFilter f = new NormalizeFilter();
f.setLogger(new TestUtils.TestLogger());
f.setContentHandler(new DefaultHandler() {
@Override
public void startElement(String uri, String localName,
String qName, Attributes attributes) throws SAXException {
assertEquals(ATTRIBUTE_CASCADE_VALUE_NOMERGE, attributes.getValue(ATTRIBUTE_NAME_CASCADE));
}
});
f.startElement(NULL_NS_URI, MAP_MAP.localName, MAP_MAP.localName, new XMLUtils.AttributesBuilder()
.add(ATTRIBUTE_NAME_CLASS, MAP_MAP.toString()).build());
}
@Test
public void testDomains() throws Exception {
final NormalizeFilter f = new NormalizeFilter();
f.setLogger(new TestUtils.TestLogger());
f.setContentHandler(new DefaultHandler() {
@Override
public void startElement(String uri, String localName,
String qName, Attributes attributes) throws SAXException {
assertEquals("(topic hi-d) (topic ut-d) (topic indexing-d) (topic hazard-d) (topic abbrev-d) (topic pr-d) (topic sw-d) (topic ui-d) a(props audience) a(props deliveryTarget) a(props platform) a(props product) a(props otherprops)",
attributes.getValue(ATTRIBUTE_NAME_DOMAINS));
assertEquals("@props/audience @props/deliveryTarget @props/platform @props/product @props/otherprops",
attributes.getValue(ATTRIBUTE_NAME_SPECIALIZATIONS));
}
});
f.startElement(NULL_NS_URI, TOPIC_TOPIC.localName, TOPIC_TOPIC.localName, new XMLUtils.AttributesBuilder()
.add(ATTRIBUTE_NAME_CLASS, TOPIC_TOPIC.toString())
.add(ATTRIBUTE_NAME_DOMAINS, "(topic hi-d)\n" +
"(topic ut-d)\n" +
"(topic indexing-d)\n" +
"(topic hazard-d)\n" +
"(topic abbrev-d)\n" +
"(topic pr-d)\n" +
"(topic sw-d)\n" +
"(topic ui-d)\n" +
"a(props audience)\n" +
"a(props deliveryTarget)\n" +
"a(props platform)\n" +
"a(props product)\n" +
"a(props otherprops) ")
.build());
}
@Test
public void testSpecializations() throws Exception {
final NormalizeFilter f = new NormalizeFilter();
f.setLogger(new TestUtils.TestLogger());
f.setContentHandler(new DefaultHandler() {
@Override
public void startElement(String uri, String localName,
String qName, Attributes attributes) throws SAXException {
assertEquals("a(props audience) a(props deliveryTarget) a(props platform) a(props product) a(props otherprops)",
attributes.getValue(ATTRIBUTE_NAME_DOMAINS));
assertEquals("@props/audience @props/deliveryTarget @props/platform @props/product @props/otherprops",
attributes.getValue(ATTRIBUTE_NAME_SPECIALIZATIONS));
}
});
f.startElement(NULL_NS_URI, TOPIC_TOPIC.localName, TOPIC_TOPIC.localName, new XMLUtils.AttributesBuilder()
.add(ATTRIBUTE_NAME_CLASS, TOPIC_TOPIC.toString())
.add(ATTRIBUTE_NAME_SPECIALIZATIONS, " @props/audience\n" +
"@props/deliveryTarget\n" +
"@props/platform\n" +
"@props/product\n" +
"@props/otherprops ")
.build());
}
@Test
public void testExistingCascade() throws Exception {
final NormalizeFilter f = new NormalizeFilter();
f.setLogger(new TestUtils.TestLogger());
f.setContentHandler(new DefaultHandler() {
@Override
public void startElement(String uri, String localName,
String qName, Attributes attributes) throws SAXException {
assertEquals(ATTRIBUTE_CASCADE_VALUE_MERGE, attributes.getValue(ATTRIBUTE_NAME_CASCADE));
}
});
f.startElement(NULL_NS_URI, MAP_MAP.localName, MAP_MAP.localName, new XMLUtils.AttributesBuilder()
.add(ATTRIBUTE_NAME_CLASS, MAP_MAP.toString())
.add(ATTRIBUTE_NAME_CASCADE, ATTRIBUTE_CASCADE_VALUE_MERGE).build());
}
}
| {
"content_hash": "3b12f3bda648ea49ecbd5c0dc06fa856",
"timestamp": "",
"source": "github",
"line_count": 104,
"max_line_length": 246,
"avg_line_length": 48.41346153846154,
"alnum_prop": 0.5835153922542204,
"repo_name": "drmacro/dita-ot",
"id": "af092752c935a1452f69be4cf6c46c5130bdb7b2",
"size": "5196",
"binary": false,
"copies": "4",
"ref": "refs/heads/develop",
"path": "src/test/java/org/dita/dost/writer/NormalizeFilterTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "10738"
},
{
"name": "C",
"bytes": "4336"
},
{
"name": "CSS",
"bytes": "60188"
},
{
"name": "HTML",
"bytes": "795861"
},
{
"name": "Java",
"bytes": "2404278"
},
{
"name": "JavaScript",
"bytes": "2246"
},
{
"name": "Shell",
"bytes": "16323"
},
{
"name": "XSLT",
"bytes": "2106965"
}
],
"symlink_target": ""
} |
<div class="container" role="presentation" data-ng-cloak >
<div class="row">
<section data-ng-controller="UserLoggingCtrl" class="signInSection">
<h2>Admin Portal Login</h2>
<a class="btn btn-primary" ng-click="login()">Sign In.</a>
</section>
</div>
</div>
| {
"content_hash": "c281058afcc622e0cef3fa7d50e7dbef",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 70,
"avg_line_length": 31.444444444444443,
"alnum_prop": 0.6431095406360424,
"repo_name": "mb4ms/event-site",
"id": "6fe884b8621d9263b2ba52dd910eb55d9ffd2689",
"size": "283",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/components/admin/userLogging/login.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "197918"
},
{
"name": "HTML",
"bytes": "64757"
},
{
"name": "JavaScript",
"bytes": "193972"
}
],
"symlink_target": ""
} |
require 'compass/import-once/activate'
# Require any additional compass plugins here.
# Set this to the root of your project when deployed:
http_path = "/"
css_dir = "test/"
sass_dir = "_sass/"
images_dir = "images"
javascripts_dir = "javascripts"
# You can select your preferred output style here (can be overridden via the command line):
# output_style = :expanded or :nested or :compact or :compressed
# To enable relative paths to assets via compass helper functions. Uncomment:
# relative_assets = true
# To disable debugging comments that display the original location of your selectors. Uncomment:
# line_comments = false
# If you prefer the indented syntax, you might want to regenerate this
# project again passing --syntax sass, or you can uncomment this:
# preferred_syntax = :sass
# and then run:
# sass-convert -R --from scss --to sass sass scss && rm -rf sass && mv scss sass
| {
"content_hash": "f001382c44d50032c54200a845d5015b",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 96,
"avg_line_length": 35.84,
"alnum_prop": 0.7421875,
"repo_name": "osmlab/basket",
"id": "bf9f5024ad919e484999478cbca3f821275f3fb1",
"size": "896",
"binary": false,
"copies": "1",
"ref": "refs/heads/gh-pages",
"path": "config.rb",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "72419"
},
{
"name": "HTML",
"bytes": "44954"
},
{
"name": "JavaScript",
"bytes": "83375"
},
{
"name": "Ruby",
"bytes": "7874"
}
],
"symlink_target": ""
} |
package com.makotokw.android.circularlistviewsample;
import android.os.Build;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.makotokw.android.widget.CircularListView;
import com.makotokw.android.widget.CircularListViewContentAlignment;
import com.makotokw.android.widget.CircularListViewListener;
public class MainActivity extends Activity {
private CircularListView mCircularListView;
private boolean mIsAdapterDirty = true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mCircularListView = (CircularListView) findViewById(R.id.circularListView);
ArrayAdapter<String> listAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
for (int i = 0; i < 10; i++) {
listAdapter.add(String.format("Item %02d", i));
}
Display display = getWindowManager().getDefaultDisplay();
mCircularListView.setRadius(Math.min(300, display.getWidth() / 2));
mCircularListView.setAdapter(listAdapter);
mCircularListView.scrollFirstItemToCenter();
mCircularListView.setCircularListViewListener(new CircularListViewListener() {
@Override
public void onCircularLayoutFinished(CircularListView circularListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
refreshCircular();
}
});
}
void refreshCircular() {
if (mIsAdapterDirty) {
mCircularListView.scrollFirstItemToCenter();
mIsAdapterDirty = false;
}
TextView centerView = (TextView) mCircularListView.getCentralChild();
if (centerView != null) {
centerView.setTextColor(getResources().getColor(R.color.center_text));
}
for (int i = 0; i < mCircularListView.getChildCount(); i++) {
TextView view = (TextView) mCircularListView.getChildAt(i);
if (view != null && view != centerView) {
view.setTextColor(getResources().getColor(R.color.default_text));
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.align_left:
mCircularListView.setCircularListViewContentAlignment(CircularListViewContentAlignment.Left);
return true;
case R.id.circler:
mCircularListView.setCircularListViewContentAlignment(CircularListViewContentAlignment.None);
return true;
case R.id.align_right:
mCircularListView.setCircularListViewContentAlignment(CircularListViewContentAlignment.Right);
return true;
default:
return false;
}
}
}
| {
"content_hash": "2261019df8690dc0c853cf8296355957",
"timestamp": "",
"source": "github",
"line_count": 92,
"max_line_length": 149,
"avg_line_length": 36.32608695652174,
"alnum_prop": 0.6744464392579294,
"repo_name": "makotokw/AndroidWZCircularListView",
"id": "2cd0f51065a100297ad5774ffee655717f51d855",
"size": "3342",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "CircularListViewSample/src/main/java/com/makotokw/android/circularlistviewsample/MainActivity.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Groovy",
"bytes": "1286"
},
{
"name": "Java",
"bytes": "15416"
},
{
"name": "Shell",
"bytes": "7484"
}
],
"symlink_target": ""
} |
<?php namespace Rtbs\ApiHelper\Exceptions;
class PromoNotFoundException extends \Exception
{
} | {
"content_hash": "505f50c231f084822991662a46c7c057",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 47,
"avg_line_length": 16,
"alnum_prop": 0.8125,
"repo_name": "whytewaters/api-helper-library",
"id": "c7069ce360ff7104d01327b046147cacd8d81dbe",
"size": "96",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Exceptions/PromoNotFoundException.php",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "191602"
}
],
"symlink_target": ""
} |
package com.druid.demo.controller;
import com.druid.demo.model.User;
import com.druid.demo.server.UserServer;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@Api(value="User action cotroller")
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserServer server;
@RequestMapping("/add")
@ApiOperation(notes="Add user",value="Add user",httpMethod="POST")
@ApiImplicitParams({
@ApiImplicitParam(name="username",paramType="query",dataType="string"),
@ApiImplicitParam(name="psw",paramType="query",dataType="string")
})
public String add(User user){
return "hello "+server.add(user);
}
@RequestMapping("/all")
@ApiOperation(notes="Find all users",value="Find users and return count numbers.",httpMethod="GET")
public String find(){
return ""+server.findAll().size();
}
@RequestMapping("/byName")
@ApiOperation(notes="Find all users",value="Find users by name and return result.",httpMethod="GET")
@ApiImplicitParams({
@ApiImplicitParam(name="username",paramType="query",dataType="string"),
})
public String findByName(String username){
return ""+server.findByName(username);
}
}
| {
"content_hash": "a61868642f18349423d8f893fd1387b3",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 101,
"avg_line_length": 32.644444444444446,
"alnum_prop": 0.7692307692307693,
"repo_name": "blueroc2003/ali-druid-demo",
"id": "24fe6d5e156fe7335e5140532baeb737d8a57263",
"size": "1469",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com.druid.demo/controller/UserController.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "38776"
},
{
"name": "Shell",
"bytes": "1320"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "5ab226c8bd08e1367cf9a37ca55cb3f8",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "e29e84f10eb7f7f2a94764e39cbefc2005553da9",
"size": "182",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Rosales/Rosaceae/Potentilla/Potentilla pseudopallens/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;
namespace DEG.ServiceCore.Helpers
{
public class JsonHelper
{
public static string Stringify(object toSerialize)
{
var serializer = new DataContractJsonSerializer(toSerialize.GetType());
string output;
using (var ms = new MemoryStream())
{
serializer.WriteObject(ms, toSerialize);
output = Encoding.UTF8.GetString(ms.ToArray());
}
return output;
}
public static T Parse<T>(string toParse) where T : class
{
var serializer = new DataContractJsonSerializer(typeof (T));
T result;
using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(toParse)))
{
result = serializer.ReadObject(ms) as T;
}
return result;
}
public static bool TryParse<T>(string toParse, out T result) where T : class
{
try
{
result = Parse<T>(toParse);
return true;
}
catch { }
result = default(T);
return false;
}
}
}
| {
"content_hash": "d1bada9872917132b610bedde522570d",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 84,
"avg_line_length": 28.711111111111112,
"alnum_prop": 0.5046439628482973,
"repo_name": "degdigital/DEG.Social",
"id": "410cba2728eefbc17d4429e2534d4032d488e7e5",
"size": "1292",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/DEG.ServiceCore/Helpers/JsonHelper.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "76262"
}
],
"symlink_target": ""
} |
import sqlite3
import os
class PysqliteError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class Pysqlite:
def __init__(self, database_name='', database_file=''):
self.dbname = database_name
if os.path.isfile(database_file) and os.access(database_file, os.R_OK):
self.dbcon = sqlite3.connect(database_file)
self.dbcur = self.dbcon.cursor()
else:
raise PysqliteError('{} could not be found or cannot be accessed!'.format(self.dbname))
def get_db_data(self, table):
try:
db_data = self.dbcur.execute('SELECT * FROM {}'.format(table))
except Exception as e:
raise PysqliteError('Pysqlite experienced the following exception: {}'.format(e))
data_list = []
for row in db_data:
data_list.append(row)
if len(data_list) == 0:
raise PysqliteError('Pysqlite found no data in the table: {} in the DB: {}'.format(table, self.dbname))
return data_list
def insert_db_data(self, table, row_string, db_data):
try:
self.dbcur.execute('INSERT INTO {} VALUES {}'.format(table, row_string), db_data)
self.dbcon.commit()
except Exception as e:
raise PysqliteError('Pysqlite experienced the following exception: {}'.format(e))
if __name__ == '__main__':
ggforcharity_db = Pysqlite('GGforCharity', 'ggforcharity.db')
data = ggforcharity_db.get_db_data('testing')
for row in data:
print(row)
ggforcharity_db.insert_db_data('testing', '(NULL, ?, ?, ?, ?, ?)', ('Day String', 100, 20, 'Event', 'purrcat259'))
for row in data:
print(row)
| {
"content_hash": "3421ea95720a44be2a2307dcd65ff151",
"timestamp": "",
"source": "github",
"line_count": 48,
"max_line_length": 118,
"avg_line_length": 36.541666666666664,
"alnum_prop": 0.5980615735461802,
"repo_name": "purrcat259/sockbot",
"id": "0b374b8373822f86a79ea6e08da2f17a6dce7800",
"size": "1754",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "pysqlite.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "23"
},
{
"name": "Python",
"bytes": "13258"
}
],
"symlink_target": ""
} |
<?php
namespace Geekhub\UserBundle\Controller;
use HWI\Bundle\OAuthBundle\Controller\ConnectController as BaseConnectController;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
class ConnectController extends BaseConnectController
{
/**
* @param Request $request
* @param string $service
*
* @return RedirectResponse
*/
public function redirectToServiceAction(Request $request, $service)
{
if ($request->hasSession()) {
// initialize the session for preventing SessionUnavailableException
$session = $request->getSession();
$session->start();
$providerKey = $this->container->getParameter('hwi_oauth.firewall_name');
$request->getSession()->set('_security.' . $providerKey . '.target_path', $request->headers->get('referer'));
}
return new RedirectResponse($this->container->get('hwi_oauth.security.oauth_utils')->getAuthorizationUrl($request, $service));
}
}
| {
"content_hash": "1fa06b85776008034f1c1a0c37fa199e",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 134,
"avg_line_length": 34.8,
"alnum_prop": 0.6819923371647509,
"repo_name": "geekhub-php/CheDream2",
"id": "db86174aae520b9de9120d8d5bde68d7538e583c",
"size": "1044",
"binary": false,
"copies": "1",
"ref": "refs/heads/slicing",
"path": "src/Geekhub/UserBundle/Controller/ConnectController.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "2647"
},
{
"name": "CSS",
"bytes": "435196"
},
{
"name": "Gherkin",
"bytes": "13756"
},
{
"name": "HTML",
"bytes": "153274"
},
{
"name": "JavaScript",
"bytes": "116088"
},
{
"name": "PHP",
"bytes": "323342"
},
{
"name": "Shell",
"bytes": "4236"
}
],
"symlink_target": ""
} |
using namespace arangodb::basics;
Utf8Helper Utf8Helper::DefaultUtf8Helper;
Utf8Helper::Utf8Helper(std::string const& lang) : _coll(nullptr) {
setCollatorLanguage(lang);
}
Utf8Helper::Utf8Helper() : Utf8Helper("") {}
Utf8Helper::~Utf8Helper() {
if (_coll) {
delete _coll;
if (this == &DefaultUtf8Helper) {
u_cleanup();
}
}
}
int Utf8Helper::compareUtf8(char const* left, char const* right) const {
TRI_ASSERT(left != nullptr);
TRI_ASSERT(right != nullptr);
if (!_coll) {
LOG(ERR) << "no Collator in Utf8Helper::compareUtf8()!";
return (strcmp(left, right));
}
UErrorCode status = U_ZERO_ERROR;
int result =
_coll->compareUTF8(StringPiece(left), StringPiece(right), status);
if (U_FAILURE(status)) {
LOG(ERR) << "error in Collator::compareUTF8(...): " << u_errorName(status);
return (strcmp(left, right));
}
return result;
}
int Utf8Helper::compareUtf8(char const* left, size_t leftLength,
char const* right, size_t rightLength) const {
TRI_ASSERT(left != nullptr);
TRI_ASSERT(right != nullptr);
TRI_ASSERT(_coll);
UErrorCode status = U_ZERO_ERROR;
int result =
_coll->compareUTF8(StringPiece(left, (int32_t)leftLength),
StringPiece(right, (int32_t)rightLength), status);
if (U_FAILURE(status)) {
LOG(ERR) << "error in Collator::compareUTF8(...): " << u_errorName(status);
return (strncmp(left, right, leftLength < rightLength ? leftLength : rightLength));
}
return result;
}
int Utf8Helper::compareUtf16(uint16_t const* left, size_t leftLength,
uint16_t const* right, size_t rightLength) const {
TRI_ASSERT(left != nullptr);
TRI_ASSERT(right != nullptr);
if (!_coll) {
LOG(ERR) << "no Collator in Utf8Helper::compareUtf16()!";
if (leftLength == rightLength) {
return memcmp((const void*)left, (const void*)right, leftLength * 2);
}
int result =
memcmp((const void*)left, (const void*)right,
leftLength < rightLength ? leftLength * 2 : rightLength * 2);
if (result == 0) {
if (leftLength < rightLength) {
return -1;
}
return 1;
}
return result;
}
// ..........................................................................
// Take note here: we are assuming that the ICU type UChar is two bytes.
// There is no guarantee that this will be the case on all platforms and
// compilers.
// ..........................................................................
return _coll->compare((const UChar*)left, (int32_t)leftLength,
(const UChar*)right, (int32_t)rightLength);
}
bool Utf8Helper::setCollatorLanguage(std::string const& lang) {
#ifdef _WIN32
TRI_FixIcuDataEnv();
#endif
UErrorCode status = U_ZERO_ERROR;
if (_coll) {
ULocDataLocaleType type = ULOC_ACTUAL_LOCALE;
const Locale& locale = _coll->getLocale(type, status);
if (U_FAILURE(status)) {
LOG(ERR) << "error in Collator::getLocale(...): " << u_errorName(status);
return false;
}
if (lang == locale.getName()) {
return true;
}
}
Collator* coll;
if (lang == "") {
// get default collator for empty language
coll = Collator::createInstance(status);
} else {
Locale locale(lang.c_str());
coll = Collator::createInstance(locale, status);
}
if (U_FAILURE(status)) {
LOG(ERR) << "error in Collator::createInstance(): " << u_errorName(status);
if (coll) {
delete coll;
}
return false;
}
// set the default attributes for sorting:
coll->setAttribute(UCOL_CASE_FIRST, UCOL_UPPER_FIRST, status); // A < a
coll->setAttribute(UCOL_NORMALIZATION_MODE, UCOL_OFF,
status); // no normalization
coll->setAttribute(
UCOL_STRENGTH, UCOL_IDENTICAL,
status); // UCOL_IDENTICAL, UCOL_PRIMARY, UCOL_SECONDARY, UCOL_TERTIARY
if (U_FAILURE(status)) {
LOG(ERR) << "error in Collator::setAttribute(...): " << u_errorName(status);
delete coll;
return false;
}
if (_coll) {
delete _coll;
}
_coll = coll;
return true;
}
std::string Utf8Helper::getCollatorLanguage() {
if (_coll) {
UErrorCode status = U_ZERO_ERROR;
ULocDataLocaleType type = ULOC_VALID_LOCALE;
const Locale& locale = _coll->getLocale(type, status);
if (U_FAILURE(status)) {
LOG(ERR) << "error in Collator::getLocale(...): " << u_errorName(status);
return "";
}
return locale.getLanguage();
}
return "";
}
std::string Utf8Helper::getCollatorCountry() {
if (_coll) {
UErrorCode status = U_ZERO_ERROR;
ULocDataLocaleType type = ULOC_VALID_LOCALE;
const Locale& locale = _coll->getLocale(type, status);
if (U_FAILURE(status)) {
LOG(ERR) << "error in Collator::getLocale(...): " << u_errorName(status);
return "";
}
return locale.getCountry();
}
return "";
}
////////////////////////////////////////////////////////////////////////////////
/// @brief Lowercase the characters in a UTF-8 string.
////////////////////////////////////////////////////////////////////////////////
std::string Utf8Helper::toLowerCase(std::string const& src) {
int32_t utf8len = 0;
char* utf8 = tolower(TRI_UNKNOWN_MEM_ZONE, src.c_str(), (int32_t)src.length(),
utf8len);
if (utf8 == nullptr) {
return std::string("");
}
std::string result(utf8, utf8len);
TRI_Free(TRI_UNKNOWN_MEM_ZONE, utf8);
return result;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief Lowercase the characters in a UTF-8 string.
////////////////////////////////////////////////////////////////////////////////
char* Utf8Helper::tolower(TRI_memory_zone_t* zone, char const* src,
int32_t srcLength, int32_t& dstLength) {
char* utf8_dest = nullptr;
if (src == nullptr || srcLength == 0) {
utf8_dest = (char*)TRI_Allocate(zone, sizeof(char), false);
if (utf8_dest != nullptr) {
utf8_dest[0] = '\0';
}
dstLength = 0;
return utf8_dest;
}
uint32_t options = U_FOLD_CASE_DEFAULT;
UErrorCode status = U_ZERO_ERROR;
std::string locale = getCollatorLanguage();
LocalUCaseMapPointer csm(ucasemap_open(locale.c_str(), options, &status));
if (U_FAILURE(status)) {
LOG(ERR) << "error in ucasemap_open(...): " << u_errorName(status);
} else {
utf8_dest =
(char*)TRI_Allocate(zone, (srcLength + 1) * sizeof(char), false);
if (utf8_dest == nullptr) {
return nullptr;
}
dstLength = ucasemap_utf8ToLower(csm.getAlias(), utf8_dest, srcLength + 1,
src, srcLength, &status);
if (status == U_BUFFER_OVERFLOW_ERROR) {
status = U_ZERO_ERROR;
TRI_Free(zone, utf8_dest);
utf8_dest =
(char*)TRI_Allocate(zone, (dstLength + 1) * sizeof(char), false);
if (utf8_dest == nullptr) {
return nullptr;
}
dstLength = ucasemap_utf8ToLower(csm.getAlias(), utf8_dest, dstLength + 1,
src, srcLength, &status);
}
if (U_FAILURE(status)) {
LOG(ERR) << "error in ucasemap_utf8ToLower(...): " << u_errorName(status);
TRI_Free(zone, utf8_dest);
} else {
return utf8_dest;
}
}
utf8_dest = TRI_LowerAsciiString(zone, src);
if (utf8_dest != nullptr) {
dstLength = (int32_t)strlen(utf8_dest);
}
return utf8_dest;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief Uppercase the characters in a UTF-8 string.
////////////////////////////////////////////////////////////////////////////////
std::string Utf8Helper::toUpperCase(std::string const& src) {
int32_t utf8len = 0;
char* utf8 = toupper(TRI_UNKNOWN_MEM_ZONE, src.c_str(), (int32_t)src.length(),
utf8len);
if (utf8 == nullptr) {
return std::string("");
}
std::string result(utf8, utf8len);
TRI_Free(TRI_UNKNOWN_MEM_ZONE, utf8);
return result;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief Lowercase the characters in a UTF-8 string.
////////////////////////////////////////////////////////////////////////////////
char* Utf8Helper::toupper(TRI_memory_zone_t* zone, char const* src,
int32_t srcLength, int32_t& dstLength) {
char* utf8_dest = nullptr;
if (src == nullptr || srcLength == 0) {
utf8_dest = (char*)TRI_Allocate(zone, sizeof(char), false);
if (utf8_dest != nullptr) {
utf8_dest[0] = '\0';
}
dstLength = 0;
return utf8_dest;
}
uint32_t options = U_FOLD_CASE_DEFAULT;
UErrorCode status = U_ZERO_ERROR;
std::string locale = getCollatorLanguage();
LocalUCaseMapPointer csm(ucasemap_open(locale.c_str(), options, &status));
if (U_FAILURE(status)) {
LOG(ERR) << "error in ucasemap_open(...): " << u_errorName(status);
} else {
utf8_dest =
(char*)TRI_Allocate(zone, (srcLength + 1) * sizeof(char), false);
if (utf8_dest == nullptr) {
return nullptr;
}
dstLength = ucasemap_utf8ToUpper(csm.getAlias(), utf8_dest, srcLength, src,
srcLength, &status);
if (status == U_BUFFER_OVERFLOW_ERROR) {
status = U_ZERO_ERROR;
TRI_Free(zone, utf8_dest);
utf8_dest =
(char*)TRI_Allocate(zone, (dstLength + 1) * sizeof(char), false);
if (utf8_dest == nullptr) {
return nullptr;
}
dstLength = ucasemap_utf8ToUpper(csm.getAlias(), utf8_dest, dstLength + 1,
src, srcLength, &status);
}
if (U_FAILURE(status)) {
LOG(ERR) << "error in ucasemap_utf8ToUpper(...): " << u_errorName(status);
TRI_Free(zone, utf8_dest);
} else {
return utf8_dest;
}
}
utf8_dest = TRI_UpperAsciiString(zone, src);
if (utf8_dest != nullptr) {
dstLength = (int32_t)strlen(utf8_dest);
}
return utf8_dest;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief Extract the words from a UTF-8 string.
////////////////////////////////////////////////////////////////////////////////
bool Utf8Helper::getWords(std::vector<std::string>& words,
std::string const& text, size_t minimalLength,
size_t maximalLength, bool lowerCase) {
UErrorCode status = U_ZERO_ERROR;
UnicodeString word;
if (text.empty()) {
return true;
}
size_t textLength = text.size();
if (textLength < minimalLength) {
// input text is shorter than required minimum length
return true;
}
size_t textUtf16Length = 0;
UChar* textUtf16 = nullptr;
if (lowerCase) {
// lower case string
int32_t lowerLength = 0;
char* lower =
tolower(TRI_UNKNOWN_MEM_ZONE, text.c_str(), (int32_t)textLength, lowerLength);
if (lower == nullptr) {
// out of memory
return false;
}
if (lowerLength == 0) {
TRI_Free(TRI_UNKNOWN_MEM_ZONE, lower);
return false;
}
textUtf16 = TRI_Utf8ToUChar(TRI_UNKNOWN_MEM_ZONE, lower, lowerLength,
&textUtf16Length);
TRI_Free(TRI_UNKNOWN_MEM_ZONE, lower);
} else {
textUtf16 = TRI_Utf8ToUChar(TRI_UNKNOWN_MEM_ZONE, text.c_str(), (int32_t)textLength,
&textUtf16Length);
}
if (textUtf16 == nullptr) {
return false;
}
ULocDataLocaleType type = ULOC_VALID_LOCALE;
const Locale& locale = _coll->getLocale(type, status);
if (U_FAILURE(status)) {
TRI_Free(TRI_UNKNOWN_MEM_ZONE, textUtf16);
LOG(ERR) << "error in Collator::getLocale(...): " << u_errorName(status);
return false;
}
UChar* tempUtf16 = (UChar*)TRI_Allocate(
TRI_UNKNOWN_MEM_ZONE, (textUtf16Length + 1) * sizeof(UChar), false);
if (tempUtf16 == nullptr) {
TRI_Free(TRI_UNKNOWN_MEM_ZONE, textUtf16);
return false;
}
// estimate an initial vector size. this is not accurate, but setting the
// initial size to some
// value in the correct order of magnitude will save a lot of vector
// reallocations later
size_t initialWordCount = textLength / (2 * (minimalLength + 1));
if (initialWordCount < 32) {
// alloc at least 32 pointers (= 256b)
initialWordCount = 32;
} else if (initialWordCount > 8192) {
// alloc at most 8192 pointers (= 64kb)
initialWordCount = 8192;
}
// Reserve initialWordCount additional words in the vector
words.reserve(words.size() + initialWordCount);
BreakIterator* wordIterator =
BreakIterator::createWordInstance(locale, status);
UnicodeString utext(textUtf16);
wordIterator->setText(utext);
int32_t start = wordIterator->first();
for (int32_t end = wordIterator->next(); end != BreakIterator::DONE;
start = end, end = wordIterator->next()) {
size_t tempUtf16Length = (size_t)(end - start);
// end - start = word length
if (tempUtf16Length >= minimalLength) {
size_t chunkLength = tempUtf16Length;
if (chunkLength > maximalLength) {
chunkLength = maximalLength;
}
utext.extractBetween(start, (int32_t)(start + chunkLength), tempUtf16, 0);
size_t utf8WordLength;
char* utf8Word = TRI_UCharToUtf8(TRI_UNKNOWN_MEM_ZONE, tempUtf16,
chunkLength, &utf8WordLength);
if (utf8Word != nullptr) {
std::string word(utf8Word, utf8WordLength);
words.emplace_back(word);
TRI_Free(TRI_UNKNOWN_MEM_ZONE, utf8Word);
}
}
}
delete wordIterator;
TRI_Free(TRI_UNKNOWN_MEM_ZONE, textUtf16);
TRI_Free(TRI_UNKNOWN_MEM_ZONE, tempUtf16);
return true;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief builds a regex matcher for the specified pattern
////////////////////////////////////////////////////////////////////////////////
RegexMatcher* Utf8Helper::buildMatcher(std::string const& pattern) {
UErrorCode status = U_ZERO_ERROR;
auto matcher = std::make_unique<RegexMatcher>(
UnicodeString::fromUTF8(pattern), 0, status);
if (U_FAILURE(status)) {
return nullptr;
}
return matcher.release();
}
////////////////////////////////////////////////////////////////////////////////
/// @brief whether or not value matches a regex
////////////////////////////////////////////////////////////////////////////////
bool Utf8Helper::matches(RegexMatcher* matcher, char const* value,
size_t valueLength, bool partial, bool& error) {
TRI_ASSERT(value != nullptr);
UnicodeString v = UnicodeString::fromUTF8(
StringPiece(value, static_cast<int32_t>(valueLength)));
matcher->reset(v);
UErrorCode status = U_ZERO_ERROR;
error = false;
TRI_ASSERT(matcher != nullptr);
UBool result;
if (partial) {
// partial match
result = matcher->find(status);
} else {
// full match
result = matcher->matches(status);
}
if (U_FAILURE(status)) {
error = true;
}
return (result ? true : false);
}
////////////////////////////////////////////////////////////////////////////////
/// @brief Lowercase the characters in a UTF-8 string (implemented in
/// Basic/Utf8Helper.cpp)
////////////////////////////////////////////////////////////////////////////////
char* TRI_tolower_utf8(TRI_memory_zone_t* zone, char const* src,
int32_t srcLength, int32_t* dstLength) {
return Utf8Helper::DefaultUtf8Helper.tolower(zone, src, srcLength,
*dstLength);
}
////////////////////////////////////////////////////////////////////////////////
/// @brief convert a utf-8 string to a uchar (utf-16)
////////////////////////////////////////////////////////////////////////////////
UChar* TRI_Utf8ToUChar(TRI_memory_zone_t* zone, char const* utf8,
size_t inLength, size_t* outLength) {
int32_t utf16Length;
// 1. convert utf8 string to utf16
// calculate utf16 string length
UErrorCode status = U_ZERO_ERROR;
u_strFromUTF8(nullptr, 0, &utf16Length, utf8, (int32_t)inLength, &status);
if (status != U_BUFFER_OVERFLOW_ERROR) {
return nullptr;
}
UChar* utf16 =
(UChar*)TRI_Allocate(zone, (utf16Length + 1) * sizeof(UChar), false);
if (utf16 == nullptr) {
return nullptr;
}
// now convert
status = U_ZERO_ERROR;
// the +1 will append a 0 byte at the end
u_strFromUTF8(utf16, utf16Length + 1, nullptr, utf8, (int32_t)inLength,
&status);
if (status != U_ZERO_ERROR) {
TRI_Free(zone, utf16);
return nullptr;
}
*outLength = (size_t)utf16Length;
return utf16;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief convert a uchar (utf-16) to a utf-8 string
////////////////////////////////////////////////////////////////////////////////
char* TRI_UCharToUtf8(TRI_memory_zone_t* zone, UChar const* uchar,
size_t inLength, size_t* outLength) {
int32_t utf8Length;
// calculate utf8 string length
UErrorCode status = U_ZERO_ERROR;
u_strToUTF8(nullptr, 0, &utf8Length, uchar, (int32_t)inLength, &status);
if (status != U_ZERO_ERROR && status != U_BUFFER_OVERFLOW_ERROR) {
return nullptr;
}
char* utf8 = static_cast<char*>(TRI_Allocate(zone, utf8Length + 1, false));
if (utf8 == nullptr) {
return nullptr;
}
// convert to utf8
status = U_ZERO_ERROR;
// the +1 will append a 0 byte at the end
u_strToUTF8(utf8, utf8Length + 1, nullptr, uchar, (int32_t)inLength, &status);
if (status != U_ZERO_ERROR) {
TRI_Free(zone, utf8);
return nullptr;
}
*outLength = (size_t)utf8Length;
return utf8;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief normalize an utf8 string (NFC)
////////////////////////////////////////////////////////////////////////////////
char* TRI_normalize_utf8_to_NFC(TRI_memory_zone_t* zone, char const* utf8,
size_t inLength, size_t* outLength) {
size_t utf16Length;
*outLength = 0;
char* utf8Dest;
if (inLength == 0) {
utf8Dest = static_cast<char*>(TRI_Allocate(zone, sizeof(char), false));
if (utf8Dest != nullptr) {
utf8Dest[0] = '\0';
}
return utf8Dest;
}
UChar* utf16 = TRI_Utf8ToUChar(zone, utf8, inLength, &utf16Length);
if (utf16 == nullptr) {
return nullptr;
}
// continue in TR_normalize_utf16_to_NFC
utf8Dest = TRI_normalize_utf16_to_NFC(zone, (uint16_t const*)utf16,
(int32_t)utf16Length, outLength);
TRI_Free(zone, utf16);
return utf8Dest;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief normalize an utf8 string (NFC)
////////////////////////////////////////////////////////////////////////////////
char* TRI_normalize_utf16_to_NFC(TRI_memory_zone_t* zone, uint16_t const* utf16,
size_t inLength, size_t* outLength) {
*outLength = 0;
char* utf8Dest;
if (inLength == 0) {
utf8Dest = static_cast<char*>(TRI_Allocate(zone, sizeof(char), false));
if (utf8Dest != nullptr) {
utf8Dest[0] = '\0';
}
return utf8Dest;
}
UErrorCode status = U_ZERO_ERROR;
UNormalizer2 const* norm2 =
unorm2_getInstance(nullptr, "nfc", UNORM2_COMPOSE, &status);
if (status != U_ZERO_ERROR) {
return nullptr;
}
// normalize UChar (UTF-16)
UChar* utf16Dest;
bool mustFree;
char buffer[512];
if (inLength < sizeof(buffer) / sizeof(UChar)) {
// use a static buffer
utf16Dest = (UChar*)&buffer[0];
mustFree = false;
} else {
// use dynamic memory
utf16Dest =
(UChar*)TRI_Allocate(zone, (inLength + 1) * sizeof(UChar), false);
if (utf16Dest == nullptr) {
return nullptr;
}
mustFree = true;
}
size_t overhead = 0;
int32_t utf16DestLength;
while (true) {
status = U_ZERO_ERROR;
utf16DestLength =
unorm2_normalize(norm2, (UChar*)utf16, (int32_t)inLength, utf16Dest,
(int32_t)(inLength + overhead + 1), &status);
if (status == U_ZERO_ERROR) {
break;
}
if (status == U_BUFFER_OVERFLOW_ERROR ||
status == U_STRING_NOT_TERMINATED_WARNING) {
// output buffer was too small. now re-try with a bigger buffer (inLength
// + overhead size)
if (mustFree) {
// free original buffer first so we don't leak
TRI_Free(zone, utf16Dest);
mustFree = false;
}
if (overhead == 0) {
// set initial overhead size
if (inLength < 256) {
overhead = 16;
} else if (inLength < 4096) {
overhead = 128;
} else {
overhead = 256;
}
} else {
// use double buffer size
overhead += overhead;
if (overhead >= 1024 * 1024) {
// enough is enough
return nullptr;
}
}
utf16Dest = (UChar*)TRI_Allocate(
zone, (inLength + overhead + 1) * sizeof(UChar), false);
if (utf16Dest != nullptr) {
// got new memory. now try again with the adjusted, bigger buffer
mustFree = true;
continue;
}
// fall-through intentional
}
if (mustFree) {
TRI_Free(zone, utf16Dest);
}
return nullptr;
}
// Convert data back from UChar (UTF-16) to UTF-8
utf8Dest =
TRI_UCharToUtf8(zone, utf16Dest, (size_t)utf16DestLength, outLength);
if (mustFree) {
TRI_Free(zone, utf16Dest);
}
return utf8Dest;
}
| {
"content_hash": "cfa6aa855dca644aa75214f5e3134d55",
"timestamp": "",
"source": "github",
"line_count": 743,
"max_line_length": 88,
"avg_line_length": 29.10228802153432,
"alnum_prop": 0.5483512926050964,
"repo_name": "m0ppers/arangodb",
"id": "28a0844c8b5655e7e626bb01a019b42e5454efdb",
"size": "22913",
"binary": false,
"copies": "1",
"ref": "refs/heads/devel",
"path": "lib/Basics/Utf8Helper.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Ada",
"bytes": "89080"
},
{
"name": "Assembly",
"bytes": "397438"
},
{
"name": "Batchfile",
"bytes": "36479"
},
{
"name": "C",
"bytes": "4981599"
},
{
"name": "C#",
"bytes": "96430"
},
{
"name": "C++",
"bytes": "273207213"
},
{
"name": "CLIPS",
"bytes": "5291"
},
{
"name": "CMake",
"bytes": "526333"
},
{
"name": "CSS",
"bytes": "634304"
},
{
"name": "Cuda",
"bytes": "52444"
},
{
"name": "DIGITAL Command Language",
"bytes": "33549"
},
{
"name": "Emacs Lisp",
"bytes": "14357"
},
{
"name": "Fortran",
"bytes": "1856"
},
{
"name": "Groff",
"bytes": "272212"
},
{
"name": "Groovy",
"bytes": "131"
},
{
"name": "HTML",
"bytes": "3470113"
},
{
"name": "IDL",
"bytes": "14"
},
{
"name": "Java",
"bytes": "2325801"
},
{
"name": "JavaScript",
"bytes": "66968092"
},
{
"name": "LLVM",
"bytes": "38070"
},
{
"name": "Lex",
"bytes": "1231"
},
{
"name": "Lua",
"bytes": "16189"
},
{
"name": "M4",
"bytes": "64965"
},
{
"name": "Makefile",
"bytes": "1268118"
},
{
"name": "Max",
"bytes": "36857"
},
{
"name": "Module Management System",
"bytes": "1545"
},
{
"name": "NSIS",
"bytes": "28404"
},
{
"name": "Objective-C",
"bytes": "30435"
},
{
"name": "Objective-C++",
"bytes": "2503"
},
{
"name": "PHP",
"bytes": "39473"
},
{
"name": "Pascal",
"bytes": "145688"
},
{
"name": "Perl",
"bytes": "205308"
},
{
"name": "Python",
"bytes": "6937381"
},
{
"name": "QML",
"bytes": "593"
},
{
"name": "QMake",
"bytes": "16692"
},
{
"name": "R",
"bytes": "5123"
},
{
"name": "Rebol",
"bytes": "354"
},
{
"name": "Ruby",
"bytes": "910409"
},
{
"name": "SAS",
"bytes": "1847"
},
{
"name": "Scheme",
"bytes": "10604"
},
{
"name": "Shell",
"bytes": "986221"
},
{
"name": "Swift",
"bytes": "116"
},
{
"name": "Vim script",
"bytes": "4075"
},
{
"name": "XSLT",
"bytes": "473118"
},
{
"name": "Yacc",
"bytes": "72510"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
<project xmlns="http://maven.apache.org/DECORATION/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/DECORATION/1.0.0 http://maven.apache.org/xsd/decoration-1.0.0.xsd">
<body>
<menu name="Overview">
<item name="Introduction" href="index.html"/>
<item name="Goals" href="plugin-info.html"/>
<item name="Usage" href="usage.html"/>
<item name="FAQ" href="faq.html"/>
</menu>
<menu name="Examples">
<item name="Specifying a character encoding scheme"
href="/examples/encoding.html"/>
<item name="Specifying resource directories"
href="/examples/resource-directory.html"/>
<item name="Filtering"
href="/examples/filter.html"/>
<item name="Including and excluding files and directories"
href="/examples/include-exclude.html"/>
<item name="Escape Filtering"
href="/examples/escape-filtering.html"/>
<item name="Copy Resources"
href="/examples/copy-resources.html"/>
<item name="Binaries Filtering"
href="/examples/binaries-filtering.html"/>
<item name="Custom Resources Filters"
href="/examples/custom-resource-filters.html"/>
</menu>
</body>
</project>
| {
"content_hash": "61da2126b3b306a4daa4c6b1b1572b7b",
"timestamp": "",
"source": "github",
"line_count": 51,
"max_line_length": 113,
"avg_line_length": 41.15686274509804,
"alnum_prop": 0.690328727965698,
"repo_name": "khmarbaise/maven-plugins",
"id": "1ec15b50c7b3a4e0b570bb19af2277eddfb2938c",
"size": "2099",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "maven-resources-plugin/src/site/site.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "46161"
},
{
"name": "Groovy",
"bytes": "123305"
},
{
"name": "Java",
"bytes": "8362357"
},
{
"name": "JavaScript",
"bytes": "1695"
},
{
"name": "Shell",
"bytes": "618"
}
],
"symlink_target": ""
} |
<?php
require_once("core/ui/UIComponent.php");
abstract class UIControl extends UIComponent {
/**
* Tip text or message for the control.
*
* @var string
*/
protected $tip = "";
/**
* Set if control is scrollable or not.
*
* @var boolean
*/
protected $scrollable = false;
public function UIControl() {}
} | {
"content_hash": "feccd60e883f269ae31f1f432f780846",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 46,
"avg_line_length": 16.727272727272727,
"alnum_prop": 0.5706521739130435,
"repo_name": "pomed/Framework",
"id": "9c53435561b5d2cb46dd0b73106207bda867c011",
"size": "642",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "framework/ui/UIControl.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "424"
},
{
"name": "PHP",
"bytes": "226769"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<!--[if IE 8]> <html class="no-js lt-ie9" lang="en" > <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="en" > <!--<![endif]-->
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Foundation 4</title>
<link rel="stylesheet" href="../stylesheets/app.css">
<script src="javascripts/vendor/custom.modernizr.js"></script>
</head>
<body>
<nav class="top-bar">
<ul class="title-area">
<!-- Title Area -->
<li class="name">
<h1><a href="../index.html">HSE.TV </a></h1>
</li>
<!-- Remove the class "menu-icon" to get rid of menu icon. Take out "Menu" to just have icon alone -->
<li class="toggle-topbar menu-icon"><a href="#"><span>Menu</span></a></li>
</ul>
<section class="top-bar-section">
<!-- Left Nav Section -->
<ul class="left">
<li class="divider"></li>
<li class="active"><a href="index.html">Progress</a></li>
<li class="divider"></li>
<li class="active"><a href="#">Course</a>
<li class="divider"></li>
<li><a href="#">Support</li>
</ul>
<!-- Right Nav Section -->
<ul class="right">
<li class="has-dropdown"><a href="#">Admin</a>
<ul class="dropdown">
<li><a href="#" class="">Add Course</a></li>
<li><a href="#">Add Module</a></li>
<li><a href="#">Add Video</a></li>
</ul>
</li>
<li class="divider"></li>
<li class="has-form">
<form>
<div class="row collapse">
<div class="small-8 columns">
<input type="text">
</div>
<div class="small-4 columns">
<a href="#" class="alert button">Search</a>
</div>
</div>
</form>
</li>
<li class="divider show-for-small"></li>
<li class="has-form">
<a class="button" href="#">Button!</a>
</li>
</ul>
</section>
</nav>
<div class="row">
<ul class="breadcrumbs">
<li><a href="index.html">Home</a></li>
<li class="current">Course 1: VCA Basic Course</li>
</ul>
</div>
<header class="row">
<div class="panel callout">
<h1>VCA Basic Course</h1>
<p>This course is a preparation for the VCA Exam.</p>
</div>
</header>
<div class="row">
<div class="large-9 columns">
<div class="row">
<h3 class="subheader">Wetgeving, gezondheid, milieu</h3>
<div class="large-4 columsn">
<img class="left" src="../images/fundamentals.png" width="126" height="126" />
</div>
<div class="large-8 columns">
<p>De basis met betrekking tot wetgeving, gezondheid en milieu</p>
<a class="small button success right" href="module.html">Get started</a>
</div>
</div>
<div class="row">
<br />
<hr />
</div>
<div class="row">
<h3 class="subheader">Toezicht op welzijn op het werk</h3>
<div class="large-4 columsn">
<img class="left" src="../images/vca_basic_security_badge.png" width="126" height="126" />
</div>
<div class="large-8 columns">
<p>De basis met betrekking tot wetgeving, gezondheid en milieu</p>
<a class="small button success right" href="#">Get started</a>
</div>
</div>
<div class="row">
<br />
<hr />
</div>
<div class="row">
<h3 class="subheader">Inspectieprocedures</h3>
<div class="large-4 columsn">
<img class="left" src="../images/document-types.png" width="126" height="126" />
</div>
<div class="large-8 columns">
<p>De basis met betrekking tot wetgeving, gezondheid en milieu</p>
<a class="small button success right" href="#">Get started</a>
</div>
</div>
<div class="row">
<br />
<hr />
</div>
<div class="row">
<h3 class="subheader">Organisatie van Veiligheid Bescherming en Bescherming</h3>
<div class="large-4 columsn">
<img class="left" src="../images/installation.png" width="126" height="126" />
</div>
<div class="large-8 columns">
<p>De basis met betrekking tot wetgeving, gezondheid en milieu</p>
<a class="small button success right" href="#">Get started</a>
</div>
</div>
<div class="row">
<br />
<hr />
</div>
<div class="row">
<h3 class="subheader">De arbeidsinspectie</h3>
<div class="large-4 columsn">
<img class="left" src="../images/stylesheets.png" width="126" height="126" />
</div>
<div class="large-8 columns">
<p>De basis met betrekking tot wetgeving, gezondheid en milieu</p>
<a class="small button success right" href="#">Get started</a>
</div>
</div>
<div class="row">
<br />
<hr />
</div>
<div class="row">
<h3 class="subheader">Samenwerking tussen werkgever, opdrachtgever en onderaannemer</h3>
<div class="large-4 columsn">
<img class="left" src="../images/templating.png" width="126" height="126" />
</div>
<div class="large-8 columns">
<p>De basis met betrekking tot wetgeving, gezondheid en milieu</p>
<a class="small button success right" href="#">Get started</a>
</div>
</div>
</div>
</div>
<footer class="row">
<div class="large-12 columns">
<hr />
<div class="row">
<div class="large-6 columns">
<p>©Safetatwork 2013 Contact</p>
</div>
<div class="large-6 columns">
<ul class="inline-list right">
<li>Sign Up</li>
<li>Course</li>
<li>Support</li>
</ul>
</div>
</div>
</div>
</footer>
<script>
document.write('<script src=' +
('__proto__' in {} ? 'javascripts/vendor/zepto' : 'javascripts/vendor/jquery') +
'.js><\/script>')
</script>
<script src="javascripts/foundation/foundation.js"></script>
<script src="javascripts/foundation/foundation.abide.js"></script>
<script src="javascripts/foundation/foundation.alerts.js"></script>
<script src="javascripts/foundation/foundation.clearing.js"></script>
<script src="javascripts/foundation/foundation.cookie.js"></script>
<script src="javascripts/foundation/foundation.dropdown.js"></script>
<script src="javascripts/foundation/foundation.forms.js"></script>
<script src="javascripts/foundation/foundation.interchange.js"></script>
<script src="javascripts/foundation/foundation.joyride.js"></script>
<script src="javascripts/foundation/foundation.magellan.js"></script>
<script src="javascripts/foundation/foundation.orbit.js"></script>
<script src="javascripts/foundation/foundation.placeholder.js"></script>
<script src="javascripts/foundation/foundation.reveal.js"></script>
<script src="javascripts/foundation/foundation.section.js"></script>
<script src="javascripts/foundation/foundation.tooltips.js"></script>
<script src="javascripts/foundation/foundation.topbar.js"></script>
<script>
$(document).foundation();
</script>
</body>
</html>
| {
"content_hash": "0055aadfb87fa8d476df12b85a9f5ddb",
"timestamp": "",
"source": "github",
"line_count": 229,
"max_line_length": 106,
"avg_line_length": 31.85589519650655,
"alnum_prop": 0.5610692254969157,
"repo_name": "acandael/HSE.TV",
"id": "1f8c5dfa80cdf4338f87af6b6e0f67fd012266d8",
"size": "7295",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "public/course.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "366004"
},
{
"name": "JavaScript",
"bytes": "159179"
},
{
"name": "Ruby",
"bytes": "888"
}
],
"symlink_target": ""
} |
require 'rubygems' if RUBY_VERSION < '1.9.0'
require 'sensu-plugin/check/cli'
class CheckDirSize < Sensu::Plugin::Check::CLI
option :directory,
description: 'Directory to stat (full path not including trailing slash)',
short: '-d /path/to/directory',
long: '--directory /path/to/directory',
required: true
option :warn,
description: 'The size (in bytes) of the directory where WARNING is raised',
short: '-w SIZE_IN_BYTES',
long: '--warn SIZE_IN_BYTES',
default: 3_500_000,
required: false
option :crit,
description: 'The size (in bytes) of the directory where CRITICAL is raised',
short: '-c SIZE_IN_BYTES',
long: '--critical SIZE_IN_BYTES',
default: 4_000_000,
required: false
option :ignore_missing,
description: 'Do not throw CRITICAL if the directory is missing',
long: '--ignore-missing',
boolean: true,
default: false,
required: false
option :du_path,
description: 'The path to the `du` command',
long: '--du-path /path/to/du',
short: '-p /path/to/du',
default: '/usr/bin/du',
required: false
# Even though most everything should have 'du' installed by default, let's do a quick sanity check
def check_external_dependency
critical "This system does not have 'du' at #{config[:du_path]}!" unless File.exist? config[:du_path]
end
def du_directory
if Dir.exist? config[:directory]
cmd = "#{config[:du_path]} #{config[:directory]} --bytes --summarize | /usr/bin/awk '{ printf \"%s\",$1 }'"
@dir_size = `#{cmd}`
else
if config[:ignore_missing] == true
ok "Directory #{config[:directory]} does not exist (--ignore-missing was set)"
else
critical "Directory #{config[:directory]} does not exist!"
end
end
end
def compare_size
if @dir_size.to_i >= config[:crit].to_i
critical "Directory #{config[:directory]} is greater than #{format_bytes(config[:crit].to_i)} bytes [actual size: #{format_bytes(@dir_size.to_i)} bytes]"
elsif @dir_size.to_i >= config[:warn].to_i
warning "Directory #{config[:directory]} is greater than #{format_bytes(config[:warn].to_i)} bytes [actual size: #{format_bytes(@dir_size.to_i)} bytes]"
else
ok "Directory #{config[:directory]} is within size limit"
end
end
def run
check_external_dependency
du_directory
compare_size
end
# Helper functions
def format_bytes(number)
number.to_s.reverse.gsub(/(\d{3})(?=\d)/, '\\1,').reverse
end
end
| {
"content_hash": "4b5832b2ccf6bce3c650edced2a513f8",
"timestamp": "",
"source": "github",
"line_count": 77,
"max_line_length": 159,
"avg_line_length": 34.1948051948052,
"alnum_prop": 0.6156475503228257,
"repo_name": "sensu-plugins/sensu-plugins-filesystem-checks",
"id": "35d34b77039e5dcbc040af0e91c70b1deeb02958",
"size": "3764",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "bin/check-dir-size.rb",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "30641"
}
],
"symlink_target": ""
} |
@implementation HTTPSValidityTestCase
- (void)onWillSendRequest:(NSMutableURLRequest*)request
{
NSURL* url = [NSURL URLWithString:@"https://github.com/"];
[request setURL:url];
}
@end
| {
"content_hash": "601505b49bce65dd94fc759e71e74495",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 62,
"avg_line_length": 21.555555555555557,
"alnum_prop": 0.7268041237113402,
"repo_name": "zqxiaojin/JCFConnection",
"id": "e43fa1100105ca2820f936ebb6c1f5805611fced",
"size": "373",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "JCFConnection/JCFConnectionTest/HTTPSValidityTestCase.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "13776"
},
{
"name": "Objective-C",
"bytes": "20296"
},
{
"name": "Objective-C++",
"bytes": "90541"
}
],
"symlink_target": ""
} |
$LOAD_PATH.unshift(File.dirname(__FILE__))
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
require 'has_offers'
require 'spec'
require 'spec/autorun'
Spec::Runner.configure do |config|
end
| {
"content_hash": "78bcc7bcb8513c37e0167c9ccd520737",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 66,
"avg_line_length": 23.555555555555557,
"alnum_prop": 0.6886792452830188,
"repo_name": "Sentia/has_offers",
"id": "ee79298eb7ae92fa57cf99cd99f19ec50a4a6594",
"size": "212",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spec/spec_helper.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "6209"
}
],
"symlink_target": ""
} |
import path from 'node:path';
import {findUp, findUpSync} from 'find-up';
import {readPackage, readPackageSync} from 'read-pkg';
export async function readPackageUp(options) {
const filePath = await findUp('package.json', options);
if (!filePath) {
return;
}
return {
packageJson: await readPackage({...options, cwd: path.dirname(filePath)}),
path: filePath,
};
}
export function readPackageUpSync(options) {
const filePath = findUpSync('package.json', options);
if (!filePath) {
return;
}
return {
packageJson: readPackageSync({...options, cwd: path.dirname(filePath)}),
path: filePath,
};
}
| {
"content_hash": "352e1f5076b98d7a655421c9a2a26528",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 76,
"avg_line_length": 22.925925925925927,
"alnum_prop": 0.7043618739903069,
"repo_name": "sindresorhus/read-pkg-up",
"id": "4e3a231f243ada5f0684a62d11e6e4a4f8785f8e",
"size": "619",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "index.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "1147"
},
{
"name": "TypeScript",
"bytes": "1184"
}
],
"symlink_target": ""
} |
package terminal
import (
"bufio"
"errors"
"fmt"
"go/parser"
"go/scanner"
"io"
"math"
"os"
"os/exec"
"path/filepath"
"reflect"
"regexp"
"sort"
"strconv"
"strings"
"text/tabwriter"
"github.com/cosiner/argv"
"github.com/go-delve/delve/service"
"github.com/go-delve/delve/service/api"
"github.com/go-delve/delve/service/debugger"
)
const optimizedFunctionWarning = "Warning: debugging optimized function"
type cmdPrefix int
const (
noPrefix = cmdPrefix(0)
onPrefix = cmdPrefix(1 << iota)
deferredPrefix
revPrefix
)
type callContext struct {
Prefix cmdPrefix
Scope api.EvalScope
Breakpoint *api.Breakpoint
}
func (ctx *callContext) scoped() bool {
return ctx.Scope.GoroutineID >= 0 || ctx.Scope.Frame > 0
}
type frameDirection int
const (
frameSet frameDirection = iota
frameUp
frameDown
)
type cmdfunc func(t *Term, ctx callContext, args string) error
type command struct {
aliases []string
builtinAliases []string
allowedPrefixes cmdPrefix
helpMsg string
cmdFn cmdfunc
}
// Returns true if the command string matches one of the aliases for this command
func (c command) match(cmdstr string) bool {
for _, v := range c.aliases {
if v == cmdstr {
return true
}
}
return false
}
// Commands represents the commands for Delve terminal process.
type Commands struct {
cmds []command
lastCmd cmdfunc
client service.Client
frame int // Current frame as set by frame/up/down commands.
}
var (
// LongLoadConfig loads more information:
// * Follows pointers
// * Loads more array values
// * Does not limit struct fields
LongLoadConfig = api.LoadConfig{true, 1, 64, 64, -1}
// ShortLoadConfig loads less information, not following pointers
// and limiting struct fields loaded to 3.
ShortLoadConfig = api.LoadConfig{false, 0, 64, 0, 3}
)
// ByFirstAlias will sort by the first
// alias of a command.
type ByFirstAlias []command
func (a ByFirstAlias) Len() int { return len(a) }
func (a ByFirstAlias) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ByFirstAlias) Less(i, j int) bool { return a[i].aliases[0] < a[j].aliases[0] }
// DebugCommands returns a Commands struct with default commands defined.
func DebugCommands(client service.Client) *Commands {
c := &Commands{client: client}
c.cmds = []command{
{aliases: []string{"help", "h"}, cmdFn: c.help, helpMsg: `Prints the help message.
help [command]
Type "help" followed by the name of a command for more information about it.`},
{aliases: []string{"break", "b"}, cmdFn: breakpoint, helpMsg: `Sets a breakpoint.
break [name] <linespec>
See $GOPATH/src/github.com/go-delve/delve/Documentation/cli/locspec.md for the syntax of linespec.
See also: "help on", "help cond" and "help clear"`},
{aliases: []string{"trace", "t"}, cmdFn: tracepoint, helpMsg: `Set tracepoint.
trace [name] <linespec>
A tracepoint is a breakpoint that does not stop the execution of the program, instead when the tracepoint is hit a notification is displayed. See $GOPATH/src/github.com/go-delve/delve/Documentation/cli/locspec.md for the syntax of linespec.
See also: "help on", "help cond" and "help clear"`},
{aliases: []string{"restart", "r"}, cmdFn: restart, helpMsg: `Restart process.
restart [checkpoint]
restart [-noargs] newargv...
For recorded processes restarts from the start or from the specified
checkpoint. For normal processes restarts the process, optionally changing
the arguments. With -noargs, the process starts with an empty commandline.
`},
{aliases: []string{"continue", "c"}, cmdFn: c.cont, helpMsg: "Run until breakpoint or program termination."},
{aliases: []string{"step", "s"}, cmdFn: c.step, helpMsg: "Single step through program."},
{aliases: []string{"step-instruction", "si"}, allowedPrefixes: revPrefix, cmdFn: c.stepInstruction, helpMsg: "Single step a single cpu instruction."},
{aliases: []string{"next", "n"}, cmdFn: c.next, helpMsg: `Step over to next source line.
next [count]
Optional [count] argument allows you to skip multiple lines.
`},
{aliases: []string{"stepout", "so"}, cmdFn: c.stepout, helpMsg: "Step out of the current function."},
{aliases: []string{"call"}, cmdFn: c.call, helpMsg: `Resumes process, injecting a function call (EXPERIMENTAL!!!)
call [-unsafe] <function call expression>
Current limitations:
- only pointers to stack-allocated objects can be passed as argument.
- only some automatic type conversions are supported.
- functions can only be called on running goroutines that are not
executing the runtime.
- the current goroutine needs to have at least 256 bytes of free space on
the stack.
- functions can only be called when the goroutine is stopped at a safe
point.
- calling a function will resume execution of all goroutines.
- only supported on linux's native backend.
`},
{aliases: []string{"threads"}, cmdFn: threads, helpMsg: "Print out info for every traced thread."},
{aliases: []string{"thread", "tr"}, cmdFn: thread, helpMsg: `Switch to the specified thread.
thread <id>`},
{aliases: []string{"clear"}, cmdFn: clear, helpMsg: `Deletes breakpoint.
clear <breakpoint name or id>`},
{aliases: []string{"clearall"}, cmdFn: clearAll, helpMsg: `Deletes multiple breakpoints.
clearall [<linespec>]
If called with the linespec argument it will delete all the breakpoints matching the linespec. If linespec is omitted all breakpoints are deleted.`},
{aliases: []string{"goroutines", "grs"}, cmdFn: goroutines, helpMsg: `List program goroutines.
goroutines [-u (default: user location)|-r (runtime location)|-g (go statement location)|-s (start location)] [ -t (stack trace)]
Print out info for every goroutine. The flag controls what information is shown along with each goroutine:
-u displays location of topmost stackframe in user code
-r displays location of topmost stackframe (including frames inside private runtime functions)
-g displays location of go instruction that created the goroutine
-s displays location of the start function
-t displays stack trace of goroutine
If no flag is specified the default is -u.`},
{aliases: []string{"goroutine", "gr"}, allowedPrefixes: onPrefix, cmdFn: c.goroutine, helpMsg: `Shows or changes current goroutine
goroutine
goroutine <id>
goroutine <id> <command>
Called without arguments it will show information about the current goroutine.
Called with a single argument it will switch to the specified goroutine.
Called with more arguments it will execute a command on the specified goroutine.`},
{aliases: []string{"breakpoints", "bp"}, cmdFn: breakpoints, helpMsg: "Print out info for active breakpoints."},
{aliases: []string{"print", "p"}, allowedPrefixes: onPrefix | deferredPrefix, cmdFn: printVar, helpMsg: `Evaluate an expression.
[goroutine <n>] [frame <m>] print <expression>
See $GOPATH/src/github.com/go-delve/delve/Documentation/cli/expr.md for a description of supported expressions.`},
{aliases: []string{"whatis"}, cmdFn: whatisCommand, helpMsg: `Prints type of an expression.
whatis <expression>`},
{aliases: []string{"set"}, cmdFn: setVar, helpMsg: `Changes the value of a variable.
[goroutine <n>] [frame <m>] set <variable> = <value>
See $GOPATH/src/github.com/go-delve/delve/Documentation/cli/expr.md for a description of supported expressions. Only numerical variables and pointers can be changed.`},
{aliases: []string{"sources"}, cmdFn: sources, helpMsg: `Print list of source files.
sources [<regex>]
If regex is specified only the source files matching it will be returned.`},
{aliases: []string{"funcs"}, cmdFn: funcs, helpMsg: `Print list of functions.
funcs [<regex>]
If regex is specified only the functions matching it will be returned.`},
{aliases: []string{"types"}, cmdFn: types, helpMsg: `Print list of types
types [<regex>]
If regex is specified only the types matching it will be returned.`},
{aliases: []string{"args"}, allowedPrefixes: onPrefix | deferredPrefix, cmdFn: args, helpMsg: `Print function arguments.
[goroutine <n>] [frame <m>] args [-v] [<regex>]
If regex is specified only function arguments with a name matching it will be returned. If -v is specified more information about each function argument will be shown.`},
{aliases: []string{"locals"}, allowedPrefixes: onPrefix | deferredPrefix, cmdFn: locals, helpMsg: `Print local variables.
[goroutine <n>] [frame <m>] locals [-v] [<regex>]
The name of variables that are shadowed in the current scope will be shown in parenthesis.
If regex is specified only local variables with a name matching it will be returned. If -v is specified more information about each local variable will be shown.`},
{aliases: []string{"vars"}, cmdFn: vars, helpMsg: `Print package variables.
vars [-v] [<regex>]
If regex is specified only package variables with a name matching it will be returned. If -v is specified more information about each package variable will be shown.`},
{aliases: []string{"regs"}, cmdFn: regs, helpMsg: `Print contents of CPU registers.
regs [-a]
Argument -a shows more registers.`},
{aliases: []string{"exit", "quit", "q"}, cmdFn: exitCommand, helpMsg: `Exit the debugger.
exit [-c]
When connected to a headless instance started with the --accept-multiclient, pass -c to resume the execution of the target process before disconnecting.`},
{aliases: []string{"list", "ls", "l"}, cmdFn: listCommand, helpMsg: `Show source code.
[goroutine <n>] [frame <m>] list [<linespec>]
Show source around current point or provided linespec.`},
{aliases: []string{"stack", "bt"}, allowedPrefixes: onPrefix, cmdFn: stackCommand, helpMsg: `Print stack trace.
[goroutine <n>] [frame <m>] stack [<depth>] [-full] [-offsets] [-defer] [-a <n>] [-adepth <depth>]
-full every stackframe is decorated with the value of its local variables and arguments.
-offsets prints frame offset of each frame.
-defer prints deferred function call stack for each frame.
-a <n> prints stacktrace of n ancestors of the selected goroutine (target process must have tracebackancestors enabled)
-adepth <depth> configures depth of ancestor stacktrace
`},
{aliases: []string{"frame"},
cmdFn: func(t *Term, ctx callContext, arg string) error {
return c.frameCommand(t, ctx, arg, frameSet)
},
helpMsg: `Set the current frame, or execute command on a different frame.
frame <m>
frame <m> <command>
The first form sets frame used by subsequent commands such as "print" or "set".
The second form runs the command on the given frame.`},
{aliases: []string{"up"},
cmdFn: func(t *Term, ctx callContext, arg string) error {
return c.frameCommand(t, ctx, arg, frameUp)
},
helpMsg: `Move the current frame up.
up [<m>]
up [<m>] <command>
Move the current frame up by <m>. The second form runs the command on the given frame.`},
{aliases: []string{"down"},
cmdFn: func(t *Term, ctx callContext, arg string) error {
return c.frameCommand(t, ctx, arg, frameDown)
},
helpMsg: `Move the current frame down.
down [<m>]
down [<m>] <command>
Move the current frame down by <m>. The second form runs the command on the given frame.`},
{aliases: []string{"deferred"}, cmdFn: c.deferredCommand, helpMsg: `Executes command in the context of a deferred call.
deferred <n> <command>
Executes the specified command (print, args, locals) in the context of the n-th deferred call in the current frame.`},
{aliases: []string{"source"}, cmdFn: c.sourceCommand, helpMsg: `Executes a file containing a list of delve commands
source <path>
If path ends with the .star extension it will be interpreted as a starlark script. See $GOPATH/src/github.com/go-delve/delve/Documentation/cli/starlark.md for the syntax.
If path is a single '-' character an interactive starlark interpreter will start instead. Type 'exit' to exit.`},
{aliases: []string{"disassemble", "disass"}, cmdFn: disassCommand, helpMsg: `Disassembler.
[goroutine <n>] [frame <m>] disassemble [-a <start> <end>] [-l <locspec>]
If no argument is specified the function being executed in the selected stack frame will be executed.
-a <start> <end> disassembles the specified address range
-l <locspec> disassembles the specified function`},
{aliases: []string{"on"}, cmdFn: c.onCmd, helpMsg: `Executes a command when a breakpoint is hit.
on <breakpoint name or id> <command>.
Supported commands: print, stack and goroutine)`},
{aliases: []string{"condition", "cond"}, cmdFn: conditionCmd, helpMsg: `Set breakpoint condition.
condition <breakpoint name or id> <boolean expression>.
Specifies that the breakpoint or tracepoint should break only if the boolean expression is true.`},
{aliases: []string{"config"}, cmdFn: configureCmd, helpMsg: `Changes configuration parameters.
config -list
Show all configuration parameters.
config -save
Saves the configuration file to disk, overwriting the current configuration file.
config <parameter> <value>
Changes the value of a configuration parameter.
config substitute-path <from> <to>
config substitute-path <from>
Adds or removes a path substitution rule.
config alias <command> <alias>
config alias <alias>
Defines <alias> as an alias to <command> or removes an alias.`},
{aliases: []string{"edit", "ed"}, cmdFn: edit, helpMsg: `Open where you are in $DELVE_EDITOR or $EDITOR
edit [locspec]
If locspec is omitted edit will open the current source file in the editor, otherwise it will open the specified location.`},
{aliases: []string{"libraries"}, cmdFn: libraries, helpMsg: `List loaded dynamic libraries`},
}
if client == nil || client.Recorded() {
c.cmds = append(c.cmds, command{
aliases: []string{"rewind", "rw"},
cmdFn: rewind,
helpMsg: "Run backwards until breakpoint or program termination.",
})
c.cmds = append(c.cmds, command{
aliases: []string{"check", "checkpoint"},
cmdFn: checkpoint,
helpMsg: `Creates a checkpoint at the current position.
checkpoint [note]
The "note" is arbitrary text that can be used to identify the checkpoint, if it is not specified it defaults to the current filename:line position.`,
})
c.cmds = append(c.cmds, command{
aliases: []string{"checkpoints"},
cmdFn: checkpoints,
helpMsg: "Print out info for existing checkpoints.",
})
c.cmds = append(c.cmds, command{
aliases: []string{"clear-checkpoint", "clearcheck"},
cmdFn: clearCheckpoint,
helpMsg: `Deletes checkpoint.
clear-checkpoint <id>`,
})
c.cmds = append(c.cmds, command{
aliases: []string{"rev"},
cmdFn: c.revCmd,
helpMsg: `Reverses the execution of the target program for the command specified.
Currently, only the rev step-instruction command is supported.`,
})
for i := range c.cmds {
v := &c.cmds[i]
if v.match("restart") {
v.helpMsg = `Restart process from a checkpoint or event.
restart [event number or checkpoint id]`
}
}
}
sort.Sort(ByFirstAlias(c.cmds))
return c
}
// Register custom commands. Expects cf to be a func of type cmdfunc,
// returning only an error.
func (c *Commands) Register(cmdstr string, cf cmdfunc, helpMsg string) {
for _, v := range c.cmds {
if v.match(cmdstr) {
v.cmdFn = cf
return
}
}
c.cmds = append(c.cmds, command{aliases: []string{cmdstr}, cmdFn: cf, helpMsg: helpMsg})
}
// Find will look up the command function for the given command input.
// If it cannot find the command it will default to noCmdAvailable().
// If the command is an empty string it will replay the last command.
func (c *Commands) Find(cmdstr string, prefix cmdPrefix) cmdfunc {
// If <enter> use last command, if there was one.
if cmdstr == "" {
if c.lastCmd != nil {
return c.lastCmd
}
return nullCommand
}
for _, v := range c.cmds {
if v.match(cmdstr) {
if prefix != noPrefix && v.allowedPrefixes&prefix == 0 {
continue
}
c.lastCmd = v.cmdFn
return v.cmdFn
}
}
return noCmdAvailable
}
// CallWithContext takes a command and a context that command should be executed in.
func (c *Commands) CallWithContext(cmdstr string, t *Term, ctx callContext) error {
vals := strings.SplitN(strings.TrimSpace(cmdstr), " ", 2)
cmdname := vals[0]
var args string
if len(vals) > 1 {
args = strings.TrimSpace(vals[1])
}
return c.Find(cmdname, ctx.Prefix)(t, ctx, args)
}
// Call takes a command to execute.
func (c *Commands) Call(cmdstr string, t *Term) error {
ctx := callContext{Prefix: noPrefix, Scope: api.EvalScope{GoroutineID: -1, Frame: c.frame, DeferredCall: 0}}
return c.CallWithContext(cmdstr, t, ctx)
}
// Merge takes aliases defined in the config struct and merges them with the default aliases.
func (c *Commands) Merge(allAliases map[string][]string) {
for i := range c.cmds {
if c.cmds[i].builtinAliases != nil {
c.cmds[i].aliases = append(c.cmds[i].aliases[:0], c.cmds[i].builtinAliases...)
}
}
for i := range c.cmds {
if aliases, ok := allAliases[c.cmds[i].aliases[0]]; ok {
if c.cmds[i].builtinAliases == nil {
c.cmds[i].builtinAliases = make([]string, len(c.cmds[i].aliases))
copy(c.cmds[i].builtinAliases, c.cmds[i].aliases)
}
c.cmds[i].aliases = append(c.cmds[i].aliases, aliases...)
}
}
}
var noCmdError = errors.New("command not available")
func noCmdAvailable(t *Term, ctx callContext, args string) error {
return noCmdError
}
func nullCommand(t *Term, ctx callContext, args string) error {
return nil
}
func (c *Commands) help(t *Term, ctx callContext, args string) error {
if args != "" {
for _, cmd := range c.cmds {
for _, alias := range cmd.aliases {
if alias == args {
fmt.Println(cmd.helpMsg)
return nil
}
}
}
return noCmdError
}
fmt.Println("The following commands are available:")
w := new(tabwriter.Writer)
w.Init(os.Stdout, 0, 8, 0, '-', 0)
for _, cmd := range c.cmds {
h := cmd.helpMsg
if idx := strings.Index(h, "\n"); idx >= 0 {
h = h[:idx]
}
if len(cmd.aliases) > 1 {
fmt.Fprintf(w, " %s (alias: %s) \t %s\n", cmd.aliases[0], strings.Join(cmd.aliases[1:], " | "), h)
} else {
fmt.Fprintf(w, " %s \t %s\n", cmd.aliases[0], h)
}
}
if err := w.Flush(); err != nil {
return err
}
fmt.Println("Type help followed by a command for full documentation.")
return nil
}
type byThreadID []*api.Thread
func (a byThreadID) Len() int { return len(a) }
func (a byThreadID) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a byThreadID) Less(i, j int) bool { return a[i].ID < a[j].ID }
func threads(t *Term, ctx callContext, args string) error {
threads, err := t.client.ListThreads()
if err != nil {
return err
}
state, err := t.client.GetState()
if err != nil {
return err
}
sort.Sort(byThreadID(threads))
for _, th := range threads {
prefix := " "
if state.CurrentThread != nil && state.CurrentThread.ID == th.ID {
prefix = "* "
}
if th.Function != nil {
fmt.Printf("%sThread %d at %#v %s:%d %s\n",
prefix, th.ID, th.PC, ShortenFilePath(th.File),
th.Line, th.Function.Name())
} else {
fmt.Printf("%sThread %s\n", prefix, formatThread(th))
}
}
return nil
}
func thread(t *Term, ctx callContext, args string) error {
if len(args) == 0 {
return fmt.Errorf("you must specify a thread")
}
tid, err := strconv.Atoi(args)
if err != nil {
return err
}
oldState, err := t.client.GetState()
if err != nil {
return err
}
newState, err := t.client.SwitchThread(tid)
if err != nil {
return err
}
oldThread := "<none>"
newThread := "<none>"
if oldState.CurrentThread != nil {
oldThread = strconv.Itoa(oldState.CurrentThread.ID)
}
if newState.CurrentThread != nil {
newThread = strconv.Itoa(newState.CurrentThread.ID)
}
fmt.Printf("Switched from %s to %s\n", oldThread, newThread)
return nil
}
type byGoroutineID []*api.Goroutine
func (a byGoroutineID) Len() int { return len(a) }
func (a byGoroutineID) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a byGoroutineID) Less(i, j int) bool { return a[i].ID < a[j].ID }
// The number of goroutines we're going to request on each RPC call
const goroutineBatchSize = 10000
func printGoroutines(t *Term, gs []*api.Goroutine, fgl formatGoroutineLoc, bPrintStack bool, state *api.DebuggerState) error {
for _, g := range gs {
prefix := " "
if state.SelectedGoroutine != nil && g.ID == state.SelectedGoroutine.ID {
prefix = "* "
}
fmt.Printf("%sGoroutine %s\n", prefix, formatGoroutine(g, fgl))
if bPrintStack {
stack, err := t.client.Stacktrace(g.ID, 10, false, nil)
if err != nil {
return err
}
printStack(stack, "\t", false)
}
}
return nil
}
func goroutines(t *Term, ctx callContext, argstr string) error {
args := strings.Split(argstr, " ")
var fgl = fglUserCurrent
bPrintStack := false
switch len(args) {
case 0:
// nothing to do
case 1, 2:
for _, arg := range args {
switch arg {
case "-u":
fgl = fglUserCurrent
case "-r":
fgl = fglRuntimeCurrent
case "-g":
fgl = fglGo
case "-s":
fgl = fglStart
case "-t":
bPrintStack = true
case "":
// nothing to do
default:
return fmt.Errorf("wrong argument: '%s'", arg)
}
}
default:
return fmt.Errorf("too many arguments")
}
state, err := t.client.GetState()
if err != nil {
return err
}
var (
start = 0
gslen = 0
gs []*api.Goroutine
)
for start >= 0 {
gs, start, err = t.client.ListGoroutines(start, goroutineBatchSize)
if err != nil {
return err
}
sort.Sort(byGoroutineID(gs))
err = printGoroutines(t, gs, fgl, bPrintStack, state)
if err != nil {
return err
}
gslen += len(gs)
}
fmt.Printf("[%d goroutines]\n", gslen)
return nil
}
func selectedGID(state *api.DebuggerState) int {
if state.SelectedGoroutine == nil {
return 0
}
return state.SelectedGoroutine.ID
}
func (c *Commands) goroutine(t *Term, ctx callContext, argstr string) error {
args := strings.SplitN(argstr, " ", 2)
if ctx.Prefix == onPrefix {
if len(args) != 1 || args[0] != "" {
return errors.New("too many arguments to goroutine")
}
ctx.Breakpoint.Goroutine = true
return nil
}
if len(args) == 1 {
if args[0] == "" {
return printscope(t)
}
gid, err := strconv.Atoi(argstr)
if err != nil {
return err
}
oldState, err := t.client.GetState()
if err != nil {
return err
}
newState, err := t.client.SwitchGoroutine(gid)
if err != nil {
return err
}
c.frame = 0
fmt.Printf("Switched from %d to %d (thread %d)\n", selectedGID(oldState), gid, newState.CurrentThread.ID)
return nil
}
var err error
ctx.Scope.GoroutineID, err = strconv.Atoi(args[0])
if err != nil {
return err
}
return c.CallWithContext(args[1], t, ctx)
}
// Handle "frame", "up", "down" commands.
func (c *Commands) frameCommand(t *Term, ctx callContext, argstr string, direction frameDirection) error {
frame := 1
arg := ""
if len(argstr) == 0 {
if direction == frameSet {
return errors.New("not enough arguments")
}
} else {
args := strings.SplitN(argstr, " ", 2)
var err error
if frame, err = strconv.Atoi(args[0]); err != nil {
return err
}
if len(args) > 1 {
arg = args[1]
}
}
switch direction {
case frameUp:
frame = c.frame + frame
case frameDown:
frame = c.frame - frame
}
if len(arg) > 0 {
ctx.Scope.Frame = frame
return c.CallWithContext(arg, t, ctx)
}
if frame < 0 {
return fmt.Errorf("Invalid frame %d", frame)
}
stack, err := t.client.Stacktrace(ctx.Scope.GoroutineID, frame, false, nil)
if err != nil {
return err
}
if frame >= len(stack) {
return fmt.Errorf("Invalid frame %d", frame)
}
c.frame = frame
state, err := t.client.GetState()
if err != nil {
return err
}
printcontext(t, state)
th := stack[frame]
fmt.Printf("Frame %d: %s:%d (PC: %x)\n", frame, ShortenFilePath(th.File), th.Line, th.PC)
printfile(t, th.File, th.Line, true)
return nil
}
func (c *Commands) deferredCommand(t *Term, ctx callContext, argstr string) error {
ctx.Prefix = deferredPrefix
space := strings.Index(argstr, " ")
var err error
ctx.Scope.DeferredCall, err = strconv.Atoi(argstr[:space])
if err != nil {
return err
}
if ctx.Scope.DeferredCall <= 0 {
return errors.New("argument of deferred must be a number greater than 0 (use 'stack -defer' to see the list of deferred calls)")
}
return c.CallWithContext(argstr[space:], t, ctx)
}
func printscope(t *Term) error {
state, err := t.client.GetState()
if err != nil {
return err
}
fmt.Printf("Thread %s\n", formatThread(state.CurrentThread))
if state.SelectedGoroutine != nil {
writeGoroutineLong(os.Stdout, state.SelectedGoroutine, "")
}
return nil
}
func formatThread(th *api.Thread) string {
if th == nil {
return "<nil>"
}
return fmt.Sprintf("%d at %s:%d", th.ID, ShortenFilePath(th.File), th.Line)
}
type formatGoroutineLoc int
const (
fglRuntimeCurrent = formatGoroutineLoc(iota)
fglUserCurrent
fglGo
fglStart
)
func formatLocation(loc api.Location) string {
return fmt.Sprintf("%s:%d %s (%#v)", ShortenFilePath(loc.File), loc.Line, loc.Function.Name(), loc.PC)
}
func formatGoroutine(g *api.Goroutine, fgl formatGoroutineLoc) string {
if g == nil {
return "<nil>"
}
if g.Unreadable != "" {
return fmt.Sprintf("(unreadable %s)", g.Unreadable)
}
var locname string
var loc api.Location
switch fgl {
case fglRuntimeCurrent:
locname = "Runtime"
loc = g.CurrentLoc
case fglUserCurrent:
locname = "User"
loc = g.UserCurrentLoc
case fglGo:
locname = "Go"
loc = g.GoStatementLoc
case fglStart:
locname = "Start"
loc = g.StartLoc
}
thread := ""
if g.ThreadID != 0 {
thread = fmt.Sprintf(" (thread %d)", g.ThreadID)
}
return fmt.Sprintf("%d - %s: %s%s", g.ID, locname, formatLocation(loc), thread)
}
func writeGoroutineLong(w io.Writer, g *api.Goroutine, prefix string) {
fmt.Fprintf(w, "%sGoroutine %d:\n%s\tRuntime: %s\n%s\tUser: %s\n%s\tGo: %s\n%s\tStart: %s\n",
prefix, g.ID,
prefix, formatLocation(g.CurrentLoc),
prefix, formatLocation(g.UserCurrentLoc),
prefix, formatLocation(g.GoStatementLoc),
prefix, formatLocation(g.StartLoc))
}
func parseArgs(args string) ([]string, error) {
if args == "" {
return nil, nil
}
v, err := argv.Argv([]rune(args), argv.ParseEnv(os.Environ()),
func(s []rune, _ map[string]string) ([]rune, error) {
return nil, fmt.Errorf("Backtick not supported in '%s'", string(s))
})
if err != nil {
return nil, err
}
if len(v) != 1 {
return nil, fmt.Errorf("Illegal commandline '%s'", args)
}
return v[0], nil
}
// parseOptionalCount parses an optional count argument.
// If there are not arguments, a value of 1 is returned as the default.
func parseOptionalCount(arg string) (int64, error) {
if len(arg) == 0 {
return 1, nil
}
return strconv.ParseInt(arg, 0, 64)
}
func restart(t *Term, ctx callContext, args string) error {
v, err := parseArgs(args)
if err != nil {
return err
}
var restartPos string
var resetArgs bool
if t.client.Recorded() {
if len(v) > 1 {
return fmt.Errorf("restart: illegal position '%v'", v)
}
if len(v) == 1 {
restartPos = v[0]
v = nil
}
} else if len(v) > 0 {
resetArgs = true
if v[0] == "-noargs" {
if len(v) > 1 {
return fmt.Errorf("restart: -noargs does not take any arg")
}
v = nil
}
}
discarded, err := t.client.RestartFrom(restartPos, resetArgs, v)
if err != nil {
return err
}
if !t.client.Recorded() {
fmt.Println("Process restarted with PID", t.client.ProcessPid())
}
for i := range discarded {
fmt.Printf("Discarded %s at %s: %v\n", formatBreakpointName(discarded[i].Breakpoint, false), formatBreakpointLocation(discarded[i].Breakpoint), discarded[i].Reason)
}
if t.client.Recorded() {
state, err := t.client.GetState()
if err != nil {
return err
}
printcontext(t, state)
printfile(t, state.CurrentThread.File, state.CurrentThread.Line, true)
}
return nil
}
func printcontextNoState(t *Term) {
state, _ := t.client.GetState()
if state == nil || state.CurrentThread == nil {
return
}
printcontext(t, state)
}
func (c *Commands) cont(t *Term, ctx callContext, args string) error {
c.frame = 0
stateChan := t.client.Continue()
var state *api.DebuggerState
for state = range stateChan {
if state.Err != nil {
printcontextNoState(t)
return state.Err
}
printcontext(t, state)
}
printfile(t, state.CurrentThread.File, state.CurrentThread.Line, true)
return nil
}
func continueUntilCompleteNext(t *Term, state *api.DebuggerState, op string, shouldPrintFile bool) error {
if !state.NextInProgress {
if shouldPrintFile {
printfile(t, state.CurrentThread.File, state.CurrentThread.Line, true)
}
return nil
}
for {
fmt.Printf("\tbreakpoint hit during %s, continuing...\n", op)
stateChan := t.client.Continue()
var state *api.DebuggerState
for state = range stateChan {
if state.Err != nil {
printcontextNoState(t)
return state.Err
}
printcontext(t, state)
}
if !state.NextInProgress {
printfile(t, state.CurrentThread.File, state.CurrentThread.Line, true)
return nil
}
}
}
func scopePrefixSwitch(t *Term, ctx callContext) error {
if ctx.Scope.GoroutineID > 0 {
_, err := t.client.SwitchGoroutine(ctx.Scope.GoroutineID)
if err != nil {
return err
}
}
return nil
}
func exitedToError(state *api.DebuggerState, err error) (*api.DebuggerState, error) {
if err == nil && state.Exited {
return nil, fmt.Errorf("Process has exited with status %d", state.ExitStatus)
}
return state, err
}
func (c *Commands) step(t *Term, ctx callContext, args string) error {
if err := scopePrefixSwitch(t, ctx); err != nil {
return err
}
c.frame = 0
state, err := exitedToError(t.client.Step())
if err != nil {
printcontextNoState(t)
return err
}
printcontext(t, state)
return continueUntilCompleteNext(t, state, "step", true)
}
var notOnFrameZeroErr = errors.New("not on topmost frame")
func (c *Commands) stepInstruction(t *Term, ctx callContext, args string) error {
if err := scopePrefixSwitch(t, ctx); err != nil {
return err
}
if c.frame != 0 {
return notOnFrameZeroErr
}
var fn func() (*api.DebuggerState, error)
if ctx.Prefix == revPrefix {
fn = t.client.ReverseStepInstruction
} else {
fn = t.client.StepInstruction
}
state, err := exitedToError(fn())
if err != nil {
printcontextNoState(t)
return err
}
printcontext(t, state)
printfile(t, state.CurrentThread.File, state.CurrentThread.Line, true)
return nil
}
func (c *Commands) revCmd(t *Term, ctx callContext, args string) error {
if len(args) == 0 {
return errors.New("not enough arguments")
}
ctx.Prefix = revPrefix
if err := c.CallWithContext(args, t, ctx); err != nil {
return err
}
return nil
}
func (c *Commands) next(t *Term, ctx callContext, args string) error {
if err := scopePrefixSwitch(t, ctx); err != nil {
return err
}
if c.frame != 0 {
return notOnFrameZeroErr
}
var count int64
var err error
if count, err = parseOptionalCount(args); err != nil {
return err
} else if count <= 0 {
return errors.New("Invalid next count")
}
for ; count > 0; count-- {
state, err := exitedToError(t.client.Next())
if err != nil {
printcontextNoState(t)
return err
}
// If we're about the exit the loop, print the context.
finishedNext := count == 1
if finishedNext {
printcontext(t, state)
}
if err := continueUntilCompleteNext(t, state, "next", finishedNext); err != nil {
return err
}
}
return nil
}
func (c *Commands) stepout(t *Term, ctx callContext, args string) error {
if err := scopePrefixSwitch(t, ctx); err != nil {
return err
}
if c.frame != 0 {
return notOnFrameZeroErr
}
state, err := exitedToError(t.client.StepOut())
if err != nil {
printcontextNoState(t)
return err
}
printcontext(t, state)
return continueUntilCompleteNext(t, state, "stepout", true)
}
func (c *Commands) call(t *Term, ctx callContext, args string) error {
if err := scopePrefixSwitch(t, ctx); err != nil {
return err
}
const unsafePrefix = "-unsafe "
unsafe := false
if strings.HasPrefix(args, unsafePrefix) {
unsafe = true
args = args[len(unsafePrefix):]
}
state, err := exitedToError(t.client.Call(ctx.Scope.GoroutineID, args, unsafe))
c.frame = 0
if err != nil {
printcontextNoState(t)
return err
}
printcontext(t, state)
return continueUntilCompleteNext(t, state, "call", true)
}
func clear(t *Term, ctx callContext, args string) error {
if len(args) == 0 {
return fmt.Errorf("not enough arguments")
}
id, err := strconv.Atoi(args)
var bp *api.Breakpoint
if err == nil {
bp, err = t.client.ClearBreakpoint(id)
} else {
bp, err = t.client.ClearBreakpointByName(args)
}
if err != nil {
return err
}
fmt.Printf("%s cleared at %s\n", formatBreakpointName(bp, true), formatBreakpointLocation(bp))
return nil
}
func clearAll(t *Term, ctx callContext, args string) error {
breakPoints, err := t.client.ListBreakpoints()
if err != nil {
return err
}
var locPCs map[uint64]struct{}
if args != "" {
locs, err := t.client.FindLocation(api.EvalScope{GoroutineID: -1, Frame: 0}, args)
if err != nil {
return err
}
locPCs = make(map[uint64]struct{})
for _, loc := range locs {
locPCs[loc.PC] = struct{}{}
}
}
for _, bp := range breakPoints {
if locPCs != nil {
if _, ok := locPCs[bp.Addr]; !ok {
continue
}
}
if bp.ID < 0 {
continue
}
_, err := t.client.ClearBreakpoint(bp.ID)
if err != nil {
fmt.Printf("Couldn't delete %s at %s: %s\n", formatBreakpointName(bp, false), formatBreakpointLocation(bp), err)
}
fmt.Printf("%s cleared at %s\n", formatBreakpointName(bp, true), formatBreakpointLocation(bp))
}
return nil
}
// ByID sorts breakpoints by ID.
type ByID []*api.Breakpoint
func (a ByID) Len() int { return len(a) }
func (a ByID) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ByID) Less(i, j int) bool { return a[i].ID < a[j].ID }
func breakpoints(t *Term, ctx callContext, args string) error {
breakPoints, err := t.client.ListBreakpoints()
if err != nil {
return err
}
sort.Sort(ByID(breakPoints))
for _, bp := range breakPoints {
fmt.Printf("%s at %v (%d)\n", formatBreakpointName(bp, true), formatBreakpointLocation(bp), bp.TotalHitCount)
var attrs []string
if bp.Cond != "" {
attrs = append(attrs, fmt.Sprintf("\tcond %s", bp.Cond))
}
if bp.Stacktrace > 0 {
attrs = append(attrs, fmt.Sprintf("\tstack %d", bp.Stacktrace))
}
if bp.Goroutine {
attrs = append(attrs, "\tgoroutine")
}
if bp.LoadArgs != nil {
if *(bp.LoadArgs) == LongLoadConfig {
attrs = append(attrs, "\targs -v")
} else {
attrs = append(attrs, "\targs")
}
}
if bp.LoadLocals != nil {
if *(bp.LoadLocals) == LongLoadConfig {
attrs = append(attrs, "\tlocals -v")
} else {
attrs = append(attrs, "\tlocals")
}
}
for i := range bp.Variables {
attrs = append(attrs, fmt.Sprintf("\tprint %s", bp.Variables[i]))
}
if len(attrs) > 0 {
fmt.Printf("%s\n", strings.Join(attrs, "\n"))
}
}
return nil
}
func setBreakpoint(t *Term, ctx callContext, tracepoint bool, argstr string) error {
args := strings.SplitN(argstr, " ", 2)
requestedBp := &api.Breakpoint{}
locspec := ""
switch len(args) {
case 1:
locspec = argstr
case 2:
if api.ValidBreakpointName(args[0]) == nil {
requestedBp.Name = args[0]
locspec = args[1]
} else {
locspec = argstr
}
default:
return fmt.Errorf("address required")
}
requestedBp.Tracepoint = tracepoint
locs, err := t.client.FindLocation(ctx.Scope, locspec)
if err != nil {
if requestedBp.Name == "" {
return err
}
requestedBp.Name = ""
locspec = argstr
var err2 error
locs, err2 = t.client.FindLocation(ctx.Scope, locspec)
if err2 != nil {
return err
}
}
for _, loc := range locs {
requestedBp.Addr = loc.PC
bp, err := t.client.CreateBreakpoint(requestedBp)
if err != nil {
return err
}
fmt.Printf("%s set at %s\n", formatBreakpointName(bp, true), formatBreakpointLocation(bp))
}
return nil
}
func breakpoint(t *Term, ctx callContext, args string) error {
return setBreakpoint(t, ctx, false, args)
}
func tracepoint(t *Term, ctx callContext, args string) error {
return setBreakpoint(t, ctx, true, args)
}
func edit(t *Term, ctx callContext, args string) error {
file, lineno, _, err := getLocation(t, ctx, args, false)
if err != nil {
return err
}
var editor string
if editor = os.Getenv("DELVE_EDITOR"); editor == "" {
if editor = os.Getenv("EDITOR"); editor == "" {
return fmt.Errorf("Neither DELVE_EDITOR or EDITOR is set")
}
}
cmd := exec.Command(editor, fmt.Sprintf("+%d", lineno), file)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
return cmd.Run()
}
func printVar(t *Term, ctx callContext, args string) error {
if len(args) == 0 {
return fmt.Errorf("not enough arguments")
}
if ctx.Prefix == onPrefix {
ctx.Breakpoint.Variables = append(ctx.Breakpoint.Variables, args)
return nil
}
val, err := t.client.EvalVariable(ctx.Scope, args, t.loadConfig())
if err != nil {
return err
}
fmt.Println(val.MultilineString(""))
return nil
}
func whatisCommand(t *Term, ctx callContext, args string) error {
if len(args) == 0 {
return fmt.Errorf("not enough arguments")
}
val, err := t.client.EvalVariable(ctx.Scope, args, ShortLoadConfig)
if err != nil {
return err
}
if val.Type != "" {
fmt.Println(val.Type)
}
if val.RealType != val.Type {
fmt.Printf("Real type: %s\n", val.RealType)
}
if val.Kind == reflect.Interface && len(val.Children) > 0 {
fmt.Printf("Concrete type: %s\n", val.Children[0].Type)
}
if t.conf.ShowLocationExpr && val.LocationExpr != "" {
fmt.Printf("location: %s\n", val.LocationExpr)
}
return nil
}
func setVar(t *Term, ctx callContext, args string) error {
// HACK: in go '=' is not an operator, we detect the error and try to recover from it by splitting the input string
_, err := parser.ParseExpr(args)
if err == nil {
return fmt.Errorf("syntax error '=' not found")
}
el, ok := err.(scanner.ErrorList)
if !ok || el[0].Msg != "expected '==', found '='" {
return err
}
lexpr := args[:el[0].Pos.Offset]
rexpr := args[el[0].Pos.Offset+1:]
return t.client.SetVariable(ctx.Scope, lexpr, rexpr)
}
func printFilteredVariables(varType string, vars []api.Variable, filter string, cfg api.LoadConfig) error {
reg, err := regexp.Compile(filter)
if err != nil {
return err
}
match := false
for _, v := range vars {
if reg == nil || reg.Match([]byte(v.Name)) {
match = true
name := v.Name
if v.Flags&api.VariableShadowed != 0 {
name = "(" + name + ")"
}
if cfg == ShortLoadConfig {
fmt.Printf("%s = %s\n", name, v.SinglelineString())
} else {
fmt.Printf("%s = %s\n", name, v.MultilineString(""))
}
}
}
if !match {
fmt.Printf("(no %s)\n", varType)
}
return nil
}
func printSortedStrings(v []string, err error) error {
if err != nil {
return err
}
sort.Strings(v)
for _, d := range v {
fmt.Println(d)
}
return nil
}
func sources(t *Term, ctx callContext, args string) error {
return printSortedStrings(t.client.ListSources(args))
}
func funcs(t *Term, ctx callContext, args string) error {
return printSortedStrings(t.client.ListFunctions(args))
}
func types(t *Term, ctx callContext, args string) error {
return printSortedStrings(t.client.ListTypes(args))
}
func parseVarArguments(args string, t *Term) (filter string, cfg api.LoadConfig) {
if v := strings.SplitN(args, " ", 2); len(v) >= 1 && v[0] == "-v" {
if len(v) == 2 {
return v[1], t.loadConfig()
} else {
return "", t.loadConfig()
}
}
return args, ShortLoadConfig
}
func args(t *Term, ctx callContext, args string) error {
filter, cfg := parseVarArguments(args, t)
if ctx.Prefix == onPrefix {
if filter != "" {
return fmt.Errorf("filter not supported on breakpoint")
}
ctx.Breakpoint.LoadArgs = &cfg
return nil
}
vars, err := t.client.ListFunctionArgs(ctx.Scope, cfg)
if err != nil {
return err
}
return printFilteredVariables("args", vars, filter, cfg)
}
func locals(t *Term, ctx callContext, args string) error {
filter, cfg := parseVarArguments(args, t)
if ctx.Prefix == onPrefix {
if filter != "" {
return fmt.Errorf("filter not supported on breakpoint")
}
ctx.Breakpoint.LoadLocals = &cfg
return nil
}
locals, err := t.client.ListLocalVariables(ctx.Scope, cfg)
if err != nil {
return err
}
return printFilteredVariables("locals", locals, filter, cfg)
}
func vars(t *Term, ctx callContext, args string) error {
filter, cfg := parseVarArguments(args, t)
vars, err := t.client.ListPackageVariables(filter, cfg)
if err != nil {
return err
}
return printFilteredVariables("vars", vars, filter, cfg)
}
func regs(t *Term, ctx callContext, args string) error {
includeFp := false
if args == "-a" {
includeFp = true
}
regs, err := t.client.ListRegisters(0, includeFp)
if err != nil {
return err
}
fmt.Println(regs)
return nil
}
func stackCommand(t *Term, ctx callContext, args string) error {
sa, err := parseStackArgs(args)
if err != nil {
return err
}
if ctx.Prefix == onPrefix {
ctx.Breakpoint.Stacktrace = sa.depth
return nil
}
var cfg *api.LoadConfig
if sa.full {
cfg = &ShortLoadConfig
}
stack, err := t.client.Stacktrace(ctx.Scope.GoroutineID, sa.depth, sa.readDefers, cfg)
if err != nil {
return err
}
printStack(stack, "", sa.offsets)
if sa.ancestors > 0 {
ancestors, err := t.client.Ancestors(ctx.Scope.GoroutineID, sa.ancestors, sa.ancestorDepth)
if err != nil {
return err
}
for _, ancestor := range ancestors {
fmt.Printf("Created by Goroutine %d:\n", ancestor.ID)
if ancestor.Unreadable != "" {
fmt.Printf("\t%s\n", ancestor.Unreadable)
continue
}
printStack(ancestor.Stack, "\t", false)
}
}
return nil
}
type stackArgs struct {
depth int
full bool
offsets bool
readDefers bool
ancestors int
ancestorDepth int
}
func parseStackArgs(argstr string) (stackArgs, error) {
r := stackArgs{
depth: 50,
full: false,
}
if argstr != "" {
args := strings.Split(argstr, " ")
for i := 0; i < len(args); i++ {
numarg := func(name string) (int, error) {
if i >= len(args) {
return 0, fmt.Errorf("expected number after %s", name)
}
n, err := strconv.Atoi(args[i])
if err != nil {
return 0, fmt.Errorf("expected number after %s: %v", name, err)
}
return n, nil
}
switch args[i] {
case "-full":
r.full = true
case "-offsets":
r.offsets = true
case "-defer":
r.readDefers = true
case "-a":
i++
n, err := numarg("-a")
if err != nil {
return stackArgs{}, err
}
r.ancestors = n
case "-adepth":
i++
n, err := numarg("-adepth")
if err != nil {
return stackArgs{}, err
}
r.ancestorDepth = n
default:
n, err := strconv.Atoi(args[i])
if err != nil {
return stackArgs{}, fmt.Errorf("depth must be a number")
}
r.depth = n
}
}
}
if r.ancestors > 0 && r.ancestorDepth == 0 {
r.ancestorDepth = r.depth
}
return r, nil
}
// getLocation returns the current location or the locations specified by the argument.
// getLocation is used to process the argument of list and edit commands.
func getLocation(t *Term, ctx callContext, args string, showContext bool) (file string, lineno int, showarrow bool, err error) {
switch {
case len(args) == 0 && !ctx.scoped():
state, err := t.client.GetState()
if err != nil {
return "", 0, false, err
}
if showContext {
printcontext(t, state)
}
if state.SelectedGoroutine != nil {
return state.SelectedGoroutine.CurrentLoc.File, state.SelectedGoroutine.CurrentLoc.Line, true, nil
}
return state.CurrentThread.File, state.CurrentThread.Line, true, nil
case len(args) == 0 && ctx.scoped():
locs, err := t.client.Stacktrace(ctx.Scope.GoroutineID, ctx.Scope.Frame, false, nil)
if err != nil {
return "", 0, false, err
}
if ctx.Scope.Frame >= len(locs) {
return "", 0, false, fmt.Errorf("Frame %d does not exist in goroutine %d", ctx.Scope.Frame, ctx.Scope.GoroutineID)
}
loc := locs[ctx.Scope.Frame]
gid := ctx.Scope.GoroutineID
if gid < 0 {
state, err := t.client.GetState()
if err != nil {
return "", 0, false, err
}
if state.SelectedGoroutine != nil {
gid = state.SelectedGoroutine.ID
}
}
if showContext {
fmt.Printf("Goroutine %d frame %d at %s:%d (PC: %#x)\n", gid, ctx.Scope.Frame, loc.File, loc.Line, loc.PC)
}
return loc.File, loc.Line, true, nil
default:
locs, err := t.client.FindLocation(ctx.Scope, args)
if err != nil {
return "", 0, false, err
}
if len(locs) > 1 {
return "", 0, false, debugger.AmbiguousLocationError{Location: args, CandidatesLocation: locs}
}
loc := locs[0]
if showContext {
fmt.Printf("Showing %s:%d (PC: %#x)\n", loc.File, loc.Line, loc.PC)
}
return loc.File, loc.Line, false, nil
}
}
func listCommand(t *Term, ctx callContext, args string) error {
file, lineno, showarrow, err := getLocation(t, ctx, args, true)
if err != nil {
return err
}
return printfile(t, file, lineno, showarrow)
}
func (c *Commands) sourceCommand(t *Term, ctx callContext, args string) error {
if len(args) == 0 {
return fmt.Errorf("wrong number of arguments: source <filename>")
}
if filepath.Ext(args) == ".star" {
_, err := t.starlarkEnv.Execute(args, nil, "main", nil)
return err
}
if args == "-" {
return t.starlarkEnv.REPL()
}
return c.executeFile(t, args)
}
var disasmUsageError = errors.New("wrong number of arguments: disassemble [-a <start> <end>] [-l <locspec>]")
func disassCommand(t *Term, ctx callContext, args string) error {
var cmd, rest string
if args != "" {
argv := strings.SplitN(args, " ", 2)
if len(argv) != 2 {
return disasmUsageError
}
cmd = argv[0]
rest = argv[1]
}
var disasm api.AsmInstructions
var disasmErr error
switch cmd {
case "":
locs, err := t.client.FindLocation(ctx.Scope, "+0")
if err != nil {
return err
}
disasm, disasmErr = t.client.DisassemblePC(ctx.Scope, locs[0].PC, api.IntelFlavour)
case "-a":
v := strings.SplitN(rest, " ", 2)
if len(v) != 2 {
return disasmUsageError
}
startpc, err := strconv.ParseInt(v[0], 0, 64)
if err != nil {
return fmt.Errorf("wrong argument: %s is not a number", v[0])
}
endpc, err := strconv.ParseInt(v[1], 0, 64)
if err != nil {
return fmt.Errorf("wrong argument: %s is not a number", v[1])
}
disasm, disasmErr = t.client.DisassembleRange(ctx.Scope, uint64(startpc), uint64(endpc), api.IntelFlavour)
case "-l":
locs, err := t.client.FindLocation(ctx.Scope, rest)
if err != nil {
return err
}
if len(locs) != 1 {
return errors.New("expression specifies multiple locations")
}
disasm, disasmErr = t.client.DisassemblePC(ctx.Scope, locs[0].PC, api.IntelFlavour)
default:
return disasmUsageError
}
if disasmErr != nil {
return disasmErr
}
DisasmPrint(disasm, os.Stdout)
return nil
}
func libraries(t *Term, ctx callContext, args string) error {
libs, err := t.client.ListDynamicLibraries()
if err != nil {
return err
}
d := digits(len(libs))
for i := range libs {
fmt.Printf("%"+strconv.Itoa(d)+"d. %#x %s\n", i, libs[i].Address, libs[i].Path)
}
return nil
}
func digits(n int) int {
if n <= 0 {
return 1
}
return int(math.Floor(math.Log10(float64(n)))) + 1
}
const stacktraceTruncatedMessage = "(truncated)"
func printStack(stack []api.Stackframe, ind string, offsets bool) {
if len(stack) == 0 {
return
}
extranl := offsets
for i := range stack {
if extranl {
break
}
extranl = extranl || (len(stack[i].Defers) > 0) || (len(stack[i].Arguments) > 0) || (len(stack[i].Locals) > 0)
}
d := digits(len(stack) - 1)
fmtstr := "%s%" + strconv.Itoa(d) + "d 0x%016x in %s\n"
s := ind + strings.Repeat(" ", d+2+len(ind))
for i := range stack {
if stack[i].Err != "" {
fmt.Printf("%serror: %s\n", s, stack[i].Err)
continue
}
fmt.Printf(fmtstr, ind, i, stack[i].PC, stack[i].Function.Name())
fmt.Printf("%sat %s:%d\n", s, ShortenFilePath(stack[i].File), stack[i].Line)
if offsets {
fmt.Printf("%sframe: %+#x frame pointer %+#x\n", s, stack[i].FrameOffset, stack[i].FramePointerOffset)
}
for j, d := range stack[i].Defers {
deferHeader := fmt.Sprintf("%s defer %d: ", s, j+1)
s2 := strings.Repeat(" ", len(deferHeader))
if d.Unreadable != "" {
fmt.Printf("%s(unreadable defer: %s)\n", deferHeader, d.Unreadable)
continue
}
fmt.Printf("%s%#016x in %s\n", deferHeader, d.DeferredLoc.PC, d.DeferredLoc.Function.Name())
fmt.Printf("%sat %s:%d\n", s2, d.DeferredLoc.File, d.DeferredLoc.Line)
fmt.Printf("%sdeferred by %s at %s:%d\n", s2, d.DeferLoc.Function.Name(), d.DeferLoc.File, d.DeferLoc.Line)
}
for j := range stack[i].Arguments {
fmt.Printf("%s %s = %s\n", s, stack[i].Arguments[j].Name, stack[i].Arguments[j].SinglelineString())
}
for j := range stack[i].Locals {
fmt.Printf("%s %s = %s\n", s, stack[i].Locals[j].Name, stack[i].Locals[j].SinglelineString())
}
if extranl {
fmt.Println()
}
}
if len(stack) > 0 && !stack[len(stack)-1].Bottom {
fmt.Printf("%s"+stacktraceTruncatedMessage+"\n", ind)
}
}
func printcontext(t *Term, state *api.DebuggerState) {
for i := range state.Threads {
if (state.CurrentThread != nil) && (state.Threads[i].ID == state.CurrentThread.ID) {
continue
}
if state.Threads[i].Breakpoint != nil {
printcontextThread(t, state.Threads[i])
}
}
if state.CurrentThread == nil {
fmt.Println("No current thread available")
return
}
var th *api.Thread
if state.SelectedGoroutine == nil {
th = state.CurrentThread
} else {
for i := range state.Threads {
if state.Threads[i].ID == state.SelectedGoroutine.ThreadID {
th = state.Threads[i]
break
}
}
if th == nil {
printcontextLocation(state.SelectedGoroutine.CurrentLoc)
return
}
}
if th.File == "" {
fmt.Printf("Stopped at: 0x%x\n", state.CurrentThread.PC)
t.Println("=>", "no source available")
return
}
printcontextThread(t, th)
if state.When != "" {
fmt.Println(state.When)
}
}
func printcontextLocation(loc api.Location) {
fmt.Printf("> %s() %s:%d (PC: %#v)\n", loc.Function.Name(), ShortenFilePath(loc.File), loc.Line, loc.PC)
if loc.Function != nil && loc.Function.Optimized {
fmt.Println(optimizedFunctionWarning)
}
return
}
func printReturnValues(th *api.Thread) {
if th.ReturnValues == nil {
return
}
fmt.Println("Values returned:")
for _, v := range th.ReturnValues {
fmt.Printf("\t%s: %s\n", v.Name, v.MultilineString("\t"))
}
fmt.Println()
}
func printcontextThread(t *Term, th *api.Thread) {
fn := th.Function
if th.Breakpoint == nil {
printcontextLocation(api.Location{PC: th.PC, File: th.File, Line: th.Line, Function: th.Function})
printReturnValues(th)
return
}
args := ""
if th.BreakpointInfo != nil && th.Breakpoint.LoadArgs != nil && *th.Breakpoint.LoadArgs == ShortLoadConfig {
var arg []string
for _, ar := range th.BreakpointInfo.Arguments {
// For AI compatibility return values are included in the
// argument list. This is a relic of the dark ages when the
// Go debug information did not distinguish between the two.
// Filter them out here instead, so during trace operations
// they are not printed as an argument.
if (ar.Flags & api.VariableArgument) != 0 {
arg = append(arg, ar.SinglelineString())
}
}
args = strings.Join(arg, ", ")
}
bpname := ""
if th.Breakpoint.Name != "" {
bpname = fmt.Sprintf("[%s] ", th.Breakpoint.Name)
}
if hitCount, ok := th.Breakpoint.HitCount[strconv.Itoa(th.GoroutineID)]; ok {
fmt.Printf("> %s%s(%s) %s:%d (hits goroutine(%d):%d total:%d) (PC: %#v)\n",
bpname,
fn.Name(),
args,
ShortenFilePath(th.File),
th.Line,
th.GoroutineID,
hitCount,
th.Breakpoint.TotalHitCount,
th.PC)
} else {
fmt.Printf("> %s%s(%s) %s:%d (hits total:%d) (PC: %#v)\n",
bpname,
fn.Name(),
args,
ShortenFilePath(th.File),
th.Line,
th.Breakpoint.TotalHitCount,
th.PC)
}
if th.Function != nil && th.Function.Optimized {
fmt.Println(optimizedFunctionWarning)
}
printReturnValues(th)
if th.BreakpointInfo != nil {
bp := th.Breakpoint
bpi := th.BreakpointInfo
if bpi.Goroutine != nil {
writeGoroutineLong(os.Stdout, bpi.Goroutine, "\t")
}
for _, v := range bpi.Variables {
fmt.Printf("\t%s: %s\n", v.Name, v.MultilineString("\t"))
}
for _, v := range bpi.Locals {
if *bp.LoadLocals == LongLoadConfig {
fmt.Printf("\t%s: %s\n", v.Name, v.MultilineString("\t"))
} else {
fmt.Printf("\t%s: %s\n", v.Name, v.SinglelineString())
}
}
if bp.LoadArgs != nil && *bp.LoadArgs == LongLoadConfig {
for _, v := range bpi.Arguments {
fmt.Printf("\t%s: %s\n", v.Name, v.MultilineString("\t"))
}
}
if bpi.Stacktrace != nil {
fmt.Printf("\tStack:\n")
printStack(bpi.Stacktrace, "\t\t", false)
}
}
}
func printfile(t *Term, filename string, line int, showArrow bool) error {
if filename == "" {
return nil
}
file, err := os.Open(t.substitutePath(filename))
if err != nil {
return err
}
defer file.Close()
fi, _ := file.Stat()
lastModExe := t.client.LastModified()
if fi.ModTime().After(lastModExe) {
fmt.Println("Warning: listing may not match stale executable")
}
buf := bufio.NewScanner(file)
l := line
for i := 1; i < l-5; i++ {
if !buf.Scan() {
return nil
}
}
s := l - 5
if s < 1 {
s = 1
}
for i := s; i <= l+5; i++ {
if !buf.Scan() {
return nil
}
var prefix string
if showArrow {
prefix = " "
if i == l {
prefix = "=>"
}
}
prefix = fmt.Sprintf("%s%4d:\t", prefix, i)
t.Println(prefix, buf.Text())
}
return nil
}
// ExitRequestError is returned when the user
// exits Delve.
type ExitRequestError struct{}
func (ere ExitRequestError) Error() string {
return ""
}
func exitCommand(t *Term, ctx callContext, args string) error {
if args == "-c" {
if !t.client.IsMulticlient() {
return errors.New("not connected to an --accept-multiclient server")
}
t.quitContinue = true
}
return ExitRequestError{}
}
func getBreakpointByIDOrName(t *Term, arg string) (*api.Breakpoint, error) {
if id, err := strconv.Atoi(arg); err == nil {
return t.client.GetBreakpoint(id)
}
return t.client.GetBreakpointByName(arg)
}
func (c *Commands) onCmd(t *Term, ctx callContext, argstr string) error {
args := strings.SplitN(argstr, " ", 2)
if len(args) < 2 {
return errors.New("not enough arguments")
}
bp, err := getBreakpointByIDOrName(t, args[0])
if err != nil {
return err
}
ctx.Prefix = onPrefix
ctx.Breakpoint = bp
err = c.CallWithContext(args[1], t, ctx)
if err != nil {
return err
}
return t.client.AmendBreakpoint(ctx.Breakpoint)
}
func conditionCmd(t *Term, ctx callContext, argstr string) error {
args := strings.SplitN(argstr, " ", 2)
if len(args) < 2 {
return fmt.Errorf("not enough arguments")
}
bp, err := getBreakpointByIDOrName(t, args[0])
if err != nil {
return err
}
bp.Cond = args[1]
return t.client.AmendBreakpoint(bp)
}
// ShortenFilePath take a full file path and attempts to shorten
// it by replacing the current directory to './'.
func ShortenFilePath(fullPath string) string {
workingDir, _ := os.Getwd()
return strings.Replace(fullPath, workingDir, ".", 1)
}
func (c *Commands) executeFile(t *Term, name string) error {
fh, err := os.Open(name)
if err != nil {
return err
}
defer fh.Close()
scanner := bufio.NewScanner(fh)
lineno := 0
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
lineno++
if line == "" || line[0] == '#' {
continue
}
if err := c.Call(line, t); err != nil {
if _, isExitRequest := err.(ExitRequestError); isExitRequest {
return err
}
fmt.Printf("%s:%d: %v\n", name, lineno, err)
}
}
return scanner.Err()
}
func rewind(t *Term, ctx callContext, args string) error {
stateChan := t.client.Rewind()
var state *api.DebuggerState
for state = range stateChan {
if state.Err != nil {
return state.Err
}
printcontext(t, state)
}
printfile(t, state.CurrentThread.File, state.CurrentThread.Line, true)
return nil
}
func checkpoint(t *Term, ctx callContext, args string) error {
if args == "" {
state, err := t.client.GetState()
if err != nil {
return err
}
var loc api.Location = api.Location{PC: state.CurrentThread.PC, File: state.CurrentThread.File, Line: state.CurrentThread.Line, Function: state.CurrentThread.Function}
if state.SelectedGoroutine != nil {
loc = state.SelectedGoroutine.CurrentLoc
}
args = fmt.Sprintf("%s() %s:%d (%#x)", loc.Function.Name(), loc.File, loc.Line, loc.PC)
}
cpid, err := t.client.Checkpoint(args)
if err != nil {
return err
}
fmt.Printf("Checkpoint c%d created.\n", cpid)
return nil
}
func checkpoints(t *Term, ctx callContext, args string) error {
cps, err := t.client.ListCheckpoints()
if err != nil {
return err
}
w := new(tabwriter.Writer)
w.Init(os.Stdout, 4, 4, 2, ' ', 0)
fmt.Fprintln(w, "ID\tWhen\tNote")
for _, cp := range cps {
fmt.Fprintf(w, "c%d\t%s\t%s\n", cp.ID, cp.When, cp.Where)
}
w.Flush()
return nil
}
func clearCheckpoint(t *Term, ctx callContext, args string) error {
if len(args) == 0 {
return errors.New("not enough arguments to clear-checkpoint")
}
if args[0] != 'c' {
return errors.New("clear-checkpoint argument must be a checkpoint ID")
}
id, err := strconv.Atoi(args[1:])
if err != nil {
return errors.New("clear-checkpoint argument must be a checkpoint ID")
}
return t.client.ClearCheckpoint(id)
}
func formatBreakpointName(bp *api.Breakpoint, upcase bool) string {
thing := "breakpoint"
if bp.Tracepoint {
thing = "tracepoint"
}
if upcase {
thing = strings.Title(thing)
}
id := bp.Name
if id == "" {
id = strconv.Itoa(bp.ID)
}
return fmt.Sprintf("%s %s", thing, id)
}
func formatBreakpointLocation(bp *api.Breakpoint) string {
p := ShortenFilePath(bp.File)
if bp.FunctionName != "" {
return fmt.Sprintf("%#v for %s() %s:%d", bp.Addr, bp.FunctionName, p, bp.Line)
}
return fmt.Sprintf("%#v for %s:%d", bp.Addr, p, bp.Line)
}
| {
"content_hash": "27fa590334bb2b90c925fd9094fb87a4",
"timestamp": "",
"source": "github",
"line_count": 2165,
"max_line_length": 240,
"avg_line_length": 26.88498845265589,
"alnum_prop": 0.6660481737277943,
"repo_name": "dr2chase/delve",
"id": "f3eb87010c30b395ca7f6eaddfcf6f8f2f788515",
"size": "58328",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pkg/terminal/command.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "1687"
},
{
"name": "C",
"bytes": "75784"
},
{
"name": "Go",
"bytes": "1563236"
},
{
"name": "Makefile",
"bytes": "452"
},
{
"name": "Shell",
"bytes": "1910"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2010-2015 Evolveum
~
~ 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.
-->
<!--
This file is an example of Resource definition. It defines an LDAP resource
using an Identity Connector Framework LDAP connector. It contains configuration
for use with stock OpenDJ and OpenDS servers.
This is "Medium difficulty" resource definition.
It contains outbound mappings to correctly populate new accounts.
It also contains inbound mappings and definition to enable synchronization.
-->
<objects xmlns="http://midpoint.evolveum.com/xml/ns/public/common/common-3"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:c="http://midpoint.evolveum.com/xml/ns/public/common/common-3"
xmlns:t="http://prism.evolveum.com/xml/ns/public/types-3"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:ri="http://midpoint.evolveum.com/xml/ns/public/resource/instance-3"
xmlns:icfs="http://midpoint.evolveum.com/xml/ns/public/connector/icf-1/resource-schema-3"
xmlns:icfc="http://midpoint.evolveum.com/xml/ns/public/connector/icf-1/connector-schema-3"
xmlns:my="http://whatever.com/my"
xmlns:q="http://prism.evolveum.com/xml/ns/public/query-3"
xmlns:mr="http://prism.evolveum.com/xml/ns/public/matching-rule-3">
<resource oid="ef2bc95b-76e0-48e2-86d6-3d4f02d3e1a2">
<!-- Resource name. It will be displayed in GUI. -->
<name>Localhost OpenDJ</name>
<description>
LDAP resource using an Identity Connector Framework LDAP connector. It contains configuration
for use with stock OpenDJ and OpenDS servers.
This resource definition contains also definition to enable synchronization.
</description>
<connectorRef type="ConnectorType">
<description>
Reference to the ICF LDAP connector. This is dynamic reference, it will be translated to
OID during import.
</description>
<filter>
<q:equal>
<q:path>c:connectorType</q:path>
<q:value>com.evolveum.polygon.connector.ldap.LdapConnector</q:value>
</q:equal>
</filter>
</connectorRef>
<!-- Configuration section contains configuration of the connector,
such as hostnames and passwords -->
<connectorConfiguration>
<icfc:configurationProperties
xmlns:icfcldap="http://midpoint.evolveum.com/xml/ns/public/connector/icf-1/bundle/com.evolveum.polygon.connector-ldap/com.evolveum.polygon.connector.ldap.LdapConnector">
<icfcldap:port>1389</icfcldap:port>
<icfcldap:host>localhost</icfcldap:host>
<icfcldap:baseContext>dc=example,dc=com</icfcldap:baseContext>
<icfcldap:bindDn>uid=idm,ou=Administrators,dc=example,dc=com</icfcldap:bindDn>
<icfcldap:bindPassword>
<t:clearValue>secret</t:clearValue>
</icfcldap:bindPassword>
<icfcldap:pagingStrategy>auto</icfcldap:pagingStrategy>
<icfcldap:vlvSortAttribute>entryUUID</icfcldap:vlvSortAttribute>
<!-- <icfcldap:accountOperationalAttributes>ds-pwp-account-disabled</icfcldap:accountOperationalAttributes>-->
<icfcldap:operationalAttributes>ds-pwp-account-disabled</icfcldap:operationalAttributes>
<icfcldap:operationalAttributes>isMemberOf</icfcldap:operationalAttributes>
</icfc:configurationProperties>
<icfc:resultsHandlerConfiguration>
<icfc:enableNormalizingResultsHandler>false</icfc:enableNormalizingResultsHandler>
<icfc:enableFilteredResultsHandler>false</icfc:enableFilteredResultsHandler>
<icfc:enableAttributesToGetSearchResultsHandler>false</icfc:enableAttributesToGetSearchResultsHandler>
</icfc:resultsHandlerConfiguration>
</connectorConfiguration>
<!-- Resource Schema Handling definition.
This part defines how the schema defined above will be used by
midPoint. It defines expressions and limitations for individual
schema attributes.
The expressions that describe both inbound and outbound flow of
the attributes are defined in this section.
This is the part where most of the customization takes place.
-->
<schema>
<!-- workaround to MID-2723 -->
<generationConstraints>
<generateObjectClass>ri:inetOrgPerson</generateObjectClass>
<generateObjectClass>ri:groupOfUniqueNames</generateObjectClass>
<generateObjectClass>ri:groupOfNames</generateObjectClass>
<generateObjectClass>ri:organizationalUnit</generateObjectClass>
</generationConstraints>
</schema>
<schemaHandling>
<objectType>
<kind>account</kind>
<displayName>Normal Account</displayName>
<default>true</default>
<objectClass>ri:inetOrgPerson</objectClass>
<attribute>
<ref>ri:dn</ref>
<displayName>Distinguished Name</displayName>
<limitations>
<minOccurs>0</minOccurs>
<access>
<read>true</read>
<add>true</add>
<modify>true</modify>
</access>
</limitations>
<matchingRule>mr:stringIgnoreCase</matchingRule>
<outbound>
<source>
<path>$user/name</path>
</source>
<expression>
<script>
<!-- No explicit script language was specified. It means that this is Groovy -->
<code>
'uid=' + name + iterationToken + ',ou=people,dc=example,dc=com'
</code>
</script>
</expression>
</outbound>
</attribute>
<attribute>
<ref>ri:entryUUID</ref>
<displayName>Entry UUID</displayName>
<limitations>
<access>
<read>true</read>
<add>false</add>
<modify>true</modify>
</access>
</limitations>
<matchingRule>mr:stringIgnoreCase</matchingRule>
</attribute>
<attribute>
<ref>ri:cn</ref>
<displayName>Common Name</displayName>
<limitations>
<minOccurs>0</minOccurs>
<access>
<read>true</read>
<add>true</add>
<modify>true</modify>
</access>
</limitations>
<outbound>
<source>
<path>$user/fullName</path>
</source>
</outbound>
<inbound>
<target>
<path>$user/fullName</path>
</target>
</inbound>
</attribute>
<attribute>
<ref>ri:sn</ref>
<displayName>Surname</displayName>
<limitations>
<minOccurs>0</minOccurs>
</limitations>
<outbound>
<source>
<!-- The path can be shorteden like this. $user is a default source "context" in outbound -->
<path>familyName</path>
</source>
</outbound>
<inbound>
<target>
<!-- The path can be shorteden like this. $user is a default target "context" in inbound -->
<path>familyName</path>
</target>
</inbound>
</attribute>
<attribute>
<ref>ri:givenName</ref>
<displayName>Given Name</displayName>
<outbound>
<source>
<!-- Full namespace prefixes can be used in the path -->
<path>$c:user/c:givenName</path>
</source>
</outbound>
<inbound>
<target>
<path>$c:user/c:givenName</path>
</target>
</inbound>
</attribute>
<attribute>
<ref>ri:uid</ref>
<displayName>Login Name</displayName>
<matchingRule>mr:stringIgnoreCase</matchingRule>
<outbound>
<strength>weak</strength>
<source>
<description>Source may have description</description>
<path>$user/name</path>
</source>
<!-- We need to put iterationToken here as well, otherwise effect described in MID-2139 occurs -->
<expression>
<script>
<code>name + iterationToken</code>
</script>
</expression>
</outbound>
<inbound>
<target>
<description>Targets may have description</description>
<path>$c:user/c:name</path>
</target>
</inbound>
</attribute>
<attribute>
<ref>ri:description</ref>
<outbound>
<strength>weak</strength>
<expression>
<description>Expression that assigns a fixed value</description>
<value>Created by IDM</value>
</expression>
</outbound>
</attribute>
<attribute>
<ref>ri:l</ref>
<displayName>Location</displayName>
<outbound>
<source>
<path>$user/locality</path>
</source>
</outbound>
</attribute>
<attribute>
<ref>ri:employeeType</ref>
<displayName>Employee Type</displayName>
<tolerant>false</tolerant>
<outbound>
<source>
<path>$user/employeeType</path>
</source>
</outbound>
</attribute>
<iteration>
<maxIterations>5</maxIterations>
</iteration>
<protected>
<filter>
<q:equal>
<q:matching>http://prism.evolveum.com/xml/ns/public/matching-rule-3#distinguishedName</q:matching>
<q:path>attributes/ri:dn</q:path>
<q:value>uid=idm,ou=Administrators,dc=example,dc=com</q:value>
</q:equal>
</filter>
</protected>
<activation>
<administrativeStatus>
<outbound/>
<inbound>
<strength>weak</strength>
<expression>
<asIs/>
</expression>
</inbound>
</administrativeStatus>
</activation>
<credentials>
<password>
<outbound>
<expression>
<asIs/>
</expression>
</outbound>
<inbound>
<strength>weak</strength>
<expression>
<generate/>
</expression>
</inbound>
</password>
</credentials>
</objectType>
</schemaHandling>
<capabilities xmlns:cap="http://midpoint.evolveum.com/xml/ns/public/resource/capabilities-3">
<configured>
<cap:activation>
<cap:status>
<cap:attribute>ri:ds-pwp-account-disabled</cap:attribute>
<cap:enableValue/>
<cap:disableValue>true</cap:disableValue>
</cap:status>
</cap:activation>
</configured>
</capabilities>
<!--
Synchronization section describes the synchronization policy, timing,
reactions and similar synchronization settings.
-->
<synchronization>
<objectSynchronization>
<!--
The synchronization for this resource is enabled.
It means that the synchronization will react to changes detected by
the system (live sync task, discovery or reconciliation) -->
<enabled>true</enabled>
<correlation>
<q:description>
Correlation expression is a search query.
Following search query will look for users that have "name"
equal to the "uid" attribute of the account. Simply speaking,
it will look for match in usernames in the IDM and the resource.
The correlation rule always looks for users, so it will not match
any other object type.
</q:description>
<q:equal>
<q:path>name</q:path>
<expression>
<path>
declare namespace ri="http://midpoint.evolveum.com/xml/ns/public/resource/instance-3";
$account/attributes/ri:uid
</path>
</expression>
</q:equal>
</correlation>
<!-- Confirmation rule may be here, but as the search above will
always return at most one match, the confirmation rule is not needed. -->
<!-- Following section describes reactions to a situations.
The setting here assumes that this resource is authoritative,
therefore all accounts created on the resource should be
reflected as new users in IDM.
See http://wiki.evolveum.com/display/midPoint/Synchronization+Situations
-->
<reaction>
<situation>linked</situation>
<synchronize>true</synchronize>
</reaction>
<reaction>
<situation>deleted</situation>
<synchronize>true</synchronize>
<action>
<handlerUri>http://midpoint.evolveum.com/xml/ns/public/model/action-3#unlink</handlerUri>
</action>
</reaction>
<reaction>
<situation>unlinked</situation>
<synchronize>true</synchronize>
<action>
<handlerUri>http://midpoint.evolveum.com/xml/ns/public/model/action-3#link</handlerUri>
</action>
</reaction>
<reaction>
<situation>unmatched</situation>
<synchronize>true</synchronize>
<action>
<handlerUri>http://midpoint.evolveum.com/xml/ns/public/model/action-3#addFocus</handlerUri>
</action>
</reaction>
</objectSynchronization>
</synchronization>
</resource>
<task oid="91919192-76e0-59e2-86d6-3d4f02d3ffff">
<name>Synchronization: Embedded Test OpenDJ (no extensions schema)</name>
<description>
Definition of a live synchronization task. It will poll changelog and pull in changes
</description>
<taskIdentifier>91919191-76e0-59e2-86d6-3d4f02d3ffff</taskIdentifier>
<ownerRef oid="00000000-0000-0000-0000-000000000002"/>
<executionStatus>runnable</executionStatus>
<handlerUri>http://midpoint.evolveum.com/xml/ns/public/model/synchronization/task/live-sync/handler-3</handlerUri>
<objectRef oid="ef2bc95b-76e0-48e2-86d6-3d4f02d3e1a2" type="ResourceType"/>
<recurrence>recurring</recurrence>
<binding>tight</binding>
<schedule>
<interval>5</interval>
</schedule>
</task>
</objects>
| {
"content_hash": "633031be903c1638e48a11b421cf43f6",
"timestamp": "",
"source": "github",
"line_count": 419,
"max_line_length": 173,
"avg_line_length": 35.556085918854414,
"alnum_prop": 0.6055175191300846,
"repo_name": "PetrGasparik/midpoint",
"id": "130fa814b3b01ca5db760430f9e9d93c1d64c432",
"size": "14898",
"binary": false,
"copies": "1",
"ref": "refs/heads/CAS-auth",
"path": "samples/resources/opendj/opendj-localhost-medium.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "321145"
},
{
"name": "CSS",
"bytes": "234702"
},
{
"name": "HTML",
"bytes": "651627"
},
{
"name": "Java",
"bytes": "24107826"
},
{
"name": "JavaScript",
"bytes": "17224"
},
{
"name": "PLSQL",
"bytes": "2171"
},
{
"name": "PLpgSQL",
"bytes": "8169"
},
{
"name": "Shell",
"bytes": "390442"
}
],
"symlink_target": ""
} |
package org.apache.tajo.scheduler;
import java.util.Comparator;
/**
* Utility class containing scheduling algorithms used in the scheduler.
*/
public class SchedulingAlgorithms {
/**
* Compare Schedulables in order of priority and then submission time, as in
* the default FIFO scheduler in Tajo.
*/
public static class FifoComparator implements Comparator<QuerySchedulingInfo> {
@Override
public int compare(QuerySchedulingInfo q1, QuerySchedulingInfo q2) {
int res = q1.getPriority().compareTo(q2.getPriority());
if (res == 0) {
res = (int) Math.signum(q1.getStartTime() - q2.getStartTime());
}
if (res == 0) {
// In the rare case where jobs were submitted at the exact same time,
// compare them by name (which will be the QueryId) to get a deterministic ordering
res = q1.getName().compareTo(q2.getName());
}
return res;
}
}
}
| {
"content_hash": "c39a2f2661fe48c3e34dc3b74b3e6ded",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 91,
"avg_line_length": 30.129032258064516,
"alnum_prop": 0.6680942184154176,
"repo_name": "yeeunshim/tajo_test",
"id": "9c9b16df5538e3c809071f05f06f91db2e53805f",
"size": "1740",
"binary": false,
"copies": "1",
"ref": "refs/heads/yeeun",
"path": "tajo-core/src/main/java/org/apache/tajo/scheduler/SchedulingAlgorithms.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "40820"
},
{
"name": "CSS",
"bytes": "3794"
},
{
"name": "Java",
"bytes": "6319806"
},
{
"name": "JavaScript",
"bytes": "502571"
},
{
"name": "Python",
"bytes": "18628"
},
{
"name": "Shell",
"bytes": "64783"
},
{
"name": "XSLT",
"bytes": "1329"
}
],
"symlink_target": ""
} |
package ch.unibas.fittingwizard.application.tools;
import java.io.File;
import java.io.IOException;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
/**
*
* User: mhelmer
* Date: 16.12.13
* Time: 10:30
*/
public class GaussianLogModifier {
private static final Logger logger = Logger.getLogger(GaussianLogModifier.class);
public static final String BackupFileSuffix = "~";
public static final String EnteringLineString = "Entering Gaussian System";
public static final String TerminationLineString = "Normal termination of Gaussian";
public File removeHeadersFromCluster(File fileWithHeader) {
logger.info("Removing headers from cluster from file " + fileWithHeader.getAbsolutePath());
List<String> lines;
try {
lines = FileUtils.readLines(fileWithHeader);
} catch (IOException e) {
throw new RuntimeException("Could not read input file " + fileWithHeader.getAbsolutePath());
}
int enteringLine = getEnteringLine(lines);
int terminationLine = getTerminationLine(lines);
if (enteringLine > 0 && terminationLine > 0 && terminationLine != lines.size() - 1) {
createBackup(fileWithHeader);
List<String> linesWithoutHeader = lines.subList(enteringLine, terminationLine + 1);
try {
FileUtils.writeLines(fileWithHeader, linesWithoutHeader);
} catch (IOException e) {
throw new RuntimeException("Could not write file without headers. " + fileWithHeader.getAbsolutePath());
}
}
return fileWithHeader;
}
public int getEnteringLine(List<String> lines) {
return findLineWithContent(lines, EnteringLineString);
}
public int getTerminationLine(List<String> lines) {
return findLineWithContent(lines, TerminationLineString);
}
public int findLineWithContent(List<String> lines, String content) {
for (int i = 0; i < lines.size(); i++) {
String line = lines.get(i);
if (line.contains(content))
return i;
}
return -1;
}
public void createBackup(File file) {
File bak = getBackupFileName(file);
try {
FileUtils.copyFile(file, bak);
} catch (IOException e) {
throw new RuntimeException("Could not create backup file " + bak.getAbsolutePath());
}
}
private File getBackupFileName(File file) {
return new File(file.getParentFile(), file.getName() + BackupFileSuffix);
}
}
| {
"content_hash": "ed25b841f65bedd09511b1282da66aea",
"timestamp": "",
"source": "github",
"line_count": 79,
"max_line_length": 120,
"avg_line_length": 33.177215189873415,
"alnum_prop": 0.6497520030522701,
"repo_name": "MMunibas/FittingWizard",
"id": "856f5bdf1028e171ab1db679dc224985ad215273",
"size": "2814",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/ch/unibas/fittingwizard/application/tools/GaussianLogModifier.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "1333"
},
{
"name": "Java",
"bytes": "706213"
},
{
"name": "Python",
"bytes": "368299"
},
{
"name": "Shell",
"bytes": "76408"
}
],
"symlink_target": ""
} |
package org.apache.hadoop.hive.common;
import org.junit.Assert;
import org.junit.Test;
public class TestLogUtils {
@Test
public void testMaskIfPassword() {
Assert.assertNull(LogUtils.maskIfPassword("",null));
Assert.assertNull(LogUtils.maskIfPassword(null,null));
Assert.assertEquals("test", LogUtils.maskIfPassword(null,"test"));
Assert.assertEquals("test2", LogUtils.maskIfPassword("any","test2"));
Assert.assertEquals("###_MASKED_###", LogUtils.maskIfPassword("password","test3"));
Assert.assertEquals("###_MASKED_###", LogUtils.maskIfPassword("a_passWord","test4"));
Assert.assertEquals("###_MASKED_###", LogUtils.maskIfPassword("password_a","test5"));
Assert.assertEquals("###_MASKED_###", LogUtils.maskIfPassword("a_PassWord_a","test6"));
}
}
| {
"content_hash": "9345b69508dbed3b15994c73ec7a96f1",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 91,
"avg_line_length": 43.833333333333336,
"alnum_prop": 0.7072243346007605,
"repo_name": "BUPTAnderson/apache-hive-2.1.1-src",
"id": "923ac2d6280b084ec8a172ad9f13118d28bb9e95",
"size": "1595",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "common/src/test/org/apache/hadoop/hive/common/TestLogUtils.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "54136"
},
{
"name": "Batchfile",
"bytes": "51776"
},
{
"name": "C",
"bytes": "28218"
},
{
"name": "C++",
"bytes": "74801"
},
{
"name": "CSS",
"bytes": "5220"
},
{
"name": "GAP",
"bytes": "144179"
},
{
"name": "HTML",
"bytes": "51404"
},
{
"name": "HiveQL",
"bytes": "4634130"
},
{
"name": "Java",
"bytes": "34882419"
},
{
"name": "JavaScript",
"bytes": "25872"
},
{
"name": "M",
"bytes": "2176"
},
{
"name": "M4",
"bytes": "2276"
},
{
"name": "PHP",
"bytes": "148097"
},
{
"name": "PLSQL",
"bytes": "3008"
},
{
"name": "PLpgSQL",
"bytes": "223546"
},
{
"name": "Perl",
"bytes": "316401"
},
{
"name": "PigLatin",
"bytes": "12333"
},
{
"name": "Python",
"bytes": "292716"
},
{
"name": "Roff",
"bytes": "5379"
},
{
"name": "SQLPL",
"bytes": "409"
},
{
"name": "Shell",
"bytes": "206363"
},
{
"name": "TSQL",
"bytes": "1219634"
},
{
"name": "Thrift",
"bytes": "104851"
},
{
"name": "XSLT",
"bytes": "7619"
},
{
"name": "q",
"bytes": "318829"
}
],
"symlink_target": ""
} |
package org.springframework.samples.petclinic.graphql.types;
import java.util.List;
import java.util.Optional;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* @author Xiangbin HAN (hanxb2001@163.com)
*
*/
public class OwnerOrder {
private OrderField field;
private OrderType order;
@JsonProperty("field")
public OrderField getField() {
return field;
}
public void setField(OrderField field) {
this.field = field;
}
@JsonProperty("order")
public OrderType getOrder() {
return order;
}
public void setOrder(OrderType order) {
this.order = order;
}
@Override
public String toString() {
return this.field.toString() + " " + this.order.toString();
}
/**
* @param orders
* @return String
*/
public static String buildOrderJdbcQuery(List<OwnerOrder> orders) {
StringBuilder sb = new StringBuilder();
Optional<List<OwnerOrder>> nonNullOrders = Optional.ofNullable(orders);
nonNullOrders.ifPresent(list -> {
sb.append(" order by");
list.forEach(order -> {
if (order.getField().equals(OrderField.firstName))
sb.append(" first_name " + order.getOrder() + ",");
else if(order.getField().equals(OrderField.lastName))
sb.append(" last_name " + order.getOrder() + ",");
else
sb.append(" " + order.getField() + " " + order.getOrder() + ",");
});
});
if(sb.indexOf("order by") > 0)
return sb.substring(0, sb.lastIndexOf(","));
else
return "";
}
/**
* @param orders
* @return String
*/
public static String buildOrderJpaQuery(List<OwnerOrder> orders) {
StringBuilder sb = new StringBuilder();
Optional<List<OwnerOrder>> nonNullOrders = Optional.ofNullable(orders);
nonNullOrders.ifPresent(list ->
{sb.append(" order by");
list.forEach(order -> sb.append(" owner." + order.getField() + " " + order.getOrder() + ","));}
);
if(sb.indexOf("order by") > 0)
return sb.substring(0, sb.lastIndexOf(","));
else
return "";
}
}
| {
"content_hash": "cd519c4b2f4c760128eee618dfdaa162",
"timestamp": "",
"source": "github",
"line_count": 84,
"max_line_length": 107,
"avg_line_length": 27.61904761904762,
"alnum_prop": 0.5568965517241379,
"repo_name": "EMResearch/EMB",
"id": "3f3d957ede8553a4d3886f760b948f4879b60b4f",
"size": "2320",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "jdk_8_maven/cs/graphql/spring-petclinic-graphql/src/main/java/org/springframework/samples/petclinic/graphql/types/OwnerOrder.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Awk",
"bytes": "17751"
},
{
"name": "C#",
"bytes": "314780"
},
{
"name": "CSS",
"bytes": "155749"
},
{
"name": "Dockerfile",
"bytes": "6278"
},
{
"name": "EJS",
"bytes": "13193"
},
{
"name": "HTML",
"bytes": "1980397"
},
{
"name": "Java",
"bytes": "13878146"
},
{
"name": "JavaScript",
"bytes": "4551141"
},
{
"name": "Kotlin",
"bytes": "62153"
},
{
"name": "Less",
"bytes": "29035"
},
{
"name": "Lex",
"bytes": "1418"
},
{
"name": "Perl",
"bytes": "82062"
},
{
"name": "Procfile",
"bytes": "26"
},
{
"name": "Pug",
"bytes": "3626"
},
{
"name": "Python",
"bytes": "129221"
},
{
"name": "Ruby",
"bytes": "683"
},
{
"name": "Shell",
"bytes": "51395"
},
{
"name": "Smarty",
"bytes": "2380"
},
{
"name": "Starlark",
"bytes": "23296"
},
{
"name": "TSQL",
"bytes": "4320"
},
{
"name": "Thrift",
"bytes": "1245"
},
{
"name": "TypeScript",
"bytes": "701370"
},
{
"name": "XSLT",
"bytes": "18724"
}
],
"symlink_target": ""
} |
/** \file MachOBinaryFile.h
* \brief This file contains the definition of the class MachOBinaryFile.
*/
#ifndef __MACHOBINARYFILE_H__
#define __MACHOBINARYFILE_H__
#include "BinaryFile.h"
#include <string>
#include <vector>
/**
* This file contains the definition of the MachOBinaryFile class, and some
* other definitions specific to the Mac OS-X version of the BinaryFile object
* This is my bare bones implementation of a Mac OS-X binary loader.
*/
// Given a little endian value x, load its value assuming big endian order
// Note: must be able to take address of x
// Note: Unlike the LH macro in BinaryFile.h, the parameter is not a pointer
#define _BMMH(x) \
((unsigned)((Byte *)(&x))[3] + ((unsigned)((Byte *)(&x))[2] << 8) + ((unsigned)((Byte *)(&x))[1] << 16) + \
((unsigned)((Byte *)(&x))[0] << 24))
// With this one, x IS a pounsigneder
#define _BMMH2(x) \
((unsigned)((Byte *)(x))[3] + ((unsigned)((Byte *)(x))[2] << 8) + ((unsigned)((Byte *)(x))[1] << 16) + \
((unsigned)((Byte *)(x))[0] << 24))
#define _BMMHW(x) (((unsigned)((Byte *)(&x))[1]) + ((unsigned)((Byte *)(&x))[0] << 8))
struct mach_header;
class MachOBinaryFile : public QObject,
public LoaderInterface,
public ObjcAccessInterface {
Q_OBJECT
Q_PLUGIN_METADATA(IID LoaderInterface_iid)
Q_INTERFACES(LoaderInterface)
Q_INTERFACES(ObjcAccessInterface)
public:
MachOBinaryFile(); // Default constructor
virtual ~MachOBinaryFile(); // Destructor
void initialize(IBoomerang *sys) override;
bool Open(const char *sName); // Open the file for r/w; ???
void Close() override; // Close file opened with Open()
void UnLoad() override; // Unload the image
LOAD_FMT GetFormat() const override; // Get format (i.e. LOADFMT_MACHO)
MACHINE getMachine() const override; // Get machine (i.e. MACHINE_PPC)
bool isLibrary() const;
ADDRESS getImageBase() override;
size_t getImageSize() override;
ADDRESS GetMainEntryPoint() override;
ADDRESS GetEntryPoint() override;
DWord getDelta();
//
// -- -- -- -- -- -- -- -- --
//
// Internal information
// Dump headers, etc
bool DisplayDetails(const char *fileName, FILE *f = stdout) override ;
protected:
int machORead2(short *ps) const; // Read 2 bytes from native addr
int machORead4(int *pi) const; // Read 4 bytes from native addr
// void * BMMH(void *x);
// char * BMMH(char *x);
// const char * BMMH(const char *x);
// unsigned int BMMH(long int & x);
int32_t BMMH(int32_t x);
uint32_t BMMH(uint32_t x);
unsigned short BMMHW(unsigned short x);
public:
std::map<QString, ObjcModule> &getObjcModules() override { return modules; }
bool LoadFromMemory(QByteArray &data) override;
int canLoad(QIODevice &dev) const override;
private:
bool PostLoad(void *handle) override; // Called after archive member loaded
void findJumps(ADDRESS curr); // Find names for jumps to IATs
char *base; // Beginning of the loaded image
ADDRESS entrypoint, loaded_addr;
unsigned loaded_size;
MACHINE machine;
bool swap_bytes;
std::map<QString, ObjcModule> modules;
std::vector<struct section> sections;
class IBinaryImage *Image;
class IBinarySymbolTable *Symbols;
};
#endif // ifndef __MACHOBINARYFILE_H__
| {
"content_hash": "fb95cf7c61dfb646b07edf56bf1a400e",
"timestamp": "",
"source": "github",
"line_count": 98,
"max_line_length": 120,
"avg_line_length": 38.66326530612245,
"alnum_prop": 0.5774610715228292,
"repo_name": "nemerle/boomerang",
"id": "9ddecab57ba9270724e487fcc8712d33f2a6d626",
"size": "4034",
"binary": false,
"copies": "1",
"ref": "refs/heads/next",
"path": "loader/machO/MachOBinaryFile.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Assembly",
"bytes": "15779"
},
{
"name": "C",
"bytes": "1012955"
},
{
"name": "C++",
"bytes": "6953684"
},
{
"name": "CMake",
"bytes": "23497"
},
{
"name": "FORTRAN",
"bytes": "380"
},
{
"name": "Haskell",
"bytes": "8324"
},
{
"name": "Lex",
"bytes": "21167"
},
{
"name": "Matlab",
"bytes": "112810"
},
{
"name": "Max",
"bytes": "15769"
},
{
"name": "Objective-C",
"bytes": "361242"
},
{
"name": "Perl6",
"bytes": "1015"
},
{
"name": "Python",
"bytes": "9103"
},
{
"name": "Ruby",
"bytes": "210145"
},
{
"name": "Shell",
"bytes": "11057"
},
{
"name": "TypeScript",
"bytes": "75"
},
{
"name": "XSLT",
"bytes": "5650"
},
{
"name": "Yacc",
"bytes": "64180"
}
],
"symlink_target": ""
} |
package ru.job4j.collections.map;
import org.hamcrest.Matchers;
import org.junit.Test;
import javax.swing.text.html.HTMLDocument;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.NoSuchElementException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.*;
public class SimpleHashMapTest {
@Test
public void whenAddCellWithDifferentAndSameHash() {
SimpleHashMap<Integer, String> hashMap = new SimpleHashMap<>();
boolean rsl1 = hashMap.insert(27, "Olga");
assertThat(rsl1, is(true));
boolean rsl2 = hashMap.insert(569, "Katya");
assertThat(rsl2, is(true));
boolean rsl3 = hashMap.insert(81, "Masha");
assertThat(rsl3, is(true));
boolean rsl4 = hashMap.insert(9, "Olga");
assertThat(rsl4, is(false));
boolean rsl5 = hashMap.insert(38945, "Roma");
assertThat(rsl5, is(true));
boolean rsl6 = hashMap.insert(1114, "Oleg");
assertThat(rsl6, is(true));
boolean rsl7 = hashMap.delete(38945);
assertThat(rsl7, is(true));
Iterator iterator = hashMap.iterator();
assertThat(iterator.hasNext(), Matchers.is(true));
assertThat(iterator.next(), Matchers.is("Masha"));
assertThat(iterator.hasNext(), Matchers.is(true));
assertThat(iterator.next(), Matchers.is("Oleg"));
assertThat(iterator.hasNext(), Matchers.is(true));
assertThat(iterator.next(), Matchers.is("Olga"));
assertThat(iterator.hasNext(), Matchers.is(true));
assertThat(iterator.next(), Matchers.is("Katya"));
assertThat(iterator.hasNext(), Matchers.is(false));
}
@Test(expected = ConcurrentModificationException.class)
public void shouldThrowConcurrentModificationException() {
SimpleHashMap<Integer, String> hashMap = new SimpleHashMap<>();
hashMap.insert(111, "Person1");
hashMap.insert(212, "Person2");
hashMap.insert(313, "Person3");
hashMap.insert(414, "Person4");
hashMap.insert(515, "Person5");
Iterator it = hashMap.iterator();
hashMap.insert(616, "Person6");
hashMap.insert(717, "Person7");
hashMap.insert(818, "Person8");
it.hasNext();
}
@Test (expected = NoSuchElementException.class)
public void shouldThrowNoSuchElementException() {
SimpleHashMap<Integer, String> hashMap = new SimpleHashMap<>();
hashMap.insert(111, "Person1");
hashMap.insert(212, "Person2");
hashMap.insert(313, "Person3");
Iterator it = hashMap.iterator();
assertThat(it.hasNext(), Matchers.is(true));
assertThat(it.next(), Matchers.is("Person1"));
assertThat(it.hasNext(), Matchers.is(true));
assertThat(it.next(), Matchers.is("Person2"));
assertThat(it.hasNext(), Matchers.is(true));
assertThat(it.next(), Matchers.is("Person3"));
assertThat(it.hasNext(), Matchers.is(false));
it.next();
}
} | {
"content_hash": "cb7ca6e0ed2dbb855c999b17941e32a5",
"timestamp": "",
"source": "github",
"line_count": 81,
"max_line_length": 71,
"avg_line_length": 38.03703703703704,
"alnum_prop": 0.6488153197013956,
"repo_name": "Mrsananabos/ashveytser",
"id": "30e1a9ce422759cead4268d155d29cebb2b40f6d",
"size": "3081",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "chapter_003/src/test/java/ru/job4j/collections/map/SimpleHashMapTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "2150"
},
{
"name": "HTML",
"bytes": "62484"
},
{
"name": "Java",
"bytes": "453586"
},
{
"name": "JavaScript",
"bytes": "27530"
},
{
"name": "XSLT",
"bytes": "349"
}
],
"symlink_target": ""
} |
from __future__ import unicode_literals, print_function, division
__author__ = "mozman <mozman@gmx.at>"
import copy
from .compatibility import is_string
from .xmlns import register_class, CN, wrap, etree
from . import wrapcache
from .base import GenericWrapper
from .protection import random_protection_key
from .propertymixins import TableVisibilityMixin
from .propertymixins import StringProperty, BooleanProperty
from .tableutils import address_to_index, get_cell_index
from .tablerowcontroller import TableRowController
from .tablecolumncontroller import TableColumnController
from .cellspancontroller import CellSpanController
@register_class
class Table(GenericWrapper):
TAG = CN('table:table')
style_name = StringProperty(CN('table:style-name'))
print_ = BooleanProperty(CN('table:print'))
def __init__(self, name='NEWTABLE', size=(10, 10), xmlnode=None):
def init_attributes_by_xmlnode():
self._cellmatrix = TableRowController(self.xmlnode)
self._columns_info = TableColumnController(self.xmlnode)
self._cell_span_controller = CellSpanController(self._cellmatrix)
def set_new_table_metrics():
self.name = name
self._cellmatrix.reset(size)
self._columns_info.reset(size[1])
super(Table, self).__init__(xmlnode=xmlnode)
init_attributes_by_xmlnode()
if xmlnode is None:
set_new_table_metrics()
wrapcache.add(self)
def __getitem__(self, key):
if isinstance(key, int):
return self.get_child(key)
else:
return self.get_cell(get_cell_index(key))
def __setitem__(self, key, cell):
if isinstance(key, int):
self.set_child(key, cell)
else:
self.set_cell(get_cell_index(key), cell)
@property
def name(self):
return self.get_attr(CN('table:name'))
@name.setter
def name(self, value):
return self.set_attr(CN('table:name'), self._normalize_sheet_name(value))
@staticmethod
def _normalize_sheet_name(name):
for subst in "\t\r'\"":
name = name.replace(subst, ' ')
return name.strip()
@property
def protected(self):
return self.get_bool_attr(CN('table:protected'))
@protected.setter
def protected(self, value):
self.set_bool_attr(CN('table:protected'), value)
if self.protected:
self.set_attr(CN('table:protection-key'), random_protection_key())
def nrows(self):
""" Count of table rows. """
return self._cellmatrix.nrows()
def ncols(self):
""" Count of table columns. """
return self._cellmatrix.ncols()
def reset(self, size=(10, 10)):
preserve_name = self.name
super(Table, self).clear()
self.name = preserve_name
self._cellmatrix.reset(size)
self._columns_info.reset(size[1])
def clear(self):
size = (self.nrows(), self.ncols())
self.reset(size)
def copy(self, newname=None):
newtable = Table(xmlnode=copy.deepcopy(self.xmlnode))
if newname is None:
newname = 'CopyOf' + self.name
newtable.name = newname
return newtable
def get_cell(self, pos):
""" Get cell at position 'pos', where 'pos' is a tuple (row, column). """
return wrap(self._cellmatrix.get_cell(pos))
def set_cell(self, pos, cell):
""" Set cell at position 'pos', where 'pos' is a tuple (row, column). """
if not hasattr(cell, 'kind') or cell.kind != 'Cell':
raise TypeError("invalid type of 'cell'.")
self._cellmatrix.set_cell(pos, cell.xmlnode)
def itercells(self):
""" Iterate over all cells, returns tuples (pos, cell). """
for irow, row in enumerate(self.rows()):
for icol, cell in enumerate(row):
yield ((irow, icol), cell)
def row(self, index):
if is_string(index):
index, column = address_to_index(index)
return [wrap(e) for e in self._cellmatrix.row(index)]
def rows(self):
for index in range(self.nrows()):
yield self.row(index)
def column(self, index):
if is_string(index):
row, index = address_to_index(index)
return [wrap(e) for e in self._cellmatrix.column(index)]
def columns(self):
for index in range(self.ncols()):
yield self.column(index)
def row_info(self, index):
if is_string(index):
index, column = address_to_index(index)
return wrap(self._cellmatrix.row(index))
def column_info(self, index):
if is_string(index):
row, index = address_to_index(index)
return wrap(self._columns_info.get_table_column(index))
def append_rows(self, count=1):
self._cellmatrix.append_rows(count)
def insert_rows(self, index, count=1):
# CAUTION: this will break refernces in formulas!
self._cellmatrix.insert_rows(index, count)
def delete_rows(self, index, count=1):
# CAUTION: this will break refernces in formulas!
self._cellmatrix.delete_rows(index, count)
def append_columns(self, count=1):
self._cellmatrix.append_columns(count)
self._columns_info.append(count)
def insert_columns(self, index, count=1):
# CAUTION: this will break refernces in formulas!
self._cellmatrix.insert_columns(index, count)
self._columns_info.insert(index, count)
def delete_columns(self, index, count=1):
# CAUTION: this will break refernces in formulas!
self._cellmatrix.delete_columns(index, count)
self._columns_info.delete(index, count)
def set_cell_span(self, pos, size):
self._cell_span_controller.set_span(get_cell_index(pos), size)
def remove_cell_span(self, pos):
self._cell_span_controller.remove_span(get_cell_index(pos))
@register_class
class TableColumn(GenericWrapper, TableVisibilityMixin):
TAG = CN('table:table-column')
style_name = StringProperty(CN('table:style-name'))
default_cell_style_name = StringProperty(CN('table:default-cell-style-name'))
@register_class
class TableRow(TableColumn):
TAG = CN('table:table-row')
def __init__(self, ncols=10, xmlnode=None):
super(TableRow, self).__init__(xmlnode=xmlnode)
if xmlnode is None:
self._setup(ncols)
def _setup(self, ncols):
for col in range(ncols):
self.xmlnode.append(etree.Element(CN('table:table-cell')))
| {
"content_hash": "fe1d11f2bca9786708082e0dd1a79ce4",
"timestamp": "",
"source": "github",
"line_count": 195,
"max_line_length": 81,
"avg_line_length": 34.728205128205126,
"alnum_prop": 0.6101594802126403,
"repo_name": "iwschris/ezodf2",
"id": "eaf885152c0e3dc7253b19c4ea18ea148483abb5",
"size": "6913",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ezodf2/table.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "351944"
},
{
"name": "Shell",
"bytes": "4505"
}
],
"symlink_target": ""
} |
<?php
/**
* Ajax calls
* $.ajax({
* 'url' : 'xhr/sites/[id]/sync
* });
*/
Route::group(['prefix' => '/xhr'], function () {
/**
* List all themes
*/
Route::match(['GET'], '/themes', [
'uses' => 'App\Controller\Ajax\ThemeController@all'
]);
/**
* List all theme categories
*/
Route::match(['GET'], '/themes/categories', [
'uses' => 'App\Controller\Ajax\ThemeController@categories'
]);
/**
* Gets all Page
*/
Route::match(['GET'], '/sites', [
'before' => ['auth.admin'],
'uses' => 'App\Controller\Ajax\SiteController@all'
]);
/**
* Updates a Page
*/
Route::match(['POST'], '/sites/{site_id}', [
'before' => ['site.manager'],
'uses' => 'App\Controller\Ajax\SiteController@update'
]);
Route::match(['POST'], '/sites/{site_id}/subdomain', [
'before' => ['site.manager'],
'uses' => 'App\Controller\Ajax\SiteController@updateSubdomain'
]);
Route::match(['POST'], '/sites/{site_id}/domain', [
'before' => ['site.manager'],
'uses' => 'App\Controller\Ajax\SiteController@updateDomain'
]);
/**
* Gets all page posts
*/
Route::match(['GET'], '/sites/{site_id}/posts', [
'before' => ['site.manager'],
'uses' => 'App\Controller\Ajax\SiteController@posts'
]);
/**
* Gets all page feeds
*/
Route::match(['GET'], '/sites/{site_id}/feeds', [
'before' => ['site.manager'],
'uses' => 'App\Controller\Ajax\SiteController@feeds'
]);
/**
* Gets all page albums
*/
Route::match(['GET'], '/sites/{site_id}/albums', [
'before' => ['site.manager'],
'uses' => 'App\Controller\Ajax\SiteController@albums'
]);
/**
* Gets all page photos
*/
Route::match(['GET'], '/sites/{site_id}/photos', [
'before' => ['site.manager'],
'uses' => 'App\Controller\Ajax\SiteController@photos'
]);
/**
* Gets all page events
*/
Route::match(['GET'], '/sites/{site_id}/events', [
'before' => ['site.manager'],
'uses' => 'App\Controller\Ajax\SiteController@events'
]);
/**
* Updates page theme option / options
*/
Route::match(['POST'], '/sites/{site_id}/options', [
'as' => 'xhr.sites.theme.options:post',
'uses' => 'App\Controller\Ajax\SiteController@setOption'
])->where('site_id', '[0-9]+');
Route::match(['GET'], '/users/{user_id}/sites', [
'uses' => 'App\Controller\Ajax\UserController@sites'
])->where('user_id', '[a-zA-Z0-9]+');
/**
* #xhr.sites.sync
*/
Route::match(['POST'], '/sites/{site_id}/sync', [
'uses' => 'AjaxController@syncPage'
]);
/**
* Change site theme
*/
Route::match(['POST'], '/sites/{site_id}/editor/theme', [
'uses' => 'AjaxController@editorTheme'
])->where('site_id', '[0-9]+');
});
| {
"content_hash": "0648d17ac7860ae6b587d48fa76d7c32",
"timestamp": "",
"source": "github",
"line_count": 115,
"max_line_length": 70,
"avg_line_length": 25.85217391304348,
"alnum_prop": 0.5079044735956946,
"repo_name": "asm-products/pageweb",
"id": "f57d3f40fb78ad1831168dc3021c6f8bba732233",
"size": "2973",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/routes/xhr.php",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "CSS",
"bytes": "1754830"
},
{
"name": "JavaScript",
"bytes": "505997"
},
{
"name": "PHP",
"bytes": "930295"
}
],
"symlink_target": ""
} |
import unittest
import frappe
class TestClient(unittest.TestCase):
def test_set_value(self):
todo = frappe.get_doc(dict(doctype="ToDo", description="test")).insert()
frappe.set_value("ToDo", todo.name, "description", "test 1")
self.assertEqual(frappe.get_value("ToDo", todo.name, "description"), "test 1")
frappe.set_value("ToDo", todo.name, {"description": "test 2"})
self.assertEqual(frappe.get_value("ToDo", todo.name, "description"), "test 2")
def test_delete(self):
from frappe.client import delete
todo = frappe.get_doc(dict(doctype="ToDo", description="description")).insert()
delete("ToDo", todo.name)
self.assertFalse(frappe.db.exists("ToDo", todo.name))
self.assertRaises(frappe.DoesNotExistError, delete, "ToDo", todo.name)
def test_http_valid_method_access(self):
from frappe.client import delete
from frappe.handler import execute_cmd
frappe.set_user("Administrator")
frappe.local.request = frappe._dict()
frappe.local.request.method = "POST"
frappe.local.form_dict = frappe._dict(
{"doc": dict(doctype="ToDo", description="Valid http method"), "cmd": "frappe.client.save"}
)
todo = execute_cmd("frappe.client.save")
self.assertEqual(todo.get("description"), "Valid http method")
delete("ToDo", todo.name)
def test_http_invalid_method_access(self):
from frappe.handler import execute_cmd
frappe.set_user("Administrator")
frappe.local.request = frappe._dict()
frappe.local.request.method = "GET"
frappe.local.form_dict = frappe._dict(
{"doc": dict(doctype="ToDo", description="Invalid http method"), "cmd": "frappe.client.save"}
)
self.assertRaises(frappe.PermissionError, execute_cmd, "frappe.client.save")
def test_run_doc_method(self):
from frappe.handler import execute_cmd
if not frappe.db.exists("Report", "Test Run Doc Method"):
report = frappe.get_doc(
{
"doctype": "Report",
"ref_doctype": "User",
"report_name": "Test Run Doc Method",
"report_type": "Query Report",
"is_standard": "No",
"roles": [{"role": "System Manager"}],
}
).insert()
else:
report = frappe.get_doc("Report", "Test Run Doc Method")
frappe.local.request = frappe._dict()
frappe.local.request.method = "GET"
# Whitelisted, works as expected
frappe.local.form_dict = frappe._dict(
{
"dt": report.doctype,
"dn": report.name,
"method": "toggle_disable",
"cmd": "run_doc_method",
"args": 0,
}
)
execute_cmd(frappe.local.form_dict.cmd)
# Not whitelisted, throws permission error
frappe.local.form_dict = frappe._dict(
{
"dt": report.doctype,
"dn": report.name,
"method": "create_report_py",
"cmd": "run_doc_method",
"args": 0,
}
)
self.assertRaises(frappe.PermissionError, execute_cmd, frappe.local.form_dict.cmd)
def test_array_values_in_request_args(self):
import requests
from frappe.auth import CookieManager, LoginManager
frappe.utils.set_request(path="/")
frappe.local.cookie_manager = CookieManager()
frappe.local.login_manager = LoginManager()
frappe.local.login_manager.login_as("Administrator")
params = {
"doctype": "DocType",
"fields": ["name", "modified"],
"sid": frappe.session.sid,
}
headers = {
"accept": "application/json",
"content-type": "application/json",
}
url = (
f"http://{frappe.local.site}:{frappe.conf.webserver_port}/api/method/frappe.client.get_list"
)
res = requests.post(url, json=params, headers=headers)
self.assertEqual(res.status_code, 200)
data = res.json()
first_item = data["message"][0]
self.assertTrue("name" in first_item)
self.assertTrue("modified" in first_item)
frappe.local.login_manager.logout()
def test_client_get(self):
from frappe.client import get
todo = frappe.get_doc(doctype="ToDo", description="test").insert()
filters = {"name": todo.name}
filters_json = frappe.as_json(filters)
self.assertEqual(get("ToDo", filters=filters).description, "test")
self.assertEqual(get("ToDo", filters=filters_json).description, "test")
todo.delete()
def test_client_insert(self):
from frappe.client import insert
def get_random_title():
return f"test-{frappe.generate_hash()}"
# test insert dict
doc = {"doctype": "Note", "title": get_random_title(), "content": "test"}
note1 = insert(doc)
self.assertTrue(note1)
# test insert json
doc["title"] = get_random_title()
json_doc = frappe.as_json(doc)
note2 = insert(json_doc)
self.assertTrue(note2)
# test insert child doc without parent fields
child_doc = {"doctype": "Note Seen By", "user": "Administrator"}
with self.assertRaises(frappe.ValidationError):
insert(child_doc)
# test insert child doc with parent fields
child_doc = {
"doctype": "Note Seen By",
"user": "Administrator",
"parenttype": "Note",
"parent": note1.name,
"parentfield": "seen_by",
}
note3 = insert(child_doc)
self.assertTrue(note3)
# cleanup
frappe.delete_doc("Note", note1.name)
frappe.delete_doc("Note", note2.name)
def test_client_insert_many(self):
from frappe.client import insert, insert_many
def get_random_title():
return f"test-{frappe.generate_hash(length=5)}"
# insert a (parent) doc
note1 = {"doctype": "Note", "title": get_random_title(), "content": "test"}
note1 = insert(note1)
doc_list = [
{
"doctype": "Note Seen By",
"user": "Administrator",
"parenttype": "Note",
"parent": note1.name,
"parentfield": "seen_by",
},
{
"doctype": "Note Seen By",
"user": "Administrator",
"parenttype": "Note",
"parent": note1.name,
"parentfield": "seen_by",
},
{
"doctype": "Note Seen By",
"user": "Administrator",
"parenttype": "Note",
"parent": note1.name,
"parentfield": "seen_by",
},
{"doctype": "Note", "title": get_random_title(), "content": "test"},
{"doctype": "Note", "title": get_random_title(), "content": "test"},
]
# insert all docs
docs = insert_many(doc_list)
# make sure only 1 name is returned for the parent upon insertion of child docs
self.assertEqual(len(docs), 3)
self.assertIn(note1.name, docs)
# cleanup
for doc in docs:
frappe.delete_doc("Note", doc)
| {
"content_hash": "d59b43c9bb0467019865fb7f131048ea",
"timestamp": "",
"source": "github",
"line_count": 225,
"max_line_length": 96,
"avg_line_length": 27.604444444444443,
"alnum_prop": 0.6631782321687328,
"repo_name": "yashodhank/frappe",
"id": "1a1c4f3232e124362ec6b57e63c9d550abf38f22",
"size": "6281",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "frappe/tests/test_client.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "320627"
},
{
"name": "GCC Machine Description",
"bytes": "2474"
},
{
"name": "HTML",
"bytes": "179539"
},
{
"name": "JavaScript",
"bytes": "1099003"
},
{
"name": "Python",
"bytes": "1430023"
},
{
"name": "Shell",
"bytes": "517"
}
],
"symlink_target": ""
} |
import { Component, Host, h, Prop } from '@stencil/core';
import { ItemsClient } from '../../../services/ItemsClient';
import state from "../../../store/store";
@Component({
tag: 'dnn-action-create-folder',
styleUrl: '../dnn-action.scss',
shadow: true,
})
export class DnnActionCreateFolder {
@Prop() parentFolderId: number;
private readonly itemsClient: ItemsClient;
constructor(){
this.itemsClient = new ItemsClient(state.moduleId);
}
private handleClick(): void {
if (this.parentFolderId){
this.itemsClient.getFolderContent(this.parentFolderId, 0, 0)
.then(data => {
state.currentItems = data;
this.showModal();
})
.catch(error => alert(error));
return;
}
this.showModal();
}
private showModal(){
const modal = document.createElement("dnn-modal");
modal.backdropDismiss = false;
modal.showCloseButton = false;
const editor = document.createElement("dnn-rm-create-folder");
modal.appendChild(editor);
document.body.appendChild(modal);
modal.show();
}
render() {
return (
<Host>
<button onClick={() => this.handleClick()}>
<svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 0 24 24" width="24px" fill="#000000"><path d="M0 0h24v24H0V0z" fill="none"/><path d="M20 6h-8l-2-2H4c-1.11 0-1.99.89-1.99 2L2 18c0 1.11.89 2 2 2h16c1.11 0 2-.89 2-2V8c0-1.11-.89-2-2-2zm-1 8h-3v3h-2v-3h-3v-2h3V9h2v3h3v2z"/></svg>
<span>{state.localization.AddFolder}</span>
</button>
</Host>
);
}
}
| {
"content_hash": "2ab9be294111959b6a2e680dc99cf1d2",
"timestamp": "",
"source": "github",
"line_count": 54,
"max_line_length": 303,
"avg_line_length": 29.01851851851852,
"alnum_prop": 0.6292278238672623,
"repo_name": "valadas/Dnn.Platform",
"id": "956cae8d6bd2c23c6762a121cf56daacc2e9d7fa",
"size": "1567",
"binary": false,
"copies": "3",
"ref": "refs/heads/develop",
"path": "DNN Platform/Modules/ResourceManager/ResourceManager.Web/src/components/actions/dnn-action-create-folder/dnn-action-create-folder.tsx",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP.NET",
"bytes": "522038"
},
{
"name": "Batchfile",
"bytes": "289"
},
{
"name": "C#",
"bytes": "21868942"
},
{
"name": "CSS",
"bytes": "920009"
},
{
"name": "HTML",
"bytes": "543211"
},
{
"name": "JavaScript",
"bytes": "8406477"
},
{
"name": "Less",
"bytes": "566334"
},
{
"name": "PowerShell",
"bytes": "5984"
},
{
"name": "SCSS",
"bytes": "12527"
},
{
"name": "Shell",
"bytes": "1429"
},
{
"name": "TSQL",
"bytes": "128041"
},
{
"name": "TypeScript",
"bytes": "135977"
},
{
"name": "Visual Basic .NET",
"bytes": "114706"
},
{
"name": "XSLT",
"bytes": "11388"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PriceChangeAlert
{
class Program
{
static void Main(string[] args)
{
int numberOfPrices = int.Parse(Console.ReadLine());
double significanceThreshold = double.Parse(Console.ReadLine());
double lastPrice = double.Parse(Console.ReadLine());
for (int i = 0; i < numberOfPrices - 1; i++)
{
double currentPrice = double.Parse(Console.ReadLine());
double difference = CalculateDifference(lastPrice, currentPrice);
bool isDifferent = CheckForDifference(difference, significanceThreshold);
string output = PrintDifference(currentPrice, lastPrice, difference, isDifferent);
Console.WriteLine(output);
lastPrice = currentPrice;
}
}
static string PrintDifference(double currentPrice, double lastPrice, double difference, bool trueOrFalse)
{
string output = null;
difference *= 100;
if (difference == 0)
{
output = $"NO CHANGE: {currentPrice}";
}
else if (!trueOrFalse)
{
output = $"MINOR CHANGE: {lastPrice} to {currentPrice} ({difference:F2}%)";
}
else if (trueOrFalse && difference > 0)
{
output = $"PRICE UP: {lastPrice} to {currentPrice} ({difference:F2}%)";
}
else if (trueOrFalse && difference < 0)
{
output = $"PRICE DOWN: {lastPrice} to {currentPrice} ({difference:F2}%)";
}
return output;
}
static bool CheckForDifference(double border, double isDiff)
{
return Math.Abs(border) >= isDiff;
}
static double CalculateDifference(double lastPrice, double currentPrice)
{
return (currentPrice - lastPrice) / lastPrice;
}
}
}
| {
"content_hash": "d8e3cc411a302bef2f3cb61b526c72f0",
"timestamp": "",
"source": "github",
"line_count": 72,
"max_line_length": 113,
"avg_line_length": 29.22222222222222,
"alnum_prop": 0.5522813688212928,
"repo_name": "MinorGlitch/Programming-Fundamentals",
"id": "ef1e367b7641e74526f95925761a049184b2f9c6",
"size": "2106",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Methods. Debugging and Troubleshooting Code - Lab/PriceChangeAlert/Program.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "475661"
}
],
"symlink_target": ""
} |
Angular touch-enabled option selector. [Live Demo](http://kzf.github.io/AngularTouchSelect)
# Usage
For Usage instructions refer to the [Live Demo](http://kzf.github.io/AngularTouchSelect).
| {
"content_hash": "4c86de4cb38baf235ae98b8d899a7a81",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 91,
"avg_line_length": 47.75,
"alnum_prop": 0.7853403141361257,
"repo_name": "kzf/AngularTouchSelect",
"id": "26c0656a275b51a552469f1202f1c41f6fbdf9f6",
"size": "213",
"binary": false,
"copies": "1",
"ref": "refs/heads/gh-pages",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "10346"
},
{
"name": "JavaScript",
"bytes": "38968"
}
],
"symlink_target": ""
} |
@implementation XCJoinLinesAction
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
- (instancetype)init
{
if((self = [super init])) {
self.title = NSLocalizedString(@"Joins the selection's lines into one line", @"");
self.subtitle = NSLocalizedString(@"Default deliminter is \" \", can be optionally specified", @"");
self.argumentHint = NSLocalizedString(@"", @"");
self.enabled = YES;
}
return self;
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
- (BOOL)acceptsArguments
{
return YES;
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
- (BOOL)validateArgumentsWithContext:(id<XCIDEContext>)context arguments:(NSString *)arguments
{
return YES;
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
- (BOOL)executeWithContext:(id<XCIDEContext>)context
{
return [self joineLinesInContext:context delimiter:@" "];
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
- (BOOL)executeWithContext:(id<XCIDEContext>)context arguments:(NSString *)arguments
{
return [self joineLinesInContext:context delimiter:arguments];
}
#pragma mark - Helpers
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
- (BOOL)joineLinesInContext:(id<XCIDEContext>)context delimiter:(NSString *)delimiter
{
NSString *fullText = [context.sourceCodeTextView string];
NSArray *rangesForSelection = [context retrieveTextSelectionRanges];
[context.sourceCodeDocument.textStorage beginEditing];
[rangesForSelection enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(NSValue *value, NSUInteger idx, BOOL *stop) {
NSRange range = value.rangeValue;
NSString *textSelection = [fullText substringWithRange:range];
NSArray *lineComponents = [textSelection componentsSeparatedByString:@"\n"];
NSMutableArray *trimmedLines = [NSMutableArray array];
for(NSString *line in lineComponents) {
NSString *trimmedLine = [line stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
[trimmedLines addObject:trimmedLine];
}
NSString *joinedSelection = [trimmedLines componentsJoinedByString:delimiter];
[context.sourceCodeDocument.textStorage replaceCharactersInRange:range
withString:joinedSelection
withUndoManager:context.sourceCodeDocument.undoManager];
[context.sourceCodeDocument.textStorage indentCharacterRange:NSMakeRange(range.location, joinedSelection.length)
undoManager:context.sourceCodeDocument.undoManager];
}];
[context.sourceCodeDocument.textStorage endEditing];
return YES;
}
@end
| {
"content_hash": "bda7c475ec2f74d4b61a8ea300ddfe5c",
"timestamp": "",
"source": "github",
"line_count": 83,
"max_line_length": 131,
"avg_line_length": 42.46987951807229,
"alnum_prop": 0.47716312056737586,
"repo_name": "pdcgomes/XCActionBar",
"id": "aebfe732f7edddec6b94b030986ac8b91b860a90",
"size": "3917",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "PGXcodeActionBrowser/Model/Actions/XCJoinLinesAction.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "321554"
},
{
"name": "Shell",
"bytes": "455"
}
],
"symlink_target": ""
} |
@class DataItemView;
@interface NumberWrappingLayoutCalculator : NSObject
@property (nonatomic, strong) NSArray *dataItems;
- (void)calculateLayoutSizesForDataItems:(NSArray *)items inSize:(CGSize)size;
- (DataItemView *)dataItemViewNearestLocationNearLocation:(CGPoint)location;
@end
| {
"content_hash": "6ab873abe85d83edb38be44364c9e993",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 78,
"avg_line_length": 28.9,
"alnum_prop": 0.8166089965397924,
"repo_name": "jdunwoody/DateMaths",
"id": "ef515f93df405604f63e19a102f102fdc39ae467",
"size": "490",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "DateMaths/CollectionView/NumberWrappingLayoutCalculator.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "96656"
},
{
"name": "Ruby",
"bytes": "2615"
}
],
"symlink_target": ""
} |
class Logistician
module HTTPError
attr_reader :http_status, :http_block
attr_writer :http_status, :http_block
def self.annote( exception, http_status = nil, &http_block )
exception.extend( self )
exception.http_status = http_status
exception.http_block = http_block
end
def self.new(msg, status, &block)
self::Class.new(msg, status, &block)
end
class Class < Exception
include HTTPError
def initialize(msg, http_status=500,&http_block)
super(msg)
self.http_status = http_status
self.http_block = http_block || lambda{|rsp| rsp['Content-Type']='text/plain' ; http_status < 500 ? rsp.write(msg) : rsp.write('Something went wrong') }
end
end
end
end
require 'logistician/utils'
require 'logistician/exporter'
require 'logistician/resource'
require 'logistician/tree_destructor'
require 'logistician/repository'
| {
"content_hash": "ee8f82bfe7dfb3f2a360cb7469250fcf",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 160,
"avg_line_length": 24.89189189189189,
"alnum_prop": 0.6731813246471227,
"repo_name": "xing/racktables_api",
"id": "a71c44782b98b5a4d59cb00a46c5b9960648f96c",
"size": "921",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/logistician.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "135331"
}
],
"symlink_target": ""
} |
package com.vaadin.data.provider;
import com.vaadin.shared.data.sort.SortDirection;
import com.vaadin.ui.Grid.Column;
/**
* Sorting information for {@link Grid}.
*
* @param <T>
* the grid type
*/
public class GridSortOrder<T> extends SortOrder<Column<T, ?>> {
/**
* Construct sorting information for usage in a {@link Grid}.
*
* @param column
* the column to be sorted
* @param direction
* sorting direction
*/
public GridSortOrder(Column<T, ?> column, SortDirection direction) {
super(column, direction);
}
/**
* Gets the column this sorting information is attached to.
*
* @return the column being sorted
*/
@Override
public Column<T, ?> getSorted() {
return super.getSorted();
}
/**
* Creates a new grid sort builder with given sorting using ascending sort
* direction.
*
* @param by
* the column to sort by
* @param <T>
* the grid type
*
* @return the grid sort builder
*/
public static <T> GridSortOrderBuilder<T> asc(Column<T, ?> by) {
return new GridSortOrderBuilder<T>().thenAsc(by);
}
/**
* Creates a new grid sort builder with given sorting using descending sort
* direction.
*
* @param by
* the column to sort by
* @param <T>
* the grid type
*
* @return the grid sort builder
*/
public static <T> GridSortOrderBuilder<T> desc(Column<T, ?> by) {
return new GridSortOrderBuilder<T>().thenDesc(by);
}
}
| {
"content_hash": "9ca0818895bec914e04bbeb5f3118d16",
"timestamp": "",
"source": "github",
"line_count": 66,
"max_line_length": 79,
"avg_line_length": 24.848484848484848,
"alnum_prop": 0.5701219512195121,
"repo_name": "Legioth/vaadin",
"id": "ffb17d301d7a9bec3aa54187bf3799f5afddc0da",
"size": "2235",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "server/src/main/java/com/vaadin/data/provider/GridSortOrder.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "731725"
},
{
"name": "HTML",
"bytes": "109487"
},
{
"name": "Java",
"bytes": "22536450"
},
{
"name": "JavaScript",
"bytes": "126895"
},
{
"name": "Python",
"bytes": "35283"
},
{
"name": "Roff",
"bytes": "4039"
},
{
"name": "Shell",
"bytes": "14720"
},
{
"name": "Smarty",
"bytes": "175"
}
],
"symlink_target": ""
} |
/*----------------------------------------------------------------------
Global/Adaptive Image Binarization
based on Discriminant Criterion (Otsu's method) otsubin.h
(C) 2000-2009 Hideaki Goto (see accompanying LICENSE file)
Written by H.Goto, Apr 2000
Revised by H.Goto, Sep 2003
Revised by H.Goto, Dec 2005
Revised by H.Goto, May 2007
Revised by H.Goto, Apr 2009
Revised by H.Goto, May 2009
----------------------------------------------------------------------*/
#ifndef _otsubin_h
#define _otsubin_h
#ifdef __cplusplus
extern "C" {
#endif
double threshold_otsu(SIPImage *image,int x0,int y0,int w,int h);
int adpt_binarize_otsu(SIPImage *src, SIPImage *dst, int csize, int interpolate);
int binarize_otsu(SIPImage *src, SIPImage *dst, double *threshold);
#ifdef __cplusplus
}
#endif
#endif /* _otsubin_h */
| {
"content_hash": "5d07afe21fd9afb53d0020683129c04e",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 81,
"avg_line_length": 29.433333333333334,
"alnum_prop": 0.5673839184597962,
"repo_name": "el-hoshino/HandwrAIter",
"id": "8e82a94dea5438835b46f14534eea432374180e5",
"size": "883",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "server/nhocr/nhocr-0.21/libnhocr/otsubin.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "834168"
},
{
"name": "C++",
"bytes": "753856"
},
{
"name": "CSS",
"bytes": "81045"
},
{
"name": "Groff",
"bytes": "206792"
},
{
"name": "HTML",
"bytes": "5997"
},
{
"name": "JavaScript",
"bytes": "42164"
},
{
"name": "Lua",
"bytes": "3503"
},
{
"name": "Makefile",
"bytes": "269044"
},
{
"name": "Objective-C",
"bytes": "369983"
},
{
"name": "Objective-C++",
"bytes": "37057"
},
{
"name": "Python",
"bytes": "4106"
},
{
"name": "Ruby",
"bytes": "10479"
},
{
"name": "Shell",
"bytes": "66585"
},
{
"name": "Swift",
"bytes": "20423"
}
],
"symlink_target": ""
} |
<mods xmlns="http://www.loc.gov/mods/v3" xmlns:exslt="http://exslt.org/common" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xlink="http://www.w3.org/1999/xlink" xsi:schemaLocation="http://www.loc.gov/mods/v3 http://www.loc.gov/standards/mods/v3/mods-3-3.xsd" version="3.3" ID="P0b002ee180e7ba18">
<name type="corporate">
<namePart>United States Government Printing Office</namePart>
<role>
<roleTerm type="text" authority="marcrelator">printer</roleTerm>
<roleTerm type="code" authority="marcrelator">prt</roleTerm>
</role>
<role>
<roleTerm type="text" authority="marcrelator">distributor</roleTerm>
<roleTerm type="code" authority="marcrelator">dst</roleTerm>
</role>
</name>
<name type="corporate">
<namePart>United States</namePart>
<namePart>United States Court of Appeals for the Eighth Circuit</namePart>
<role>
<roleTerm type="text" authority="marcrelator">author</roleTerm>
<roleTerm type="code" authority="marcrelator">aut</roleTerm>
</role>
<description>Government Organization</description>
</name>
<typeOfResource>text</typeOfResource>
<genre authority="marcgt">government publication</genre>
<language>
<languageTerm authority="iso639-2b" type="code">eng</languageTerm>
</language>
<extension>
<collectionCode>USCOURTS</collectionCode>
<category>Judicial Publications</category>
<branch>judicial</branch>
<dateIngested>2011-10-13</dateIngested>
</extension>
<originInfo>
<publisher>Administrative Office of the United States Courts</publisher>
<dateIssued encoding="w3cdtf">2006-01-10</dateIssued>
<issuance>monographic</issuance>
</originInfo>
<physicalDescription>
<note type="source content type">deposited</note>
<digitalOrigin>born digital</digitalOrigin>
</physicalDescription>
<classification authority="sudocs">JU 2.11</classification>
<identifier type="uri">http://www.gpo.gov/fdsys/pkg/USCOURTS-ca8-04-03347</identifier>
<identifier type="local">P0b002ee180e7ba18</identifier>
<recordInfo>
<recordContentSource authority="marcorg">DGPO</recordContentSource>
<recordCreationDate encoding="w3cdtf">2011-10-13</recordCreationDate>
<recordChangeDate encoding="w3cdtf">2011-10-13</recordChangeDate>
<recordIdentifier source="DGPO">USCOURTS-ca8-04-03347</recordIdentifier>
<recordOrigin>machine generated</recordOrigin>
<languageOfCataloging>
<languageTerm authority="iso639-2b" type="code">eng</languageTerm>
</languageOfCataloging>
</recordInfo>
<accessCondition type="GPO scope determination">fdlp</accessCondition>
<extension>
<docClass>USCOURTS</docClass>
<accessId>USCOURTS-ca8-04-03347</accessId>
<courtType>Appellate</courtType>
<courtCode>ca8</courtCode>
<courtCircuit>8th</courtCircuit>
<courtSortOrder>1080</courtSortOrder>
<caseNumber>04-03347</caseNumber>
<natureSuitCode>863</natureSuitCode>
<natureSuit>Social Security - DIWC/DIWW (405(g))</natureSuit>
<party firstName="Donna" fullName="Donna J. Bailey" lastName="Bailey" middleName="J." role="Appellant"></party>
<party firstName="Jo Anne" fullName="Jo Anne B. Barnhart" lastName="Barnhart" middleName="B." role="Appellee"></party>
</extension>
<titleInfo>
<title>Donna Bailey v. Jo Anne Barnhart</title>
<partNumber>04-03347</partNumber>
</titleInfo>
<location>
<url access="object in context" displayLabel="Content Detail">http://www.gpo.gov/fdsys/pkg/USCOURTS-ca8-04-03347/content-detail.html</url>
</location>
<classification authority="sudocs">JU 2.11</classification>
<identifier type="preferred citation">04-03347;04-3347</identifier>
<name type="corporate">
<namePart>United States Court of Appeals for the Eighth Circuit</namePart>
<namePart>8th Circuit</namePart>
<namePart></namePart>
<affiliation>U.S. Courts</affiliation>
<role>
<roleTerm authority="marcrelator" type="text">author</roleTerm>
<roleTerm authority="marcrelator" type="code">aut</roleTerm>
</role>
</name>
<name type="personal">
<displayForm>Donna J. Bailey</displayForm>
<namePart type="family">Bailey</namePart>
<namePart type="given">Donna</namePart>
<namePart type="termsOfAddress"></namePart>
<description>Appellant</description>
</name>
<name type="personal">
<displayForm>Jo Anne B. Barnhart</displayForm>
<namePart type="family">Barnhart</namePart>
<namePart type="given">Jo Anne</namePart>
<namePart type="termsOfAddress"></namePart>
<description>Appellee</description>
</name>
<extension>
<docClass>USCOURTS</docClass>
<accessId>USCOURTS-ca8-04-03347</accessId>
<courtType>Appellate</courtType>
<courtCode>ca8</courtCode>
<courtCircuit>8th</courtCircuit>
<courtSortOrder>1080</courtSortOrder>
<caseNumber>04-03347</caseNumber>
<natureSuitCode>863</natureSuitCode>
<natureSuit>Social Security - DIWC/DIWW (405(g))</natureSuit>
<party firstName="Donna" fullName="Donna J. Bailey" lastName="Bailey" middleName="J." role="Appellant"></party>
<party firstName="Jo Anne" fullName="Jo Anne B. Barnhart" lastName="Barnhart" middleName="B." role="Appellee"></party>
</extension>
<relatedItem type="constituent" ID="id-USCOURTS-ca8-04-03347-0" xlink:href="http://www.gpo.gov/fdsys/granule/USCOURTS-ca8-04-03347/USCOURTS-ca8-04-03347-0/mods.xml">
<titleInfo>
<title>Donna Bailey v. Jo Anne Barnhart</title>
<subTitle>THE COURT: Michael J. Melloy, Frank J. Magill, Raymond W. Gruender . PER CURIAM OPINION FILED: UNPUBLISHED [04-3347] [1995166]</subTitle>
<partNumber>0</partNumber>
</titleInfo>
<originInfo>
<dateIssued>2006-01-10</dateIssued>
</originInfo>
<relatedItem xlink:href="http://www.gpo.gov/fdsys/pkg/pdf/USCOURTS-ca8-04-03347-0.pdf" type="otherFormat">
<identifier type="FDsys Unique ID">D09002ee180e7c532</identifier>
</relatedItem>
<identifier type="uri">http://www.gpo.gov/fdsys/granule/USCOURTS-ca8-04-03347/USCOURTS-ca8-04-03347-0</identifier>
<identifier type="former granule identifier">ca8-04-03347_0.pdf</identifier>
<location>
<url access="object in context" displayLabel="Content Detail">http://www.gpo.gov/fdsys/granule/USCOURTS-ca8-04-03347/USCOURTS-ca8-04-03347-0/content-detail.html</url>
<url access="raw object" displayLabel="PDF rendition">http://www.gpo.gov/fdsys/pkg/USCOURTS-ca8-04-03347/pdf/USCOURTS-ca8-04-03347-0.pdf</url>
</location>
<extension>
<searchTitle>USCOURTS 04-03347; Donna Bailey v. Jo Anne Barnhart; </searchTitle>
<courtName>United States Court of Appeals for the Eighth Circuit</courtName>
<accessId>USCOURTS-ca8-04-03347-0</accessId>
<sequenceNumber>0</sequenceNumber>
<dateIssued>2006-01-10</dateIssued>
<docketText>THE COURT: Michael J. Melloy, Frank J. Magill, Raymond W. Gruender . PER CURIAM OPINION FILED: UNPUBLISHED [04-3347] [1995166]</docketText>
</extension>
</relatedItem>
</mods> | {
"content_hash": "02aed7928706b3708953b6012a0e2d41",
"timestamp": "",
"source": "github",
"line_count": 142,
"max_line_length": 311,
"avg_line_length": 46.7112676056338,
"alnum_prop": 0.761797075229911,
"repo_name": "m4h7/juriscraper",
"id": "cb44b43b4d199c58a972bcd76ebe6ace5778b517",
"size": "6633",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "juriscraper/fdsys/examples/2006/ca8-04-03347.xml",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "HTML",
"bytes": "27160373"
},
{
"name": "Makefile",
"bytes": "88"
},
{
"name": "Python",
"bytes": "623951"
}
],
"symlink_target": ""
} |
package org.ripple.bouncycastle.asn1.cryptopro;
import org.ripple.bouncycastle.asn1.ASN1EncodableVector;
import org.ripple.bouncycastle.asn1.ASN1Object;
import org.ripple.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.ripple.bouncycastle.asn1.ASN1Primitive;
import org.ripple.bouncycastle.asn1.ASN1Sequence;
import org.ripple.bouncycastle.asn1.ASN1TaggedObject;
import org.ripple.bouncycastle.asn1.DERSequence;
public class GOST3410PublicKeyAlgParameters
extends ASN1Object
{
private ASN1ObjectIdentifier publicKeyParamSet;
private ASN1ObjectIdentifier digestParamSet;
private ASN1ObjectIdentifier encryptionParamSet;
public static GOST3410PublicKeyAlgParameters getInstance(
ASN1TaggedObject obj,
boolean explicit)
{
return getInstance(ASN1Sequence.getInstance(obj, explicit));
}
public static GOST3410PublicKeyAlgParameters getInstance(
Object obj)
{
if (obj instanceof GOST3410PublicKeyAlgParameters)
{
return (GOST3410PublicKeyAlgParameters)obj;
}
if(obj != null)
{
return new GOST3410PublicKeyAlgParameters(ASN1Sequence.getInstance(obj));
}
return null;
}
public GOST3410PublicKeyAlgParameters(
ASN1ObjectIdentifier publicKeyParamSet,
ASN1ObjectIdentifier digestParamSet)
{
this.publicKeyParamSet = publicKeyParamSet;
this.digestParamSet = digestParamSet;
this.encryptionParamSet = null;
}
public GOST3410PublicKeyAlgParameters(
ASN1ObjectIdentifier publicKeyParamSet,
ASN1ObjectIdentifier digestParamSet,
ASN1ObjectIdentifier encryptionParamSet)
{
this.publicKeyParamSet = publicKeyParamSet;
this.digestParamSet = digestParamSet;
this.encryptionParamSet = encryptionParamSet;
}
/**
* @deprecated use getInstance()
*/
public GOST3410PublicKeyAlgParameters(
ASN1Sequence seq)
{
this.publicKeyParamSet = (ASN1ObjectIdentifier)seq.getObjectAt(0);
this.digestParamSet = (ASN1ObjectIdentifier)seq.getObjectAt(1);
if (seq.size() > 2)
{
this.encryptionParamSet = (ASN1ObjectIdentifier)seq.getObjectAt(2);
}
}
public ASN1ObjectIdentifier getPublicKeyParamSet()
{
return publicKeyParamSet;
}
public ASN1ObjectIdentifier getDigestParamSet()
{
return digestParamSet;
}
public ASN1ObjectIdentifier getEncryptionParamSet()
{
return encryptionParamSet;
}
public ASN1Primitive toASN1Primitive()
{
ASN1EncodableVector v = new ASN1EncodableVector();
v.add(publicKeyParamSet);
v.add(digestParamSet);
if (encryptionParamSet != null)
{
v.add(encryptionParamSet);
}
return new DERSequence(v);
}
}
| {
"content_hash": "8b0d2f5a86440364931cc850ede1ce63",
"timestamp": "",
"source": "github",
"line_count": 104,
"max_line_length": 85,
"avg_line_length": 28.221153846153847,
"alnum_prop": 0.6844974446337309,
"repo_name": "cping/RipplePower",
"id": "573e29ce27d04423fabc70749ecd07a9decbdef8",
"size": "2935",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "eclipse/jcoinlibs/src/org/ripple/bouncycastle/asn1/cryptopro/GOST3410PublicKeyAlgParameters.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "1424"
},
{
"name": "C++",
"bytes": "161794"
},
{
"name": "HTML",
"bytes": "1274"
},
{
"name": "Java",
"bytes": "15692829"
},
{
"name": "Objective-C",
"bytes": "403"
}
],
"symlink_target": ""
} |
(function ($, document, window, undefined) {
'use strict';
$.fn.pagepiling = function (custom) {
var PP = $.fn.pagepiling;
var container = $(this);
var lastScrolledDestiny;
var lastAnimation = 0;
var isTouch = (('ontouchstart' in window) || (navigator.msMaxTouchPoints > 0) || (navigator.maxTouchPoints));
var touchStartY = 0, touchStartX = 0, touchEndY = 0, touchEndX = 0;
var scrollings = [];
//Defines the delay to take place before being able to scroll to the next section
//BE CAREFUL! Not recommened to change it under 400 for a good behavior in laptops and
//Apple devices (laptops, mouses...)
var scrollDelay = 600;
// Create some defaults, extending them with any options that were provided
var options = $.extend(true, {
direction: 'vertical',
menu: null,
verticalCentered: true,
sectionsColor: [],
anchors: [],
scrollingSpeed: 700,
easing: 'easeInQuart',
loopBottom: false,
loopTop: false,
css3: true,
navigation: {
textColor: '#000',
bulletsColor: '#000',
position: 'right',
tooltips: []
},
normalScrollElements: null,
normalScrollElementTouchThreshold: 5,
touchSensitivity: 5,
keyboardScrolling: true,
sectionSelector: '.section',
animateAnchor: false,
//events
afterLoad: null,
onLeave: null,
afterRender: null
}, custom);
//easeInQuart animation included in the plugin
$.extend($.easing,{ easeInQuart: function (x, t, b, c, d) { return c*(t/=d)*t*t*t + b; }});
/**
* Defines the scrolling speed
*/
PP.setScrollingSpeed = function(value){
options.scrollingSpeed = value;
};
/**
* Adds or remove the possiblity of scrolling through sections by using the mouse wheel or the trackpad.
*/
PP.setMouseWheelScrolling = function (value){
if(value){
addMouseWheelHandler();
}else{
removeMouseWheelHandler();
}
};
/**
* Adds or remove the possiblity of scrolling through sections by using the mouse wheel/trackpad or touch gestures.
*/
PP.setAllowScrolling = function (value){
if(value){
PP.setMouseWheelScrolling(true);
addTouchHandler();
}else{
PP.setMouseWheelScrolling(false);
removeTouchHandler();
}
};
/**
* Adds or remove the possiblity of scrolling through sections by using the keyboard arrow keys
*/
PP.setKeyboardScrolling = function (value){
options.keyboardScrolling = value;
};
/**
* Moves sectio up
*/
PP.moveSectionUp = function () {
var prev = $('.pp-section.active').prev('.pp-section');
//looping to the bottom if there's no more sections above
if (!prev.length && options.loopTop) {
prev = $('.pp-section').last();
}
if (prev.length) {
scrollPage(prev);
}
};
/**
* Moves sectio down
*/
PP.moveSectionDown = function () {
var next = $('.pp-section.active').next('.pp-section');
//looping to the top if there's no more sections below
if(!next.length && options.loopBottom){
next = $('.pp-section').first();
}
if (next.length) {
scrollPage(next);
}
};
/**
* Moves the site to the given anchor or index
*/
PP.moveTo = function (section){
var destiny = '';
if(isNaN(section)){
destiny = $(document).find('[data-anchor="'+section+'"]');
}else{
destiny = $('.pp-section').eq( (section -1) );
}
if(destiny.length > 0){
scrollPage(destiny);
}
};
//adding internal class names to void problem with common ones
$(options.sectionSelector).each(function(){
$(this).addClass('pp-section');
});
//if css3 is not supported, it will use jQuery animations
if(options.css3){
options.css3 = support3d();
}
$(container).css({
'overflow' : 'hidden',
'-ms-touch-action': 'none', /* Touch detection for Windows 8 */
'touch-action': 'none' /* IE 11 on Windows Phone 8.1*/
});
//init
PP.setAllowScrolling(true);
//creating the navigation dots
if (!$.isEmptyObject(options.navigation) ) {
addVerticalNavigation();
}
var zIndex = $('.pp-section').length;
$('.pp-section').each(function (index) {
$(this).data('data-index', index);
$(this).css('z-index', zIndex);
//if no active section is defined, the 1st one will be the default one
if (!index && $('.pp-section.active').length === 0) {
$(this).addClass('active');
}
if (typeof options.anchors[index] !== 'undefined') {
$(this).attr('data-anchor', options.anchors[index]);
}
if (typeof options.sectionsColor[index] !== 'undefined') {
$(this).css('background-color', options.sectionsColor[index]);
}
if(options.verticalCentered && !$(this).hasClass('pp-scrollable')){
addTableClass($(this));
}
zIndex = zIndex - 1;
}).promise().done(function(){
//vertical centered of the navigation + first bullet active
if(options.navigation){
$('#pp-nav').css('margin-top', '-' + ($('#pp-nav').height()/2) + 'px');
$('#pp-nav').find('li').eq($('.pp-section.active').index('.pp-section')).find('a').addClass('active');
}
$(window).on('load', function() {
scrollToAnchor();
});
$.isFunction( options.afterRender ) && options.afterRender.call( this);
});
/**
* Enables vertical centering by wrapping the content and the use of table and table-cell
*/
function addTableClass(element){
element.addClass('pp-table').wrapInner('<div class="pp-tableCell" style="height:100%" />');
}
/**
* Retuns `up` or `down` depending on the scrolling movement to reach its destination
* from the current section.
*/
function getYmovement(destiny){
var fromIndex = $('.pp-section.active').index('.pp-section');
var toIndex = destiny.index('.pp-section');
if(fromIndex > toIndex){
return 'up';
}
return 'down';
}
/**
* Scrolls the page to the given destination
*/
function scrollPage(destination, animated) {
var v ={
destination: destination,
animated: animated,
activeSection: $('.pp-section.active'),
anchorLink: destination.data('anchor'),
sectionIndex: destination.index('.pp-section'),
toMove: destination,
yMovement: getYmovement(destination),
leavingSection: $('.pp-section.active').index('.pp-section') + 1
};
//quiting when activeSection is the target element
if(v.activeSection.is(destination)){ return; }
if(typeof v.animated === 'undefined'){
v.animated = true;
}
if(typeof v.anchorLink !== 'undefined'){
setURLHash(v.anchorLink, v.sectionIndex);
}
v.destination.addClass('active').siblings().removeClass('active');
v.sectionsToMove = getSectionsToMove(v);
//scrolling down (moving sections up making them disappear)
if (v.yMovement === 'down') {
v.translate3d = getTranslate3d();
v.scrolling = '-100%';
if(!options.css3){
v.sectionsToMove.each(function(index){
if(index != v.activeSection.index('.pp-section')){
$(this).css(getScrollProp(v.scrolling));
}
});
}
v.animateSection = v.activeSection;
}
//scrolling up (moving section down to the viewport)
else {
v.translate3d = 'translate3d(0px, 0px, 0px)';
v.scrolling = '0';
v.animateSection = destination;
}
$.isFunction(options.onLeave) && options.onLeave.call(this, v.leavingSection, (v.sectionIndex + 1), v.yMovement);
performMovement(v);
activateMenuElement(v.anchorLink);
activateNavDots(v.anchorLink, v.sectionIndex);
lastScrolledDestiny = v.anchorLink;
var timeNow = new Date().getTime();
lastAnimation = timeNow;
}
/**
* Performs the movement (by CSS3 or by jQuery)
*/
function performMovement(v){
if(options.css3){
transformContainer(v.animateSection, v.translate3d, v.animated);
v.sectionsToMove.each(function(){
transformContainer($(this), v.translate3d, v.animated);
});
setTimeout(function () {
afterSectionLoads(v);
}, options.scrollingSpeed);
}else{
v.scrollOptions = getScrollProp(v.scrolling);
if(v.animated){
v.animateSection.animate(
v.scrollOptions,
options.scrollingSpeed, options.easing, function () {
readjustSections(v);
afterSectionLoads(v);
});
}else{
v.animateSection.css(getScrollProp(v.scrolling));
setTimeout(function(){
readjustSections(v);
afterSectionLoads(v);
},400);
}
}
}
/**
* Actions to execute after a secion is loaded
*/
function afterSectionLoads(v){
//callback (afterLoad) if the site is not just resizing and readjusting the slides
$.isFunction(options.afterLoad) && options.afterLoad.call(this, v.anchorLink, (v.sectionIndex + 1));
}
function getSectionsToMove(v){
var sectionToMove;
if(v.yMovement === 'down'){
sectionToMove = $('.pp-section').map(function(index){
if (index < v.destination.index('.pp-section')){
return $(this);
}
});
}else{
sectionToMove = $('.pp-section').map(function(index){
if (index > v.destination.index('.pp-section')){
return $(this);
}
});
}
return sectionToMove;
}
/**
* Returns the sections to re-adjust in the background after the section loads.
*/
function readjustSections(v){
if(v.yMovement === 'up'){
v.sectionsToMove.each(function(index){
$(this).css(getScrollProp(v.scrolling));
});
}
}
/**
* Gets the property used to create the scrolling effect when using jQuery animations
* depending on the plugin direction option.
*/
function getScrollProp(propertyValue){
if(options.direction === 'vertical'){
return {'top': propertyValue};
}
return {'left': propertyValue};
}
/**
* Scrolls the site without anymations (usually used in the background without the user noticing it)
*/
function silentScroll(section, offset){
if (options.css3) {
transformContainer(section, getTranslate3d(), false);
}
else{
section.css(getScrollProp(offset));
}
}
/**
* Sets the URL hash for a section with slides
*/
function setURLHash(anchorLink, sectionIndex){
if(options.anchors.length){
location.hash = anchorLink;
setBodyClass(location.hash);
}else{
setBodyClass(String(sectionIndex));
}
}
/**
* Sets a class for the body of the page depending on the active section / slide
*/
function setBodyClass(text){
//removing the #
text = text.replace('#','');
//removing previous anchor classes
$('body')[0].className = $('body')[0].className.replace(/\b\s?pp-viewing-[^\s]+\b/g, '');
//adding the current anchor
$('body').addClass('pp-viewing-' + text);
}
//TO DO
function scrollToAnchor(){
//getting the anchor link in the URL and deleting the `#`
var value = window.location.hash.replace('#', '');
var sectionAnchor = value;
var section = $(document).find('.pp-section[data-anchor="'+sectionAnchor+'"]');
if(section.length > 0){ //if theres any #
scrollPage(section, options.animateAnchor);
}
}
/**
* Determines if the transitions between sections still taking place.
* The variable `scrollDelay` adds a "save zone" for devices such as Apple laptops and Apple magic mouses
*/
function isMoving(){
var timeNow = new Date().getTime();
// Cancel scroll if currently animating or within quiet period
if (timeNow - lastAnimation < scrollDelay + options.scrollingSpeed) {
return true;
}
return false;
}
//detecting any change on the URL to scroll to the given anchor link
//(a way to detect back history button as we play with the hashes on the URL)
$(window).on('hashchange', hashChangeHandler);
/**
* Actions to do when the hash (#) in the URL changes.
*/
function hashChangeHandler(){
var value = window.location.hash.replace('#', '').split('/');
var sectionAnchor = value[0];
if(sectionAnchor.length){
/*in order to call scrollpage() only once for each destination at a time
It is called twice for each scroll otherwise, as in case of using anchorlinks `hashChange`
event is fired on every scroll too.*/
if (sectionAnchor && sectionAnchor !== lastScrolledDestiny) {
var section;
if(isNaN(sectionAnchor)){
section = $(document).find('[data-anchor="'+sectionAnchor+'"]');
}else{
section = $('.pp-section').eq( (sectionAnchor -1) );
}
scrollPage(section);
}
}
}
/**
* Cross browser transformations
*/
function getTransforms(translate3d) {
return {
'-webkit-transform': translate3d,
'-moz-transform': translate3d,
'-ms-transform': translate3d,
'transform': translate3d
};
}
/**
* Adds a css3 transform property to the container class with or without animation depending on the animated param.
*/
function transformContainer(element, translate3d, animated) {
element.toggleClass('pp-easing', animated);
element.css(getTransforms(translate3d));
}
/**
* Sliding with arrow keys, both, vertical and horizontal
*/
$(document).keydown(function (e) {
if(options.keyboardScrolling && !isMoving()){
//Moving the main page with the keyboard arrows if keyboard scrolling is enabled
switch (e.which) {
//up
case 38:
case 33:
PP.moveSectionUp();
break;
//down
case 40:
case 34:
PP.moveSectionDown();
break;
//Home
case 36:
PP.moveTo(1);
break;
//End
case 35:
PP.moveTo($('.pp-section').length);
break;
//left
case 37:
PP.moveSectionUp();
break;
//right
case 39:
PP.moveSectionDown();
break;
default:
return; // exit this handler for other keys
}
}
});
/**
* If `normalScrollElements` is used, the mouse wheel scrolling will scroll normally
* over the defined elements in the option.
*/
if(options.normalScrollElements){
$(document).on('mouseenter', options.normalScrollElements, function () {
PP.setMouseWheelScrolling(false);
});
$(document).on('mouseleave', options.normalScrollElements, function(){
PP.setMouseWheelScrolling(true);
});
}
/**
* Detecting mousewheel scrolling
*
* http://blogs.sitepointstatic.com/examples/tech/mouse-wheel/index.html
* http://www.sitepoint.com/html5-javascript-mouse-wheel/
*/
var prevTime = new Date().getTime();
function MouseWheelHandler(e) {
var curTime = new Date().getTime();
// cross-browser wheel delta
e = e || window.event;
var value = e.wheelDelta || -e.deltaY || -e.detail;
var delta = Math.max(-1, Math.min(1, value));
var horizontalDetection = typeof e.wheelDeltaX !== 'undefined' || typeof e.deltaX !== 'undefined';
var isScrollingVertically = (Math.abs(e.wheelDeltaX) < Math.abs(e.wheelDelta)) || (Math.abs(e.deltaX ) < Math.abs(e.deltaY) || !horizontalDetection);
//Limiting the array to 150 (lets not waste memory!)
if(scrollings.length > 149){
scrollings.shift();
}
//keeping record of the previous scrollings
scrollings.push(Math.abs(value));
//time difference between the last scroll and the current one
var timeDiff = curTime-prevTime;
prevTime = curTime;
//haven't they scrolled in a while?
//(enough to be consider a different scrolling action to scroll another section)
if(timeDiff > 200){
//emptying the array, we dont care about old scrollings for our averages
scrollings = [];
}
if(!isMoving()){
var activeSection = $('.pp-section.active');
var scrollable = isScrollable(activeSection);
var averageEnd = getAverage(scrollings, 10);
var averageMiddle = getAverage(scrollings, 70);
var isAccelerating = averageEnd >= averageMiddle;
if(isAccelerating && isScrollingVertically){
//scrolling down?
if (delta < 0) {
scrolling('down', scrollable);
//scrolling up?
}else if(delta>0){
scrolling('up', scrollable);
}
}
return false;
}
}
/**
* Gets the average of the last `number` elements of the given array.
*/
function getAverage(elements, number){
var sum = 0;
//taking `number` elements from the end to make the average, if there are not enought, 1
var lastElements = elements.slice(Math.max(elements.length - number, 1));
for(var i = 0; i < lastElements.length; i++){
sum = sum + lastElements[i];
}
return Math.ceil(sum/number);
}
/**
* Determines the way of scrolling up or down:
* by 'automatically' scrolling a section or by using the default and normal scrolling.
*/
function scrolling(type, scrollable){
var check;
var scrollSection;
if(type == 'down'){
check = 'bottom';
scrollSection = PP.moveSectionDown;
}else{
check = 'top';
scrollSection = PP.moveSectionUp;
}
if(scrollable.length > 0 ){
//is the scrollbar at the start/end of the scroll?
if(isScrolled(check, scrollable)){
scrollSection();
}else{
return true;
}
}else{
//moved up/down
scrollSection();
}
}
/**
* Return a boolean depending on whether the scrollable element is at the end or at the start of the scrolling
* depending on the given type.
*/
function isScrolled(type, scrollable){
if(type === 'top'){
return !scrollable.scrollTop();
}else if(type === 'bottom'){
return scrollable.scrollTop() + 1 + scrollable.innerHeight() >= scrollable[0].scrollHeight;
}
}
/**
* Determines whether the active section or slide is scrollable through and scrolling bar
*/
function isScrollable(activeSection){
return activeSection.filter('.pp-scrollable');
}
/**
* Removes the auto scrolling action fired by the mouse wheel and tackpad.
* After this function is called, the mousewheel and trackpad movements won't scroll through sections.
*/
function removeMouseWheelHandler(){
if (container.get(0).addEventListener) {
container.get(0).removeEventListener('mousewheel', MouseWheelHandler, false); //IE9, Chrome, Safari, Oper
container.get(0).removeEventListener('wheel', MouseWheelHandler, false); //Firefox
} else {
container.get(0).detachEvent('onmousewheel', MouseWheelHandler); //IE 6/7/8
}
}
/**
* Adds the auto scrolling action for the mouse wheel and tackpad.
* After this function is called, the mousewheel and trackpad movements will scroll through sections
*/
function addMouseWheelHandler(){
if (container.get(0).addEventListener) {
container.get(0).addEventListener('mousewheel', MouseWheelHandler, false); //IE9, Chrome, Safari, Oper
container.get(0).addEventListener('wheel', MouseWheelHandler, false); //Firefox
} else {
container.get(0).attachEvent('onmousewheel', MouseWheelHandler); //IE 6/7/8
}
}
/**
* Adds the possibility to auto scroll through sections on touch devices.
*/
function addTouchHandler(){
if(isTouch){
//Microsoft pointers
var MSPointer = getMSPointer();
container.off('touchstart ' + MSPointer.down).on('touchstart ' + MSPointer.down, touchStartHandler);
container.off('touchmove ' + MSPointer.move).on('touchmove ' + MSPointer.move, touchMoveHandler);
}
}
/**
* Removes the auto scrolling for touch devices.
*/
function removeTouchHandler(){
if(isTouch){
//Microsoft pointers
var MSPointer = getMSPointer();
container.off('touchstart ' + MSPointer.down);
container.off('touchmove ' + MSPointer.move);
}
}
/*
* Returns and object with Microsoft pointers (for IE<11 and for IE >= 11)
* http://msdn.microsoft.com/en-us/library/ie/dn304886(v=vs.85).aspx
*/
function getMSPointer(){
var pointer;
//IE >= 11 & rest of browsers
if(window.PointerEvent){
pointer = { down: 'pointerdown', move: 'pointermove', up: 'pointerup'};
}
//IE < 11
else{
pointer = { down: 'MSPointerDown', move: 'MSPointerMove', up: 'MSPointerUp'};
}
return pointer;
}
/**
* Gets the pageX and pageY properties depending on the browser.
* https://github.com/alvarotrigo/fullPage.js/issues/194#issuecomment-34069854
*/
function getEventsPage(e){
var events = new Array();
events.y = (typeof e.pageY !== 'undefined' && (e.pageY || e.pageX) ? e.pageY : e.touches[0].pageY);
events.x = (typeof e.pageX !== 'undefined' && (e.pageY || e.pageX) ? e.pageX : e.touches[0].pageX);
return events;
}
/**
* As IE >= 10 fires both touch and mouse events when using a mouse in a touchscreen
* this way we make sure that is really a touch event what IE is detecting.
*/
function isReallyTouch(e){
//if is not IE || IE is detecting `touch` or `pen`
return typeof e.pointerType === 'undefined' || e.pointerType != 'mouse';
}
/**
* Getting the starting possitions of the touch event
*/
function touchStartHandler(event){
var e = event.originalEvent;
if(isReallyTouch(e)){
var touchEvents = getEventsPage(e);
touchStartY = touchEvents.y;
touchStartX = touchEvents.x;
}
}
/* Detecting touch events
*/
function touchMoveHandler(event){
var e = event.originalEvent;
// additional: if one of the normalScrollElements isn't within options.normalScrollElementTouchThreshold hops up the DOM chain
if ( !checkParentForNormalScrollElement(event.target) && isReallyTouch(e) ) {
var activeSection = $('.pp-section.active');
var scrollable = isScrollable(activeSection);
if(!scrollable.length){
event.preventDefault();
}
if (!isMoving()) {
var touchEvents = getEventsPage(e);
touchEndY = touchEvents.y;
touchEndX = touchEvents.x;
//$('body').append('<span style="position:fixed; top: 250px; left: 20px; z-index:88; font-size: 25px; color: #000;">touchEndY: ' + touchEndY + '</div>');
//X movement bigger than Y movement?
if (options.direction === 'horizontal' && Math.abs(touchStartX - touchEndX) > (Math.abs(touchStartY - touchEndY))) {
//is the movement greater than the minimum resistance to scroll?
if (Math.abs(touchStartX - touchEndX) > (container.width() / 100 * options.touchSensitivity)) {
if (touchStartX > touchEndX) {
scrolling('down', scrollable);
} else if (touchEndX > touchStartX) {
scrolling('up', scrollable);
}
}
} else {
if (Math.abs(touchStartY - touchEndY) > (container.height() / 100 * options.touchSensitivity)) {
if (touchStartY > touchEndY) {
scrolling('down', scrollable);
} else if (touchEndY > touchStartY) {
scrolling('up', scrollable);
}
}
}
}
}
}
/**
* recursive function to loop up the parent nodes to check if one of them exists in options.normalScrollElements
* Currently works well for iOS - Android might need some testing
* @param {Element} el target element / jquery selector (in subsequent nodes)
* @param {int} hop current hop compared to options.normalScrollElementTouchThreshold
* @return {boolean} true if there is a match to options.normalScrollElements
*/
function checkParentForNormalScrollElement (el, hop) {
hop = hop || 0;
var parent = $(el).parent();
if (hop < options.normalScrollElementTouchThreshold &&
parent.is(options.normalScrollElements) ) {
return true;
} else if (hop == options.normalScrollElementTouchThreshold) {
return false;
} else {
return checkParentForNormalScrollElement(parent, ++hop);
}
}
/**
* Creates a vertical navigation bar.
*/
function addVerticalNavigation(){
$('body').append('<div id="pp-nav"><ul></ul></div>');
var nav = $('#pp-nav');
nav.css('color', options.navigation.textColor);
nav.addClass(options.navigation.position);
for(var cont = 0; cont < $('.pp-section').length; cont++){
var link = '';
if(options.anchors.length){
link = options.anchors[cont];
}
if(options.navigation.tooltips !== 'undefined'){
var tooltip = options.navigation.tooltips[cont];
if(typeof tooltip === 'undefined'){
tooltip = '';
}
}
nav.find('ul').append('<li data-tooltip="' + tooltip + '"><a href="#' + link + '"><span></span></a></li>');
}
nav.find('span').css('border-color', options.navigation.bulletsColor);
}
/**
* Scrolls to the section when clicking the navigation bullet
*/
$(document).on('click touchstart', '#pp-nav a', function(e){
e.preventDefault();
var index = $(this).parent().index();
scrollPage($('.pp-section').eq(index));
});
/**
* Navigation tooltips
*/
$(document).on({
mouseenter: function(){
var tooltip = $(this).data('tooltip');
$('<div class="pp-tooltip ' + options.navigation.position +'">' + tooltip + '</div>').hide().appendTo($(this)).fadeIn(200);
},
mouseleave: function(){
$(this).find('.pp-tooltip').fadeOut(200, function() {
$(this).remove();
});
}
}, '#pp-nav li');
/**
* Activating the website navigation dots according to the given slide name.
*/
function activateNavDots(name, sectionIndex){
if(options.navigation){
$('#pp-nav').find('.active').removeClass('active');
if(name){
$('#pp-nav').find('a[href="#' + name + '"]').addClass('active');
}else{
$('#pp-nav').find('li').eq(sectionIndex).find('a').addClass('active');
}
}
}
/**
* Activating the website main menu elements according to the given slide name.
*/
function activateMenuElement(name){
if(options.menu){
$(options.menu).find('.active').removeClass('active');
$(options.menu).find('[data-menuanchor="'+name+'"]').addClass('active');
}
}
/**
* Checks for translate3d support
* @return boolean
* http://stackoverflow.com/questions/5661671/detecting-transform-translate3d-support
*/
function support3d() {
var el = document.createElement('p'),
has3d,
transforms = {
'webkitTransform':'-webkit-transform',
'OTransform':'-o-transform',
'msTransform':'-ms-transform',
'MozTransform':'-moz-transform',
'transform':'transform'
};
// Add it to the body to get the computed style.
document.body.insertBefore(el, null);
for (var t in transforms) {
if (el.style[t] !== undefined) {
el.style[t] = 'translate3d(1px,1px,1px)';
has3d = window.getComputedStyle(el).getPropertyValue(transforms[t]);
}
}
document.body.removeChild(el);
return (has3d !== undefined && has3d.length > 0 && has3d !== 'none');
}
/**
* Gets the translate3d property to apply when using css3:true depending on the `direction` option.
*/
function getTranslate3d(){
if (options.direction !== 'vertical') {
return 'translate3d(-100%, 0px, 0px)';
}
return 'translate3d(0px, -100%, 0px)';
}
};
})(jQuery, document, window); | {
"content_hash": "9824006a01b84fdb0eacc10840fbddc9",
"timestamp": "",
"source": "github",
"line_count": 969,
"max_line_length": 172,
"avg_line_length": 36.4984520123839,
"alnum_prop": 0.48664008821783017,
"repo_name": "cdnjs/cdnjs",
"id": "37908e28d54f42af09bcda9bb7a518c17847a9b3",
"size": "35549",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "ajax/libs/pagePiling.js/1.5.6/jquery.pagepiling.js",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
using System;
namespace Free.Core.Extensions.CharExtensions
{
/// <summary>
/// Added methods to the <see cref="Char"/> class.
/// </summary>
/// <threadsafety static="true" instance="true"/>
[CLSCompliant(false)]
public static class CharExtensions
{
/// <summary>
/// The minimum allowed radix value as argument in <see cref="Digit"/>.
/// Only character in ['0' '1'] will return a non-minus-one value.
/// </summary>
public const uint MinimumRadix = 1;
/// <summary>
/// The minimum allowed radix value as argument in <see cref="Digit"/>.
/// Only character in ['0'-'9', 'a'-'z', 'A'-'Z'] will return a non-minus-one value.
/// </summary>
public const uint MaximumRadix = 36;
/// <summary>
/// Determines whether a character is a hexadecimal digit character [0-9, a-f, A-F].
/// </summary>
/// <param name="ch">The <b>string</b> to test.</param>
/// <returns><b>true</b> if the character is a hexadecimal digit character; otherwise, <b>false</b>.</returns>
public static bool IsHexDigit(this char ch)
{
if ((ch < '0' || ch > '9') && (ch < 'A' || ch > 'F') && (ch < 'a' || ch > 'f')) return false;
return true;
}
/// <summary>
/// Converts a character to it number value limiting the result with the specified <paramref name="radix"/>.
/// </summary>
/// <param name="ch">The character to convert.</param>
/// <param name="radix">The radix. The result value will be check against this. [<see cref="MinimumRadix"/> <see cref="MaximumRadix"/>]</param>
/// <returns>The number value of the character regarding the radix; otherwise, minus one (-1).</returns>
public static int Digit(this char ch, uint radix=10)
{
int value = -1;
if (radix >= MinimumRadix && radix <= MaximumRadix)
{
if (ch >= '0' && ch <= '9') value = ch - '0';
if (ch >= 'a' && ch <= 'z') value = 10 + ch - 'a';
if (ch >= 'A' && ch <= 'Z') value = 10 + ch - 'A';
}
return (value < (int)radix) ? value : -1;
}
}
#if USE_NAMESPACE_DOC_CLASSES
/// <summary>
/// Added methods to the <see cref="Char"/> class.
/// </summary>
[System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
class NamespaceDoc { }
#endif
}
| {
"content_hash": "16233cd4e1abef991c99f184030b7757",
"timestamp": "",
"source": "github",
"line_count": 63,
"max_line_length": 145,
"avg_line_length": 34.76190476190476,
"alnum_prop": 0.6146118721461187,
"repo_name": "shintadono/Free.Core",
"id": "c462ae066f99c899140898ab5b2725e754cb1489",
"size": "2192",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Extensions/CharExtensions.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "714716"
}
],
"symlink_target": ""
} |
.. currentmodule:: altair
.. _user-guide-encoding:
Encodings
---------
The key to creating meaningful visualizations is to map *properties of the data*
to *visual properties* in order to effectively communicate information.
In Alair, this mapping of visual properties to data columns is referred to
as an **encoding**, and is most often expressed through the :meth:`Chart.encode`
method.
For example, here we will visualize the cars dataset using four of the available
encodings: ``x`` (the x-axis value), ``y`` (the y-axis value),
``color`` (the color of the marker), and ``shape`` (the shape of the point marker):
.. altair-plot::
import altair as alt
from vega_datasets import data
cars = data.cars()
alt.Chart(cars).mark_point().encode(
x='Horsepower',
y='Miles_per_Gallon',
color='Origin',
shape='Origin'
)
For data specified as a DataFrame, Altair can automatically determine the
correct data type for each encoding, and creates appropriate scales and
legends to represent the data.
.. _encoding-channels:
Encoding Channels
~~~~~~~~~~~~~~~~~
Altair provides a number of encoding channels that can be useful in different
circumstances; the following table summarizes them:
Position Channels:
========== =================== ================================= ===================================
Channel Altair Class Description Example
========== =================== ================================= ===================================
x :class:`X` The x-axis value :ref:`gallery_simple_scatter`
y :class:`Y` The y-axis value :ref:`gallery_simple_scatter`
x2 :class:`X2` Second x value for ranges :ref:`gallery_error_bars_with_ci`
y2 :class:`Y2` Second y value for ranges :ref:`gallery_line_with_ci`
longitude :class:`Longitude` Longitude for geo charts :ref:`gallery_airports`
latitude :class:`Latitude` Latitude for geo charts :ref:`gallery_airports`
longitude2 :class:`Longitude2` Second longitude value for ranges N/A
latitude2 :class:`Latitude2` Second latitude value for ranges N/A
========== =================== ================================= ===================================
Mark Property Channels:
======= ================ ======================== =========================================
Channel Altair Class Description Example
======= ================ ======================== =========================================
color :class:`Color` The color of the mark :ref:`gallery_simple_heatmap`
fill :class:`Fill` The fill for the mark N/A
opacity :class:`Opacity` The opacity of the mark :ref:`gallery_horizon_graph`
shape :class:`Shape` The shape of the mark N/A
size :class:`Size` The size of the mark :ref:`gallery_table_bubble_plot_github`
stroke :class:`Stroke` The stroke of the mark N/A
======= ================ ======================== =========================================
Text and Tooltip Channels:
======= ================ ======================== =========================================
Channel Altair Class Description Example
======= ================ ======================== =========================================
text :class:`Text` Text to use for the mark :ref:`gallery_scatter_with_labels`
key :class:`Key` -- N/A
tooltip :class:`Tooltip` The tooltip value N/A
======= ================ ======================== =========================================
Hyperlink Channel:
======= ================ ======================== =========================================
Channel Altair Class Description Example
======= ================ ======================== =========================================
href :class:`Href` Hyperlink for points N/A
======= ================ ======================== =========================================
Level of Detail Channel:
======= ================ =============================== =========================================
Channel Altair Class Description Example
======= ================ =============================== =========================================
detail :class:`Detail` Additional property to group by :ref:`gallery_select_detail`
======= ================ =============================== =========================================
Order Channel:
======= ================ ============================= =====================================
Channel Altair Class Description Example
======= ================ ============================= =====================================
order :class:`Order` Sets the order of the marks :ref:`gallery_connected_scatterplot`
======= ================ ============================= =====================================
Facet Channels:
======= ================ ============================ ============================================
Channel Altair Class Description Example
======= ================ ============================ ============================================
column :class:`Column` The column of a faceted plot :ref:`gallery_trellis_scatter_plot`
row :class:`Row` The row of a faceted plot :ref:`gallery_beckers_barley_trellis_plot`
======= ================ ============================ ============================================
.. _data-types:
Data Types
~~~~~~~~~~
The details of any mapping depend on the *type* of the data. Altair recognizes
four main data types:
============ ============== ================================================
Data Type Shorthand Code Description
============ ============== ================================================
quantitative ``Q`` a continuous real-valued quantity
ordinal ``O`` a discrete ordered quantity
nominal ``N`` a discrete unordered category
temporal ``T`` a time or date value
============ ============== ================================================
If types are not specified for data input as a DataFrame, Altair defaults to
``quantitative`` for any numeric data, ``temporal`` for date/time data, and
``nominal`` for string data, but be aware that these defaults are by no means
always the correct choice!
The types can either be expressed in a long-form using the channel encoding
classes such as :class:`X` and :class:`Y`, or in short-form using the
:ref:`Shorthand Syntax <shorthand-description>` discussed below.
For example, the following two methods of specifying the type will lead to
identical plots:
.. altair-plot::
alt.Chart(cars).mark_point().encode(
x='Acceleration:Q',
y='Miles_per_Gallon:Q',
color='Origin:N'
)
.. altair-plot::
alt.Chart(cars).mark_point().encode(
alt.X('Acceleration', type='quantitative'),
alt.Y('Miles_per_Gallon', type='quantitative'),
alt.Color('Origin', type='nominal')
)
The shorthand form, ``x="name:Q"``, is useful for its lack of boilerplate
when doing quick data explorations. The long-form,
``alt.X('name', type='quantitative')``, is useful when doing more fine-tuned
adjustments to the encoding, such as binning, axis and scale properties,
or more.
Specifying the correct type for your data is important, as it affects the
way Altair represents your encoding in the resulting plot.
.. _type-legend-scale:
Effect of Data Type on Color Scales
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
As an example of this, here we will represent the same data three different ways,
with the color encoded as a *quantitative*, *ordinal*, and *nominal* type,
using three vertically-concatenated charts (see :ref:`vconcat-chart`):
.. altair-plot::
base = alt.Chart(cars).mark_point().encode(
x='Horsepower:Q',
y='Miles_per_Gallon:Q',
).properties(
width=150,
height=150
)
alt.vconcat(
base.encode(color='Cylinders:Q').properties(title='quantitative'),
base.encode(color='Cylinders:O').properties(title='ordinal'),
base.encode(color='Cylinders:N').properties(title='nominal'),
)
The type specification influences the way Altair, via Vega-Lite, decides on
the color scale to represent the value, and influences whether a discrete
or continuous legend is used.
.. _type-axis-scale:
Effect of Data Type on Axis Scales
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Similarly, for x and y axis encodings, the type used for the data will affect
the scales used and the characteristics of the mark. For example, here is the
difference between a ``quantitative`` and ``ordinal`` scale for an column
that contains integers specifying a year:
.. altair-plot::
pop = data.population.url
base = alt.Chart(pop).mark_bar().encode(
alt.Y('mean(people):Q', axis=alt.Axis(title='total population'))
).properties(
width=200,
height=200
)
alt.hconcat(
base.encode(x='year:Q').properties(title='year=quantitative'),
base.encode(x='year:O').properties(title='year=ordinal')
)
In altair, quantitative scales always start at zero unless otherwise
specified, while ordinal scales are limited to the values within the data.
Overriding the behavior of including zero in the axis, we see that even then
the precise appearance of the marks representing the data are affected by
the data type:
.. altair-plot::
base.encode(
alt.X('year:Q',
scale=alt.Scale(zero=False)
)
)
Because quantitative values do not have an inherent width, the bars do not
fill the entire space between the values.
This view also makes clear the missing year of data that was not immediately
apparent when we treated the years as categories.
This kind of behavior is sometimes surprising to new users, but it emphasizes
the importance of thinking carefully about your data types when visualizing
data: a visual encoding that is suitable for categorical data may not be
suitable for quantitative data, and vice versa.
.. _encoding-channel-options:
Encoding Channel Options
~~~~~~~~~~~~~~~~~~~~~~~~
Each encoding channel allows for a number of additional options to be expressed;
these can control things like axis properties, scale properties, headers and
titles, binning parameters, aggregation, sorting, and many more.
The particular options that are available vary by encoding type; the various
options are listed below.
The :class:`X` and :class:`Y` encodings accept the following options:
.. altair-object-table:: altair.PositionFieldDef
The :class:`Color`, :class:`Fill`, :class:`Opacity`, :class:`Shape`,
:class:`Size`, and :class:`Stroke` encodings accept the following options:
.. altair-object-table:: altair.MarkPropFieldDefWithCondition
The :class:`Row` and :class:`Column` encodings accept the following options:
.. altair-object-table:: altair.FacetFieldDef
The :class:`Text` and :class:`Tooltip` encodings accept the following options:
.. altair-object-table:: altair.TextFieldDefWithCondition
The :class:`Detail`, :class:`Key`, :class:`Latitude`, :class:`Latitude2`,
:class:`Longitude`, :class:`Longitude2`, :class:`X2`
and :class:`Y2` encodings accept the following options:
.. altair-object-table:: altair.FieldDef
The :class:`Href` encoding accepts the following options:
.. altair-object-table:: altair.FieldDefWithCondition
The :class:`Order` encoding accepts the following options:
.. altair-object-table:: altair.OrderFieldDef
.. _encoding-aggregates:
Binning and Aggregation
~~~~~~~~~~~~~~~~~~~~~~~
Beyond simple channel encodings, Altair's visualizations are built on the
concept of the database-style grouping and aggregation; that is, the
`split-apply-combine <https://www.jstatsoft.org/article/view/v040i01>`_
abstraction that underpins many data analysis approaches.
For example, building a histogram from a one-dimensional dataset involves
splitting data based on the bin it falls in, aggregating the results within
each bin using a *count* of the data, and then combining the results into
a final figure.
In Altair, such an operation looks like this:
.. altair-plot::
alt.Chart(cars).mark_bar().encode(
alt.X('Horsepower', bin=True),
y='count()'
# could also use alt.Y(aggregate='count', type='quantitative')
)
Notice here we use the shorthand version of expressing an encoding channel
(see :ref:`shorthand-description`) with the ``count`` aggregation,
which is the one aggregation that does not require a field to be
specified.
Similarly, we can create a two-dimensional histogram using, for example, the
size of points to indicate counts within the grid (sometimes called
a "Bubble Plot"):
.. altair-plot::
alt.Chart(cars).mark_point().encode(
alt.X('Horsepower', bin=True),
alt.Y('Miles_per_Gallon', bin=True),
size='count()',
)
There is no need, however, to limit aggregations to counts alone. For example,
we could similarly create a plot where the color of each point
represents the mean of a third quantity, such as acceleration:
.. altair-plot::
alt.Chart(cars).mark_circle().encode(
alt.X('Horsepower', bin=True),
alt.Y('Miles_per_Gallon', bin=True),
size='count()',
color='average(Acceleration):Q'
)
In addition to ``count`` and ``average``, there are a large number of available
aggregation functions built into Altair; they are listed in the following table:
========= =========================================================================== =====================================
Aggregate Description Example
========= =========================================================================== =====================================
argmin An input data object containing the minimum field value. N/A
argmax An input data object containing the maximum field value. N/A
average The mean (average) field value. Identical to mean. :ref:`gallery_layer_line_color_rule`
count The total count of data objects in the group. :ref:`gallery_simple_heatmap`
distinct The count of distinct field values. N/A
max The maximum field value. :ref:`gallery_boxplot_max_min`
mean The mean (average) field value. :ref:`gallery_layered_plot_with_dual_axis`
median The median field value :ref:`gallery_boxplot_max_min`
min The minimum field value. :ref:`gallery_boxplot_max_min`
missing The count of null or undefined field values. N/A
q1 The lower quartile boundary of values. :ref:`gallery_boxplot_max_min`
q3 The upper quartile boundary of values. :ref:`gallery_boxplot_max_min`
ci0 The lower boundary of the bootstrapped 95% confidence interval of the mean. :ref:`gallery_error_bars_with_ci`
ci1 The upper boundary of the bootstrapped 95% confidence interval of the mean. :ref:`gallery_error_bars_with_ci`
stderr The standard error of the field values. N/A
stdev The sample standard deviation of field values. N/A
stdevp The population standard deviation of field values. N/A
sum The sum of field values. :ref:`gallery_streamgraph`
valid The count of field values that are not null or undefined. N/A
values ?? N/A
variance The sample variance of field values. N/A
variancep The population variance of field values. N/A
========= =========================================================================== =====================================
.. _shorthand-description:
Encoding Shorthands
~~~~~~~~~~~~~~~~~~~
For convenience, Altair allows the specification of the variable name along
with the aggregate and type within a simple shorthand string syntax.
This makes use of the type shorthand codes listed in :ref:`data-types`
as well as the aggregate names listed in :ref:`encoding-aggregates`.
The following table shows examples of the shorthand specification alongside
the long-form equivalent:
=================== =======================================================
Shorthand Equivalent long-form
=================== =======================================================
``x='name'`` ``alt.X('name')``
``x='name:Q'`` ``alt.X('name', type='quantitative')``
``x='sum(name)'`` ``alt.X('name', aggregate='sum')``
``x='sum(name):Q'`` ``alt.X('name', aggregate='sum', type='quantitative')``
``x='count():Q'`` ``alt.X(aggregate='count', type='quantitative')``
=================== =======================================================
.. _ordering-channels:
Ordering marks
~~~~~~~~~~~~~~
The `order` option and :class:`Order` channel can sort how marks are drawn on the chart.
For stacked marks, this controls the order of components of the stack. Here, the elements of each bar are sorted alphabetically by the name of the nominal data in the color channel.
.. altair-plot::
import altair as alt
from vega_datasets import data
barley = data.barley()
alt.Chart(barley).mark_bar().encode(
x='variety:N',
y='sum(yield):Q',
color='site:N',
order=alt.Order("site", sort="ascending")
)
The order can be reversed by changing the sort option to `descending`.
.. altair-plot::
import altair as alt
from vega_datasets import data
barley = data.barley()
alt.Chart(barley).mark_bar().encode(
x='variety:N',
y='sum(yield):Q',
color='site:N',
order=alt.Order("site", sort="descending")
)
The same approach works for other mark types, like stacked areas charts.
.. altair-plot::
import altair as alt
from vega_datasets import data
barley = data.barley()
alt.Chart(barley).mark_area().encode(
x='variety:N',
y='sum(yield):Q',
color='site:N',
order=alt.Order("site", sort="ascending")
)
For line marks, the `order` channel encodes the order in which data points are connected. This can be useful for creating a scatterplot that draws lines between the dots using a different field than the x and y axes.
.. altair-plot::
import altair as alt
from vega_datasets import data
driving = data.driving()
points = alt.Chart(driving).mark_circle().encode(
alt.X('miles', scale=alt.Scale(zero=False)),
alt.Y('gas', scale=alt.Scale(zero=False))
)
lines = alt.Chart(driving).mark_line().encode(
alt.X('miles', scale=alt.Scale(zero=False)),
alt.Y('gas', scale=alt.Scale(zero=False)),
order='year'
)
points + lines
| {
"content_hash": "84e24260e25e7a23e8198f75a116c3cc",
"timestamp": "",
"source": "github",
"line_count": 474,
"max_line_length": 216,
"avg_line_length": 41.30168776371308,
"alnum_prop": 0.557542013587373,
"repo_name": "ellisonbg/altair",
"id": "424b1ee9e862e400e5c4a3b1dd5f5cb44a065fd1",
"size": "19577",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "doc/user_guide/encoding.rst",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Jupyter Notebook",
"bytes": "136763"
},
{
"name": "Makefile",
"bytes": "312"
},
{
"name": "Python",
"bytes": "1150719"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:android="http://schemas.android.com/apk/res/android">
<string name="low_memory_error">"Tidak dapat menyelesaikan operasi sebelumnya karena sisa memori sedikit"</string>
<string name="opening_file_error">"Gagal membuka file terpilih"</string>
<string name="color_picker_button_more">"Lainnya"</string>
<string name="color_picker_hue">"Rona"</string>
<string name="color_picker_saturation">"Saturasi"</string>
<string name="color_picker_value">"Nilai"</string>
<string name="color_picker_button_set">"Setel"</string>
<string name="color_picker_button_cancel">"Batal"</string>
<string name="color_picker_dialog_title">"Pilih warna"</string>
<string name="color_picker_button_red">"Merah"</string>
<string name="color_picker_button_cyan">"Sian"</string>
<string name="color_picker_button_blue">"Biru"</string>
<string name="color_picker_button_green">"Hijau"</string>
<string name="color_picker_button_magenta">"Magenta"</string>
<string name="color_picker_button_yellow">"Kuning"</string>
<string name="color_picker_button_black">"Hitam"</string>
<string name="color_picker_button_white">"Putih"</string>
<string name="copy_to_clipboard_failure_message">"Gagal menyalin ke papan klip"</string>
<string name="accessibility_date_picker_month">"Bulan"</string>
<string name="accessibility_date_picker_year">"Tahun"</string>
<string name="date_picker_dialog_set">"Setel"</string>
<string name="month_picker_dialog_title">"Setel bulan"</string>
<string name="accessibility_date_picker_week">"Minggu"</string>
<string name="week_picker_dialog_title">"Setel minggu"</string>
<string name="time_picker_dialog_am">"AM"</string>
<string name="time_picker_dialog_pm">"PM"</string>
<string name="time_picker_dialog_title">"Setel waktu"</string>
<string name="accessibility_time_picker_hour">"Jam"</string>
<string name="accessibility_time_picker_minute">"Menit"</string>
<string name="accessibility_time_picker_second">"Detik"</string>
<string name="accessibility_time_picker_milli">"Milidetik"</string>
<string name="accessibility_time_picker_ampm">"AM/PM"</string>
<string name="time_picker_dialog_hour_minute_separator">"."</string>
<string name="time_picker_dialog_minute_second_separator">"."</string>
<string name="time_picker_dialog_second_subsecond_separator">":"</string>
<string name="date_time_picker_dialog_title">"Setel tanggal dan waktu"</string>
<string name="accessibility_datetime_picker_date">"Tanggal"</string>
<string name="accessibility_datetime_picker_time">"Waktu"</string>
<string name="date_picker_dialog_other_button_label">"Lainnya"</string>
<string name="date_picker_dialog_title">"Setel tanggal"</string>
<string name="date_picker_dialog_clear">"Hapus"</string>
<string name="autofill_popup_content_description">"Menampilkan munculan isi otomatis"</string>
<string name="password_generation_popup_content_description">"Menampilkan munculan pembuatan sandi"</string>
<string name="autofill_keyboard_accessory_content_description">"Saran yang tersedia"</string>
</resources>
| {
"content_hash": "3e648e6bc9002c37e9e72a61ec35a99f",
"timestamp": "",
"source": "github",
"line_count": 47,
"max_line_length": 114,
"avg_line_length": 64.74468085106383,
"alnum_prop": 0.7578047978968123,
"repo_name": "judax/OculusMobileSDKHeadTrackingXWalkViewExtension",
"id": "8a395040709ac24e0041f20767f4463dff90330a",
"size": "3043",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "3rdparty/crosswalk-webview-18.48.477.13-arm/res/values-in/android_ui_strings.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "22429"
}
],
"symlink_target": ""
} |
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.android_webview.test;
import android.util.Pair;
import androidx.test.filters.SmallTest;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.chromium.android_webview.AwContents;
import org.chromium.android_webview.test.TestAwContentsClient.OnReceivedLoginRequestHelper;
import org.chromium.base.test.util.Feature;
import org.chromium.net.test.util.TestWebServer;
import java.util.ArrayList;
import java.util.List;
/**
* Tests for the AwContentsClient.onReceivedLoginRequest callback.
*/
@RunWith(AwJUnit4ClassRunner.class)
public class AwContentsClientAutoLoginTest {
@Rule
public AwActivityTestRule mActivityTestRule = new AwActivityTestRule();
private TestAwContentsClient mContentsClient = new TestAwContentsClient();
private void autoLoginTestHelper(final String testName, final String xAutoLoginHeader,
final String expectedRealm, final String expectedAccount, final String expectedArgs)
throws Throwable {
AwTestContainerView testView =
mActivityTestRule.createAwTestContainerViewOnMainSync(mContentsClient);
AwContents awContents = testView.getAwContents();
final OnReceivedLoginRequestHelper loginRequestHelper =
mContentsClient.getOnReceivedLoginRequestHelper();
final String path = "/" + testName + ".html";
final String html = testName;
List<Pair<String, String>> headers = new ArrayList<Pair<String, String>>();
headers.add(Pair.create("x-auto-login", xAutoLoginHeader));
TestWebServer webServer = TestWebServer.start();
try {
final String pageUrl = webServer.setResponse(path, html, headers);
final int callCount = loginRequestHelper.getCallCount();
mActivityTestRule.loadUrlAsync(awContents, pageUrl);
loginRequestHelper.waitForCallback(callCount);
Assert.assertEquals(expectedRealm, loginRequestHelper.getRealm());
Assert.assertEquals(expectedAccount, loginRequestHelper.getAccount());
Assert.assertEquals(expectedArgs, loginRequestHelper.getArgs());
} finally {
webServer.shutdown();
}
}
@Test
@Feature({"AndroidWebView"})
@SmallTest
public void testAutoLoginOnGoogleCom() throws Throwable {
autoLoginTestHelper(
"testAutoLoginOnGoogleCom", /* testName */
"realm=com.google&account=foo%40bar.com&args=random_string", /* xAutoLoginHeader */
"com.google", /* expectedRealm */
"foo@bar.com", /* expectedAccount */
"random_string" /* expectedArgs */);
}
@Test
@Feature({"AndroidWebView"})
@SmallTest
public void testAutoLoginWithNullAccount() throws Throwable {
autoLoginTestHelper(
"testAutoLoginOnGoogleCom", /* testName */
"realm=com.google&args=not.very.inventive", /* xAutoLoginHeader */
"com.google", /* expectedRealm */
null, /* expectedAccount */
"not.very.inventive" /* expectedArgs */);
}
@Test
@Feature({"AndroidWebView"})
@SmallTest
public void testAutoLoginOnNonGoogle() throws Throwable {
autoLoginTestHelper(
"testAutoLoginOnGoogleCom", /* testName */
"realm=com.bar&account=foo%40bar.com&args=args", /* xAutoLoginHeader */
"com.bar", /* expectedRealm */
"foo@bar.com", /* expectedAccount */
"args" /* expectedArgs */);
}
}
| {
"content_hash": "60f9e042705f594772ae8440bf566fd2",
"timestamp": "",
"source": "github",
"line_count": 99,
"max_line_length": 99,
"avg_line_length": 38.515151515151516,
"alnum_prop": 0.6677157094151587,
"repo_name": "ric2b/Vivaldi-browser",
"id": "f10350a4e968417b110c4882895fe0d5834eb9d8",
"size": "3813",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "chromium/android_webview/javatests/src/org/chromium/android_webview/test/AwContentsClientAutoLoginTest.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wikidot="http://www.wikidot.com/rss-namespace">
<channel>
<title>Comments for page "Black Market"</title>
<link>http://bvs.wikidot.com/forum/t-114433/black-market</link>
<description>Posts in the discussion thread "Black Market"</description>
<copyright></copyright>
<lastBuildDate>Sun, 10 Jul 2022 03:57:55 +0000</lastBuildDate>
<item>
<guid>http://bvs.wikidot.com/forum/t-114433#post-702219</guid>
<title>(no title)</title>
<link>http://bvs.wikidot.com/forum/t-114433/black-market#post-702219</link>
<description></description>
<pubDate>Wed, 17 Feb 2010 16:33:47 +0000</pubDate>
<wikidot:authorName>Agent Inari</wikidot:authorName> <wikidot:authorUserId>392886</wikidot:authorUserId> <content:encoded>
<![CDATA[
<p>This upgrade won't help if your Village Contribution is over 250,000 Ryo for the day. Is this before or after Upkeep rate is applied?</p>
]]>
</content:encoded> </item>
</channel>
</rss> | {
"content_hash": "f4adccb27b2c50cf20684ae7602c5eb7",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 148,
"avg_line_length": 49.130434782608695,
"alnum_prop": 0.6884955752212389,
"repo_name": "tn5421/tn5421.github.io",
"id": "fb138806a56b2e345dab0645e2252915bc3735d8",
"size": "1130",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "bvs.wikidot.com/feed/forum/t-114433.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "400301089"
}
],
"symlink_target": ""
} |
package net.violet.platform.message.application.factories;
import java.util.HashMap;
import java.util.Map;
import net.violet.platform.applications.WeatherHandler;
import net.violet.platform.daemons.schedulers.AbstractScheduler.MessageProcessUnit;
import net.violet.platform.datamodel.Files;
import net.violet.platform.datamodel.MockTestBase;
import net.violet.platform.datamodel.SchedulingType;
import net.violet.platform.datamodel.Source;
import net.violet.platform.datamodel.Subscription;
import net.violet.platform.datamodel.factories.Factories;
import net.violet.platform.datamodel.mock.SourceMock;
import net.violet.platform.datamodel.mock.SubscriptionMock;
import net.violet.platform.dataobjects.SubscriptionData;
import net.violet.platform.dataobjects.SubscriptionSchedulingData;
import net.violet.platform.dataobjects.SubscriptionSchedulingSettingsData;
import net.violet.platform.dataobjects.MessageData.Palette;
import net.violet.platform.message.MessageDraft;
import net.violet.platform.message.MessageSignature;
import net.violet.platform.message.application.factories.AbstractMessageFactory.Message2Send;
import net.violet.platform.schedulers.AmbiantHandler;
import net.violet.platform.util.CCalendar;
import net.violet.platform.util.Constantes;
import net.violet.platform.xmpp.JabberMessageFactory;
import org.apache.log4j.Logger;
import org.junit.Assert;
import org.junit.Test;
public class WeatherMessageFactoryTest extends MockTestBase {
private static final Logger LOGGER = Logger.getLogger(WeatherMessageFactoryTest.class);
@Test
public void getMessageWithoutContentTest() {
final Subscription theSubscription = new SubscriptionMock(1, Factories.APPLICATION.findByName("net.violet.weather"), getKowalskyObject());
final CCalendar theDeliveryDate = new CCalendar(false);
theDeliveryDate.addMillis(3600000);
final WeatherMessageFactory factory = (WeatherMessageFactory) AbstractMessageFactory.getFactoryByApplication(theSubscription.getApplication());
try {
final SubscriptionData theSubscriptionData = SubscriptionData.getData(theSubscription);
final SubscriptionSchedulingData theScheduling = SubscriptionSchedulingData.create(theSubscriptionData, SchedulingType.SCHEDULING_TYPE.Ambiant);
final Message2Send message = factory.getMessage(new MessageProcessUnit(theScheduling, theDeliveryDate, null) {
@Override
public void runWhenSuccessful() {
}
}).get(0);
Assert.assertEquals(Constantes.QUEUE_TTL_SERVICE, message.getTTL());
Assert.assertEquals(WeatherMessageFactory.TITLE, message.getTitle());
Assert.assertEquals(Palette.RANDOM, message.getColorPal());
Assert.assertEquals(theSubscriptionData, message.getSubscription());
Assert.assertEquals(MessageSignature.WEATHER_SIGNATURE, message.getSignature());
Assert.assertEquals(theSubscription.getObject(), message.getRecipient());
Assert.assertEquals(JabberMessageFactory.IDLE_MODE, message.getMode());
Assert.assertNull(message.getBody());
} catch (final Exception e) {
WeatherMessageFactoryTest.LOGGER.fatal(e, e);
Assert.fail(e.getMessage());
}
}
@Test
public void getMessageWithTodayAndCelsiusTest() {
final Subscription theSubscription = new SubscriptionMock(1, Factories.APPLICATION.findByName("net.violet.weather"), getKowalskyObject());
final Source source = new SourceMock(8205, "Nmeteo.FRANCE.Orléans.weather", 3);
new SourceMock(8206, "Nmeteo.FRANCE.Orléans.temp", 21);
final Map<String, Object> settings = new HashMap<String, Object>();
settings.put(WeatherHandler.LANGUAGE, "fr-FR");
settings.put(WeatherHandler.UNIT, "1");
settings.put(WeatherHandler.SOURCE, source.getSource_path());
theSubscription.setSettings(settings);
final CCalendar theDeliveryDate = new CCalendar(false);
theDeliveryDate.setTimeMYSQL("08:00:00");
final WeatherMessageFactory factory = (WeatherMessageFactory) AbstractMessageFactory.getFactoryByApplication(theSubscription.getApplication());
try {
final SubscriptionData theSubscriptionData = SubscriptionData.getData(theSubscription);
final SubscriptionSchedulingData theScheduling = SubscriptionSchedulingData.create(theSubscriptionData, SchedulingType.SCHEDULING_TYPE.Ambiant);
final Message2Send message = factory.getMessage(new MessageProcessUnit(theScheduling, theDeliveryDate, null) {
@Override
public void runWhenSuccessful() {
}
}).get(0);
Assert.assertEquals(Constantes.QUEUE_TTL_SERVICE, message.getTTL());
Assert.assertEquals(WeatherMessageFactory.TITLE, message.getTitle());
Assert.assertEquals(Palette.RANDOM, message.getColorPal());
Assert.assertEquals(theSubscriptionData, message.getSubscription());
Assert.assertEquals(MessageSignature.WEATHER_SIGNATURE, message.getSignature());
Assert.assertEquals(theSubscription.getObject(), message.getRecipient());
Assert.assertEquals(JabberMessageFactory.IDLE_MODE, message.getMode());
Assert.assertFalse(message.isStream());
final Files[] theFiles = message.getBody();
Assert.assertEquals(4, theFiles.length);
Assert.assertEquals("broadcast/broad/config/weather/fr/today.mp3", theFiles[0].getPath());
checkCelsius(theFiles);
} catch (final Exception e) {
WeatherMessageFactoryTest.LOGGER.fatal(e, e);
Assert.fail(e.toString());
}
}
private void checkCelsius(Files[] inFiles) {
checkSkyAndTemp(inFiles);
Assert.assertEquals("broadcast/broad/config/weather/fr/degree.mp3", inFiles[3].getPath());
}
private void checkFahrenheit(Files[] inFiles) {
checkSkyAndTemp(inFiles);
Assert.assertEquals("broadcast/broad/config/weather/fr/farenheit.mp3", inFiles[3].getPath());
}
private void checkSkyAndTemp(Files[] inFiles) {
Assert.assertEquals("broadcast/broad/config/weather/fr/sky/3.mp3", inFiles[1].getPath());
Assert.assertEquals("broadcast/broad/config/weather/fr/temp/21.mp3", inFiles[2].getPath());
}
@Test
public void getMessageWithTomorrowAndFahrenheitTest() {
final Subscription theSubscription = new SubscriptionMock(1, Factories.APPLICATION.findByName("net.violet.weather"), getKowalskyObject());
final Source source = new SourceMock(8205, "Nmeteo.FRANCE.Orléans.weather", 3);
new SourceMock(8206, "Nmeteo.FRANCE.Orléans.temp", -6);
final Map<String, Object> settings = new HashMap<String, Object>();
settings.put(WeatherHandler.LANGUAGE, "fr-FR");
settings.put(WeatherHandler.UNIT, "2");
settings.put(WeatherHandler.SOURCE, source.getSource_path());
theSubscription.setSettings(settings);
final CCalendar theDeliveryDate = new CCalendar(false);
theDeliveryDate.setTimeMYSQL("16:00:00");
final WeatherMessageFactory factory = (WeatherMessageFactory) AbstractMessageFactory.getFactoryByApplication(theSubscription.getApplication());
try {
final SubscriptionData theSubscriptionData = SubscriptionData.getData(theSubscription);
final SubscriptionSchedulingData theScheduling = SubscriptionSchedulingData.create(theSubscriptionData, SchedulingType.SCHEDULING_TYPE.Ambiant);
final Message2Send message = factory.getMessage(new MessageProcessUnit(theScheduling, theDeliveryDate, null) {
@Override
public void runWhenSuccessful() {
}
}).get(0);
Assert.assertEquals(Constantes.QUEUE_TTL_SERVICE, message.getTTL());
Assert.assertEquals(WeatherMessageFactory.TITLE, message.getTitle());
Assert.assertEquals(Palette.RANDOM, message.getColorPal());
Assert.assertEquals(theSubscriptionData, message.getSubscription());
Assert.assertEquals(MessageSignature.WEATHER_SIGNATURE, message.getSignature());
Assert.assertEquals(theSubscription.getObject(), message.getRecipient());
Assert.assertEquals(JabberMessageFactory.IDLE_MODE, message.getMode());
final Files[] theFiles = message.getBody();
Assert.assertEquals(4, theFiles.length);
Assert.assertEquals("broadcast/broad/config/weather/fr/tomorrow.mp3", theFiles[0].getPath());
checkFahrenheit(theFiles);
for (final Files aFile : message.getBody()) {
WeatherMessageFactoryTest.LOGGER.info(aFile.getPath());
}
} catch (final Exception e) {
WeatherMessageFactoryTest.LOGGER.fatal(e, e);
Assert.fail(e.toString());
}
}
@Test
public void getMessageWithoutDeliveryTest() {
final Subscription theSubscription = new SubscriptionMock(1, Factories.APPLICATION.findByName("net.violet.weather"), getKowalskyObject());
final Source source = new SourceMock(8205, "Nmeteo.FRANCE.Orléans.weather", 3);
new SourceMock(8206, "Nmeteo.FRANCE.Orléans.temp", 21);
final Map<String, Object> settings = new HashMap<String, Object>();
settings.put(WeatherHandler.LANGUAGE, "fr-FR");
settings.put(WeatherHandler.UNIT, "1");
settings.put(WeatherHandler.SOURCE, source.getSource_path());
theSubscription.setSettings(settings);
final CCalendar theDeliveryDate = null;
final WeatherMessageFactory factory = (WeatherMessageFactory) AbstractMessageFactory.getFactoryByApplication(theSubscription.getApplication());
try {
final SubscriptionData theSubscriptionData = SubscriptionData.getData(theSubscription);
final SubscriptionSchedulingData theScheduling = SubscriptionSchedulingData.create(theSubscriptionData, SchedulingType.SCHEDULING_TYPE.Ambiant);
final Message2Send message = factory.getMessage(new MessageProcessUnit(theScheduling, theDeliveryDate, null) {
@Override
public void runWhenSuccessful() {
}
}).get(0);
Assert.assertEquals(Constantes.QUEUE_TTL_SERVICE, message.getTTL());
Assert.assertEquals(WeatherMessageFactory.TITLE, message.getTitle());
Assert.assertEquals(Palette.RANDOM, message.getColorPal());
Assert.assertEquals(theSubscriptionData, message.getSubscription());
Assert.assertEquals(MessageSignature.WEATHER_SIGNATURE, message.getSignature());
Assert.assertEquals(theSubscription.getObject(), message.getRecipient());
Assert.assertEquals(JabberMessageFactory.IDLE_MODE, message.getMode());
final Files[] theFiles = message.getBody();
Assert.assertEquals(4, theFiles.length);
checkCelsius(theFiles);
} catch (final Exception e) {
WeatherMessageFactoryTest.LOGGER.fatal(e, e);
Assert.fail(e.toString());
}
}
@Test
public void getMessageWithHighestTempTest() {
final Subscription theSubscription = new SubscriptionMock(1, Factories.APPLICATION.findByName("net.violet.weather"), getKowalskyObject());
final Source source = new SourceMock(8205, "Nmeteo.FRANCE.Orléans.weather", 3);
new SourceMock(8206, "Nmeteo.FRANCE.Orléans.temp", WeatherMessageFactory.TEMP_MAX + 10);
final Map<String, Object> settings = new HashMap<String, Object>();
settings.put(WeatherHandler.LANGUAGE, "fr-FR");
settings.put(WeatherHandler.UNIT, "1");
settings.put(WeatherHandler.SOURCE, source.getSource_path());
theSubscription.setSettings(settings);
final CCalendar theDeliveryDate = new CCalendar(false);
theDeliveryDate.setTimeMYSQL("16:00:00");
final WeatherMessageFactory factory = (WeatherMessageFactory) AbstractMessageFactory.getFactoryByApplication(theSubscription.getApplication());
try {
final SubscriptionData theSubscriptionData = SubscriptionData.getData(theSubscription);
final SubscriptionSchedulingData theScheduling = SubscriptionSchedulingData.create(theSubscriptionData, SchedulingType.SCHEDULING_TYPE.Ambiant);
final Message2Send message = factory.getMessage(new MessageProcessUnit(theScheduling, theDeliveryDate, null) {
@Override
public void runWhenSuccessful() {
}
}).get(0);
Assert.assertEquals(Constantes.QUEUE_TTL_SERVICE, message.getTTL());
Assert.assertEquals(WeatherMessageFactory.TITLE, message.getTitle());
Assert.assertEquals(Palette.RANDOM, message.getColorPal());
Assert.assertEquals(theSubscriptionData, message.getSubscription());
Assert.assertEquals(MessageSignature.WEATHER_SIGNATURE, message.getSignature());
Assert.assertEquals(theSubscription.getObject(), message.getRecipient());
Assert.assertEquals(JabberMessageFactory.IDLE_MODE, message.getMode());
final Files[] theFiles = message.getBody();
Assert.assertEquals(4, theFiles.length);
Assert.assertEquals("broadcast/broad/config/weather/fr/tomorrow.mp3", theFiles[0].getPath());
Assert.assertEquals("broadcast/broad/config/weather/fr/temp/" + WeatherMessageFactory.TEMP_MAX + ".mp3", theFiles[2].getPath());
for (final Files aFile : message.getBody()) {
WeatherMessageFactoryTest.LOGGER.info(aFile.getPath());
}
} catch (final Exception e) {
WeatherMessageFactoryTest.LOGGER.fatal(e, e);
Assert.fail(e.toString());
}
}
@Test
public void getMessageWithLowestTempTest() {
final Subscription theSubscription = new SubscriptionMock(1, Factories.APPLICATION.findByName("net.violet.weather"), getKowalskyObject());
final Source source = new SourceMock(8205, "Nmeteo.FRANCE.Orléans.weather", 3);
new SourceMock(8206, "Nmeteo.FRANCE.Orléans.temp", WeatherMessageFactory.TEMP_MIN - 10);
final Map<String, Object> settings = new HashMap<String, Object>();
settings.put(WeatherHandler.LANGUAGE, "fr-FR");
settings.put(WeatherHandler.UNIT, "1");
settings.put(WeatherHandler.SOURCE, source.getSource_path());
theSubscription.setSettings(settings);
final CCalendar theDeliveryDate = new CCalendar(false);
theDeliveryDate.setTimeMYSQL("16:00:00");
final WeatherMessageFactory factory = (WeatherMessageFactory) AbstractMessageFactory.getFactoryByApplication(theSubscription.getApplication());
try {
final SubscriptionData theSubscriptionData = SubscriptionData.getData(theSubscription);
final SubscriptionSchedulingData theScheduling = SubscriptionSchedulingData.create(theSubscriptionData, SchedulingType.SCHEDULING_TYPE.Ambiant);
final Message2Send message = factory.getMessage(new MessageProcessUnit(theScheduling, theDeliveryDate, null) {
@Override
public void runWhenSuccessful() {
}
}).get(0);
Assert.assertEquals(Constantes.QUEUE_TTL_SERVICE, message.getTTL());
Assert.assertEquals(WeatherMessageFactory.TITLE, message.getTitle());
Assert.assertEquals(Palette.RANDOM, message.getColorPal());
Assert.assertEquals(theSubscriptionData, message.getSubscription());
Assert.assertEquals(MessageSignature.WEATHER_SIGNATURE, message.getSignature());
Assert.assertEquals(theSubscription.getObject(), message.getRecipient());
Assert.assertEquals(JabberMessageFactory.IDLE_MODE, message.getMode());
final Files[] theFiles = message.getBody();
Assert.assertEquals(4, theFiles.length);
Assert.assertEquals("broadcast/broad/config/weather/fr/tomorrow.mp3", theFiles[0].getPath());
Assert.assertEquals("broadcast/broad/config/weather/fr/temp/" + WeatherMessageFactory.TEMP_MIN + ".mp3", theFiles[2].getPath());
for (final Files aFile : message.getBody()) {
WeatherMessageFactoryTest.LOGGER.info(aFile.getPath());
}
} catch (final Exception e) {
WeatherMessageFactoryTest.LOGGER.fatal(e, e);
Assert.fail(e.toString());
}
}
@Test
public void getSourceMessageNoLastTimeTest() {
final Source source = new SourceMock(8205, "Nmeteo.FRANCE.Orléans.weather", 3, System.currentTimeMillis());
final Subscription theSubscription = new SubscriptionMock(1, Factories.APPLICATION.findByName("net.violet.weather"), getKowalskyObject());
final Map<String, Object> settings = new HashMap<String, Object>();
settings.put(WeatherHandler.LANGUAGE, "fr-FR");
settings.put(WeatherHandler.SOURCE, source.getSource_path());
theSubscription.setSettings(settings);
final SubscriptionData theSubscriptionData = SubscriptionData.getData(theSubscription);
final SubscriptionSchedulingData theScheduling = SubscriptionSchedulingData.create(theSubscriptionData, SchedulingType.SCHEDULING_TYPE.Ambiant);
final WeatherMessageFactory factory = (WeatherMessageFactory) AbstractMessageFactory.getFactoryByApplication(theSubscription.getApplication());
final long theLastTime = System.currentTimeMillis();
final MessageDraft theMessage = factory.getSourceMessage(theScheduling, theLastTime);
Assert.assertNotNull(theMessage);
Assert.assertTrue(theMessage.isSourceModeUpdate());
Assert.assertEquals(new Integer((int) source.getSource_val()), theMessage.getSources().get(Integer.toString(factory.getSource().getId())));
Assert.assertEquals(Constantes.QUEUE_TTL_SOURCES, theMessage.getTTLInSecond());
final SubscriptionSchedulingSettingsData theLastTimeSetting = SubscriptionSchedulingSettingsData.findBySubscriptionSchedulingAndKey(theScheduling, AmbiantHandler.LAST_TIME);
Assert.assertNotNull(theLastTimeSetting);
Assert.assertEquals(theLastTime, Long.parseLong(theLastTimeSetting.getValue()));
source.delete();
}
@Test
public void getSourceMessageWithLastTimeNUTest() {
final long sourceUpdateTime = System.currentTimeMillis() / 1000;
final Source source = new SourceMock(3, "Nmeteo.FRANCE.Orléans.weather", 3, sourceUpdateTime);
final long theLastTime = sourceUpdateTime * 1000;
final Subscription theSubscription = new SubscriptionMock(1, Factories.APPLICATION.findByName("net.violet.weather"), getKowalskyObject());
final Map<String, Object> settings = new HashMap<String, Object>();
settings.put(WeatherHandler.LANGUAGE, "fr-FR");
settings.put(WeatherHandler.SOURCE, source.getSource_path());
theSubscription.setSettings(settings);
final SubscriptionData theSubscriptionData = SubscriptionData.getData(theSubscription);
final SubscriptionSchedulingData theScheduling = SubscriptionSchedulingData.create(theSubscriptionData, SchedulingType.SCHEDULING_TYPE.Ambiant);
theScheduling.createSetting(AmbiantHandler.LAST_TIME, Long.toString(theLastTime));
final WeatherMessageFactory factory = (WeatherMessageFactory) AbstractMessageFactory.getFactoryByApplication(theSubscription.getApplication());
final MessageDraft theMessage = factory.getSourceMessage(theScheduling, theLastTime);
Assert.assertNull(theMessage);
source.delete();
}
@Test
public void getSourceMessageWithLastTimeUTest() {
final long sourceUpdateTime = System.currentTimeMillis() / 1000;
final Source source = new SourceMock(8205, "Nmeteo.FRANCE.Orléans.weather", 3, sourceUpdateTime + 60);
final long theLastTime = sourceUpdateTime * 1000;
final Subscription theSubscription = new SubscriptionMock(1, Factories.APPLICATION.findByName("net.violet.weather"), getKowalskyObject());
final Map<String, Object> settings = new HashMap<String, Object>();
settings.put(WeatherHandler.LANGUAGE, "fr-FR");
settings.put(WeatherHandler.SOURCE, source.getSource_path());
theSubscription.setSettings(settings);
final SubscriptionData theSubscriptionData = SubscriptionData.getData(theSubscription);
final SubscriptionSchedulingData theScheduling = SubscriptionSchedulingData.create(theSubscriptionData, SchedulingType.SCHEDULING_TYPE.Ambiant);
theScheduling.createSetting(AmbiantHandler.LAST_TIME, Long.toString(theLastTime));
final WeatherMessageFactory factory = (WeatherMessageFactory) AbstractMessageFactory.getFactoryByApplication(theSubscription.getApplication());
final MessageDraft theMessage = factory.getSourceMessage(theScheduling, theLastTime);
Assert.assertNotNull(theMessage);
Assert.assertTrue(theMessage.isSourceModeUpdate());
Assert.assertEquals(new Integer((int) source.getSource_val()), theMessage.getSources().get(Integer.toString(factory.getSource().getId())));
Assert.assertEquals(Constantes.QUEUE_TTL_SOURCES, theMessage.getTTLInSecond());
final SubscriptionSchedulingSettingsData theLastTimeSetting = SubscriptionSchedulingSettingsData.findBySubscriptionSchedulingAndKey(theScheduling, AmbiantHandler.LAST_TIME);
Assert.assertNotNull(theLastTimeSetting);
Assert.assertEquals(theLastTime, Long.parseLong(theLastTimeSetting.getValue()));
source.delete();
}
}
| {
"content_hash": "e5dff569bee4b03f1553a78b51801264",
"timestamp": "",
"source": "github",
"line_count": 419,
"max_line_length": 175,
"avg_line_length": 47.105011933174225,
"alnum_prop": 0.7906470081572681,
"repo_name": "sebastienhouzet/nabaztag-source-code",
"id": "a0d3ff2bd2b44a049e17378822aaa67070bfb9c6",
"size": "19750",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "server/OS/test/net/violet/platform/message/application/factories/WeatherMessageFactoryTest.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "20745"
},
{
"name": "Batchfile",
"bytes": "8750"
},
{
"name": "C",
"bytes": "4993666"
},
{
"name": "C++",
"bytes": "1334194"
},
{
"name": "CSS",
"bytes": "181849"
},
{
"name": "Dylan",
"bytes": "98"
},
{
"name": "HTML",
"bytes": "788676"
},
{
"name": "Inno Setup",
"bytes": "532"
},
{
"name": "Java",
"bytes": "13700728"
},
{
"name": "JavaScript",
"bytes": "710228"
},
{
"name": "Lex",
"bytes": "4485"
},
{
"name": "Makefile",
"bytes": "9861"
},
{
"name": "PHP",
"bytes": "44903"
},
{
"name": "Perl",
"bytes": "12017"
},
{
"name": "Ruby",
"bytes": "2935"
},
{
"name": "Shell",
"bytes": "40087"
},
{
"name": "SourcePawn",
"bytes": "21480"
},
{
"name": "TeX",
"bytes": "13161"
}
],
"symlink_target": ""
} |
# Makefile.in generated by automake 1.9.6 from Makefile.am.
# config/Makefile. Generated from Makefile.in by configure.
# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
# 2003, 2004, 2005 Free Software Foundation, Inc.
# This Makefile.in is free software; the Free Software Foundation
# gives unlimited permission to copy and/or distribute it,
# with or without modifications, as long as this notice is preserved.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
# PARTICULAR PURPOSE.
srcdir = .
top_srcdir = ..
pkgdatadir = $(datadir)/pnetlib
pkglibdir = $(libdir)/pnetlib
pkgincludedir = $(includedir)/pnetlib
top_builddir = ..
am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
INSTALL = /usr/bin/install -c
install_sh_DATA = $(install_sh) -c -m 644
install_sh_PROGRAM = $(install_sh) -c
install_sh_SCRIPT = $(install_sh) -c
INSTALL_HEADER = $(INSTALL_DATA)
transform = $(program_transform_name)
NORMAL_INSTALL = :
PRE_INSTALL = :
POST_INSTALL = :
NORMAL_UNINSTALL = :
PRE_UNINSTALL = :
POST_UNINSTALL = :
build_triplet = i686-pc-linux-gnu
host_triplet = i686-pc-linux-gnu
subdir = config
DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in
ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
am__aclocal_m4_deps = $(top_srcdir)/configure.in
am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
$(ACLOCAL_M4)
mkinstalldirs = $(SHELL) $(top_srcdir)/mkinstalldirs
CONFIG_CLEAN_FILES =
depcomp =
am__depfiles_maybe =
SOURCES =
DIST_SOURCES =
am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`;
am__vpath_adj = case $$p in \
$(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \
*) f=$$p;; \
esac;
am__strip_dir = `echo $$p | sed -e 's|^.*/||'`;
am__installdirs = "$(DESTDIR)$(pnetconfigdir)"
pnetconfigDATA_INSTALL = $(INSTALL_DATA)
DATA = $(pnetconfig_DATA)
DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
ACLOCAL = ${SHELL} /home/jeff/dev/dev_apps/sand/qca_designer/lib/pnetlib-0.8.0/missing --run aclocal-1.9
AMDEP_FALSE = #
AMDEP_TRUE =
AMTAR = ${SHELL} /home/jeff/dev/dev_apps/sand/qca_designer/lib/pnetlib-0.8.0/missing --run tar
AR = ar
AS = as
ASSEMBLY_LINKER = pnet
AUTOCONF = ${SHELL} /home/jeff/dev/dev_apps/sand/qca_designer/lib/pnetlib-0.8.0/missing --run autoconf
AUTOHEADER = ${SHELL} /home/jeff/dev/dev_apps/sand/qca_designer/lib/pnetlib-0.8.0/missing --run autoheader
AUTOMAKE = ${SHELL} /home/jeff/dev/dev_apps/sand/qca_designer/lib/pnetlib-0.8.0/missing --run automake-1.9
AWK = gawk
CC = gcc
CCDEPMODE = depmode=none
CFLAGS = -g -O2
CLRWRAP = /usr/local/bin/clrwrap
CPP = gcc -E
CPPFLAGS =
CSANT = /usr/local/bin/csant
CSANT_FLAGS = --compiler cscc -Dcscc="$(CSHARP_COMPILER)" -Dcscc.plugins.cs="$(CSHARP_PLUGIN)" --profile "$(top_srcdir)/profiles/$(PROFILE_NAME)" -Dresgen="$(CYG_RESGEN)" -Dilgac="$(CYG_ILGAC)" --assembly-cache "$(DESTDIR)$(CYG_CACHE)"
CSCC_FLAGS =
CSHARP_COMPILER = /usr/local/bin/cscc
CSHARP_COMPILER_CYGWIN = /usr/local/bin/cscc
CSHARP_PLUGIN =
CXX = g++
CXXCPP = g++ -E
CXXDEPMODE = depmode=none
CXXFLAGS = -g -O2
CYGPATH =
CYGPATH_W = echo
CYG_CACHE = ${exec_prefix}/lib/cscc/lib
CYG_ILGAC = /usr/local/bin/ilgac
CYG_RESGEN = /usr/local/bin/resgen
DEFS = -DPACKAGE_NAME=\"\" -DPACKAGE_TARNAME=\"\" -DPACKAGE_VERSION=\"\" -DPACKAGE_STRING=\"\" -DPACKAGE_BUGREPORT=\"\" -DPACKAGE=\"pnetlib\" -DVERSION=\"0.8.0\" -DSTDC_HEADERS=1 -DHAVE_SYS_TYPES_H=1 -DHAVE_SYS_STAT_H=1 -DHAVE_STDLIB_H=1 -DHAVE_STRING_H=1 -DHAVE_MEMORY_H=1 -DHAVE_STRINGS_H=1 -DHAVE_INTTYPES_H=1 -DHAVE_STDINT_H=1 -DHAVE_UNISTD_H=1 -DHAVE_DLFCN_H=1 -DX_DISPLAY_MISSING=1 -DSTDC_HEADERS=1 -DTIME_WITH_SYS_TIME=1 -DHAVE_TIME_H=1 -DHAVE_SYS_TIME_H=1 -DHAVE_SYS_TYPES_H=1 -DHAVE_SYS_SELECT_H=1 -DHAVE_UNISTD_H=1 -DHAVE_SYS_STAT_H=1 -DHAVE_SELECT=1
DEPDIR = .deps
DLLTOOL = dlltool
ECHO = echo
ECHO_C =
ECHO_N = -n
ECHO_T =
EGREP = /bin/grep -E
EXEEXT =
F77 =
FFLAGS =
FRAMEWORK_VERSION = 2.0.0.0
GREP = /bin/grep
HAS_EXTENDED_NUMERICS_FALSE = #
HAS_EXTENDED_NUMERICS_TRUE =
HAS_REFLECTION_FALSE = #
HAS_REFLECTION_TRUE =
ILFIND = /usr/local/bin/ilfind
ILGAC = /usr/local/bin/ilgac
ILRUN = /usr/local/bin/ilrun
INSTALL_AS_DEFAULT = true
INSTALL_DATA = ${INSTALL} -m 644
INSTALL_PROGRAM = ${INSTALL}
INSTALL_SCRIPT = ${INSTALL}
INSTALL_STRIP_PROGRAM = ${SHELL} $(install_sh) -c -s
LDFLAGS =
LIBOBJS =
LIBS =
LIBTOOL = $(SHELL) $(top_builddir)/libtool
LN_S = ln -s
LTLIBOBJS =
MAINT = #
MAINTAINER_MODE_FALSE =
MAINTAINER_MODE_TRUE = #
MAKEINFO = ${SHELL} /home/jeff/dev/dev_apps/sand/qca_designer/lib/pnetlib-0.8.0/missing --run makeinfo
OBJDUMP = /usr/bin/objdump
OBJEXT = o
PACKAGE = pnetlib
PACKAGE_BUGREPORT =
PACKAGE_NAME =
PACKAGE_STRING =
PACKAGE_TARNAME =
PACKAGE_VERSION =
PATH_SEPARATOR = :
PNET_PATH = /home/jeff/dev/dev_apps/sand/qca_designer/lib/pnetlib-0.8.0/../pnet
PNET_RESGEN_FALSE = #
PNET_RESGEN_TRUE =
PROFILE_NAME = full
RANLIB = ranlib
RESGEN = /usr/local/bin/resgen
RESGEN_FLAGS = -tR
RESGEN_LATIN1 = -l
SECONDARY_VERSION = 8.0.50727.42
SET_MAKE =
SHELL = /bin/bash
STRIP = strip
TREECC = /usr/local/bin/treecc
TREECC_VERSION = 0.3.4
VERSION = 0.8.0
X11_LIB =
XFT_CONFIG = no
XFT_INC =
XFT_LIB =
XMKMF =
X_CFLAGS =
X_EXTRA_LIBS =
X_LIBS =
X_PRE_LIBS =
X_char = sbyte
X_dev_t = ulong
X_gid_t = uint
X_ino64_t = ulong
X_ino_t = uint
X_int = int
X_long = int
X_longlong = long
X_mode_t = uint
X_nlink_t = uint
X_off64_t = long
X_off_t = int
X_pid_t = int
X_schar = sbyte
X_short = short
X_size_t = uint
X_ssize_t = int
X_time_t = int
X_uchar = byte
X_uid_t = uint
X_uint = uint
X_ulong = uint
X_ulonglong = ulong
X_ushort = ushort
ac_ct_CC = gcc
ac_ct_CXX = g++
ac_ct_F77 =
am__fastdepCC_FALSE =
am__fastdepCC_TRUE = #
am__fastdepCXX_FALSE =
am__fastdepCXX_TRUE = #
am__include = include
am__leading_dot = .
am__quote =
am__tar = ${AMTAR} chof - "$$tardir"
am__untar = ${AMTAR} xf -
bindir = ${exec_prefix}/bin
build = i686-pc-linux-gnu
build_alias =
build_cpu = i686
build_os = linux-gnu
build_vendor = pc
datadir = ${datarootdir}
datarootdir = ${prefix}/share
docdir = ${datarootdir}/doc/${PACKAGE}
dvidir = ${docdir}
exec_prefix = ${prefix}
host = i686-pc-linux-gnu
host_alias =
host_cpu = i686
host_os = linux-gnu
host_vendor = pc
htmldir = ${docdir}
includedir = ${prefix}/include
infodir = ${datarootdir}/info
install_sh = /home/jeff/dev/dev_apps/sand/qca_designer/lib/pnetlib-0.8.0/install-sh
libdir = ${exec_prefix}/lib
libexecdir = ${exec_prefix}/libexec
localedir = ${datarootdir}/locale
localstatedir = ${prefix}/var
mandir = ${datarootdir}/man
mkdir_p = mkdir -p --
oldincludedir = /usr/include
pdfdir = ${docdir}
prefix = /usr/local
program_transform_name = s,x,x,
psdir = ${docdir}
sbindir = ${exec_prefix}/sbin
sharedstatedir = ${prefix}/com
sysconfdir = ${prefix}/etc
target_alias =
pnetconfigdir = $(datadir)/cscc/config
pnetconfig_DATA = machine.default
all: all-am
.SUFFIXES:
$(srcdir)/Makefile.in: # $(srcdir)/Makefile.am $(am__configure_deps)
@for dep in $?; do \
case '$(am__configure_deps)' in \
*$$dep*) \
cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh \
&& exit 0; \
exit 1;; \
esac; \
done; \
echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu --ignore-deps config/Makefile'; \
cd $(top_srcdir) && \
$(AUTOMAKE) --gnu --ignore-deps config/Makefile
.PRECIOUS: Makefile
Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
@case '$?' in \
*config.status*) \
cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \
*) \
echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \
cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \
esac;
$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
$(top_srcdir)/configure: # $(am__configure_deps)
cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
$(ACLOCAL_M4): # $(am__aclocal_m4_deps)
cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
mostlyclean-libtool:
-rm -f *.lo
clean-libtool:
-rm -rf .libs _libs
distclean-libtool:
-rm -f libtool
uninstall-info-am:
install-pnetconfigDATA: $(pnetconfig_DATA)
@$(NORMAL_INSTALL)
test -z "$(pnetconfigdir)" || $(mkdir_p) "$(DESTDIR)$(pnetconfigdir)"
@list='$(pnetconfig_DATA)'; for p in $$list; do \
if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \
f=$(am__strip_dir) \
echo " $(pnetconfigDATA_INSTALL) '$$d$$p' '$(DESTDIR)$(pnetconfigdir)/$$f'"; \
$(pnetconfigDATA_INSTALL) "$$d$$p" "$(DESTDIR)$(pnetconfigdir)/$$f"; \
done
uninstall-pnetconfigDATA:
@$(NORMAL_UNINSTALL)
@list='$(pnetconfig_DATA)'; for p in $$list; do \
f=$(am__strip_dir) \
echo " rm -f '$(DESTDIR)$(pnetconfigdir)/$$f'"; \
rm -f "$(DESTDIR)$(pnetconfigdir)/$$f"; \
done
tags: TAGS
TAGS:
ctags: CTAGS
CTAGS:
distdir: $(DISTFILES)
@srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \
topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \
list='$(DISTFILES)'; for file in $$list; do \
case $$file in \
$(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \
$(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \
esac; \
if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \
if test "$$dir" != "$$file" && test "$$dir" != "."; then \
dir="/$$dir"; \
$(mkdir_p) "$(distdir)$$dir"; \
else \
dir=''; \
fi; \
if test -d $$d/$$file; then \
if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \
fi; \
cp -pR $$d/$$file $(distdir)$$dir || exit 1; \
else \
test -f $(distdir)/$$file \
|| cp -p $$d/$$file $(distdir)/$$file \
|| exit 1; \
fi; \
done
check-am: all-am
check: check-am
all-am: Makefile $(DATA)
installdirs:
for dir in "$(DESTDIR)$(pnetconfigdir)"; do \
test -z "$$dir" || $(mkdir_p) "$$dir"; \
done
install: install-am
install-exec: install-exec-am
install-data: install-data-am
uninstall: uninstall-am
install-am: all-am
@$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
installcheck: installcheck-am
install-strip:
$(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
`test -z '$(STRIP)' || \
echo "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'"` install
mostlyclean-generic:
clean-generic:
distclean-generic:
-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
maintainer-clean-generic:
@echo "This command is intended for maintainers to use"
@echo "it deletes files that may require special tools to rebuild."
clean: clean-am
clean-am: clean-generic clean-libtool mostlyclean-am
distclean: distclean-am
-rm -f Makefile
distclean-am: clean-am distclean-generic distclean-libtool
dvi: dvi-am
dvi-am:
html: html-am
info: info-am
info-am:
install-data-am: install-pnetconfigDATA
install-exec-am:
install-info: install-info-am
install-man:
installcheck-am:
maintainer-clean: maintainer-clean-am
-rm -f Makefile
maintainer-clean-am: distclean-am maintainer-clean-generic
mostlyclean: mostlyclean-am
mostlyclean-am: mostlyclean-generic mostlyclean-libtool
pdf: pdf-am
pdf-am:
ps: ps-am
ps-am:
uninstall-am: uninstall-info-am uninstall-pnetconfigDATA
.PHONY: all all-am check check-am clean clean-generic clean-libtool \
distclean distclean-generic distclean-libtool distdir dvi \
dvi-am html html-am info info-am install install-am \
install-data install-data-am install-exec install-exec-am \
install-info install-info-am install-man \
install-pnetconfigDATA install-strip installcheck \
installcheck-am installdirs maintainer-clean \
maintainer-clean-generic mostlyclean mostlyclean-generic \
mostlyclean-libtool pdf pdf-am ps ps-am uninstall uninstall-am \
uninstall-info-am uninstall-pnetconfigDATA
# Tell versions [3.59,3.63) of GNU make to not export all variables.
# Otherwise a system limit (for SysV at least) may be exceeded.
.NOEXPORT:
| {
"content_hash": "6cb673e701a19a0399541018bba7c697",
"timestamp": "",
"source": "github",
"line_count": 417,
"max_line_length": 560,
"avg_line_length": 29.40767386091127,
"alnum_prop": 0.6717768898311995,
"repo_name": "jjenki11/blaze-chem-rendering",
"id": "194c7b8af91e90a85b48f31f3608d72aac01aafe",
"size": "12263",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "qca_designer/lib/pnetlib-0.8.0/config/Makefile",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Shell",
"bytes": "2476"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "f5e84065df0c11f279a513846855e10d",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "3519d9c3c420d89892d8d0c277d8044cbf94dc2d",
"size": "200",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Artemisia/Artemisia vulgaris/Artemisia vulgaris articulatopilosa/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
package sockslib.server.io;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* The class <code>StreamPipe</code> represents a pipe the can transfer data source a input
* stream destination
* a output stream.
*
* @author Youchao Feng
* @version 1.0
* @date Apr 6, 2015 11:37:16 PM
*/
public class StreamPipe implements Runnable, Pipe {
/**
* Logger that subclasses also can use.
*/
protected static final Logger logger = LoggerFactory.getLogger(StreamPipe.class);
/**
* Default buffer size.
*/
private static final int BUFFER_SIZE = 1024 * 1024 * 5;
private Map<String, Object> attributes = new HashMap<>();
/**
* Listeners
*/
private List<PipeListener> pipeListeners;
/**
* Input stream.
*/
private InputStream source;
/**
* Output stream.
*/
private OutputStream destination;
/**
* Buffer size.
*/
private int bufferSize = BUFFER_SIZE;
/**
* Running thread.
*/
private Thread runningThread;
/**
* A flag.
*/
private boolean running = false;
/**
* Name of the pipe.
*/
private String name;
private boolean daemon = false;
/**
* Constructs a Pipe instance with a input stream and a output stream.
*
* @param source stream where it comes source.
* @param destination stream where it will be transferred destination.
*/
public StreamPipe(InputStream source, OutputStream destination) {
this(source, destination, null);
}
/**
* Constructs an instance of {@link StreamPipe}.
*
* @param source stream where it comes source.
* @param destination stream where it will be transferred destination.
* @param name Name of {@link StreamPipe}.
*/
public StreamPipe(InputStream source, OutputStream destination, @Nullable String name) {
this.source = checkNotNull(source, "Argument [source] may not be null");
this.destination = checkNotNull(destination, "Argument [destination] may not be null");
pipeListeners = new ArrayList<>();
this.name = name;
}
@Override
public boolean start() {
if (!running) { // If the pipe is not running, run it.
running = true;
runningThread = new Thread(this);
runningThread.setDaemon(daemon);
runningThread.start();
for (PipeListener listener : pipeListeners) {
listener.onStart(this);
}
return true;
}
return false;
}
@Override
public boolean stop() {
if (running) { // if the pipe is working, stop it.
running = false;
if (runningThread != null) {
runningThread.interrupt();
}
for (int i = 0; i < pipeListeners.size(); i++) {
PipeListener listener = pipeListeners.get(i);
listener.onStop(this);
}
return true;
}
return false;
}
@Override
public void run() {
byte[] buffer = new byte[bufferSize];
while (running) {
int size = doTransfer(buffer);
if (size == -1) {
stop();
}
}
}
/**
* Transfer a buffer.
*
* @param buffer Buffer that transfer once.
* @return number of byte that transferred.
*/
protected int doTransfer(byte[] buffer) {
int length = -1;
try {
length = source.read(buffer);
if (length > 0) { // transfer the buffer destination output stream.
destination.write(buffer, 0, length);
destination.flush();
for (int i = 0; i < pipeListeners.size(); i++) {
pipeListeners.get(i).onTransfer(this, buffer, length);
}
}
} catch (IOException e) {
for (int i = 0; i < pipeListeners.size(); i++) {
pipeListeners.get(i).onError(this, e);
}
stop();
}
return length;
}
@Override
public boolean close() {
stop();
try {
source.close();
destination.close();
return true;
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
return false;
}
@Override
public int getBufferSize() {
return bufferSize;
}
@Override
public void setBufferSize(int bufferSize) {
this.bufferSize = bufferSize;
}
@Override
public boolean isRunning() {
return running;
}
@Override
public void addPipeListener(PipeListener pipeListener) {
pipeListeners.add(pipeListener);
}
@Override
public void removePipeListener(PipeListener pipeListener) {
pipeListeners.remove(pipeListener);
}
/**
* Returns all {@link PipeListener}.
*
* @return All {@link PipeListener}.
*/
public List<PipeListener> getPipeListeners() {
return pipeListeners;
}
/**
* Sets {@link PipeListener}.
*
* @param pipeListeners a List of {@link PipeListener}.
*/
public void setPipeListeners(List<PipeListener> pipeListeners) {
this.pipeListeners = pipeListeners;
}
/**
* Returns name of {@link StreamPipe}.
*
* @return Name of {@link StreamPipe}.
*/
@Override
public String getName() {
return name;
}
/**
* Sets a name.
*
* @param name Name of {@link StreamPipe}.
*/
@Override
public void setName(String name) {
this.name = name;
}
@Override
public void setAttribute(String name, Object value) {
attributes.put(name, value);
}
@Override
public Object getAttribute(String name) {
return attributes.get(name);
}
@Override
public Map<String, Object> getAttributes() {
return attributes;
}
public Thread getRunningThread() {
return runningThread;
}
public boolean isDaemon() {
return daemon;
}
public void setDaemon(boolean daemon) {
this.daemon = daemon;
}
}
| {
"content_hash": "7722af25492b6fc3780e272c710b1f80",
"timestamp": "",
"source": "github",
"line_count": 280,
"max_line_length": 91,
"avg_line_length": 21.07857142857143,
"alnum_prop": 0.6326668925787868,
"repo_name": "fengyouchao/fucksocks",
"id": "08a011e59958c6a18e631f8909e2b3095e7a8e40",
"size": "6514",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/sockslib/server/io/StreamPipe.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "474485"
}
],
"symlink_target": ""
} |
#include "platform/CCGLView.h"
#include "base/CCTouch.h"
#include "base/CCDirector.h"
#include "base/CCEventDispatcher.h"
NS_CC_BEGIN
namespace {
static Touch* g_touches[EventTouch::MAX_TOUCHES] = { nullptr };
static unsigned int g_indexBitsUsed = 0;
// System touch pointer ID (It may not be ascending order number) <-> Ascending order number from 0
static std::map<intptr_t, int> g_touchIdReorderMap;
static int getUnUsedIndex()
{
int i;
int temp = g_indexBitsUsed;
for (i = 0; i < EventTouch::MAX_TOUCHES; i++) {
if (! (temp & 0x00000001)) {
g_indexBitsUsed |= (1 << i);
return i;
}
temp >>= 1;
}
// all bits are used
return -1;
}
static std::vector<Touch*> getAllTouchesVector()
{
std::vector<Touch*> ret;
int i;
int temp = g_indexBitsUsed;
for (i = 0; i < EventTouch::MAX_TOUCHES; i++) {
if ( temp & 0x00000001) {
ret.push_back(g_touches[i]);
}
temp >>= 1;
}
return ret;
}
static void removeUsedIndexBit(int index)
{
if (index < 0 || index >= EventTouch::MAX_TOUCHES)
{
return;
}
unsigned int temp = 1 << index;
temp = ~temp;
g_indexBitsUsed &= temp;
}
}
//default context attributions are setted as follows
GLContextAttrs GLView::_glContextAttrs = {5, 6, 5, 0, 16, 8};
void GLView::setGLContextAttrs(GLContextAttrs& glContextAttrs)
{
_glContextAttrs = glContextAttrs;
}
GLContextAttrs GLView::getGLContextAttrs()
{
return _glContextAttrs;
}
GLView::GLView()
: _scaleX(1.0f)
, _scaleY(1.0f)
, _resolutionPolicy(ResolutionPolicy::UNKNOWN)
{
}
GLView::~GLView()
{
}
void GLView::pollInputEvents()
{
pollEvents();
}
void GLView::pollEvents()
{
}
void GLView::updateDesignResolutionSize()
{
if (_screenSize.width > 0 && _screenSize.height > 0
&& _designResolutionSize.width > 0 && _designResolutionSize.height > 0)
{
_scaleX = (float)_screenSize.width / _designResolutionSize.width;
_scaleY = (float)_screenSize.height / _designResolutionSize.height;
if (_resolutionPolicy == ResolutionPolicy::NO_BORDER)
{
_scaleX = _scaleY = MAX(_scaleX, _scaleY);
}
else if (_resolutionPolicy == ResolutionPolicy::SHOW_ALL)
{
_scaleX = _scaleY = MIN(_scaleX, _scaleY);
}
else if ( _resolutionPolicy == ResolutionPolicy::FIXED_HEIGHT) {
_scaleX = _scaleY;
_designResolutionSize.width = ceilf(_screenSize.width/_scaleX);
}
else if ( _resolutionPolicy == ResolutionPolicy::FIXED_WIDTH) {
_scaleY = _scaleX;
_designResolutionSize.height = ceilf(_screenSize.height/_scaleY);
}
// calculate the rect of viewport
float viewPortW = _designResolutionSize.width * _scaleX;
float viewPortH = _designResolutionSize.height * _scaleY;
_viewPortRect.setRect((_screenSize.width - viewPortW) / 2, (_screenSize.height - viewPortH) / 2, viewPortW, viewPortH);
// reset director's member variables to fit visible rect
auto director = Director::getInstance();
director->_winSizeInPoints = getDesignResolutionSize();
director->createStatsLabel();
director->setGLDefaultValues();
}
}
void GLView::setDesignResolutionSize(float width, float height, ResolutionPolicy resolutionPolicy)
{
// CCASSERT(resolutionPolicy != ResolutionPolicy::UNKNOWN, "should set resolutionPolicy");
if (width == 0.0f || height == 0.0f)
{
return;
}
_designResolutionSize.setSize(width, height);
_resolutionPolicy = resolutionPolicy;
updateDesignResolutionSize();
}
const Size& GLView::getDesignResolutionSize() const
{
return _designResolutionSize;
}
const Size& GLView::getFrameSize() const
{
return _screenSize;
}
void GLView::setFrameSize(float width, float height)
{
_designResolutionSize = _screenSize = Size(width, height);
}
Rect GLView::getVisibleRect() const
{
Rect ret;
ret.size = getVisibleSize();
ret.origin = getVisibleOrigin();
return ret;
}
Size GLView::getVisibleSize() const
{
if (_resolutionPolicy == ResolutionPolicy::NO_BORDER)
{
return Size(_screenSize.width/_scaleX, _screenSize.height/_scaleY);
}
else
{
return _designResolutionSize;
}
}
Vec2 GLView::getVisibleOrigin() const
{
if (_resolutionPolicy == ResolutionPolicy::NO_BORDER)
{
return Vec2((_designResolutionSize.width - _screenSize.width/_scaleX)/2,
(_designResolutionSize.height - _screenSize.height/_scaleY)/2);
}
else
{
return Vec2::ZERO;
}
}
void GLView::setViewPortInPoints(float x , float y , float w , float h)
{
glViewport((GLint)(x * _scaleX + _viewPortRect.origin.x),
(GLint)(y * _scaleY + _viewPortRect.origin.y),
(GLsizei)(w * _scaleX),
(GLsizei)(h * _scaleY));
}
void GLView::setScissorInPoints(float x , float y , float w , float h)
{
glScissor((GLint)(x * _scaleX + _viewPortRect.origin.x),
(GLint)(y * _scaleY + _viewPortRect.origin.y),
(GLsizei)(w * _scaleX),
(GLsizei)(h * _scaleY));
}
bool GLView::isScissorEnabled()
{
return (GL_FALSE == glIsEnabled(GL_SCISSOR_TEST)) ? false : true;
}
Rect GLView::getScissorRect() const
{
GLfloat params[4];
glGetFloatv(GL_SCISSOR_BOX, params);
float x = (params[0] - _viewPortRect.origin.x) / _scaleX;
float y = (params[1] - _viewPortRect.origin.y) / _scaleY;
float w = params[2] / _scaleX;
float h = params[3] / _scaleY;
return Rect(x, y, w, h);
}
void GLView::setViewName(const std::string& viewname )
{
_viewName = viewname;
}
const std::string& GLView::getViewName() const
{
return _viewName;
}
void GLView::handleTouchesBegin(int num, intptr_t ids[], float xs[], float ys[])
{
intptr_t id = 0;
float x = 0.0f;
float y = 0.0f;
int unusedIndex = 0;
EventTouch touchEvent;
for (int i = 0; i < num; ++i)
{
id = ids[i];
x = xs[i];
y = ys[i];
auto iter = g_touchIdReorderMap.find(id);
// it is a new touch
if (iter == g_touchIdReorderMap.end())
{
unusedIndex = getUnUsedIndex();
// The touches is more than MAX_TOUCHES ?
if (unusedIndex == -1) {
CCLOG("The touches is more than MAX_TOUCHES, unusedIndex = %d", unusedIndex);
continue;
}
Touch* touch = g_touches[unusedIndex] = new (std::nothrow) Touch();
touch->setTouchInfo(unusedIndex, (x - _viewPortRect.origin.x) / _scaleX,
(y - _viewPortRect.origin.y) / _scaleY);
CCLOGINFO("x = %f y = %f", touch->getLocationInView().x, touch->getLocationInView().y);
g_touchIdReorderMap.insert(std::make_pair(id, unusedIndex));
touchEvent._touches.push_back(touch);
}
}
if (touchEvent._touches.size() == 0)
{
CCLOG("touchesBegan: size = 0");
return;
}
touchEvent._eventCode = EventTouch::EventCode::BEGAN;
auto dispatcher = Director::getInstance()->getEventDispatcher();
dispatcher->dispatchEvent(&touchEvent);
}
void GLView::handleTouchesMove(int num, intptr_t ids[], float xs[], float ys[])
{
intptr_t id = 0;
float x = 0.0f;
float y = 0.0f;
EventTouch touchEvent;
for (int i = 0; i < num; ++i)
{
id = ids[i];
x = xs[i];
y = ys[i];
auto iter = g_touchIdReorderMap.find(id);
if (iter == g_touchIdReorderMap.end())
{
CCLOG("if the index doesn't exist, it is an error");
continue;
}
CCLOGINFO("Moving touches with id: %d, x=%f, y=%f", id, x, y);
Touch* touch = g_touches[iter->second];
if (touch)
{
touch->setTouchInfo(iter->second, (x - _viewPortRect.origin.x) / _scaleX,
(y - _viewPortRect.origin.y) / _scaleY);
touchEvent._touches.push_back(touch);
}
else
{
// It is error, should return.
CCLOG("Moving touches with id: %ld error", (long int)id);
return;
}
}
if (touchEvent._touches.size() == 0)
{
CCLOG("touchesMoved: size = 0");
return;
}
touchEvent._eventCode = EventTouch::EventCode::MOVED;
auto dispatcher = Director::getInstance()->getEventDispatcher();
dispatcher->dispatchEvent(&touchEvent);
}
void GLView::handleTouchesOfEndOrCancel(EventTouch::EventCode eventCode, int num, intptr_t ids[], float xs[], float ys[])
{
intptr_t id = 0;
float x = 0.0f;
float y = 0.0f;
EventTouch touchEvent;
for (int i = 0; i < num; ++i)
{
id = ids[i];
x = xs[i];
y = ys[i];
auto iter = g_touchIdReorderMap.find(id);
if (iter == g_touchIdReorderMap.end())
{
CCLOG("if the index doesn't exist, it is an error");
continue;
}
/* Add to the set to send to the director */
Touch* touch = g_touches[iter->second];
if (touch)
{
CCLOGINFO("Ending touches with id: %d, x=%f, y=%f", id, x, y);
touch->setTouchInfo(iter->second, (x - _viewPortRect.origin.x) / _scaleX,
(y - _viewPortRect.origin.y) / _scaleY);
touchEvent._touches.push_back(touch);
g_touches[iter->second] = nullptr;
removeUsedIndexBit(iter->second);
g_touchIdReorderMap.erase(id);
}
else
{
CCLOG("Ending touches with id: %ld error", static_cast<long>(id));
return;
}
}
if (touchEvent._touches.size() == 0)
{
CCLOG("touchesEnded or touchesCancel: size = 0");
return;
}
touchEvent._eventCode = eventCode;
auto dispatcher = Director::getInstance()->getEventDispatcher();
dispatcher->dispatchEvent(&touchEvent);
for (auto& touch : touchEvent._touches)
{
// release the touch object.
touch->release();
}
}
void GLView::handleTouchesEnd(int num, intptr_t ids[], float xs[], float ys[])
{
handleTouchesOfEndOrCancel(EventTouch::EventCode::ENDED, num, ids, xs, ys);
}
void GLView::handleTouchesCancel(int num, intptr_t ids[], float xs[], float ys[])
{
handleTouchesOfEndOrCancel(EventTouch::EventCode::CANCELLED, num, ids, xs, ys);
}
const Rect& GLView::getViewPortRect() const
{
return _viewPortRect;
}
std::vector<Touch*> GLView::getAllTouches() const
{
return getAllTouchesVector();
}
float GLView::getScaleX() const
{
return _scaleX;
}
float GLView::getScaleY() const
{
return _scaleY;
}
NS_CC_END
| {
"content_hash": "3e1c681736691763fb5475dcb421ee97",
"timestamp": "",
"source": "github",
"line_count": 433,
"max_line_length": 127,
"avg_line_length": 25.803695150115473,
"alnum_prop": 0.575404994182404,
"repo_name": "tangyiyang/v3quick-classic",
"id": "f5c0f622f7ac202e9c5ed622066e196b9a16e8bf",
"size": "12466",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "cocos/platform/CCGLView.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "23441"
},
{
"name": "C",
"bytes": "10996977"
},
{
"name": "C#",
"bytes": "61008"
},
{
"name": "C++",
"bytes": "11719723"
},
{
"name": "CMake",
"bytes": "5928"
},
{
"name": "CSS",
"bytes": "8089"
},
{
"name": "GLSL",
"bytes": "86819"
},
{
"name": "Groff",
"bytes": "2339"
},
{
"name": "HTML",
"bytes": "252175"
},
{
"name": "Java",
"bytes": "279505"
},
{
"name": "Lua",
"bytes": "3382095"
},
{
"name": "Makefile",
"bytes": "72468"
},
{
"name": "Objective-C",
"bytes": "450461"
},
{
"name": "Objective-C++",
"bytes": "337926"
},
{
"name": "PHP",
"bytes": "96197"
},
{
"name": "Python",
"bytes": "850"
},
{
"name": "Shell",
"bytes": "19303"
}
],
"symlink_target": ""
} |
<?php
namespace MySimpleORM\Mapper;
class Database
{
/**
* Variables
*
* @var [string] $Host
* @var [string] $Database
* @var [string] $User
* @var [string] $Password
* @var [mysqli] $Instance
*/
protected $Host;
protected $MysqlPort;
protected $Database;
protected $User;
protected $Sql;
protected $Password;
protected $Instance;
/**
* Database::__construct()
* Constructor & destructor
*/
public function __construct()
{
$this->setup();
}
public function __destruct()
{}
/**
* Database::setup()
* This function is a kind of parametrized constructor. Sets up the database's host, user, etc.
* Very useful when playing with different databases, as well as for unit testing.
*
* @return void
*/
public function setup($host = false, $username = false, $password = false, $database = false, $port = false)
{
if(getenv("TRAVIS") == true) {
$this->Host = "127.0.0.1";
$this->User = "root";
$this->Password = "";
$this->Database = "travis";
$this->MysqlPort = "3306";
} else {
$this->Host = $host ?: getenv("DB_HOST");
$this->User = $username ?: getenv("DB_USERNAME");
$this->Password = $password ?: getenv("DB_PASSWORD");
$this->Database = $database ?: getenv("DB_DATABASE");
$this->MysqlPort = $port ?: getenv("DB_PORT");
}
}
/**
* Database::connect()
* Opens up the connection to the database based on the object's attributes¸
*
* @return void
*/
public function connect()
{
$con = mysqli_connect($this->Host, $this->User, $this->Password, $this->Database, $this->MysqlPort);
if (mysqli_connect_errno()) {
die($this->getError());
} else {
$this->Instance = $con;
}
return $this->Instance;
}
/**
* Database::disconnect()
* Closes the database's connection to avoid conflict and release memory
*
* @return void
*/
public function disconnect()
{
if (!mysqli_close($this->Instance)) {
die($this->getError());
}
}
/**
* Database::select()
* Format SQL and returns query content
*
* @param [string] $table
* @param [array] $columns
* @param [array] $wheres
* @param [array] $joins
* @param [array] $orderbys
* @return [array] $results
*/
public function select($table, $columns = null, $wheres = null, $joins = null, $orderbys = null)
{
//Variables
$return = array();
if ($table != "" || $table != null) {
//Open up connection
$this->connect();
//SELECT statement
$this->Sql = "SELECT ";
//COLUMNS
if ($columns != "" || $columns != null) {
foreach ($columns as $index => $column) {
if ($index == 0) {
$this->Sql .= $column;
} else {
$this->Sql .= ", " . $column;
}
}
} else {
$this->Sql .= "*";
}
//FROM statement
$this->Sql .= " FROM " . $table;
//JOINS
if ($joins != "" || $joins != null) {
foreach ($joins as $join) {
$this->Sql .= ' ' . $join["orientation"] . " JOIN " . $join["referenced_table"] . " ON " . $join["table_name"] . "." . $join["column_name"] . " = " . $join["referenced_table"] . "." . $join["referenced_column"];
}
}
//WHERE statement
if ($wheres != "" || $wheres != null) {
foreach ($wheres as $index => $where) {
//if string format SQL
if (gettype($where["value"]) == "string" && !is_numeric($where["value"])) {
$where["value"] = "'" . $where["value"] . "'";
$where["value"] = htmlentities(utf8_encode($where["value"]));
$where["condition"] = "LIKE";
}
if ($index == 0) {
$this->Sql .= " WHERE " . $where["column"] . " " . $where["condition"] . " " . $where["value"];
} else {
if (sizeof($wheres) == $index) {
$this->Sql .= " " . $where["column"] . " " . $where["condition"] . " " . $where["value"];
} else {
$this->Sql .= " " . $where["operation"] . " " . $where["column"] . " " . $where["condition"] . " " . $where["value"];
}
}
}
}
//ORDER BY statement
if ($orderbys != "" || $orderbys != null) {
foreach ($orderbys as $index => $orderby) {
if ($index == 0) {
$this->Sql .= " ORDER BY " . $orderby;
} else {
$this->Sql .= ", " . $orderby;
}
}
}
$this->Sql .= ";";
$results = $this->Instance->query($this->Sql);
if (!$results) {
die($this->getError());
}
while ($row = $results->fetch_assoc()) {
$return[] = $row;
}
array_walk_recursive($return, function (&$item, $key) {
$item = html_entity_decode(utf8_decode($item));
});
$this->disconnect();
return $return;
} else {
die("Must provide a table to query the database.");
}
}
/**
* Database::insert()
* Format SQL and inserts into database
*
* @param [type] $table
* @param [type] $columns
* @param [type] $values
* @return void
*/
public function insert($table, $columns, $values)
{
if ($table != "" || $table != null) {
$this->connect();
$this->Sql = "INSERT INTO " . $table;
if (($columns != "" || $columns != null) || sizeof($columns) != sizeof($values)) {
$this->Sql .= "(";
//COLUMNS
foreach ($columns as $index => $column) {
if ($index == 0) {
$this->Sql .= $column;
} else {
$this->Sql .= ", " . $column;
}
}
$this->Sql .= ") VALUES (";
if ($values != "" || $values != null) {
//VALUES
foreach ($values as $index => $value) {
if (gettype($value) == "string" && !is_numeric($value)) {
$value = "'" . trim(htmlentities(utf8_encode($value))) . "'";
}
if ($index == 0) {
$this->Sql .= $value;
} else {
$this->Sql .= ", " . $value;
}
}
$this->Sql .= ");";
//insert into database
if (!$this->Instance->query($this->Sql)) {
die($this->getError());
}
}
} else {
die("Either set columns or set the same amount of columns/values to insert");
}
$this->disconnect();
} else {
die("Must provide a table to insert to");
}
}
/**
* Database::delete()
* Format SQL and deletes the specific row in the database
*
* @param [string] $table
* @param [array] $columns
* @param [array] $values
* @return [boolean] ? (true) row deleted : error;
*/
public function delete($table, $wheres = null)
{
if ($table != "" || $table != null) {
$this->connect();
$this->Sql = "DELETE FROM " . $table;
//WHERE
if ($wheres != "" || $wheres != null) {
foreach ($wheres as $index => $where) {
//if string format SQL
if (gettype($where["value"]) == "string" && !is_numeric($where["value"])) {
$where["value"] = "'" . trim($where["value"]) . "'";
$where["value"] = htmlentities(utf8_encode($where["value"]));
$where["condition"] = "LIKE";
}
if ($index == 0) {
$this->Sql .= " WHERE " . $where["column"] . " " . $where["condition"] . " " . $where["value"];
} else {
if (sizeof($wheres) == $index) {
$this->Sql .= " " . $where["column"] . " " . $where["condition"] . " " . $where["value"];
} else {
$this->Sql .= " " . $where["operation"] . " " . $where["column"] . " " . $where["condition"] . " " . $where["value"];
}
}
}
}
$this->Sql .= ";";
//delete from database
if (!$this->Instance->query($this->Sql)) {
die($this->getError());
}
$this->disconnect();
} else {
die("Must provide a table to delete from");
}
}
/**
* Database::update()
* Format SQL and updates the specific row in the database
*
* @return [boolean] ? (true) row updated : error;
*/
public function update($table, $columns, $values, $wheres = null)
{
if ($table != "" || $table != null) {
$this->connect();
$this->Sql = "UPDATE " . $table;
//SET columns, [...]
if (($columns != "" || $columns != null) || sizeof($columns) != sizeof($values)) {
$this->Sql .= " SET ";
//COLUMNS
foreach ($columns as $index => $column) {
if (gettype($values[$index]) == "string" && !is_numeric($values[$index])) {
$values[$index] = "'" . trim($values[$index]) . "'";
$values[$index] = htmlentities(utf8_encode($values[$index]));
}
if ($index == 0) {
$this->Sql .= "" . $column . " = " . $values[$index];
} else {
$this->Sql .= ", " . $column . " = " . $values[$index];
}
}
} else {
die("Either set columns or set the same amount of columns/values to insert");
}
//WHERE
if ($wheres != "" || $wheres != null) {
foreach ($wheres as $index => $where) {
//if string format SQL
if (gettype($where["value"]) == "string" && !is_numeric($where["value"])) {
$where["value"] = "'" . $where["value"] . "'";
$where["value"] = trim(htmlentities(utf8_encode($where["value"])));
$where["condition"] = "LIKE";
}
if ($index == 0) {
$this->Sql .= " WHERE " . $where["column"] . " " . $where["condition"] . " " . $where["value"];
} else {
if (sizeof($wheres) == $index) {
$this->Sql .= " " . $where["column"] . " " . $where["condition"] . " " . $where["value"];
} else {
$this->Sql .= " " . $where["operation"] . " " . $where["column"] . " " . $where["condition"] . " " . $where["value"];
}
}
}
}
$this->Sql .= ";";
//update in database
if (!$this->Instance->query($this->Sql)) {
die($this->getError());
}
$this->disconnect();
} else {
die("Must provide a table to delete from");
}
}
public function getKeys($table, $type = "primary")
{
$this->connect();
if ($type == "primary") {
$this->Sql = "SHOW COLUMNS FROM " . $table . ";";
$results = $this->Instance->query($this->Sql);
foreach ($results as $row) {
if ($row["Key"] == "PRI") {
$this->disconnect();
return $row["Field"];
}
}
} else if ($type == "foreign") {
$fk_array = array();
$return = array();
$this->Sql = "SHOW CREATE TABLE " . $table;
$results = $this->Instance->query($this->Sql);
while ($row = $results->fetch_assoc()) {
$fk_array[] = $row;
}
$fk_array = explode("FOREIGN KEY", $fk_array[0]["Create Table"]);
foreach ($fk_array as $fk) {
if (strpos($fk, "REFERENCES")) {
$column_name = substr($fk, 3, strpos($fk, ")") - 4);
$return[] = array($column_name);
}
}
$this->disconnect();
return $return;
}
}
public function getJoinsArray($table)
{
$fk_array = array();
$return = array();
$this->Sql = "SHOW CREATE TABLE " . $table;
$results = $this->Instance->query($this->Sql);
if (!$results) {
die($this->getError());
}
while ($row = $results->fetch_assoc()) {
$fk_array[] = $row;
}
$fk_array = explode("FOREIGN KEY", $fk_array[0]["Create Table"]);
foreach ($fk_array as $fk) {
if (strpos($fk, "REFERENCES")) {
//Isolate referenced table
$referenced_table = substr($fk, strpos($fk, "REFERENCES"));
$referenced_table = substr($referenced_table, strpos($referenced_table, "`") + 1);
$referenced_table = substr($referenced_table, 0, strpos($referenced_table, "`"));
//Isolate referenced column
$referenced_column = substr($fk, strrpos($fk, "(") + 2);
$referenced_column = substr($referenced_column, 0, strpos($fk, ")") - 4);
//Isolate current table's column (should be the same as referenced)
$column_name = substr($fk, 3, strpos($fk, ")") - 4);
$return[] = array(
"orientation" => "INNER",
"referenced_table" => $referenced_table,
"referenced_column" => $referenced_column,
"column_name" => $column_name,
"table_name" => $table,
);
}
}
return $return;
}
public function getSql()
{
return $this->Sql;
}
private function getError()
{
return "<br/>" . $this->Sql . "<br/> SQL Exception #" . $this->Instance->errno . " : " . $this->Instance->error . "<br/>";
}
}
| {
"content_hash": "007bcdd7d49f732d20d860b3bf7484ae",
"timestamp": "",
"source": "github",
"line_count": 461,
"max_line_length": 231,
"avg_line_length": 33.420824295010846,
"alnum_prop": 0.4057895761666775,
"repo_name": "delirius325/MySimpleORM",
"id": "977c7613613cc8897780acc9662ffcef1a4f9728",
"size": "15408",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/MySimpleORM/Mapper/Database.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "28444"
}
],
"symlink_target": ""
} |
using Medallion.Threading.Postgres;
using NUnit.Framework;
using System.Data;
namespace Medallion.Threading.Tests.Postgres;
public class PostgresDistributedReaderWriterLockTest
{
[Test]
public void TestValidatesConstructorArguments()
{
Assert.Throws<ArgumentNullException>(() => new PostgresDistributedReaderWriterLock(new(0), default(string)!));
Assert.Throws<ArgumentNullException>(() => new PostgresDistributedReaderWriterLock(new(0), default(IDbConnection)!));
}
}
| {
"content_hash": "5f1ba870f40ae3a18d942b16822339fe",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 125,
"avg_line_length": 33.6,
"alnum_prop": 0.7638888888888888,
"repo_name": "madelson/DistributedLock",
"id": "de544b94db9cd166bda2bbc78e1b5cf411769f54",
"size": "506",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "DistributedLock.Tests/Tests/Postgres/PostgresDistributedReaderWriterLockTest.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "1170451"
}
],
"symlink_target": ""
} |
package com.example.fw;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.FluentWait;
import org.openqa.selenium.support.ui.Wait;
import com.example.tests.ContactData;
import com.example.utils.SortedListOf;
public class ContactHelper extends WebDriverHelperBase {
public ContactHelper(ApplicationManager manager) {
super(manager);
}
public List<ContactData> getUIContacts() {
SortedListOf<ContactData> contacts = new SortedListOf<ContactData>();
//List<ContactData> contacts = new ArrayList<ContactData>();
manager.navigateTo().mainPage();
List<WebElement> rows = driver.findElements(By
.xpath("//table[@id='maintable']//tr[@name='entry']"));
// System.out.println(rows.size());
for (WebElement row : rows) {
String firstName = row.findElement(By.xpath(".//td[3]")).getText();
String lastName = row.findElement(By.xpath(".//td[2]")).getText();
String emailPrime = row.findElement(By.xpath(".//td[4]")).getText();
String homePhone = row.findElement(By.xpath(".//td[5]")).getText();
contacts.add(new ContactData().withFirstName(firstName)
.withLastName(lastName).withEmailPrime(emailPrime)
.withHomePhone(homePhone));
}
return contacts;
}
public ContactHelper createContact(ContactData contact) {
manager.navigateTo().mainPage();
gotoContactPage();
waitPage();
filloutContactForm(contact);
submitContactCreation();
returnToMainPage();
manager.getModel().addContact(contact);
return this;
}
public ContactHelper modifyContact(int index, ContactData contact) {
initContactModification(index);
filloutContactForm(contact);
submitContactModification();
returnToMainPage();
manager.getModel().removeContact(index).addContact(contact);
return this;
}
public ContactHelper deleteContact(int index) {
initContactModification(index);
submitContactDeletion();
returnToMainPage();
manager.getModel().removeContact(index);
return this;
}
// ----------------------------------------------------------------------------------------
public ContactHelper gotoContactPage() {
click(By.linkText("add new"));
return this;
}
public ContactHelper submitContactCreation() {
click(By.name("submit"));
return this;
}
public ContactHelper returnToContactPage() {
click(By.linkText("add next"));
return this;
}
public ContactHelper returnToMainPage() {
click(By.linkText("home page"));
return this;
}
public ContactHelper filloutContactForm(ContactData contact) {
type(By.name("firstname"), contact.getFirstName());
type(By.name("lastname"), contact.getLastName());
type(By.name("address"), contact.getAddressPrime());
type(By.name("home"), contact.getHomePhone());
type(By.name("mobile"), contact.getCellPhone());
type(By.name("work"), contact.getWorkPhone());
type(By.name("email"), contact.getEmailPrime());
type(By.name("email2"), contact.getEmailSecond());
selectByText(By.name("bday"), contact.getBirthDay());
selectByText(By.name("bmonth"), contact.getBirthMonth());
type(By.name("byear"), contact.getBirthYear());
type(By.name("address2"), contact.getAddressSec());
type(By.name("phone2"), contact.getPhoneAdd());
return this;
}
public ContactHelper initContactModification(int index) {
click(By.cssSelector("#maintable tr:nth-of-type(" + (index + 2) + ")"
+ " img[alt='Edit']"));
return this;
}
public ContactHelper submitContactModification() {
click(By.cssSelector("#content input[value='Update']"));
return this;
}
public ContactHelper submitContactDeletion() {
click(By.cssSelector("#content input[value='Delete']"));
return this;
}
private void waitPage() {
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withMessage("Element was not found")
.withTimeout(20, TimeUnit.SECONDS)
.pollingEvery(1, TimeUnit.SECONDS);
wait.until(ExpectedConditions.presenceOfElementLocated(By
.name("submit")));
}
}
| {
"content_hash": "664413d04631d38dedf98e320e57037f",
"timestamp": "",
"source": "github",
"line_count": 136,
"max_line_length": 92,
"avg_line_length": 30.529411764705884,
"alnum_prop": 0.7112235067437379,
"repo_name": "makarkina/JavaForTesters",
"id": "b528e402c77ca4c5df9020d1ebacd8d9d4d2e783",
"size": "4152",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "addressbook-selenium-tests/src/com/example/fw/ContactHelper.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "462"
},
{
"name": "CSS",
"bytes": "5640"
},
{
"name": "HTML",
"bytes": "25683"
},
{
"name": "Java",
"bytes": "165303"
},
{
"name": "JavaScript",
"bytes": "3555"
}
],
"symlink_target": ""
} |
<?php
namespace DTS\eBaySDK\Trading\Types\Test;
use DTS\eBaySDK\Trading\Types\StoreCustomListingHeaderLinkType;
class StoreCustomListingHeaderLinkTypeTest extends \PHPUnit_Framework_TestCase
{
private $obj;
protected function setUp()
{
$this->obj = new StoreCustomListingHeaderLinkType();
}
public function testCanBeCreated()
{
$this->assertInstanceOf('\DTS\eBaySDK\Trading\Types\StoreCustomListingHeaderLinkType', $this->obj);
}
public function testExtendsBaseType()
{
$this->assertInstanceOf('\DTS\eBaySDK\Types\BaseType', $this->obj);
}
}
| {
"content_hash": "a9ea97dcb393707c019a15595f162cc7",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 107,
"avg_line_length": 23.576923076923077,
"alnum_prop": 0.7096247960848288,
"repo_name": "michabbb-backup/ebay-sdk-trading",
"id": "d8465cd22ea156018b3d05255f2d4973d5008129",
"size": "1343",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "test/DTS/eBaySDK/Trading/Types/StoreCustomListingHeaderLinkTypeTest.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Makefile",
"bytes": "1963"
},
{
"name": "PHP",
"bytes": "4776677"
}
],
"symlink_target": ""
} |
using JustLogic.Core;
using System.Collections.Generic;
using UnityEngine;
[UnitMenu("Physics/Settings/Get Solver Iteration Count")]
[UnitFriendlyName("Physics.Get Solver Iteration Count")]
[UnitUsage(typeof(System.Int32), HideExpressionInActionsList = true)]
public class JLPhysicsGetSolverIterationCount : JLExpression
{
public override object GetAnyResult(IExecutionContext context)
{
return Physics.solverIterationCount;
}
}
| {
"content_hash": "eec0b65d1dc22a543f173b29af328791",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 69,
"avg_line_length": 28.375,
"alnum_prop": 0.7841409691629956,
"repo_name": "AqlaSolutions/JustLogic",
"id": "84bbab190b5dd39c5d2ecadae677a0996f708b34",
"size": "2102",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Assets/JustLogicUnits/Generated/Physics/JLPhysicsGetSolverIterationCount.cs",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Batchfile",
"bytes": "2892"
},
{
"name": "C#",
"bytes": "3394070"
},
{
"name": "JavaScript",
"bytes": "23005"
}
],
"symlink_target": ""
} |
<?php
namespace Mailgun\Api;
use Http\Client\Exception as HttplugException;
use Http\Client\HttpClient;
use Mailgun\Exception\UnknownErrorException;
use Mailgun\Hydrator\Hydrator;
use Mailgun\Hydrator\NoopHydrator;
use Mailgun\Exception\HttpClientException;
use Mailgun\Exception\HttpServerException;
use Mailgun\RequestBuilder;
use Psr\Http\Message\ResponseInterface;
/**
* @author Tobias Nyholm <tobias.nyholm@gmail.com>
*/
abstract class HttpApi
{
/**
* The HTTP client.
*
* @var HttpClient
*/
private $httpClient;
/**
* @var Hydrator
*/
protected $hydrator;
/**
* @var RequestBuilder
*/
protected $requestBuilder;
/**
* @param HttpClient $httpClient
* @param RequestBuilder $requestBuilder
* @param Hydrator $hydrator
*/
public function __construct(HttpClient $httpClient, RequestBuilder $requestBuilder, Hydrator $hydrator)
{
$this->httpClient = $httpClient;
$this->requestBuilder = $requestBuilder;
if (!$hydrator instanceof NoopHydrator) {
$this->hydrator = $hydrator;
}
}
/**
* @param ResponseInterface $response
* @param string $class
*
* @return mixed|ResponseInterface
*
* @throws \Exception
*/
protected function hydrateResponse(ResponseInterface $response, $class)
{
if (!$this->hydrator) {
return $response;
}
if (200 !== $response->getStatusCode() && 201 !== $response->getStatusCode()) {
$this->handleErrors($response);
}
return $this->hydrator->hydrate($response, $class);
}
/**
* Throw the correct exception for this error.
*
* @param ResponseInterface $response
*
* @throws \Exception
*/
protected function handleErrors(ResponseInterface $response)
{
$statusCode = $response->getStatusCode();
switch ($statusCode) {
case 400:
throw HttpClientException::badRequest($response);
case 401:
throw HttpClientException::unauthorized($response);
case 402:
throw HttpClientException::requestFailed($response);
case 404:
throw HttpClientException::notFound($response);
case 413:
throw HttpClientException::payloadTooLarge($response);
case 500 <= $statusCode:
throw HttpServerException::serverError($statusCode);
default:
throw new UnknownErrorException();
}
}
/**
* Send a GET request with query parameters.
*
* @param string $path Request path
* @param array $parameters GET parameters
* @param array $requestHeaders Request Headers
*
* @return ResponseInterface
*/
protected function httpGet($path, array $parameters = [], array $requestHeaders = [])
{
if (count($parameters) > 0) {
$path .= '?'.http_build_query($parameters);
}
try {
$response = $this->httpClient->sendRequest(
$this->requestBuilder->create('GET', $path, $requestHeaders)
);
} catch (HttplugException\NetworkException $e) {
throw HttpServerException::networkError($e);
}
return $response;
}
/**
* Send a POST request with parameters.
*
* @param string $path Request path
* @param array $parameters POST parameters
* @param array $requestHeaders Request headers
*
* @return ResponseInterface
*/
protected function httpPost($path, array $parameters = [], array $requestHeaders = [])
{
return $this->httpPostRaw($path, $this->createRequestBody($parameters), $requestHeaders);
}
/**
* Send a POST request with raw data.
*
* @param string $path Request path
* @param array|string $body Request body
* @param array $requestHeaders Request headers
*
* @return ResponseInterface
*/
protected function httpPostRaw($path, $body, array $requestHeaders = [])
{
try {
$response = $this->httpClient->sendRequest(
$this->requestBuilder->create('POST', $path, $requestHeaders, $body)
);
} catch (HttplugException\NetworkException $e) {
throw HttpServerException::networkError($e);
}
return $response;
}
/**
* Send a PUT request.
*
* @param string $path Request path
* @param array $parameters PUT parameters
* @param array $requestHeaders Request headers
*
* @return ResponseInterface
*/
protected function httpPut($path, array $parameters = [], array $requestHeaders = [])
{
try {
$response = $this->httpClient->sendRequest(
$this->requestBuilder->create('PUT', $path, $requestHeaders, $this->createRequestBody($parameters))
);
} catch (HttplugException\NetworkException $e) {
throw HttpServerException::networkError($e);
}
return $response;
}
/**
* Send a DELETE request.
*
* @param string $path Request path
* @param array $parameters DELETE parameters
* @param array $requestHeaders Request headers
*
* @return ResponseInterface
*/
protected function httpDelete($path, array $parameters = [], array $requestHeaders = [])
{
try {
$response = $this->httpClient->sendRequest(
$this->requestBuilder->create('DELETE', $path, $requestHeaders, $this->createRequestBody($parameters))
);
} catch (HttplugException\NetworkException $e) {
throw HttpServerException::networkError($e);
}
return $response;
}
/**
* Prepare a set of key-value-pairs to be encoded as multipart/form-data.
*
* @param array $parameters Request parameters
*
* @return array
*/
protected function createRequestBody(array $parameters)
{
$resources = [];
foreach ($parameters as $key => $values) {
if (!is_array($values)) {
$values = [$values];
}
foreach ($values as $value) {
$resources[] = [
'name' => $key,
'content' => $value,
];
}
}
return $resources;
}
}
| {
"content_hash": "6ef2dbf7cce4346da1e4e08f60b66b04",
"timestamp": "",
"source": "github",
"line_count": 232,
"max_line_length": 118,
"avg_line_length": 28.551724137931036,
"alnum_prop": 0.5677838164251208,
"repo_name": "brideout/gen2",
"id": "b612addcdf1880460177c98c8d130864fe2c3bda",
"size": "6785",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "application/libraries/vendor/mailgun/mailgun-php/src/Mailgun/Api/HttpApi.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "592692"
},
{
"name": "HTML",
"bytes": "8603364"
},
{
"name": "JavaScript",
"bytes": "1463193"
},
{
"name": "PHP",
"bytes": "3281090"
}
],
"symlink_target": ""
} |
"""
:mod:`run`
==================
.. module:: run
:platform: Unix, Windows
:synopsis:
.. moduleauthor:: hbldh <henrik.blidh@nedomkull.com>
Created on 2014-09-09, 16:12
"""
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import
from bankidexampleapp import app
print("Running server on http://localhost:5000")
app.run(host='0.0.0.0', debug=True)
| {
"content_hash": "974ad48d48f244e602148c4f4a2a0efb",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 52,
"avg_line_length": 19.652173913043477,
"alnum_prop": 0.6769911504424779,
"repo_name": "hbldh/pybankid-example-app",
"id": "1dadd40ac15426940a8fd412152401c89d02f8d7",
"size": "498",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "run.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "17761"
},
{
"name": "Python",
"bytes": "4127"
}
],
"symlink_target": ""
} |
/**
* ReportPage constructor
*
* @param kwArgs.id [String] DOM node id
* @param kwArgs.bgColor [String] Background color of the page
* @param kwArgs.width [Int] Page content's width in pixels
* @param kwArgs.height [Int] Page content's height in pixels
* @param kwArgs.topMargin [Int] Top margin of report page in pixels
* @param kwArgs.rightMargin [Int] Right margin of report page in pixels
* @param kwArgs.bottomMargin [Int] Bottom margin of report page in pixels
* @param kwArgs.leftMargin [Int] Left margin of report page in pixels
* @param kwArgs.extraCssFileUrl [String] The path of an extra CSS file used in report page
*/
bobj.crv.newReportPage = function(kwArgs) {
kwArgs = MochiKit.Base.update({
id: bobj.uniqueId(),
bgColor: '#FFFFFF',
width: 720,
height: 984,
extraCssFileUrl: "",
documentView: bobj.crv.ReportPage.DocumentView.PRINT_LAYOUT
}, kwArgs);
var o = newWidget(kwArgs.id);
o.widgetType = 'ReportPage';
// Update instance with constructor arguments
bobj.fillIn(o, kwArgs);
// Update instance with member functions
o.initOld = o.init;
o.resizeOld = o.resize;
MochiKit.Base.update(o, bobj.crv.ReportPage);
return o;
};
bobj.crv.ReportPage = {
DocumentView : {
WEB_LAYOUT : 'weblayout',
PRINT_LAYOUT : 'printlayout'
},
/**
* Disposes report page by removing its layer and stylesheet from DOM
*/
dispose : function() {
MochiKit.DOM.removeElement (this.layer);
},
/**
* DO NOT REMOVE. USED BY WEB ELEMENTS
*/
displayScrollBars : function (isDisplay) {
this.layer.style.overflow = isDisplay ? "auto" : "hidden";
},
/**
* DO NOT REMOVE. USED BY WEB ELEMENTS
*/
isDisplayScrollBars : function () {
this.layer.style.overflow == "auto";
},
update : function(update) {
if (update && update.cons == "bobj.crv.newReportPage") {
this.updateSize ( {
width : update.args.width,
height : update.args.height
});
this.layer.scrollLeft = 0;
this.layer.scrollTop = 0;
this.updateHTML (update.args.content, false);
}
},
scrollToHighlighted : function (scrollWindow) {
if(this._iframe) {
var iframeDoc = _ie ? this._iframe.contentWindow.document : this._iframe.contentDocument;
var e = iframeDoc.getElementById("CrystalHighLighted");
if(e) {
var ePosition = MochiKit.Style.getElementPosition (e, null, iframeDoc);
if(scrollWindow) {
var reportPagePos = MochiKit.Style.getElementPosition (this.layer);
window.scrollTo (reportPagePos.x + ePosition.x , reportPagePos.y + ePosition.y);
}
else {
this.layer.scrollLeft = ePosition.x;
this.layer.scrollTop = ePosition.y;
}
}
}
},
updateHTML : function(content, useAnimation) {
if (content) {
if(!this._iframe) {
this._iframe = MochiKit.DOM.createDOM('IFRAME', {id : this.id + '_iframe', width : '100%', height : '100%', frameBorder : '0', margin : '0'})
this._pageNode.appendChild(this._iframe);
}
if(useAnimation)
this._iframe.style.display = "none";
var iframeDoc = _ie ? this._iframe.contentWindow.document : this._iframe.contentDocument;
iframeDoc.open();
iframeDoc.write(this.getIFrameHTML (content));
iframeDoc.close();
if(useAnimation)
bobj.displayElementWithAnimation(this._iframe);
}
},
getIFrameHTML : function (content) {
var extraCssFileLink = "";
if (this.extraCssFileUrl != "") {
extraCssFileLink = "<link href=\"" + this.extraCssFileUrl + "\" rel=\"stylesheet\" type=\"text/css\" />\r\n";
}
return "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">" +
"<html>\r\n" +
"<head>\r\n" +
extraCssFileLink +
"<style> body { overflow :hidden; margin : 0px;}</style>\r\n" +
"</head>\r\n" +
"<body>\r\n" +
content +
"</body>\r\n" +
"</html>";
},
/*
* Updates size of report page based on update object
* @param update [{width,height,marginLeft,marginRight,marginTop}] dimension and margins
* of report p
*/
updateSize : function(sizeObject) {
if (sizeObject) {
this.width = (sizeObject.width != undefined) ? sizeObject.width : this.width;
this.height = (sizeObject.height != undefined) ? sizeObject.height : this.height;
}
if (this._pageNode) {
var isBBM = bobj.isBorderBoxModel ();
this._pageNode.style.width = (isBBM ? this.width + 2: this.width) + 'px';
this._pageNode.style.height = (isBBM ? this.height + 2: this.height) + 'px';
}
if (this._shadowNode) {
this._shadowNode.style.width = (isBBM ? this.width + 2: this.width) + 'px';
this._shadowNode.style.height = (isBBM ? this.height + 2: this.height) + 'px';
}
},
getHTML : function() {
var h = bobj.html;
var isBBM = bobj.isBorderBoxModel ();
var layerStyle = {
width : '100%',
height : '100%',
overflow : 'auto',
position : 'absolute'
};
var pageStyle = {
position : 'relative',
width : (isBBM ? this.width + 2: this.width) + 'px',
height : (isBBM ? this.height + 2: this.height) + 'px',
'z-index' : 1,
'border-width' : '1px',
'border-style' : 'solid',
'background-color' : this.bgColor,
overflow : 'hidden',
'text-align' : 'left'
};
var shadowStyle = {
position : 'absolute',
'z-index' : 0,
display : 'none',
width : (isBBM ? this.width + 2: this.width) + 'px',
height : (isBBM ? this.height + 2: this.height) + 'px',
top : '0px',
left : '0px'
};
var shadowHTML = '';
if (this.documentView.toLowerCase () == bobj.crv.ReportPage.DocumentView.PRINT_LAYOUT) {
layerStyle['background-color'] = '#8E8E8E';
pageStyle['border-color'] = '#000000';
shadowStyle['background-color'] = '#737373';
shadowHTML = h.DIV ( {
id : this.id + '_shadow',
'class' : 'menuShadow',
style : shadowStyle
})
/* page should appear in the center for print layouts */
layerStyle['text-align'] = 'center'; /* For page centering in IE quirks mode */
pageStyle['margin'] = '0 auto'; /* center the page horizontally - CSS2 */
pageStyle['top'] = "6px";
} else {
/* Web Layout*/
layerStyle['background-color'] = '#FFFFFF';
pageStyle['border-color'] = '#FFFFFF';
/* page should appear in left for web layouts */
pageStyle['margin'] = '0';
}
var html = h.DIV ( {
id : this.id,
style : layerStyle,
'class' : 'insetBorder'
}, h.DIV ( {
id : this.id + '_page',
style : pageStyle
}), shadowHTML);
return html;
},
init : function() {
this._pageNode = getLayer (this.id + '_page');
this._shadowNode = getLayer (this.id + '_shadow');
this.initOld ();
this.updateHTML (this.content, true);
},
updateShadowLocation : function () {
var updateFunc = function () {
if(this._shadowNode && this._pageNode) {
this._shadowNode.style.display = "none"; //Must hide dropshadow as it can cause scrollbars to appear
var pageNodPos = {x : this._pageNode.offsetLeft, y : this._pageNode.offsetTop};
this._shadowNode.style.display = "block";
this._shadowNode.style.top = pageNodPos.y + (bobj.isBorderBoxModel() ? 4 : 6) + "px";
this._shadowNode.style.left = pageNodPos.x + (bobj.isBorderBoxModel() ? 4 : 6) + "px";
}
}
setTimeout(bobj.bindFunctionToObject(updateFunc,this), 0); // Must be executed after viewer has finished doLayout
},
/**
* Resizes the outer dimensions of the widget.
*/
resize : function (w, h) {
bobj.setOuterSize(this.layer, w, h);
if(_moz)
this.css.clip = bobj.getRect(0,w,h,0);
this.updateShadowLocation ();
},
/**
* @return Returns an object with width and height properties such that there
* would be no scroll bars around the page if they were applied to the widget.
*/
getBestFitSize : function() {
var page = this._pageNode;
return {
width: page.offsetWidth + 30,
height: page.offsetHeight + 30
};
},
hideFrame : function() {
this.css.borderStyle = 'none';
this._pageNode.style.border = '';
}
};
| {
"content_hash": "ea982655ea4b97e41067cd9b49c56b33",
"timestamp": "",
"source": "github",
"line_count": 280,
"max_line_length": 161,
"avg_line_length": 34.63928571428571,
"alnum_prop": 0.5266522321888855,
"repo_name": "manuelstuner/SSPES",
"id": "e5b0f46e16fa00e19f92592bde91017bb670bab6",
"size": "9762",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "SSPES/SSPES/aspnet_client/system_web/4_0_30319/crystalreportviewers13/js/crviewer/ReportPage.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "119289"
},
{
"name": "C#",
"bytes": "98635"
},
{
"name": "CSS",
"bytes": "43079"
},
{
"name": "JavaScript",
"bytes": "92206"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.