text
stringlengths 2
100k
| meta
dict |
---|---|
---
-api-id: P:Windows.Media.Audio.ReverbEffectDefinition.PositionMatrixRight
-api-type: winrt property
---
<!-- Property syntax
public byte PositionMatrixRight { get; set; }
-->
# Windows.Media.Audio.ReverbEffectDefinition.PositionMatrixRight
## -description
Gets or sets the matrix position right included in the reverberation effect definition.
## -property-value
The matrix position right value.
## -remarks
## -examples
## -see-also
| {
"pile_set_name": "Github"
} |
<resources>
<!-- Default screen margins, per the Android Design guidelines. -->
<dimen name="activity_horizontal_margin">16dp</dimen>
<dimen name="activity_vertical_margin">16dp</dimen>
<dimen name="main_app_bar_height">250dp</dimen>
<dimen name="main_overlap_top">40dp</dimen>
<dimen name="main_double_cardview_container_height">140dp</dimen>
<dimen name="default_layout_margin_halved">8dp</dimen>
<dimen name="default_layout_margin">16dp</dimen>
<dimen name="default_layout_margin_quartered">4dp</dimen>
<dimen name="textsize_very_small">9sp</dimen>
<dimen name="textsize_small">11sp</dimen>
<dimen name="textsize_medium">13sp</dimen>
<dimen name="textsize_big">16sp</dimen>
<dimen name="textsize_very_big">18sp</dimen>
<dimen name="textsize_huge">21sp</dimen>
<dimen name="textsize_very_huge">26sp</dimen>
<dimen name="textsize_enormous">36sp</dimen>
<dimen name="main_cardview_trip_height">142dp</dimen>
<dimen name="recycler_item_place">120dp</dimen>
<dimen name="map_margin_bottom">200dp</dimen>
<dimen name="item_recycler_number_dimen">24dp</dimen>
<dimen name="default_layout_margin_three_fourths">12dp</dimen>
<dimen name="item_place_details_height">380dp</dimen>
</resources>
| {
"pile_set_name": "Github"
} |
//
// MRListView.m
// Coding_iOS
//
// Created by Ease on 15/10/23.
// Copyright © 2015年 Coding. All rights reserved.
//
#import "MRListView.h"
#import "ODRefreshControl.h"
#import "SVPullToRefresh.h"
#import "Coding_NetAPIManager.h"
#import "MRPRListCell.h"
@interface MRListView ()<UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, strong) UITableView *myTableView;
@property (nonatomic, strong) ODRefreshControl *myRefreshControl;
@end
@implementation MRListView
- (instancetype)initWithFrame:(CGRect)frame{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
_myTableView = ({
UITableView *tableView = [[UITableView alloc] init];
tableView.backgroundColor = [UIColor clearColor];
tableView.delegate = self;
tableView.dataSource = self;
[tableView registerClass:[MRPRListCell class] forCellReuseIdentifier:kCellIdentifier_MRPRListCell];
tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
[self addSubview:tableView];
[tableView mas_makeConstraints:^(MASConstraintMaker *make) {
make.edges.equalTo(self);
}];
UIEdgeInsets insets = UIEdgeInsetsMake(0, 0, 49, 0);//外部 segment bar 的高度
tableView.contentInset = insets;
tableView.scrollIndicatorInsets = insets;
tableView.estimatedRowHeight = 0;
tableView.estimatedSectionHeaderHeight = 0;
tableView.estimatedSectionFooterHeight = 0;
tableView;
});
_myRefreshControl = [[ODRefreshControl alloc] initInScrollView:self.myTableView];
[_myRefreshControl addTarget:self action:@selector(refresh) forControlEvents:UIControlEventValueChanged];
__weak typeof(self) weakSelf = self;
[_myTableView addInfiniteScrollingWithActionHandler:^{
[weakSelf refreshMore:YES];
}];
}
return self;
}
- (void)refresh{
[self refreshMore:NO];
}
- (void)refreshMore:(BOOL)willLoadMore{
MRPRS *curMRPRS = [self curMRPRS];
if (curMRPRS.isLoading) {
return;
}
if (willLoadMore && !curMRPRS.canLoadMore) {
[_myTableView.infiniteScrollingView stopAnimating];
return;
}
curMRPRS.willLoadMore = willLoadMore;
[self sendRequest:curMRPRS];
}
- (void)sendRequest:(MRPRS *)curMRPRS{
if (curMRPRS.list.count <= 0) {
[self beginLoading];
}
__weak typeof(self) weakSelf = self;
__weak typeof(curMRPRS) weakMRPRS = curMRPRS;
[[Coding_NetAPIManager sharedManager] request_MRPRS_WithObj:curMRPRS andBlock:^(MRPRS *data, NSError *error) {
[weakSelf endLoading];
[weakSelf.myRefreshControl endRefreshing];
[weakSelf.myTableView.infiniteScrollingView stopAnimating];
if (data) {
[weakMRPRS configWithMRPRS:data];
[weakSelf.myTableView reloadData];
weakSelf.myTableView.showsInfiniteScrolling = [weakSelf curMRPRS].canLoadMore;
}
[weakSelf configBlankPage:EaseBlankPageTypeView hasData:([weakSelf curMRPRS].list.count > 0) hasError:(error != nil) reloadButtonBlock:^(id sender) {
[weakSelf refreshMore:NO];
}];
}];
}
- (void)refreshToQueryData{
if (self.curMRPRS.list > 0) {
__weak typeof(self) weakSelf = self;
[self configBlankPage:EaseBlankPageTypeView hasData:([self curMRPRS].list.count > 0) hasError:NO reloadButtonBlock:^(id sender) {
[weakSelf refreshMore:NO];
}];
}
[self.myTableView reloadData];
[self refresh];
}
#pragma mark TableM
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return [self curMRPRS].list.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
MRPR *curMRPR = [[self curMRPRS].list objectAtIndex:indexPath.row];
MRPRListCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier_MRPRListCell forIndexPath:indexPath];
cell.curMRPR = curMRPR;
[tableView addLineforPlainCell:cell forRowAtIndexPath:indexPath withLeftSpace:60];
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
return [MRPRListCell cellHeightWithObj:[[self curMRPRS].list objectAtIndex:indexPath.row]];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
if (self.clickedMRBlock) {
MRPR *curMR = self.curMRPRS.list[indexPath.row];
self.clickedMRBlock(curMR);
}
}
@end
| {
"pile_set_name": "Github"
} |
# This is RxJS v 4. [Find the latest version here](https://github.com/reactivex/rxjs)
# Observer object #
The Observer object provides support for push-style iteration over an observable sequence.
The Observer and Objects interfaces provide a generalized mechanism for push-based notification, also known as the observer design pattern. The Observable object represents the object that sends notifications (the provider); the Observer object represents the class that receives them (the observer).
<!-- div -->
## `Observer Methods`
- [`create`](#rxobservercreateonnext-onerror-oncompleted)
- [`fromNotifier`](#rxobserverfromotifierhandler)
## `Observer Instance Methods`
- [`asObserver`](#rxobserverprototypeasobserver)
- [`checked`](#rxobserverprototypechecked)
- [`notifyOn`](#rxobserverprototypenotifyonscheduler)
- [`onCompleted`](#rxobserverprototypeoncompleted)
- [`onError`](#rxobserverprototypeonerrorerror)
- [`onNext`](#rxobserverprototypeonnextvalue)
- [`toNotifier`](#rxobserverprototypetonotifier)
## _Observer Methods_ ##
### <a id="rxobservercreateonnext-onerror-oncompleted"></a>`Rx.Observer.create([onNext], [onError], [onCompleted])`
<a href="#rxobservercreateonnext-onerror-oncompleted">#</a> [Ⓢ](https://github.com/Reactive-Extensions/RxJS/blob/master/dist/rx.js#L1828-L1833 "View in source") [Ⓣ][1]
Creates an observer from the specified `onNext`, `onError`, and `onCompleted` actions.
#### Arguments
1. `[onNext]` *(Function)*: Observer's onNext action implementation.
2. `[onError]` *(Function)*: Observer's onError action implementation.
3. `[onCompleted]` *(Function)*: Observer's onCompleted action implementation.
#### Returns
*(Observer)*: The observer object implemented using the given actions.
#### Example
```js
var source = Rx.Observable.return(42);
var observer = Rx.Observer.create(
function (x) {
console.log('Next: ' + x);
},
function (err) {
console.log('Error: ' + err);
},
function () {
console.log('Completed');
}
);
var subscription = source.subscribe(observer);
// => Next: 42
// => Completed
```
### Location
- rx.js
* * *
### <a id="rxobserverfromotifierhandler"></a>`Rx.Observer.fromNotifier(handler, [thisArg])`
<a href="#rxobserverfromotifierhandler">#</a> [Ⓢ](https://github.com/Reactive-Extensions/RxJS/blob/master/dist/rx.js#L1843-L1851 "View in source") [Ⓣ][1]
Creates an observer from a notification callback.
#### Arguments
1. `handler` *(Function)*: Function that handles a notification.
2. `[thisArg]` *(`Any`)*: Object to use as `this` when executing `handler`.
#### Returns
*(Observer)*: The observer object that invokes the specified handler using a notification corresponding to each message it receives.
#### Example
```js
function handler(n) {
// Handle next calls
if (n.kind === 'N') {
console.log('Next: ' + n.value);
}
// Handle error calls
if (n.kind === 'E') {
console.log('Error: ' + n.exception);
}
// Handle completed
if (n.kind === 'C') {
console.log('Completed')
}
}
Rx.Observer.fromNotifier(handler).onNext(42);
// => Next: 42
Rx.Observer.fromNotifier(handler).onError(new Error('error!!!'));
// => Error: Error: error!!!
Rx.Observer.fromNotifier(handler).onCompleted();
// => false
```
### Location
- rx.js
* * *
## _Observer Instance Methods_ ##
### <a id="rxobserverprototypeasobserver"></a>`Rx.Observer.prototype.asObserver()`
<a href="#rxobserverprototypeasobserver">#</a> [Ⓢ](https://github.com/Reactive-Extensions/RxJS/blob/master/dist/rx.js#L1810-L1812 "View in source") [Ⓣ][1]
Hides the identity of an observer.
#### Returns
*(Observer)*: An observer that hides the identity of the specified observer.
#### Example
```js
function SampleObserver () {
Rx.Observer.call(this);
this.isStopped = false;
}
SampleObserver.prototype = Object.create(Rx.Observer.prototype);
SampleObserver.prototype.constructor = SampleObserver;
Object.defineProperties(SampleObserver.prototype, {
onNext: {
value: function (x) {
if (!this.isStopped) {
console.log('Next: ' + x);
}
}
},
onError: {
value: function (err) {
if (!this.isStopped) {
this.isStopped = true;
console.log('Error: ' + err);
}
}
},
onCompleted: {
value: function () {
if (!this.isStopped) {
this.isStopped = true;
console.log('Completed');
}
}
}
});
var sampleObserver = new SampleObserver();
var source = sampleObserver.asObserver();
console.log(source === sampleObserver);
// => false
```
### Location
- rx.js
* * *
### <a id="rxobserverprototypechecked"></a>`Rx.Observer.prototype.checked()`
<a href="#rxobserverprototypechecked">#</a> [Ⓢ](https://github.com/Reactive-Extensions/RxJS/blob/master/dist/rx.js#L1819 "View in source") [Ⓣ][1]
Checks access to the observer for grammar violations. This includes checking for multiple `onError` or `onCompleted` calls, as well as reentrancy in any of the observer methods.
If a violation is detected, an Error is thrown from the offending observer method call.
#### Returns
*(Observer)*: An observer that checks callbacks invocations against the observer grammar and, if the checks pass, forwards those to the specified observer.
#### Example
```js
var observer = Rx.Observer.create(
function (x) {
console.log('Next: ' + x)
},
function (err) {
console.log('Error: ' + err);
},
function () {
console.log('Completed');
}
);
var checked = observer.checked();
checked.onNext(42);
// => Next: 42
checked.onCompleted();
// => Completed
// Throws Error('Observer completed')
checked.onNext(42);
```
### Location
- rx.js
* * *
### <a id="rxobserverprototypenotifyonscheduler"></a>`Rx.Observer.prototype.notifyOn(scheduler)`
<a href="#rxobserverprototypenotifyonscheduler">#</a> [Ⓢ](https://github.com/Reactive-Extensions/RxJS/blob/master/dist/rx.js#L1858-1860 "View in source") [Ⓣ][1]
Schedules the invocation of observer methods on the given scheduler.
#### Arguments
1. `scheduler` *(Scheduler)*: Scheduler to schedule observer messages on.
#### Returns
*(Observer)*: Observer whose messages are scheduled on the given scheduler.
#### Example
```js
var observer = Rx.Observer.create(
function (x) {
console.log('Next: ' + x)
},
function (err) {
console.log('Error: ' + err);
},
function () {
console.log('Completed');
}
);
// Notify on timeout scheduler
var timeoutObserver = observer.notifyOn(Rx.Scheduler.timeout);
timeoutObserver.onNext(42);
// => Next: 42
```
### Location
- rx.js
* * *
### <a id="rxobserverprototypeoncompleted"></a>`Rx.Observer.prototype.onCompleted()`
<a href="#rxobserverprototypeoncompleted">#</a> [Ⓢ](https://github.com/Reactive-Extensions/RxJS/blob/master/dist/rx.js#L1899-L1904 "View in source") [Ⓣ][1]
Notifies the observer of the end of the sequence.
#### Example
```js
var observer = Rx.Observer.create(
function (x) {
console.log('Next: ' + x)
},
function (err) {
console.log('Error: ' + err);
},
function () {
console.log('Completed');
}
);
observer.onCompleted();
// => Completed
```
### Location
- rx.js
* * *
### <a id="rxobserverprototypeonerrorerror"></a>`Rx.Observer.prototype.onError(error)`
<a href="#rxobserverprototypeonerrorerror">#</a> [Ⓢ](https://github.com/Reactive-Extensions/RxJS/blob/master/dist/rx.js#L1889-L1894 "View in source") [Ⓣ][1]
Notifies the observer that an exception has occurred.
#### Arguments
1. `error` *(Any)*: The error that has occurred.
#### Example
```js
var observer = Rx.Observer.create(
function (x) {
console.log('Next: ' + x)
},
function (err) {
console.log('Error: ' + err);
},
function () {
console.log('Completed');
}
);
observer.onError(new Error('error!!'));
// => Error: Error: error!!
```
### Location
- rx.js
* * *
### <a id="rxobserverprototypeonnextvalue"></a>`Rx.Observer.prototype.onNext(value)`
<a href="#rxobserverprototypeonnextvalue">#</a> [Ⓢ](https://github.com/Reactive-Extensions/RxJS/blob/master/dist/rx.js#L1881-L1883 "View in source") [Ⓣ][1]
Notifies the observer of a new element in the sequence.
#### Arguments
1. `value` *(Any)*: Next element in the sequence.
#### Example
```js
var observer = Rx.Observer.create(
function (x) {
console.log('Next: ' + x)
},
function (err) {
console.log('Error: ' + err);
},
function () {
console.log('Completed');
}
);
observer.onNext(42);
// => Next: 42
```
### Location
- rx.js
* * *
### <a id="rxobserverprototypetonotifier"></a>`Rx.Observer.prototype.toNotifier()`
<a href="#rxobserverprototypetonotifier">#</a> [Ⓢ](https://github.com/Reactive-Extensions/RxJS/blob/master/dist/rx.js#L1801-L1804 "View in source") [Ⓣ][1]
Creates a notification callback from an observer.
#### Returns
*(Function)*: The function that forwards its input notification to the underlying observer.
#### Example
```js
var observer = Rx.Observer.create(
function (x) {
console.log('Next: ' + x)
},
function (err) {
console.log('Error: ' + err);
},
function () {
console.log('Completed');
}
);
var notifier = observer.toNotifier();
// Invoke with onNext
notifier(Rx.Notification.createOnNext(42));
// => Next: 42
// Invoke with onCompleted
notifier(Rx.Notification.createOnCompleted());
// => Completed
```
### Location
- rx.js
* * *
| {
"pile_set_name": "Github"
} |
@String { ICCV = {Intl. Conf. on Computer Vision (ICCV)} }
@String { IROS = {IEEE/RSJ Intl. Conf. on Intelligent Robots and Systems (IROS)} }
@String { CVPR = {IEEE Conf. on Computer Vision and Pattern Recognition (CVPR)} }
@String { IJRR = {Intl. J. of Robotics Research} }
@String { RAS = {Robotics and Autonomous Systems} }
@String { TRO = {{IEEE} Trans. Robotics} }
@String { IT = {{IEEE} Trans. Inform. Theory} }
@String { ISRR = {Proc. of the Intl. Symp. of Robotics Research (ISRR)} }
@inproceedings{Davison03iccv,
title = {Real-Time Simultaneous Localisation and Mapping with a Single Camera},
author = {A.J. Davison},
booktitle = ICCV,
year = {2003},
month = {Oct},
pages = {1403-1410}
}
@inproceedings{Dellaert10iros,
title = {Subgraph-preconditioned Conjugate Gradient for Large Scale SLAM},
author = {F. Dellaert and J. Carlson and V. Ila and K. Ni and C.E. Thorpe},
booktitle = IROS,
year = {2010},
}
@inproceedings{Dellaert99b,
title = {Using the Condensation Algorithm for Robust, Vision-based Mobile Robot Localization},
author = {F. Dellaert and D. Fox and W. Burgard and S. Thrun},
booktitle = CVPR,
year = {1999}
}
@article{Dellaert06ijrr,
title = {Square {Root} {SAM}: Simultaneous Localization and Mapping via Square Root Information Smoothing},
author = {F. Dellaert and M. Kaess},
journal = IJRR,
year = {2006},
month = {Dec},
number = {12},
pages = {1181--1203},
volume = {25},
}
@article{DurrantWhyte06ram,
title = {Simultaneous Localisation and Mapping ({SLAM}): Part {I} The Essential Algorithms},
author = {H.F. Durrant-Whyte and T. Bailey},
journal = {Robotics \& Automation Magazine},
year = {2006},
month = {Jun},
}
@inproceedings{Jian11iccv,
title = {Generalized Subgraph Preconditioners for Large-Scale Bundle Adjustment},
author = {Y.-D. Jian and D. Balcan and F. Dellaert},
booktitle = ICCV,
year = {2011},
}
@article{Kaess09ras,
title = {Covariance Recovery from a Square Root Information Matrix for Data Association},
author = {M. Kaess and F. Dellaert},
journal = RAS,
year = {2009},
}
@article{Kaess12ijrr,
title = {{iSAM2}: Incremental Smoothing and Mapping Using the {B}ayes Tree},
author = {M. Kaess and H. Johannsson and R. Roberts and V. Ila and J. Leonard and F. Dellaert},
journal = IJRR,
year = {2012},
month = {Feb},
pages = {217--236},
volume = {31},
issue = {2},
}
@article{Kaess08tro,
title = {{iSAM}: Incremental Smoothing and Mapping},
author = {M. Kaess and A. Ranganathan and F. Dellaert},
journal = TRO,
year = {2008},
month = {Dec},
number = {6},
pages = {1365-1378},
volume = {24},
}
@book{Koller09book,
title = {Probabilistic Graphical Models: Principles and Techniques},
author = {D. Koller and N. Friedman},
publisher = {The MIT Press},
year = {2009}
}
@Article{Kschischang01it,
title = {Factor Graphs and the Sum-Product Algorithm},
Author = {F.R. Kschischang and B.J. Frey and H-A. Loeliger},
Journal = IT,
Year = {2001},
Month = {February},
Number = {2},
Volume = {47}
}
@article{Loeliger04spm,
Title = {An Introduction to Factor Graphs},
Author = {H.-A. Loeliger},
Journal = {IEEE Signal Processing Magazine},
Year = {2004},
Month = {January},
Pages = {28--41}
}
@inproceedings{Nister04cvpr2,
title = {Visual Odometry},
author = {D. Nist\'er and O. Naroditsky and J. Bergen},
booktitle = CVPR,
year = {2004},
month = {Jun},
pages = {652-659},
volume = {1}
}
@InProceedings{Smith87b,
title = {A stochastic map for uncertain spatial relationships},
Author = {R. Smith and M. Self and P. Cheeseman},
Booktitle = ISRR,
Year = {1988},
Pages = {467-474}
}
| {
"pile_set_name": "Github"
} |
// Copyright 2016 CoreOS, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package natsort
import (
"sort"
)
// Less determines if a naturally comes before b. Unlike Compare it will
// fall back to a normal string comparison which considers spaces if the
// two would otherwise be equal. That helps ensure the stability of sorts.
func Less(a, b string) bool {
if r := Compare(a, b); r == 0 {
return a < b
} else {
return r < 0
}
}
// Strings natural sorts a slice of strings.
func Strings(s []string) {
sort.Slice(s, func(i, j int) bool {
return Less(s[i], s[j])
})
}
// StringsAreSorted tests whether a slice of strings is natural sorted.
func StringsAreSorted(s []string) bool {
return sort.SliceIsSorted(s, func(i, j int) bool {
return Less(s[i], s[j])
})
}
| {
"pile_set_name": "Github"
} |
<!-- YAML
added: v0.3.2
-->
* `callback` {Function} A listener callback that will be registered to listen
for the server instance's `'close'` event.
* Returns: {tls.Server}
The `server.close()` method stops the server from accepting new connections.
This function operates asynchronously. The `'close'` event will be emitted
when the server has no more open connections.
| {
"pile_set_name": "Github"
} |
package pflag
import (
"fmt"
"net"
"os"
"testing"
)
func setUpIP(ip *net.IP) *FlagSet {
f := NewFlagSet("test", ContinueOnError)
f.IPVar(ip, "address", net.ParseIP("0.0.0.0"), "IP Address")
return f
}
func TestIP(t *testing.T) {
testCases := []struct {
input string
success bool
expected string
}{
{"0.0.0.0", true, "0.0.0.0"},
{" 0.0.0.0 ", true, "0.0.0.0"},
{"1.2.3.4", true, "1.2.3.4"},
{"127.0.0.1", true, "127.0.0.1"},
{"255.255.255.255", true, "255.255.255.255"},
{"", false, ""},
{"0", false, ""},
{"localhost", false, ""},
{"0.0.0", false, ""},
{"0.0.0.", false, ""},
{"0.0.0.0.", false, ""},
{"0.0.0.256", false, ""},
{"0 . 0 . 0 . 0", false, ""},
}
devnull, _ := os.Open(os.DevNull)
os.Stderr = devnull
for i := range testCases {
var addr net.IP
f := setUpIP(&addr)
tc := &testCases[i]
arg := fmt.Sprintf("--address=%s", tc.input)
err := f.Parse([]string{arg})
if err != nil && tc.success == true {
t.Errorf("expected success, got %q", err)
continue
} else if err == nil && tc.success == false {
t.Errorf("expected failure")
continue
} else if tc.success {
ip, err := f.GetIP("address")
if err != nil {
t.Errorf("Got error trying to fetch the IP flag: %v", err)
}
if ip.String() != tc.expected {
t.Errorf("expected %q, got %q", tc.expected, ip.String())
}
}
}
}
| {
"pile_set_name": "Github"
} |
// Author:
// Created: 2012-09-23
// Last Modified: 2012-09-23
//
// The use and distribution terms for this software are covered by the
// Common Public License 1.0 (http://opensource.org/licenses/cpl.php)
// which can be found in the file CPL.TXT at the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by
// the terms of this license.
//
// You must not remove this notice, or any other, from this software.
using System;
using System.Configuration;
using System.IO;
using System.Web;
using System.Web.Caching;
using System.Xml;
using log4net;
namespace mojoPortal.Web.Commerce
{
public class WorldPayResponseHandlerProviderConfig
{
private static readonly ILog log
= LogManager.GetLogger(typeof(WorldPayResponseHandlerProviderConfig));
private ProviderSettingsCollection providerSettingsCollection
= new ProviderSettingsCollection();
public ProviderSettingsCollection Providers
{
get { return providerSettingsCollection; }
}
public static WorldPayResponseHandlerProviderConfig GetConfig()
{
try
{
if (
(HttpRuntime.Cache["WorldPayResponseHandlerProviderConfig"] != null)
&& (HttpRuntime.Cache["WorldPayResponseHandlerProviderConfig"] is WorldPayResponseHandlerProviderConfig)
)
{
return (WorldPayResponseHandlerProviderConfig)HttpRuntime.Cache["WorldPayResponseHandlerProviderConfig"];
}
WorldPayResponseHandlerProviderConfig config
= new WorldPayResponseHandlerProviderConfig();
String configFolderName = "~/Setup/ProviderConfig/worldpayresponsehandlers/";
string pathToConfigFolder
= HttpContext.Current.Server.MapPath(configFolderName);
if (!Directory.Exists(pathToConfigFolder)) return config;
DirectoryInfo directoryInfo
= new DirectoryInfo(pathToConfigFolder);
FileInfo[] configFiles = directoryInfo.GetFiles("*.config");
foreach (FileInfo fileInfo in configFiles)
{
XmlDocument configXml = new XmlDocument();
configXml.Load(fileInfo.FullName);
config.LoadValuesFromConfigurationXml(configXml.DocumentElement);
}
AggregateCacheDependency aggregateCacheDependency
= new AggregateCacheDependency();
string pathToWebConfig
= HttpContext.Current.Server.MapPath("~/Web.config");
aggregateCacheDependency.Add(new CacheDependency(pathToWebConfig));
System.Web.HttpRuntime.Cache.Insert(
"WorldPayResponseHandlerProviderConfig",
config,
aggregateCacheDependency,
DateTime.Now.AddYears(1),
TimeSpan.Zero,
System.Web.Caching.CacheItemPriority.Default,
null);
return (WorldPayResponseHandlerProviderConfig)HttpRuntime.Cache["WorldPayResponseHandlerProviderConfig"];
}
catch (HttpException ex)
{
log.Error(ex);
}
catch (System.Xml.XmlException ex)
{
log.Error(ex);
}
catch (ArgumentException ex)
{
log.Error(ex);
}
catch (NullReferenceException ex)
{
log.Error(ex);
}
return null;
}
public void LoadValuesFromConfigurationXml(XmlNode node)
{
foreach (XmlNode child in node.ChildNodes)
{
if (child.Name == "providers")
{
foreach (XmlNode providerNode in child.ChildNodes)
{
if (
(providerNode.NodeType == XmlNodeType.Element)
&& (providerNode.Name == "add")
)
{
if (
(providerNode.Attributes["name"] != null)
&& (providerNode.Attributes["type"] != null)
)
{
ProviderSettings providerSettings
= new ProviderSettings(
providerNode.Attributes["name"].Value,
providerNode.Attributes["type"].Value);
providerSettingsCollection.Add(providerSettings);
}
}
}
}
}
}
}
} | {
"pile_set_name": "Github"
} |
using Windows.UI.Xaml.Controls;
namespace AppStudio.Uwp.Samples
{
public sealed partial class CarouselHelp : UserControl
{
public CarouselHelp()
{
this.InitializeComponent();
}
}
}
| {
"pile_set_name": "Github"
} |
pragma solidity ^0.4.21;
import './OwnedUpgradeabilityProxy.sol';
/**
* @title UpgradeabilityProxyFactory
* @dev This contracts provides required functionality to create upgradeability proxies
*/
contract UpgradeabilityProxyFactory {
/**
* @dev Constructor function
*/
function UpgradeabilityProxyFactory() public {}
/**
* @dev This event will be emitted every time a new proxy is created
* @param proxy representing the address of the proxy created
*/
event ProxyCreated(address proxy);
/**
* @dev Creates an upgradeability proxy upgraded to an initial version
* @param owner representing the owner of the proxy to be set
* @param implementation representing the address of the initial implementation to be set
* @return address of the new proxy created
*/
function createProxy(address owner, address implementation) public returns (OwnedUpgradeabilityProxy) {
OwnedUpgradeabilityProxy proxy = _createProxy();
proxy.upgradeTo(implementation);
proxy.transferProxyOwnership(owner);
return proxy;
}
/**
* @dev Creates an upgradeability proxy upgraded to an initial version and call the new implementation
* @param owner representing the owner of the proxy to be set
* @param implementation representing the address of the initial implementation to be set
* @param data represents the msg.data to bet sent in the low level call. This parameter may include the function
* signature of the implementation to be called with the needed payload
* @return address of the new proxy created
*/
function createProxyAndCall(address owner, address implementation, bytes data) public payable returns (OwnedUpgradeabilityProxy) {
OwnedUpgradeabilityProxy proxy = _createProxy();
proxy.upgradeToAndCall.value(msg.value)(implementation, data);
proxy.transferProxyOwnership(owner);
return proxy;
}
/**
* @dev Internal function to create an upgradeable proxy
* @return address of the new proxy created
*/
function _createProxy() internal returns (OwnedUpgradeabilityProxy) {
OwnedUpgradeabilityProxy proxy = new OwnedUpgradeabilityProxy();
emit ProxyCreated(proxy);
return proxy;
}
}
| {
"pile_set_name": "Github"
} |
/*
*COPYRIGHT
*All modification made by Intel Corporation: © 2018 Intel Corporation.
*Copyright (c) 2015 Preferred Infrastructure, Inc.
*Copyright (c) 2015 Preferred Networks, Inc.
*
*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.
*
*/
#pragma once
#include <Python.h>
#include "mdarray.h"
#include "TR_interface.h"
#include "tensor.hpp"
//using tensor = ideep::tensor;
class distribute {
public:
//using tensor = ideep::tensor;
using data_type_t = mkldnn::memory::data_type;
enum tr_urgency {
tr_need = TR_NEED,
tr_greedy = TR_GREEDY
};
enum tr_error_code {
tr_success,
tr_fail,
tr_type_not_supported
};
// return value:
// true - multinode support is enabled in ideep
// false - no multinode support in ideep
static bool available() {
return TR_available();
}
// call once before using distribute collectives
// any distribute collective must be called AFTER this call returns
static void init() {
TR_init(-1);
}
// same as above, but set affinity of work thread to affinity
static void init(int affinity) {
assert (affinity >= 0);
TR_init(affinity);
}
// get number of nodes
static int get_world_size() {
return TR_get_world_size();
}
// get a unique rank of current node, rank is from 0 to number-of-nodes - 1
static int get_rank() {
return TR_get_rank();
}
/*
allreduce interface families
variants are:
with/without id
inplace/non-inplace
*/
// blocking allreduce add send_recv_buf together elementwisely across
// different nodes with same id
// id must >= 0, ids smaller than 0 are reserved
static tr_error_code allreduce(int id, mdarray *send_recv_buf) {
assert (id >= 0);
return _allreduce(id, send_recv_buf, send_recv_buf);
}
// same as above, result is written in recv_buf
static tr_error_code allreduce(int id, mdarray *send_buf, mdarray *recv_buf) {
assert (id >= 0);
return _allreduce(id, send_buf, recv_buf);
}
/* without id */
// when not supplying id, caller should gurantee call sequence have same order between all nodes
// note: you can still use out-of-order call sequence for all call with id
static tr_error_code allreduce(mdarray *send_recv_buf) {
int id = _get_new_implicit_id();
return _allreduce(id, send_recv_buf, send_recv_buf);
}
static tr_error_code allreduce(mdarray *send_buf, mdarray *recv_buf) {
int id = _get_new_implicit_id();
return _allreduce(id, send_buf, recv_buf);
}
/*
iallreduce interface families
variants are:
with/without id
inpace/non-inpace
with/without callback
*/
// non-blocking iallreduce add send_recv_buf together elementwisely across
// different nodes with same id
static tr_error_code iallreduce(int id, mdarray *send_recv_buf) {
assert (id >= 0);
return _iallreduce(id, send_recv_buf, send_recv_buf);
}
// same as above, a python callback function is supplied to be called
// when iallreduce is done. The callback is always initiated from
// a thread managed by distributed module. callback implementation is
// responsible for thread safety
static tr_error_code iallreduce(int id, mdarray *send_recv_buf, PyObject *callback) {
assert (id >= 0);
return _iallreduce(id, send_recv_buf, send_recv_buf, callback);
}
// same as above, the result is written in recv_buf
static tr_error_code iallreduce(int id, mdarray *send_buf, mdarray *recv_buf) {
assert (id >= 0);
return _iallreduce(id, send_buf, recv_buf);
}
// same as above with callback
static tr_error_code iallreduce(int id, mdarray *send_buf, mdarray *recv_buf, PyObject *callback) {
assert (id >= 0);
return _iallreduce(id, send_buf, recv_buf, callback);
}
/* without id */
static PyObject *iallreduce(mdarray *send_recv_buf) {
int id = _get_new_implicit_id();
tr_error_code err = _iallreduce(id, send_recv_buf, send_recv_buf);
return Py_BuildValue("ii", id, err);
}
static PyObject *iallreduce(mdarray *send_recv_buf, PyObject *callback) {
int id = _get_new_implicit_id();
tr_error_code err = _iallreduce(id, send_recv_buf, send_recv_buf, callback);
return Py_BuildValue("ii", id, err);
}
static PyObject *iallreduce(mdarray *send_buf, mdarray *recv_buf) {
int id = _get_new_implicit_id();
tr_error_code err = _iallreduce(id, send_buf, recv_buf);
return Py_BuildValue("ii", id, err);
}
static PyObject *iallreduce(mdarray *send_buf, mdarray *recv_buf, PyObject *callback) {
int id = _get_new_implicit_id();
tr_error_code err = _iallreduce(id, send_buf, recv_buf, callback);
return Py_BuildValue("ii", id, err);
}
/*
bcast
*/
// blocking broadcast buf from root node to other nodes
static tr_error_code bcast(int id, mdarray *buf, int root) {
assert (id >= 0);
return _bcast(id, buf, root);
}
/* without id */
static tr_error_code bcast(mdarray *buf, int root) {
int id = _get_new_implicit_id();
return _bcast(id, buf, root);
}
// wait for ID to finish
static void wait(int id) {
TR_wait(id);
}
// check whether collective with id is finished or not
// if urgency is tr_greedy, the check is opportunistic
// if urgency is tr_need, caller is indicating the collective is blocking
// other on going activities
static bool test(int id, tr_urgency urgency) {
TR_urgency u = TR_GREEDY;
switch (urgency) {
case tr_need: u = TR_NEED; break;
case tr_greedy: u = TR_GREEDY; break;
default: assert (!"should not get here");
}
return TR_test(id, u);
}
static bool test(int id) {
return TR_test(id, TR_GREEDY);
}
// indicating collective is blocking on going activities
static void set_urgent(int id) {
TR_set_urgent(id);
}
// wait for all collective to finish before return
static void barrier() {
TR_barrier();
}
// release all the resources for communication
static void finalize() {
TR_finalize();
}
private:
static void _callback(int id) {
//PyGILState_STATE state = PyGILState_Ensure();
PyObject *cb = distribute::_cb_map[id];
PyObject_CallFunction(cb, "i", id);
Py_DECREF(distribute::_cb_map[id]);
distribute::_cb_map[id]=NULL;
//PyGILState_Release(state);
}
static std::unordered_map<int, PyObject *> _cb_map;
static tr_error_code _allreduce(int id, mdarray *send_buf, mdarray *recv_buf) {
if (send_buf->get()->get_nelems() != recv_buf->get()->get_nelems()) {
return tr_fail;
}
if (send_buf->get()->get_data_type() != recv_buf->get()->get_data_type()) {
return tr_fail;
}
TR_datatype datatype;
switch (send_buf->get()->get_data_type()) {
case data_type_t::f32:
datatype = TR_FP32;
break;
case data_type_t::s32:
datatype = TR_INT32;
break;
default:
return tr_type_not_supported;
}
size_t num_elements = send_buf->get()->get_nelems();
TR_allreduce(id, 0, send_buf==recv_buf?TR_IN_PLACE:send_buf->get()->get_data_handle(),
recv_buf->get()->get_data_handle(), num_elements, datatype);
return tr_success;
}
static tr_error_code _iallreduce(int id, mdarray *send_buf, mdarray *recv_buf)
{
if (send_buf->get()->get_nelems() != recv_buf->get()->get_nelems()) {
return tr_fail;
}
if (send_buf->get()->get_data_type() != recv_buf->get()->get_data_type()) {
return tr_fail;
}
TR_datatype datatype;
switch (send_buf->get()->get_data_type()) {
case data_type_t::f32:
datatype = TR_FP32;
break;
case data_type_t::s32:
datatype = TR_INT32;
break;
default:
return tr_type_not_supported;
}
size_t num_elements = send_buf->get()->get_nelems();
TR_iallreduce(id, 0, send_buf==recv_buf?TR_IN_PLACE:send_buf->get()->get_data_handle(),
recv_buf->get()->get_data_handle(), num_elements, datatype, NULL);
return tr_success;
}
static tr_error_code _iallreduce(int id, mdarray *send_buf, mdarray *recv_buf, PyObject *callback)
{
if (send_buf->get()->get_nelems() != recv_buf->get()->get_nelems()) {
return tr_fail;
}
if (send_buf->get()->get_data_type() != recv_buf->get()->get_data_type()) {
return tr_fail;
}
TR_datatype datatype;
switch (send_buf->get()->get_data_type()) {
case data_type_t::f32:
datatype = TR_FP32;
break;
case data_type_t::s32:
datatype = TR_INT32;
break;
default:
return tr_type_not_supported;
}
size_t num_elements = send_buf->get()->get_nelems();
if (!PyCallable_Check(callback)) {
std::cerr << "Must pass a callable.";
}
distribute::_cb_map[id] = callback;
Py_XINCREF(callback);
TR_iallreduce(id, 0, send_buf==recv_buf?TR_IN_PLACE:send_buf->get()->get_data_handle(),
recv_buf->get()->get_data_handle(), num_elements, datatype, _callback);
return tr_success;
}
static tr_error_code _bcast(int id, mdarray *buf, int root) {
TR_datatype datatype;
switch (buf->get()->get_data_type()) {
case data_type_t::f32:
datatype = TR_FP32;
break;
case data_type_t::s32:
datatype = TR_INT32;
break;
default:
return tr_type_not_supported;
}
size_t num_elements = buf->get()->get_nelems();
TR_bcast(id, 0, buf->get()->get_data_handle(), num_elements, datatype, root);
return tr_success;
}
static int _get_new_implicit_id(void) {
// implicity id is negative and start from -2, then goes like -3, -4, -5, etc.
// -1 is reserved for internal purpose
static int implicit_id = -2;
assert (implicit_id < 0);
int ret_val = implicit_id;
implicit_id--;
return ret_val;
}
};
std::unordered_map<int, PyObject *> distribute::_cb_map;
| {
"pile_set_name": "Github"
} |
fileFormatVersion: 2
guid: e32d436e2981ea148abafc38e814d367
NativeFormatImporter:
externalObjects: {}
mainObjectFileID: 11400000
userData:
assetBundleName:
assetBundleVariant:
| {
"pile_set_name": "Github"
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<HTML style="overflow:auto;">
<HEAD>
<meta name="generator" content="JDiff v1.1.0">
<!-- Generated by the JDiff Javadoc doclet -->
<!-- (http://www.jdiff.org) -->
<meta name="description" content="JDiff is a Javadoc doclet which generates an HTML report of all the packages, classes, constructors, methods, and fields which have been removed, added or changed in any way, including their documentation, when two APIs are compared.">
<meta name="keywords" content="diff, jdiff, javadiff, java diff, java difference, API difference, difference between two APIs, API diff, Javadoc, doclet">
<TITLE>
android.support.v4.view.MenuItemCompat
</TITLE>
<link href="../../../../assets/android-developer-docs.css" rel="stylesheet" type="text/css" />
<link href="../stylesheet-jdiff.css" rel="stylesheet" type="text/css" />
<noscript>
<style type="text/css">
body{overflow:auto;}
#body-content{position:relative; top:0;}
#doc-content{overflow:visible;border-left:3px solid #666;}
#side-nav{padding:0;}
#side-nav .toggle-list ul {display:block;}
#resize-packages-nav{border-bottom:3px solid #666;}
</style>
</noscript>
<style type="text/css">
</style>
</HEAD>
<BODY>
<!-- Start of nav bar -->
<a name="top"></a>
<div id="header" style="margin-bottom:0;padding-bottom:0;">
<div id="headerLeft">
<a href="../../../../index.html" tabindex="-1" target="_top"><img src="../../../../assets/images/bg_logo.png" alt="Android Developers" /></a>
</div>
<div id="headerRight">
<div id="headerLinks">
<!-- <img src="/assets/images/icon_world.jpg" alt="" /> -->
<span class="text">
<!-- <a href="#">English</a> | -->
<nobr><a href="http://developer.android.com" target="_top">Android Developers</a> | <a href="http://www.android.com" target="_top">Android.com</a></nobr>
</span>
</div>
<div class="and-diff-id" style="margin-top:6px;margin-right:8px;">
<table class="diffspectable">
<tr>
<td colspan="2" class="diffspechead">API Diff Specification</td>
</tr>
<tr>
<td class="diffspec" style="padding-top:.25em">To Level:</td>
<td class="diffvaluenew" style="padding-top:.25em">23.2.0</td>
</tr>
<tr>
<td class="diffspec">From Level:</td>
<td class="diffvalueold">23.1.1</td>
</tr>
<tr>
<td class="diffspec">Generated</td>
<td class="diffvalue">2016.02.23 13:25</td>
</tr>
</table>
</div><!-- End and-diff-id -->
<div class="and-diff-id" style="margin-right:8px;">
<table class="diffspectable">
<tr>
<td class="diffspec" colspan="2"><a href="jdiff_statistics.html">Statistics</a>
</tr>
</table>
</div> <!-- End and-diff-id -->
</div> <!-- End headerRight -->
</div> <!-- End header -->
<div id="body-content" xstyle="padding:12px;padding-right:18px;">
<div id="doc-content" style="position:relative;">
<div id="mainBodyFluid">
<H2>
Class android.support.v4.view.<A HREF="../../../../reference/android/support/v4/view/MenuItemCompat.html" target="_top"><font size="+2"><code>MenuItemCompat</code></font></A>
</H2>
<p>Change from non-final to final.<br>
<a NAME="constructors"></a>
<p>
<a NAME="Removed"></a>
<TABLE summary="Removed Constructors" WIDTH="100%">
<TR>
<TH VALIGN="TOP" COLSPAN=2>Removed Constructors</FONT></TD>
</TH>
<TR BGCOLOR="#FFFFFF" CLASS="TableRowColor">
<TD VALIGN="TOP" WIDTH="25%">
<A NAME="android.support.v4.view.MenuItemCompat.ctor_removed()"></A>
<nobr>MenuItemCompat()</nobr>
</TD>
<TD> </TD>
</TR>
</TABLE>
<a NAME="methods"></a>
<a NAME="fields"></a>
</div>
<div id="footer">
<div id="copyright">
Except as noted, this content is licensed under
<a href="http://creativecommons.org/licenses/by/2.5/"> Creative Commons Attribution 2.5</a>.
For details and restrictions, see the <a href="/license.html">Content License</a>.
</div>
<div id="footerlinks">
<p>
<a href="http://www.android.com/terms.html">Site Terms of Service</a> -
<a href="http://www.android.com/privacy.html">Privacy Policy</a> -
<a href="http://www.android.com/branding.html">Brand Guidelines</a>
</p>
</div>
</div> <!-- end footer -->
</div><!-- end doc-content -->
</div> <!-- end body-content -->
<script src="https://www.google-analytics.com/ga.js" type="text/javascript">
</script>
<script type="text/javascript">
try {
var pageTracker = _gat._getTracker("UA-5831155-1");
pageTracker._setAllowAnchor(true);
pageTracker._initData();
pageTracker._trackPageview();
} catch(e) {}
</script>
</BODY>
</HTML>
| {
"pile_set_name": "Github"
} |
Current cluster status:
Online: [ node1 node2 ]
rsc_stonith (stonith:null): Started node1
rsc1 (ocf::pacemaker:Dummy): Stopped
Transition Summary:
Executing cluster transition:
* Resource action: rsc1 monitor on node2
* Resource action: rsc1 monitor on node1
Revised cluster status:
Online: [ node1 node2 ]
rsc_stonith (stonith:null): Started node1
rsc1 (ocf::pacemaker:Dummy): Stopped
| {
"pile_set_name": "Github"
} |
file(GLOB files RELATIVE ${INPUT_PATH} "${INPUT_PATH}/*")
file(GLOB excluded_files RELATIVE ${INPUT_PATH} "${INPUT_PATH}/.*")
foreach(excluded_file ${excluded_files})
list(REMOVE_ITEM files ${excluded_file})
endforeach()
execute_process(
COMMAND ${CMAKE_COMMAND} -E remove ${OUTPUT_FILE}
COMMAND ${CMAKE_COMMAND} -E tar cfz ${OUTPUT_FILE} ${files}
WORKING_DIRECTORY ${INPUT_PATH}
RESULT_VARIABLE result
ERROR_VARIABLE err
)
if(result)
message(FATAL_ERROR "Failed to create tarball: ${result}\n${err}")
endif()
| {
"pile_set_name": "Github"
} |
var proto = Promise.prototype;
var hasOwn = Object.prototype.hasOwnProperty;
proto.done = function (onFulfilled, onRejected) {
var self = this;
if (arguments.length > 0) {
self = this.then.apply(this, arguments);
}
self.then(null, function (err) {
Meteor._setImmediate(function () {
throw err;
});
});
};
if (! hasOwn.call(proto, "finally")) {
proto["finally"] = function (onFinally) {
var threw = false, result;
return this.then(function (value) {
result = value;
// Most implementations of Promise.prototype.finally call
// Promise.resolve(onFinally()) (or this.constructor.resolve or even
// this.constructor[Symbol.species].resolve, depending on how spec
// compliant they're trying to be), but this implementation simply
// relies on the standard Promise behavior of resolving any value
// returned from a .then callback function.
return onFinally();
}, function (error) {
// Make the final .then callback (below) re-throw the error instead
// of returning it.
threw = true;
result = error;
return onFinally();
}).then(function () {
if (threw) throw result;
return result;
});
};
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.content;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.Log;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* This class is used to store a set of values that the {@link ContentResolver}
* can process.
*/
public final class ContentValues implements Parcelable {
public static final String TAG = "ContentValues";
/** Holds the actual values */
private HashMap<String, Object> mValues;
/**
* Creates an empty set of values using the default initial size
*/
public ContentValues() {
// Choosing a default size of 8 based on analysis of typical
// consumption by applications.
mValues = new HashMap<String, Object>(8);
}
/**
* Creates an empty set of values using the given initial size
*
* @param size the initial size of the set of values
*/
public ContentValues(int size) {
mValues = new HashMap<String, Object>(size, 1.0f);
}
/**
* Creates a set of values copied from the given set
*
* @param from the values to copy
*/
public ContentValues(ContentValues from) {
mValues = new HashMap<String, Object>(from.mValues);
}
/**
* Creates a set of values copied from the given HashMap. This is used
* by the Parcel unmarshalling code.
*
* @param values the values to start with
* {@hide}
*/
private ContentValues(HashMap<String, Object> values) {
mValues = values;
}
@Override
public boolean equals(Object object) {
if (!(object instanceof ContentValues)) {
return false;
}
return mValues.equals(((ContentValues) object).mValues);
}
@Override
public int hashCode() {
return mValues.hashCode();
}
/**
* Adds a value to the set.
*
* @param key the name of the value to put
* @param value the data for the value to put
*/
public void put(String key, String value) {
mValues.put(key, value);
}
/**
* Adds all values from the passed in ContentValues.
*
* @param other the ContentValues from which to copy
*/
public void putAll(ContentValues other) {
mValues.putAll(other.mValues);
}
/**
* Adds a value to the set.
*
* @param key the name of the value to put
* @param value the data for the value to put
*/
public void put(String key, Byte value) {
mValues.put(key, value);
}
/**
* Adds a value to the set.
*
* @param key the name of the value to put
* @param value the data for the value to put
*/
public void put(String key, Short value) {
mValues.put(key, value);
}
/**
* Adds a value to the set.
*
* @param key the name of the value to put
* @param value the data for the value to put
*/
public void put(String key, Integer value) {
mValues.put(key, value);
}
/**
* Adds a value to the set.
*
* @param key the name of the value to put
* @param value the data for the value to put
*/
public void put(String key, Long value) {
mValues.put(key, value);
}
/**
* Adds a value to the set.
*
* @param key the name of the value to put
* @param value the data for the value to put
*/
public void put(String key, Float value) {
mValues.put(key, value);
}
/**
* Adds a value to the set.
*
* @param key the name of the value to put
* @param value the data for the value to put
*/
public void put(String key, Double value) {
mValues.put(key, value);
}
/**
* Adds a value to the set.
*
* @param key the name of the value to put
* @param value the data for the value to put
*/
public void put(String key, Boolean value) {
mValues.put(key, value);
}
/**
* Adds a value to the set.
*
* @param key the name of the value to put
* @param value the data for the value to put
*/
public void put(String key, byte[] value) {
mValues.put(key, value);
}
/**
* Adds a null value to the set.
*
* @param key the name of the value to make null
*/
public void putNull(String key) {
mValues.put(key, null);
}
/**
* Returns the number of values.
*
* @return the number of values
*/
public int size() {
return mValues.size();
}
/**
* Remove a single value.
*
* @param key the name of the value to remove
*/
public void remove(String key) {
mValues.remove(key);
}
/**
* Removes all values.
*/
public void clear() {
mValues.clear();
}
/**
* Returns true if this object has the named value.
*
* @param key the value to check for
* @return {@code true} if the value is present, {@code false} otherwise
*/
public boolean containsKey(String key) {
return mValues.containsKey(key);
}
/**
* Gets a value. Valid value types are {@link String}, {@link Boolean}, and
* {@link Number} implementations.
*
* @param key the value to get
* @return the data for the value
*/
public Object get(String key) {
return mValues.get(key);
}
/**
* Gets a value and converts it to a String.
*
* @param key the value to get
* @return the String for the value
*/
public String getAsString(String key) {
Object value = mValues.get(key);
return value != null ? value.toString() : null;
}
/**
* Gets a value and converts it to a Long.
*
* @param key the value to get
* @return the Long value, or null if the value is missing or cannot be converted
*/
public Long getAsLong(String key) {
Object value = mValues.get(key);
try {
return value != null ? ((Number) value).longValue() : null;
} catch (ClassCastException e) {
if (value instanceof CharSequence) {
try {
return Long.valueOf(value.toString());
} catch (NumberFormatException e2) {
Log.e(TAG, "Cannot parse Long value for " + value + " at key " + key);
return null;
}
} else {
Log.e(TAG, "Cannot cast value for " + key + " to a Long: " + value, e);
return null;
}
}
}
/**
* Gets a value and converts it to an Integer.
*
* @param key the value to get
* @return the Integer value, or null if the value is missing or cannot be converted
*/
public Integer getAsInteger(String key) {
Object value = mValues.get(key);
try {
return value != null ? ((Number) value).intValue() : null;
} catch (ClassCastException e) {
if (value instanceof CharSequence) {
try {
return Integer.valueOf(value.toString());
} catch (NumberFormatException e2) {
Log.e(TAG, "Cannot parse Integer value for " + value + " at key " + key);
return null;
}
} else {
Log.e(TAG, "Cannot cast value for " + key + " to a Integer: " + value, e);
return null;
}
}
}
/**
* Gets a value and converts it to a Short.
*
* @param key the value to get
* @return the Short value, or null if the value is missing or cannot be converted
*/
public Short getAsShort(String key) {
Object value = mValues.get(key);
try {
return value != null ? ((Number) value).shortValue() : null;
} catch (ClassCastException e) {
if (value instanceof CharSequence) {
try {
return Short.valueOf(value.toString());
} catch (NumberFormatException e2) {
Log.e(TAG, "Cannot parse Short value for " + value + " at key " + key);
return null;
}
} else {
Log.e(TAG, "Cannot cast value for " + key + " to a Short: " + value, e);
return null;
}
}
}
/**
* Gets a value and converts it to a Byte.
*
* @param key the value to get
* @return the Byte value, or null if the value is missing or cannot be converted
*/
public Byte getAsByte(String key) {
Object value = mValues.get(key);
try {
return value != null ? ((Number) value).byteValue() : null;
} catch (ClassCastException e) {
if (value instanceof CharSequence) {
try {
return Byte.valueOf(value.toString());
} catch (NumberFormatException e2) {
Log.e(TAG, "Cannot parse Byte value for " + value + " at key " + key);
return null;
}
} else {
Log.e(TAG, "Cannot cast value for " + key + " to a Byte: " + value, e);
return null;
}
}
}
/**
* Gets a value and converts it to a Double.
*
* @param key the value to get
* @return the Double value, or null if the value is missing or cannot be converted
*/
public Double getAsDouble(String key) {
Object value = mValues.get(key);
try {
return value != null ? ((Number) value).doubleValue() : null;
} catch (ClassCastException e) {
if (value instanceof CharSequence) {
try {
return Double.valueOf(value.toString());
} catch (NumberFormatException e2) {
Log.e(TAG, "Cannot parse Double value for " + value + " at key " + key);
return null;
}
} else {
Log.e(TAG, "Cannot cast value for " + key + " to a Double: " + value, e);
return null;
}
}
}
/**
* Gets a value and converts it to a Float.
*
* @param key the value to get
* @return the Float value, or null if the value is missing or cannot be converted
*/
public Float getAsFloat(String key) {
Object value = mValues.get(key);
try {
return value != null ? ((Number) value).floatValue() : null;
} catch (ClassCastException e) {
if (value instanceof CharSequence) {
try {
return Float.valueOf(value.toString());
} catch (NumberFormatException e2) {
Log.e(TAG, "Cannot parse Float value for " + value + " at key " + key);
return null;
}
} else {
Log.e(TAG, "Cannot cast value for " + key + " to a Float: " + value, e);
return null;
}
}
}
/**
* Gets a value and converts it to a Boolean.
*
* @param key the value to get
* @return the Boolean value, or null if the value is missing or cannot be converted
*/
public Boolean getAsBoolean(String key) {
Object value = mValues.get(key);
try {
return (Boolean) value;
} catch (ClassCastException e) {
if (value instanceof CharSequence) {
return Boolean.valueOf(value.toString());
} else if (value instanceof Number) {
return ((Number) value).intValue() != 0;
} else {
Log.e(TAG, "Cannot cast value for " + key + " to a Boolean: " + value, e);
return null;
}
}
}
/**
* Gets a value that is a byte array. Note that this method will not convert
* any other types to byte arrays.
*
* @param key the value to get
* @return the byte[] value, or null is the value is missing or not a byte[]
*/
public byte[] getAsByteArray(String key) {
Object value = mValues.get(key);
if (value instanceof byte[]) {
return (byte[]) value;
} else {
return null;
}
}
/**
* Returns a set of all of the keys and values
*
* @return a set of all of the keys and values
*/
public Set<Map.Entry<String, Object>> valueSet() {
return mValues.entrySet();
}
/**
* Returns a set of all of the keys
*
* @return a set of all of the keys
*/
public Set<String> keySet() {
return mValues.keySet();
}
public static final Parcelable.Creator<ContentValues> CREATOR =
new Parcelable.Creator<ContentValues>() {
@SuppressWarnings({"deprecation", "unchecked"})
public ContentValues createFromParcel(Parcel in) {
// TODO - what ClassLoader should be passed to readHashMap?
HashMap<String, Object> values = in.readHashMap(null);
return new ContentValues(values);
}
public ContentValues[] newArray(int size) {
return new ContentValues[size];
}
};
public int describeContents() {
return 0;
}
@SuppressWarnings("deprecation")
public void writeToParcel(Parcel parcel, int flags) {
parcel.writeMap(mValues);
}
/**
* Unsupported, here until we get proper bulk insert APIs.
* {@hide}
*/
@Deprecated
public void putStringArrayList(String key, ArrayList<String> value) {
mValues.put(key, value);
}
/**
* Unsupported, here until we get proper bulk insert APIs.
* {@hide}
*/
@SuppressWarnings("unchecked")
@Deprecated
public ArrayList<String> getStringArrayList(String key) {
return (ArrayList<String>) mValues.get(key);
}
/**
* Returns a string containing a concise, human-readable description of this object.
* @return a printable representation of this object.
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (String name : mValues.keySet()) {
String value = getAsString(name);
if (sb.length() > 0) sb.append(" ");
sb.append(name + "=" + value);
}
return sb.toString();
}
}
| {
"pile_set_name": "Github"
} |
# Hashes from: http://download.qt-project.org/official_releases/qt/5.3/5.3.2/submodules/qtbase-opensource-src-5.3.2.tar.xz.mirrorlist
sha256 9a16095ac46dae99d6ddab8bc07065fbe1c36501ed194a3191d07347d7826cb8 qtbase-opensource-src-5.3.2.tar.xz
sha1 faf4f33aa7e8dabcdcdf5f10824263beebbccd96 qtbase-opensource-src-5.3.2.tar.xz
md5 563e2b10274171f1184b3fd7260b4991 qtbase-opensource-src-5.3.2.tar.xz
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2018, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
module org.openjdk.skara.census {
requires java.xml;
requires java.net.http;
requires java.logging;
exports org.openjdk.skara.census;
}
| {
"pile_set_name": "Github"
} |
{
"General": {
"Precision": "float"
}
}
| {
"pile_set_name": "Github"
} |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.kafka.streams.processor.internals;
import java.util.HashMap;
import java.util.Map;
import org.apache.kafka.common.serialization.Deserializer;
import org.apache.kafka.common.serialization.LongDeserializer;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.common.serialization.Serializer;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.apache.kafka.streams.KeyValue;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.TestInputTopic;
import org.apache.kafka.streams.TestOutputTopic;
import org.apache.kafka.streams.Topology;
import org.apache.kafka.streams.TopologyTestDriver;
import org.apache.kafka.streams.kstream.Consumed;
import org.apache.kafka.streams.kstream.Grouped;
import org.apache.kafka.streams.kstream.KStream;
import org.apache.kafka.streams.kstream.Materialized;
import org.apache.kafka.streams.kstream.Named;
import org.apache.kafka.streams.kstream.Produced;
import org.apache.kafka.streams.state.Stores;
import org.apache.kafka.test.StreamsTestUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals;
public class RepartitionWithMergeOptimizingTest {
private final Logger log = LoggerFactory.getLogger(RepartitionWithMergeOptimizingTest.class);
private static final String INPUT_A_TOPIC = "inputA";
private static final String INPUT_B_TOPIC = "inputB";
private static final String COUNT_TOPIC = "outputTopic_0";
private static final String STRING_COUNT_TOPIC = "outputTopic_1";
private static final int ONE_REPARTITION_TOPIC = 1;
private static final int TWO_REPARTITION_TOPICS = 2;
private final Serializer<String> stringSerializer = new StringSerializer();
private final Deserializer<String> stringDeserializer = new StringDeserializer();
private final Pattern repartitionTopicPattern = Pattern.compile("Sink: .*-repartition");
private Properties streamsConfiguration;
private TopologyTestDriver topologyTestDriver;
private final List<KeyValue<String, Long>> expectedCountKeyValues =
Arrays.asList(KeyValue.pair("A", 6L), KeyValue.pair("B", 6L), KeyValue.pair("C", 6L));
private final List<KeyValue<String, String>> expectedStringCountKeyValues =
Arrays.asList(KeyValue.pair("A", "6"), KeyValue.pair("B", "6"), KeyValue.pair("C", "6"));
@Before
public void setUp() {
final Properties props = new Properties();
props.put(StreamsConfig.CACHE_MAX_BYTES_BUFFERING_CONFIG, 1024 * 10);
props.put(StreamsConfig.COMMIT_INTERVAL_MS_CONFIG, 5000);
streamsConfiguration = StreamsTestUtils.getStreamsConfig(
"maybe-optimized-with-merge-test-app",
"dummy-bootstrap-servers-config",
Serdes.String().getClass().getName(),
Serdes.String().getClass().getName(),
props);
}
@After
public void tearDown() {
try {
topologyTestDriver.close();
} catch (final RuntimeException e) {
log.warn("The following exception was thrown while trying to close the TopologyTestDriver (note that " +
"KAFKA-6647 causes this when running on Windows):", e);
}
}
@Test
public void shouldSendCorrectRecords_OPTIMIZED() {
runTest(StreamsConfig.OPTIMIZE, ONE_REPARTITION_TOPIC);
}
@Test
public void shouldSendCorrectResults_NO_OPTIMIZATION() {
runTest(StreamsConfig.NO_OPTIMIZATION, TWO_REPARTITION_TOPICS);
}
private void runTest(final String optimizationConfig, final int expectedNumberRepartitionTopics) {
streamsConfiguration.setProperty(StreamsConfig.TOPOLOGY_OPTIMIZATION_CONFIG, optimizationConfig);
final StreamsBuilder builder = new StreamsBuilder();
final KStream<String, String> sourceAStream =
builder.stream(INPUT_A_TOPIC, Consumed.with(Serdes.String(), Serdes.String()).withName("sourceAStream"));
final KStream<String, String> sourceBStream =
builder.stream(INPUT_B_TOPIC, Consumed.with(Serdes.String(), Serdes.String()).withName("sourceBStream"));
final KStream<String, String> mappedAStream =
sourceAStream.map((k, v) -> KeyValue.pair(v.split(":")[0], v), Named.as("mappedAStream"));
final KStream<String, String> mappedBStream =
sourceBStream.map((k, v) -> KeyValue.pair(v.split(":")[0], v), Named.as("mappedBStream"));
final KStream<String, String> mergedStream = mappedAStream.merge(mappedBStream, Named.as("mergedStream"));
mergedStream
.groupByKey(Grouped.as("long-groupByKey"))
.count(Named.as("long-count"), Materialized.as(Stores.inMemoryKeyValueStore("long-store")))
.toStream(Named.as("long-toStream"))
.to(COUNT_TOPIC, Produced.with(Serdes.String(), Serdes.Long()).withName("long-to"));
mergedStream
.groupByKey(Grouped.as("string-groupByKey"))
.count(Named.as("string-count"), Materialized.as(Stores.inMemoryKeyValueStore("string-store")))
.toStream(Named.as("string-toStream"))
.mapValues(v -> v.toString(), Named.as("string-mapValues"))
.to(STRING_COUNT_TOPIC, Produced.with(Serdes.String(), Serdes.String()).withName("string-to"));
final Topology topology = builder.build(streamsConfiguration);
topologyTestDriver = new TopologyTestDriver(topology, streamsConfiguration);
final TestInputTopic<String, String> inputTopicA = topologyTestDriver.createInputTopic(INPUT_A_TOPIC, stringSerializer, stringSerializer);
final TestInputTopic<String, String> inputTopicB = topologyTestDriver.createInputTopic(INPUT_B_TOPIC, stringSerializer, stringSerializer);
final TestOutputTopic<String, Long> countOutputTopic = topologyTestDriver.createOutputTopic(COUNT_TOPIC, stringDeserializer, new LongDeserializer());
final TestOutputTopic<String, String> stringCountOutputTopic = topologyTestDriver.createOutputTopic(STRING_COUNT_TOPIC, stringDeserializer, stringDeserializer);
inputTopicA.pipeKeyValueList(getKeyValues());
inputTopicB.pipeKeyValueList(getKeyValues());
final String topologyString = topology.describe().toString();
// Verify the topology
if (optimizationConfig.equals(StreamsConfig.OPTIMIZE)) {
assertEquals(EXPECTED_OPTIMIZED_TOPOLOGY, topologyString);
} else {
assertEquals(EXPECTED_UNOPTIMIZED_TOPOLOGY, topologyString);
}
// Verify the number of repartition topics
assertEquals(expectedNumberRepartitionTopics, getCountOfRepartitionTopicsFound(topologyString));
// Verify the expected output
assertThat(countOutputTopic.readKeyValuesToMap(), equalTo(keyValueListToMap(expectedCountKeyValues)));
assertThat(stringCountOutputTopic.readKeyValuesToMap(), equalTo(keyValueListToMap(expectedStringCountKeyValues)));
}
private <K, V> Map<K, V> keyValueListToMap(final List<KeyValue<K, V>> keyValuePairs) {
final Map<K, V> map = new HashMap<>();
for (final KeyValue<K, V> pair : keyValuePairs) {
map.put(pair.key, pair.value);
}
return map;
}
private int getCountOfRepartitionTopicsFound(final String topologyString) {
final Matcher matcher = repartitionTopicPattern.matcher(topologyString);
final List<String> repartitionTopicsFound = new ArrayList<>();
while (matcher.find()) {
repartitionTopicsFound.add(matcher.group());
}
return repartitionTopicsFound.size();
}
private List<KeyValue<String, String>> getKeyValues() {
final List<KeyValue<String, String>> keyValueList = new ArrayList<>();
final String[] keys = new String[]{"X", "Y", "Z"};
final String[] values = new String[]{"A:foo", "B:foo", "C:foo"};
for (final String key : keys) {
for (final String value : values) {
keyValueList.add(KeyValue.pair(key, value));
}
}
return keyValueList;
}
private static final String EXPECTED_OPTIMIZED_TOPOLOGY = "Topologies:\n"
+ " Sub-topology: 0\n"
+ " Source: sourceAStream (topics: [inputA])\n"
+ " --> mappedAStream\n"
+ " Source: sourceBStream (topics: [inputB])\n"
+ " --> mappedBStream\n"
+ " Processor: mappedAStream (stores: [])\n"
+ " --> mergedStream\n"
+ " <-- sourceAStream\n"
+ " Processor: mappedBStream (stores: [])\n"
+ " --> mergedStream\n"
+ " <-- sourceBStream\n"
+ " Processor: mergedStream (stores: [])\n"
+ " --> long-groupByKey-repartition-filter\n"
+ " <-- mappedAStream, mappedBStream\n"
+ " Processor: long-groupByKey-repartition-filter (stores: [])\n"
+ " --> long-groupByKey-repartition-sink\n"
+ " <-- mergedStream\n"
+ " Sink: long-groupByKey-repartition-sink (topic: long-groupByKey-repartition)\n"
+ " <-- long-groupByKey-repartition-filter\n"
+ "\n"
+ " Sub-topology: 1\n"
+ " Source: long-groupByKey-repartition-source (topics: [long-groupByKey-repartition])\n"
+ " --> long-count, string-count\n"
+ " Processor: string-count (stores: [string-store])\n"
+ " --> string-toStream\n"
+ " <-- long-groupByKey-repartition-source\n"
+ " Processor: long-count (stores: [long-store])\n"
+ " --> long-toStream\n"
+ " <-- long-groupByKey-repartition-source\n"
+ " Processor: string-toStream (stores: [])\n"
+ " --> string-mapValues\n"
+ " <-- string-count\n"
+ " Processor: long-toStream (stores: [])\n"
+ " --> long-to\n"
+ " <-- long-count\n"
+ " Processor: string-mapValues (stores: [])\n"
+ " --> string-to\n"
+ " <-- string-toStream\n"
+ " Sink: long-to (topic: outputTopic_0)\n"
+ " <-- long-toStream\n"
+ " Sink: string-to (topic: outputTopic_1)\n"
+ " <-- string-mapValues\n\n";
private static final String EXPECTED_UNOPTIMIZED_TOPOLOGY = "Topologies:\n"
+ " Sub-topology: 0\n"
+ " Source: sourceAStream (topics: [inputA])\n"
+ " --> mappedAStream\n"
+ " Source: sourceBStream (topics: [inputB])\n"
+ " --> mappedBStream\n"
+ " Processor: mappedAStream (stores: [])\n"
+ " --> mergedStream\n"
+ " <-- sourceAStream\n"
+ " Processor: mappedBStream (stores: [])\n"
+ " --> mergedStream\n"
+ " <-- sourceBStream\n"
+ " Processor: mergedStream (stores: [])\n"
+ " --> long-groupByKey-repartition-filter, string-groupByKey-repartition-filter\n"
+ " <-- mappedAStream, mappedBStream\n"
+ " Processor: long-groupByKey-repartition-filter (stores: [])\n"
+ " --> long-groupByKey-repartition-sink\n"
+ " <-- mergedStream\n"
+ " Processor: string-groupByKey-repartition-filter (stores: [])\n"
+ " --> string-groupByKey-repartition-sink\n"
+ " <-- mergedStream\n"
+ " Sink: long-groupByKey-repartition-sink (topic: long-groupByKey-repartition)\n"
+ " <-- long-groupByKey-repartition-filter\n"
+ " Sink: string-groupByKey-repartition-sink (topic: string-groupByKey-repartition)\n"
+ " <-- string-groupByKey-repartition-filter\n"
+ "\n"
+ " Sub-topology: 1\n"
+ " Source: long-groupByKey-repartition-source (topics: [long-groupByKey-repartition])\n"
+ " --> long-count\n"
+ " Processor: long-count (stores: [long-store])\n"
+ " --> long-toStream\n"
+ " <-- long-groupByKey-repartition-source\n"
+ " Processor: long-toStream (stores: [])\n"
+ " --> long-to\n"
+ " <-- long-count\n"
+ " Sink: long-to (topic: outputTopic_0)\n"
+ " <-- long-toStream\n"
+ "\n"
+ " Sub-topology: 2\n"
+ " Source: string-groupByKey-repartition-source (topics: [string-groupByKey-repartition])\n"
+ " --> string-count\n"
+ " Processor: string-count (stores: [string-store])\n"
+ " --> string-toStream\n"
+ " <-- string-groupByKey-repartition-source\n"
+ " Processor: string-toStream (stores: [])\n"
+ " --> string-mapValues\n"
+ " <-- string-count\n"
+ " Processor: string-mapValues (stores: [])\n"
+ " --> string-to\n"
+ " <-- string-toStream\n"
+ " Sink: string-to (topic: outputTopic_1)\n"
+ " <-- string-mapValues\n\n";
}
| {
"pile_set_name": "Github"
} |
#include "Action_Sendfile.h"
long hex2int(const std::string& hexStr)
{
char *offset;
if (hexStr.length() > 2) {
if (hexStr[0] == '0' && hexStr[1] == 'x') {
return strtol(hexStr.c_str(), &offset, 0);
}
}
return strtol(hexStr.c_str(), &offset, 16);
}
void Action_Sendfile::ExcuteAction(ie_data * ie, char * magic){
char* filenamelen = (char *)malloc(2);
strncpy(filenamelen, magic + 1, 2);
char* filelen = (char *)malloc(2);
strncpy(filelen, magic + 11, 2);
char* CurrentIndex = (char *)malloc(2);
strncpy(CurrentIndex, magic + 13, 2);
char* fileName = (char *)malloc(hex2int(filenamelen) + 1);
strncpy(fileName, magic + 15, hex2int(filenamelen));
strncpy(fileName + hex2int(filenamelen), "\0", 1);
char command[221] = { 0 };
strncpy_s(command, magic + 15 + hex2int(filenamelen), ie->len - 15 - hex2int(filenamelen));
HLOG("收到的信息:\n%s\n", command);//执行命令
HLOG("合计:%s : filenamelen [%d] , buflen [%d] , CurrentIndex [%d] , filelen[%d] \n", fileName, hex2int(filenamelen), ie->len - 15 - hex2int(filenamelen), hex2int(CurrentIndex), hex2int(filelen));
std::ofstream outfile;
if (hex2int(CurrentIndex) == 1) {//第一帧
outfile.open(fileName, std::ios::out | std::ios::binary);
}
else {
outfile.open(fileName, std::ios::app | std::ios::binary);
}
outfile << command;
outfile.close();
if (hex2int(CurrentIndex) == hex2int(filelen)) {//最后一帧
}
}
| {
"pile_set_name": "Github"
} |
.. cmake-module:: ../../Modules/CheckFortranCompilerFlag.cmake
| {
"pile_set_name": "Github"
} |
// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:build_daemon/data/build_target.dart';
import 'package:built_value/serializer.dart';
import 'package:web_socket_channel/io.dart';
import 'constants.dart';
import 'data/build_request.dart';
import 'data/build_status.dart';
import 'data/build_target_request.dart';
import 'data/serializers.dart';
import 'data/server_log.dart';
import 'data/shutdown_notification.dart';
import 'src/file_wait.dart';
Future<int> _existingPort(String workingDirectory) async {
var portFile = File(portFilePath(workingDirectory));
if (!await waitForFile(portFile)) throw MissingPortFile();
return int.parse(portFile.readAsStringSync());
}
Future<void> _handleDaemonStartup(
Process process,
void Function(ServerLog) logHandler,
) async {
process.stderr
.transform(utf8.decoder)
.transform(const LineSplitter())
.listen((line) {
logHandler(ServerLog((b) => b
..level = Level.SEVERE
..message = line));
});
var stdout = process.stdout
.transform(utf8.decoder)
.transform(const LineSplitter())
.asBroadcastStream();
// The daemon may log critical information prior to it successfully
// starting. Capture this data and forward to the logHandler.
//
// Whenever we see a `logStartMarker` we will parse everything between that
// and the `logEndMarker` as a `ServerLog`. Everything else is considered a
// normal INFO level log.
StringBuffer nextLogRecord;
var sub = stdout.where((line) => !_isActionMessage(line)).listen((line) {
if (nextLogRecord != null) {
if (line == logEndMarker) {
try {
logHandler(serializers
.deserialize(jsonDecode(nextLogRecord.toString())) as ServerLog);
} catch (e, s) {
logHandler(ServerLog((builder) => builder
..message = 'Failed to read log message:\n$nextLogRecord'
..level = Level.SEVERE
..error = '$e'
..stackTrace = '$s'));
}
nextLogRecord = null;
} else {
nextLogRecord.writeln(line);
}
} else if (line == logStartMarker) {
nextLogRecord = StringBuffer();
} else {
logHandler(ServerLog((b) => b
..level = Level.INFO
..message = line));
}
});
var daemonAction =
await stdout.firstWhere(_isActionMessage, orElse: () => null);
if (daemonAction == null) {
throw StateError('Unable to start build daemon.');
} else if (daemonAction == versionSkew) {
throw VersionSkew();
} else if (daemonAction == optionsSkew) {
throw OptionsSkew();
}
await sub.cancel();
}
bool _isActionMessage(String line) =>
line == versionSkew || line == readyToConnectLog || line == optionsSkew;
/// A client of the build daemon.
///
/// Handles starting and connecting to the build daemon.
///
/// Example:
/// https://pub.dev/packages/build_daemon#-example-tab-
class BuildDaemonClient {
final _buildResults = StreamController<BuildResults>.broadcast();
final _shutdownNotifications =
StreamController<ShutdownNotification>.broadcast();
final Serializers _serializers;
IOWebSocketChannel _channel;
BuildDaemonClient._(
int port,
this._serializers,
void Function(ServerLog) logHandler,
) {
_channel = IOWebSocketChannel.connect('ws://localhost:$port')
..stream.listen((data) {
var message = _serializers.deserialize(jsonDecode(data as String));
if (message is ServerLog) {
logHandler(message);
} else if (message is BuildResults) {
_buildResults.add(message);
} else if (message is ShutdownNotification) {
_shutdownNotifications.add(message);
} else {
// In practice we should never reach this state due to the
// deserialize call.
throw StateError(
'Unexpected message from the Dart Build Daemon\n $message');
}
})
// TODO(grouma) - Implement proper error handling.
.onError(print);
}
Stream<BuildResults> get buildResults => _buildResults.stream;
Stream<ShutdownNotification> get shutdownNotifications =>
_shutdownNotifications.stream;
Future<void> get finished async => await _channel.sink.done;
/// Registers a build target to be built upon any file change.
void registerBuildTarget(BuildTarget target) => _channel.sink.add(jsonEncode(
_serializers.serialize(BuildTargetRequest((b) => b..target = target))));
/// Builds all registered targets, including those not from this client.
///
/// Note this will wait for any ongoing build to finish before starting a new
/// one.
void startBuild() {
var request = BuildRequest();
_channel.sink.add(jsonEncode(_serializers.serialize(request)));
}
Future<void> close() => _channel.sink.close();
/// Connects to the current daemon instance.
///
/// If one is not running, a new daemon instance will be started.
static Future<BuildDaemonClient> connect(
String workingDirectory,
List<String> daemonCommand, {
Serializers serializersOverride,
void Function(ServerLog) logHandler,
bool includeParentEnvironment,
Map<String, String> environment,
BuildMode buildMode,
}) async {
logHandler ??= (_) {};
includeParentEnvironment ??= true;
buildMode ??= BuildMode.Auto;
var daemonSerializers = serializersOverride ?? serializers;
var daemonArgs = daemonCommand.sublist(1)
..add('--$buildModeFlag=$buildMode');
var process = await Process.start(
daemonCommand.first,
daemonArgs,
mode: ProcessStartMode.detachedWithStdio,
workingDirectory: workingDirectory,
environment: environment,
includeParentEnvironment: includeParentEnvironment,
);
await _handleDaemonStartup(process, logHandler);
return BuildDaemonClient._(
await _existingPort(workingDirectory), daemonSerializers, logHandler);
}
}
/// Thrown when the port file for the running daemon instance can't be found.
class MissingPortFile implements Exception {}
/// Thrown if the client requests conflicting options with the current daemon
/// instance.
class OptionsSkew implements Exception {}
/// Thrown if the current daemon instance version does not match that of the
/// client.
class VersionSkew implements Exception {}
| {
"pile_set_name": "Github"
} |
"use strict"
const axios = require("axios")
exports.getMeDogs = endpoint => {
const url = endpoint.url
const port = endpoint.port
return axios.request({
method: "GET",
baseURL: `${url}:${port}`,
url: "/dogs",
headers: {
Accept: "application/json",
},
})
}
exports.getMeDog = endpoint => {
const url = endpoint.url
const port = endpoint.port
return axios.request({
method: "GET",
baseURL: `${url}:${port}`,
url: "/dogs/1",
headers: {
Accept: "application/json",
},
})
}
| {
"pile_set_name": "Github"
} |
/*
* copyright (c) 2003 Fabrice Bellard
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef AVUTIL_VERSION_H
#define AVUTIL_VERSION_H
#include "macros.h"
/**
* @addtogroup version_utils
*
* Useful to check and match library version in order to maintain
* backward compatibility.
*
* @{
*/
#define AV_VERSION_INT(a, b, c) ((a)<<16 | (b)<<8 | (c))
#define AV_VERSION_DOT(a, b, c) a ##.## b ##.## c
#define AV_VERSION(a, b, c) AV_VERSION_DOT(a, b, c)
/**
* @}
*/
/**
* @file
* @ingroup lavu
* Libavutil version macros
*/
/**
* @defgroup lavu_ver Version and Build diagnostics
*
* Macros and function useful to check at compiletime and at runtime
* which version of libavutil is in use.
*
* @{
*/
#define LIBAVUTIL_VERSION_MAJOR 54
#define LIBAVUTIL_VERSION_MINOR 27
#define LIBAVUTIL_VERSION_MICRO 100
#define LIBAVUTIL_VERSION_INT AV_VERSION_INT(LIBAVUTIL_VERSION_MAJOR, \
LIBAVUTIL_VERSION_MINOR, \
LIBAVUTIL_VERSION_MICRO)
#define LIBAVUTIL_VERSION AV_VERSION(LIBAVUTIL_VERSION_MAJOR, \
LIBAVUTIL_VERSION_MINOR, \
LIBAVUTIL_VERSION_MICRO)
#define LIBAVUTIL_BUILD LIBAVUTIL_VERSION_INT
#define LIBAVUTIL_IDENT "Lavu" AV_STRINGIFY(LIBAVUTIL_VERSION)
/**
* @}
*
* @defgroup depr_guards Deprecation guards
* FF_API_* defines may be placed below to indicate public API that will be
* dropped at a future version bump. The defines themselves are not part of
* the public API and may change, break or disappear at any time.
*
* @{
*/
#ifndef FF_API_OLD_AVOPTIONS
#define FF_API_OLD_AVOPTIONS (LIBAVUTIL_VERSION_MAJOR < 55)
#endif
#ifndef FF_API_PIX_FMT
#define FF_API_PIX_FMT (LIBAVUTIL_VERSION_MAJOR < 55)
#endif
#ifndef FF_API_CONTEXT_SIZE
#define FF_API_CONTEXT_SIZE (LIBAVUTIL_VERSION_MAJOR < 55)
#endif
#ifndef FF_API_PIX_FMT_DESC
#define FF_API_PIX_FMT_DESC (LIBAVUTIL_VERSION_MAJOR < 55)
#endif
#ifndef FF_API_AV_REVERSE
#define FF_API_AV_REVERSE (LIBAVUTIL_VERSION_MAJOR < 55)
#endif
#ifndef FF_API_AUDIOCONVERT
#define FF_API_AUDIOCONVERT (LIBAVUTIL_VERSION_MAJOR < 55)
#endif
#ifndef FF_API_CPU_FLAG_MMX2
#define FF_API_CPU_FLAG_MMX2 (LIBAVUTIL_VERSION_MAJOR < 55)
#endif
#ifndef FF_API_LLS_PRIVATE
#define FF_API_LLS_PRIVATE (LIBAVUTIL_VERSION_MAJOR < 55)
#endif
#ifndef FF_API_AVFRAME_LAVC
#define FF_API_AVFRAME_LAVC (LIBAVUTIL_VERSION_MAJOR < 55)
#endif
#ifndef FF_API_VDPAU
#define FF_API_VDPAU (LIBAVUTIL_VERSION_MAJOR < 55)
#endif
#ifndef FF_API_GET_CHANNEL_LAYOUT_COMPAT
#define FF_API_GET_CHANNEL_LAYOUT_COMPAT (LIBAVUTIL_VERSION_MAJOR < 55)
#endif
#ifndef FF_API_XVMC
#define FF_API_XVMC (LIBAVUTIL_VERSION_MAJOR < 55)
#endif
#ifndef FF_API_OPT_TYPE_METADATA
#define FF_API_OPT_TYPE_METADATA (LIBAVUTIL_VERSION_MAJOR < 55)
#endif
#ifndef FF_API_DLOG
#define FF_API_DLOG (LIBAVUTIL_VERSION_MAJOR < 55)
#endif
#ifndef FF_CONST_AVUTIL55
#if LIBAVUTIL_VERSION_MAJOR >= 55
#define FF_CONST_AVUTIL55 const
#else
#define FF_CONST_AVUTIL55
#endif
#endif
/**
* @}
*/
#endif /* AVUTIL_VERSION_H */
| {
"pile_set_name": "Github"
} |
#include <mach/mcs814x.h>
.macro disable_fiq
.endm
.macro arch_ret_to_user, tmp1, tmp2
.endm
.macro get_irqnr_preamble, base, tmp
ldr \base, =mcs814x_intc_base @ base virtual address of AIC peripheral
ldr \base, [\base]
.endm
.macro get_irqnr_and_base, irqnr, irqstat, base, tmp
mov \tmp, #MCS814X_IRQ_STS0 @ load tmp with STS0 register offset
ldr \irqstat, [\base, \tmp] @ load value at base + tmp
tst \irqstat, \irqstat @ test if no active IRQ's
beq 1002f @ if no active irqs return with status 0
mov \irqnr, #0 @ start from irq zero
mov \tmp, #1 @ the mask initially 1
1001:
tst \irqstat, \tmp @ and with mask
addeq \irqnr, \irqnr, #1 @ if zero then add one to nr
moveq \tmp, \tmp, lsl #1 @ shift mask one to left
beq 1001b @ if zero then loop again
mov \irqstat, \tmp @ save the return mask
mov \tmp, #MCS814X_IRQ_STS0 @ load tmp with ICR offset
str \irqstat, [\base, \tmp] @ clear irq with selected mask
1002:
.endm
| {
"pile_set_name": "Github"
} |
#version 330
#line 1
#ifdef GL_ARB_explicit_attrib_location
#extension GL_ARB_explicit_attrib_location : require
layout(location=0) in vec3 P;
layout(location=1) in vec3 Cd;
layout(location=2) in float Alpha;
layout(location=3) in vec3 N;
layout(location=4) in vec2 uv;
layout(location=6) in uint pointSelection;
#else
in vec3 P;
in vec3 Cd;
in float Alpha;
in vec3 N;
in vec2 uv;
in uint pointSelection;
#endif
layout(std140) uniform glH_Material
{
vec3 ambient_color;
vec3 diffuse_color;
vec3 emission_color;
vec3 specular_color;
vec3 metallic_color;
float metal;
float material_alpha;
float material_alpha_parallel;
float roughness;
float diffuse_roughness;
float ior;
float reflection;
float coat_intensity;
float coat_roughness;
int specular_model;
int coat_spec_model;
float specular_tint;
bool use_geo_color;
bool use_packed_color;
bool has_textures;
bool has_diffuse_map;
bool has_spec_map;
bool has_opacity_map;
bool has_emission_map;
bool has_normal_map;
bool has_rough_map;
bool has_displace_map;
bool has_occlusion_map;
bool has_metallic_map;
bool has_coat_int_map;
bool has_coat_rough_map;
bool has_reflection_int_map;
bool has_reflect_map;
ivec4 diffuse_udim_area;
ivec4 spec_udim_area;
ivec4 opacity_udim_area;
ivec4 emission_udim_area;
ivec4 normal_udim_area;
ivec4 rough_udim_area;
ivec4 displace_udim_area;
ivec4 occlusion_udim_area;
ivec4 metallic_udim_area;
ivec4 coat_int_udim_area;
ivec4 coat_rough_udim_area;
ivec4 reflection_udim_area;
bool has_env_map;
vec3 envScale;
mat3 envRotate;
vec2 normalMapScaleShift;
vec2 normalMapScale;
vec3 normalMapXYZScale;
int normal_map_type; // space: 0=tangent, 1=world
int normal_map_ncomps; // 2 or 3 component
int displace_space;
float displace_scale;
float displace_offset;
bool displace_y_up; // vs. z-up
bool invert_opacitymap;
bool invert_roughmap;
vec4 rough_comp;
vec4 occlusion_comp;
vec4 metallic_comp;
vec4 coat_int_comp;
vec4 coat_rough_comp;
bool reflection_as_ior;
vec4 reflection_comp;
};
out parms
{
vec4 pos;
vec3 normal;
vec4 color;
vec2 texcoord0;
float selected;
} vsOut;
#if defined(VENDOR_NVIDIA) && DRIVER_MAJOR >= 343
out gl_PerVertex
{
vec4 gl_Position;
float gl_ClipDistance[2];
};
#endif
uniform mat4 glH_ViewMatrix;
uniform mat4 glH_ProjectMatrix;
uniform mat4 glH_ObjectMatrix;
uniform mat3 glH_NormalMatrix;
uniform vec2 glH_DepthRange;
float HOUpointSelection(uint point_attrib, int instance_id);
mat4 HOUfetchInstance(out vec3 Cd, out float texlayer, out int instID,
out bool has_cd, out bool is_selected);
void main()
{
vec4 vpos;
mat4 objinst;
mat3 objinst_n;
vec3 instCd;
float texlayer;
int instID;
bool isSel, hasCd;
mat4 instmat = HOUfetchInstance(instCd, texlayer, instID, hasCd, isSel);
// Object transform and instancing transform
objinst = glH_ObjectMatrix * instmat;
objinst_n = mat3(objinst);
objinst_n = transpose( inverse( objinst_n ));
// view position
vpos = vec4(P, 1.0);
vpos = glH_ViewMatrix * (objinst * vpos);
vsOut.pos = vpos / vpos.w;
// Point color and alpha
vsOut.color = vec4( Cd * instCd, Alpha );
// Point UVs
//if(has_textures)
vsOut.texcoord0 = uv;
//else
// vsOut.texcoord0 = vec2(0.0);
// Adjust normals if object/instance transform flips them
vsOut.normal = glH_NormalMatrix *
(objinst_n * N) *sign(determinant(objinst_n));
vsOut.selected = isSel ? 1.0
: HOUpointSelection(pointSelection, instID);
// projected position
gl_Position = glH_ProjectMatrix * vpos;
// near/far clip, in case zbuffer near/far are different
gl_ClipDistance[0] = -vsOut.pos.z - glH_DepthRange.x;
gl_ClipDistance[1] = glH_DepthRange.y + vsOut.pos.z;
}
| {
"pile_set_name": "Github"
} |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* \file elemwise_unary_op_trig.cc
* \brief CPU Implementation of unary trigonometric functions.
*/
#include <mxnet/base.h>
#include "elemwise_unary_op.h"
#include "./elemwise_binary_op-inl.h"
namespace mxnet {
namespace op {
// sin
MXNET_OPERATOR_REGISTER_UNARY_WITH_RSP_CSR(sin, cpu, mshadow_op::sin)
.describe(R"code(Computes the element-wise sine of the input array.
The input should be in radians (:math:`2\pi` rad equals 360 degrees).
.. math::
sin([0, \pi/4, \pi/2]) = [0, 0.707, 1]
The storage type of ``sin`` output depends upon the input storage type:
- sin(default) = default
- sin(row_sparse) = row_sparse
- sin(csr) = csr
)code" ADD_FILELINE)
.set_attr<nnvm::FGradient>("FGradient", ElemwiseGradUseIn{ "_backward_sin" });
MXNET_OPERATOR_REGISTER_BINARY_WITH_SPARSE_CPU_DR(_backward_sin, unary_bwd<mshadow_op::sin_grad>)
.set_attr<nnvm::FGradient>("FGradient",
[](const nnvm::NodePtr& n, const std::vector<nnvm::NodeEntry>& ograds) {
// ograds[0]: d^2L/dx^2
// inputs[0]: dL/dy
// inputs[1]: x (ElemwiseUseIn)
// f(x) = sin(x)
// f'(x) = cos(x)
// f''(x) = -sin(x)
auto dydx = MakeNode("cos", n->attrs.name + "_dydx",
{n->inputs[1]}, nullptr, &n);
auto d2ydx2 = MakeNode("negative", n->attrs.name + "_d2ydx2",
{nnvm::NodeEntry{
MakeNode("sin", n->attrs.name + "_grad_grad_mid", {n->inputs[1]}, nullptr, &n)
}}, nullptr, &n);
auto grad_grad_mid = MakeNode("elemwise_mul", n->attrs.name + "backward_grad_grad_mid",
{n->inputs[0], nnvm::NodeEntry{d2ydx2}}, nullptr, &n);
std::vector<nnvm::NodeEntry> ret;
ret.emplace_back(MakeNode("elemwise_mul", n->attrs.name + "_backward_grad_grad",
{ograds[0], nnvm::NodeEntry{dydx}}, nullptr, &n));
ret.emplace_back(MakeNode("elemwise_mul", n->attrs.name + "_backward_grad_grad_in",
{ograds[0], nnvm::NodeEntry{grad_grad_mid}}, nullptr, &n));
return ret;
});
// cos
MXNET_OPERATOR_REGISTER_UNARY_WITH_SPARSE_DR(cos, cpu, mshadow_op::cos)
MXNET_ADD_SPARSE_OP_ALIAS(cos)
.describe(R"code(Computes the element-wise cosine of the input array.
The input should be in radians (:math:`2\pi` rad equals 360 degrees).
.. math::
cos([0, \pi/4, \pi/2]) = [1, 0.707, 0]
The storage type of ``cos`` output is always dense
)code" ADD_FILELINE)
.set_attr<nnvm::FGradient>("FGradient", ElemwiseGradUseIn{"_backward_cos"});
MXNET_OPERATOR_REGISTER_BINARY_WITH_SPARSE_CPU(_backward_cos, unary_bwd<mshadow_op::cos_grad>)
.set_attr<nnvm::FGradient>("FGradient",
[](const nnvm::NodePtr& n, const std::vector<nnvm::NodeEntry>& ograds) {
// ograds[0]: d^2L/dx^2
// inputs[0]: dL/dy
// inputs[1]: x (ElemwiseUseIn)
// f(x) = cos(x)
// f'(x) = -sin(x)
// f''(x) = -cos(x)
auto dydx = MakeNode("negative", n->attrs.name + "_dydx",
{nnvm::NodeEntry{
MakeNode("sin", n->attrs.name + "_grad_mid", {n->inputs[1]}, nullptr, &n)
}}, nullptr, &n);
auto d2ydx2 = MakeNode("negative", n->attrs.name + "_d2ydx2",
{nnvm::NodeEntry{
MakeNode("cos", n->attrs.name + "_grad_grad_mid", {n->inputs[1]}, nullptr, &n)
}}, nullptr, &n);
auto grad_grad_mid = MakeNode("elemwise_mul", n->attrs.name + "_backward_grad_grad_mid",
{n->inputs[0], nnvm::NodeEntry{d2ydx2}}, nullptr, &n);
std::vector<nnvm::NodeEntry> ret;
// for the backward of the _backward_cos node
// first input is the ograd and second input is x (because ElemwiseUseIn)
ret.emplace_back(MakeNode("elemwise_mul", n->attrs.name + "_backward_grad_grad",
{ograds[0], nnvm::NodeEntry{dydx}}, nullptr, &n));
ret.emplace_back(MakeNode("elemwise_mul", n->attrs.name + "_backward_grad_grad_in",
{ograds[0], nnvm::NodeEntry{grad_grad_mid}}, nullptr, &n));
return ret;
});
// tan
MXNET_OPERATOR_REGISTER_UNARY_WITH_RSP_CSR(tan, cpu, mshadow_op::tan)
.describe(R"code(Computes the element-wise tangent of the input array.
The input should be in radians (:math:`2\pi` rad equals 360 degrees).
.. math::
tan([0, \pi/4, \pi/2]) = [0, 1, -inf]
The storage type of ``tan`` output depends upon the input storage type:
- tan(default) = default
- tan(row_sparse) = row_sparse
- tan(csr) = csr
)code" ADD_FILELINE)
.set_attr<nnvm::FGradient>("FGradient", ElemwiseGradUseOut{ "_backward_tan" });
MXNET_OPERATOR_REGISTER_BINARY_WITH_SPARSE_CPU_DR(_backward_tan, unary_bwd<mshadow_op::tan_grad>);
// arcsin
MXNET_OPERATOR_REGISTER_UNARY_WITH_RSP_CSR(arcsin, cpu, mshadow_op::arcsin)
.describe(R"code(Returns element-wise inverse sine of the input array.
The input should be in the range `[-1, 1]`.
The output is in the closed interval of [:math:`-\pi/2`, :math:`\pi/2`].
.. math::
arcsin([-1, -.707, 0, .707, 1]) = [-\pi/2, -\pi/4, 0, \pi/4, \pi/2]
The storage type of ``arcsin`` output depends upon the input storage type:
- arcsin(default) = default
- arcsin(row_sparse) = row_sparse
- arcsin(csr) = csr
)code" ADD_FILELINE)
.set_attr<nnvm::FGradient>("FGradient", ElemwiseGradUseIn{ "_backward_arcsin" });
MXNET_OPERATOR_REGISTER_BINARY_WITH_SPARSE_CPU_DR(_backward_arcsin,
unary_bwd<mshadow_op::arcsin_grad>);
// arccos
MXNET_OPERATOR_REGISTER_UNARY_WITH_SPARSE_DR(arccos, cpu, mshadow_op::arccos)
MXNET_ADD_SPARSE_OP_ALIAS(arccos)
.describe(R"code(Returns element-wise inverse cosine of the input array.
The input should be in range `[-1, 1]`.
The output is in the closed interval :math:`[0, \pi]`
.. math::
arccos([-1, -.707, 0, .707, 1]) = [\pi, 3\pi/4, \pi/2, \pi/4, 0]
The storage type of ``arccos`` output is always dense
)code" ADD_FILELINE)
.set_attr<nnvm::FGradient>("FGradient", ElemwiseGradUseIn{ "_backward_arccos" });
MXNET_OPERATOR_REGISTER_BINARY_WITH_SPARSE_CPU_DR(_backward_arccos,
unary_bwd<mshadow_op::arccos_grad>);
// arctan
MXNET_OPERATOR_REGISTER_UNARY_WITH_RSP_CSR(arctan, cpu, mshadow_op::arctan)
.describe(R"code(Returns element-wise inverse tangent of the input array.
The output is in the closed interval :math:`[-\pi/2, \pi/2]`
.. math::
arctan([-1, 0, 1]) = [-\pi/4, 0, \pi/4]
The storage type of ``arctan`` output depends upon the input storage type:
- arctan(default) = default
- arctan(row_sparse) = row_sparse
- arctan(csr) = csr
)code" ADD_FILELINE)
.set_attr<nnvm::FGradient>("FGradient", ElemwiseGradUseIn{ "_backward_arctan" });
MXNET_OPERATOR_REGISTER_BINARY_WITH_SPARSE_CPU_DR(_backward_arctan,
unary_bwd<mshadow_op::arctan_grad>);
// degrees
MXNET_OPERATOR_REGISTER_UNARY_WITH_RSP_CSR(degrees, cpu, mshadow_op::degrees)
.describe(R"code(Converts each element of the input array from radians to degrees.
.. math::
degrees([0, \pi/2, \pi, 3\pi/2, 2\pi]) = [0, 90, 180, 270, 360]
The storage type of ``degrees`` output depends upon the input storage type:
- degrees(default) = default
- degrees(row_sparse) = row_sparse
- degrees(csr) = csr
)code" ADD_FILELINE)
.set_attr<nnvm::FGradient>("FGradient", ElemwiseGradUseIn{ "_backward_degrees" });
MXNET_OPERATOR_REGISTER_BINARY_WITH_SPARSE_CPU_DR(_backward_degrees,
unary_bwd<mshadow_op::degrees_grad>);
// radians
MXNET_OPERATOR_REGISTER_UNARY_WITH_RSP_CSR(radians, cpu, mshadow_op::radians)
.describe(R"code(Converts each element of the input array from degrees to radians.
.. math::
radians([0, 90, 180, 270, 360]) = [0, \pi/2, \pi, 3\pi/2, 2\pi]
The storage type of ``radians`` output depends upon the input storage type:
- radians(default) = default
- radians(row_sparse) = row_sparse
- radians(csr) = csr
)code" ADD_FILELINE)
.set_attr<nnvm::FGradient>("FGradient", ElemwiseGradUseIn{ "_backward_radians" });
MXNET_OPERATOR_REGISTER_BINARY_WITH_SPARSE_CPU_DR(_backward_radians,
unary_bwd<mshadow_op::radians_grad>);
// sinh
MXNET_OPERATOR_REGISTER_UNARY_WITH_RSP_CSR(sinh, cpu, mshadow_op::sinh)
.describe(R"code(Returns the hyperbolic sine of the input array, computed element-wise.
.. math::
sinh(x) = 0.5\times(exp(x) - exp(-x))
The storage type of ``sinh`` output depends upon the input storage type:
- sinh(default) = default
- sinh(row_sparse) = row_sparse
- sinh(csr) = csr
)code" ADD_FILELINE)
.set_attr<nnvm::FGradient>("FGradient", ElemwiseGradUseIn{ "_backward_sinh" });
MXNET_OPERATOR_REGISTER_BINARY_WITH_SPARSE_CPU_DR(_backward_sinh, unary_bwd<mshadow_op::sinh_grad>);
// cosh
MXNET_OPERATOR_REGISTER_UNARY_WITH_SPARSE_DR(cosh, cpu, mshadow_op::cosh)
MXNET_ADD_SPARSE_OP_ALIAS(cosh)
.describe(R"code(Returns the hyperbolic cosine of the input array, computed element-wise.
.. math::
cosh(x) = 0.5\times(exp(x) + exp(-x))
The storage type of ``cosh`` output is always dense
)code" ADD_FILELINE)
.set_attr<nnvm::FGradient>("FGradient", ElemwiseGradUseIn{ "_backward_cosh" });
MXNET_OPERATOR_REGISTER_BINARY_WITH_SPARSE_CPU(_backward_cosh, unary_bwd<mshadow_op::cosh_grad>);
// tanh
MXNET_OPERATOR_REGISTER_UNARY_WITH_RSP_CSR(tanh, cpu, mshadow_op::tanh)
.describe(R"code(Returns the hyperbolic tangent of the input array, computed element-wise.
.. math::
tanh(x) = sinh(x) / cosh(x)
The storage type of ``tanh`` output depends upon the input storage type:
- tanh(default) = default
- tanh(row_sparse) = row_sparse
- tanh(csr) = csr
)code" ADD_FILELINE)
.set_attr<nnvm::FGradient>("FGradient", ElemwiseGradUseOut{ "_backward_tanh" });
MXNET_OPERATOR_REGISTER_BINARY_WITH_SPARSE_CPU_DR(_backward_tanh, unary_bwd<mshadow_op::tanh_grad>);
// arcsinh
MXNET_OPERATOR_REGISTER_UNARY_WITH_RSP_CSR(arcsinh, cpu, mshadow_op::arcsinh)
.describe(R"code(Returns the element-wise inverse hyperbolic sine of the input array, \
computed element-wise.
The storage type of ``arcsinh`` output depends upon the input storage type:
- arcsinh(default) = default
- arcsinh(row_sparse) = row_sparse
- arcsinh(csr) = csr
)code" ADD_FILELINE)
.set_attr<nnvm::FGradient>("FGradient", ElemwiseGradUseIn{ "_backward_arcsinh" });
MXNET_OPERATOR_REGISTER_BINARY_WITH_SPARSE_CPU_DR(_backward_arcsinh,
unary_bwd<mshadow_op::arcsinh_grad>);
// arccosh
MXNET_OPERATOR_REGISTER_UNARY_WITH_SPARSE_DR(arccosh, cpu, mshadow_op::arccosh)
MXNET_ADD_SPARSE_OP_ALIAS(arccosh)
.describe(R"code(Returns the element-wise inverse hyperbolic cosine of the input array, \
computed element-wise.
The storage type of ``arccosh`` output is always dense
)code" ADD_FILELINE)
.set_attr<nnvm::FGradient>("FGradient", ElemwiseGradUseIn{ "_backward_arccosh" });
MXNET_OPERATOR_REGISTER_BINARY_WITH_SPARSE_CPU_DR(_backward_arccosh,
unary_bwd<mshadow_op::arccosh_grad>);
// arctanh
MXNET_OPERATOR_REGISTER_UNARY_WITH_RSP_CSR(arctanh, cpu, mshadow_op::arctanh)
.describe(R"code(Returns the element-wise inverse hyperbolic tangent of the input array, \
computed element-wise.
The storage type of ``arctanh`` output depends upon the input storage type:
- arctanh(default) = default
- arctanh(row_sparse) = row_sparse
- arctanh(csr) = csr
)code" ADD_FILELINE)
.set_attr<nnvm::FGradient>("FGradient", ElemwiseGradUseIn{ "_backward_arctanh" });
MXNET_OPERATOR_REGISTER_BINARY_WITH_SPARSE_CPU_DR(_backward_arctanh,
unary_bwd<mshadow_op::arctanh_grad>);
} // namespace op
} // namespace mxnet
| {
"pile_set_name": "Github"
} |
/*
* linux/fs/ext2/inode.c
*
* Copyright (C) 1992, 1993, 1994, 1995
* Remy Card ([email protected])
* Laboratoire MASI - Institut Blaise Pascal
* Universite Pierre et Marie Curie (Paris VI)
*
* from
*
* linux/fs/minix/inode.c
*
* Copyright (C) 1991, 1992 Linus Torvalds
*
* Goal-directed block allocation by Stephen Tweedie
* ([email protected]), 1993, 1998
* Big-endian to little-endian byte-swapping/bitmaps by
* David S. Miller ([email protected]), 1995
* 64-bit file support on 64-bit platforms by Jakub Jelinek
* ([email protected])
*
* Assorted race fixes, rewrite of ext2_get_block() by Al Viro, 2000
*/
#include <linux/time.h>
#include <linux/highuid.h>
#include <linux/pagemap.h>
#include <linux/dax.h>
#include <linux/quotaops.h>
#include <linux/writeback.h>
#include <linux/buffer_head.h>
#include <linux/mpage.h>
#include <linux/fiemap.h>
#include <linux/namei.h>
#include <linux/uio.h>
#include "ext2.h"
#include "acl.h"
#include "xattr.h"
static int __ext2_write_inode(struct inode *inode, int do_sync);
/*
* Test whether an inode is a fast symlink.
*/
static inline int ext2_inode_is_fast_symlink(struct inode *inode)
{
int ea_blocks = EXT2_I(inode)->i_file_acl ?
(inode->i_sb->s_blocksize >> 9) : 0;
return (S_ISLNK(inode->i_mode) &&
inode->i_blocks - ea_blocks == 0);
}
static void ext2_truncate_blocks(struct inode *inode, loff_t offset);
static void ext2_write_failed(struct address_space *mapping, loff_t to)
{
struct inode *inode = mapping->host;
if (to > inode->i_size) {
truncate_pagecache(inode, inode->i_size);
ext2_truncate_blocks(inode, inode->i_size);
}
}
/*
* Called at the last iput() if i_nlink is zero.
*/
void ext2_evict_inode(struct inode * inode)
{
struct ext2_block_alloc_info *rsv;
int want_delete = 0;
if (!inode->i_nlink && !is_bad_inode(inode)) {
want_delete = 1;
dquot_initialize(inode);
} else {
dquot_drop(inode);
}
truncate_inode_pages_final(&inode->i_data);
if (want_delete) {
sb_start_intwrite(inode->i_sb);
/* set dtime */
EXT2_I(inode)->i_dtime = get_seconds();
mark_inode_dirty(inode);
__ext2_write_inode(inode, inode_needs_sync(inode));
/* truncate to 0 */
inode->i_size = 0;
if (inode->i_blocks)
ext2_truncate_blocks(inode, 0);
ext2_xattr_delete_inode(inode);
}
invalidate_inode_buffers(inode);
clear_inode(inode);
ext2_discard_reservation(inode);
rsv = EXT2_I(inode)->i_block_alloc_info;
EXT2_I(inode)->i_block_alloc_info = NULL;
if (unlikely(rsv))
kfree(rsv);
if (want_delete) {
ext2_free_inode(inode);
sb_end_intwrite(inode->i_sb);
}
}
typedef struct {
__le32 *p;
__le32 key;
struct buffer_head *bh;
} Indirect;
static inline void add_chain(Indirect *p, struct buffer_head *bh, __le32 *v)
{
p->key = *(p->p = v);
p->bh = bh;
}
static inline int verify_chain(Indirect *from, Indirect *to)
{
while (from <= to && from->key == *from->p)
from++;
return (from > to);
}
/**
* ext2_block_to_path - parse the block number into array of offsets
* @inode: inode in question (we are only interested in its superblock)
* @i_block: block number to be parsed
* @offsets: array to store the offsets in
* @boundary: set this non-zero if the referred-to block is likely to be
* followed (on disk) by an indirect block.
* To store the locations of file's data ext2 uses a data structure common
* for UNIX filesystems - tree of pointers anchored in the inode, with
* data blocks at leaves and indirect blocks in intermediate nodes.
* This function translates the block number into path in that tree -
* return value is the path length and @offsets[n] is the offset of
* pointer to (n+1)th node in the nth one. If @block is out of range
* (negative or too large) warning is printed and zero returned.
*
* Note: function doesn't find node addresses, so no IO is needed. All
* we need to know is the capacity of indirect blocks (taken from the
* inode->i_sb).
*/
/*
* Portability note: the last comparison (check that we fit into triple
* indirect block) is spelled differently, because otherwise on an
* architecture with 32-bit longs and 8Kb pages we might get into trouble
* if our filesystem had 8Kb blocks. We might use long long, but that would
* kill us on x86. Oh, well, at least the sign propagation does not matter -
* i_block would have to be negative in the very beginning, so we would not
* get there at all.
*/
static int ext2_block_to_path(struct inode *inode,
long i_block, int offsets[4], int *boundary)
{
int ptrs = EXT2_ADDR_PER_BLOCK(inode->i_sb);
int ptrs_bits = EXT2_ADDR_PER_BLOCK_BITS(inode->i_sb);
const long direct_blocks = EXT2_NDIR_BLOCKS,
indirect_blocks = ptrs,
double_blocks = (1 << (ptrs_bits * 2));
int n = 0;
int final = 0;
if (i_block < 0) {
ext2_msg(inode->i_sb, KERN_WARNING,
"warning: %s: block < 0", __func__);
} else if (i_block < direct_blocks) {
offsets[n++] = i_block;
final = direct_blocks;
} else if ( (i_block -= direct_blocks) < indirect_blocks) {
offsets[n++] = EXT2_IND_BLOCK;
offsets[n++] = i_block;
final = ptrs;
} else if ((i_block -= indirect_blocks) < double_blocks) {
offsets[n++] = EXT2_DIND_BLOCK;
offsets[n++] = i_block >> ptrs_bits;
offsets[n++] = i_block & (ptrs - 1);
final = ptrs;
} else if (((i_block -= double_blocks) >> (ptrs_bits * 2)) < ptrs) {
offsets[n++] = EXT2_TIND_BLOCK;
offsets[n++] = i_block >> (ptrs_bits * 2);
offsets[n++] = (i_block >> ptrs_bits) & (ptrs - 1);
offsets[n++] = i_block & (ptrs - 1);
final = ptrs;
} else {
ext2_msg(inode->i_sb, KERN_WARNING,
"warning: %s: block is too big", __func__);
}
if (boundary)
*boundary = final - 1 - (i_block & (ptrs - 1));
return n;
}
/**
* ext2_get_branch - read the chain of indirect blocks leading to data
* @inode: inode in question
* @depth: depth of the chain (1 - direct pointer, etc.)
* @offsets: offsets of pointers in inode/indirect blocks
* @chain: place to store the result
* @err: here we store the error value
*
* Function fills the array of triples <key, p, bh> and returns %NULL
* if everything went OK or the pointer to the last filled triple
* (incomplete one) otherwise. Upon the return chain[i].key contains
* the number of (i+1)-th block in the chain (as it is stored in memory,
* i.e. little-endian 32-bit), chain[i].p contains the address of that
* number (it points into struct inode for i==0 and into the bh->b_data
* for i>0) and chain[i].bh points to the buffer_head of i-th indirect
* block for i>0 and NULL for i==0. In other words, it holds the block
* numbers of the chain, addresses they were taken from (and where we can
* verify that chain did not change) and buffer_heads hosting these
* numbers.
*
* Function stops when it stumbles upon zero pointer (absent block)
* (pointer to last triple returned, *@err == 0)
* or when it gets an IO error reading an indirect block
* (ditto, *@err == -EIO)
* or when it notices that chain had been changed while it was reading
* (ditto, *@err == -EAGAIN)
* or when it reads all @depth-1 indirect blocks successfully and finds
* the whole chain, all way to the data (returns %NULL, *err == 0).
*/
static Indirect *ext2_get_branch(struct inode *inode,
int depth,
int *offsets,
Indirect chain[4],
int *err)
{
struct super_block *sb = inode->i_sb;
Indirect *p = chain;
struct buffer_head *bh;
*err = 0;
/* i_data is not going away, no lock needed */
add_chain (chain, NULL, EXT2_I(inode)->i_data + *offsets);
if (!p->key)
goto no_block;
while (--depth) {
bh = sb_bread(sb, le32_to_cpu(p->key));
if (!bh)
goto failure;
read_lock(&EXT2_I(inode)->i_meta_lock);
if (!verify_chain(chain, p))
goto changed;
add_chain(++p, bh, (__le32*)bh->b_data + *++offsets);
read_unlock(&EXT2_I(inode)->i_meta_lock);
if (!p->key)
goto no_block;
}
return NULL;
changed:
read_unlock(&EXT2_I(inode)->i_meta_lock);
brelse(bh);
*err = -EAGAIN;
goto no_block;
failure:
*err = -EIO;
no_block:
return p;
}
/**
* ext2_find_near - find a place for allocation with sufficient locality
* @inode: owner
* @ind: descriptor of indirect block.
*
* This function returns the preferred place for block allocation.
* It is used when heuristic for sequential allocation fails.
* Rules are:
* + if there is a block to the left of our position - allocate near it.
* + if pointer will live in indirect block - allocate near that block.
* + if pointer will live in inode - allocate in the same cylinder group.
*
* In the latter case we colour the starting block by the callers PID to
* prevent it from clashing with concurrent allocations for a different inode
* in the same block group. The PID is used here so that functionally related
* files will be close-by on-disk.
*
* Caller must make sure that @ind is valid and will stay that way.
*/
static ext2_fsblk_t ext2_find_near(struct inode *inode, Indirect *ind)
{
struct ext2_inode_info *ei = EXT2_I(inode);
__le32 *start = ind->bh ? (__le32 *) ind->bh->b_data : ei->i_data;
__le32 *p;
ext2_fsblk_t bg_start;
ext2_fsblk_t colour;
/* Try to find previous block */
for (p = ind->p - 1; p >= start; p--)
if (*p)
return le32_to_cpu(*p);
/* No such thing, so let's try location of indirect block */
if (ind->bh)
return ind->bh->b_blocknr;
/*
* It is going to be referred from inode itself? OK, just put it into
* the same cylinder group then.
*/
bg_start = ext2_group_first_block_no(inode->i_sb, ei->i_block_group);
colour = (current->pid % 16) *
(EXT2_BLOCKS_PER_GROUP(inode->i_sb) / 16);
return bg_start + colour;
}
/**
* ext2_find_goal - find a preferred place for allocation.
* @inode: owner
* @block: block we want
* @partial: pointer to the last triple within a chain
*
* Returns preferred place for a block (the goal).
*/
static inline ext2_fsblk_t ext2_find_goal(struct inode *inode, long block,
Indirect *partial)
{
struct ext2_block_alloc_info *block_i;
block_i = EXT2_I(inode)->i_block_alloc_info;
/*
* try the heuristic for sequential allocation,
* failing that at least try to get decent locality.
*/
if (block_i && (block == block_i->last_alloc_logical_block + 1)
&& (block_i->last_alloc_physical_block != 0)) {
return block_i->last_alloc_physical_block + 1;
}
return ext2_find_near(inode, partial);
}
/**
* ext2_blks_to_allocate: Look up the block map and count the number
* of direct blocks need to be allocated for the given branch.
*
* @branch: chain of indirect blocks
* @k: number of blocks need for indirect blocks
* @blks: number of data blocks to be mapped.
* @blocks_to_boundary: the offset in the indirect block
*
* return the total number of blocks to be allocate, including the
* direct and indirect blocks.
*/
static int
ext2_blks_to_allocate(Indirect * branch, int k, unsigned long blks,
int blocks_to_boundary)
{
unsigned long count = 0;
/*
* Simple case, [t,d]Indirect block(s) has not allocated yet
* then it's clear blocks on that path have not allocated
*/
if (k > 0) {
/* right now don't hanel cross boundary allocation */
if (blks < blocks_to_boundary + 1)
count += blks;
else
count += blocks_to_boundary + 1;
return count;
}
count++;
while (count < blks && count <= blocks_to_boundary
&& le32_to_cpu(*(branch[0].p + count)) == 0) {
count++;
}
return count;
}
/**
* ext2_alloc_blocks: multiple allocate blocks needed for a branch
* @indirect_blks: the number of blocks need to allocate for indirect
* blocks
*
* @new_blocks: on return it will store the new block numbers for
* the indirect blocks(if needed) and the first direct block,
* @blks: on return it will store the total number of allocated
* direct blocks
*/
static int ext2_alloc_blocks(struct inode *inode,
ext2_fsblk_t goal, int indirect_blks, int blks,
ext2_fsblk_t new_blocks[4], int *err)
{
int target, i;
unsigned long count = 0;
int index = 0;
ext2_fsblk_t current_block = 0;
int ret = 0;
/*
* Here we try to allocate the requested multiple blocks at once,
* on a best-effort basis.
* To build a branch, we should allocate blocks for
* the indirect blocks(if not allocated yet), and at least
* the first direct block of this branch. That's the
* minimum number of blocks need to allocate(required)
*/
target = blks + indirect_blks;
while (1) {
count = target;
/* allocating blocks for indirect blocks and direct blocks */
current_block = ext2_new_blocks(inode,goal,&count,err);
if (*err)
goto failed_out;
target -= count;
/* allocate blocks for indirect blocks */
while (index < indirect_blks && count) {
new_blocks[index++] = current_block++;
count--;
}
if (count > 0)
break;
}
/* save the new block number for the first direct block */
new_blocks[index] = current_block;
/* total number of blocks allocated for direct blocks */
ret = count;
*err = 0;
return ret;
failed_out:
for (i = 0; i <index; i++)
ext2_free_blocks(inode, new_blocks[i], 1);
if (index)
mark_inode_dirty(inode);
return ret;
}
/**
* ext2_alloc_branch - allocate and set up a chain of blocks.
* @inode: owner
* @num: depth of the chain (number of blocks to allocate)
* @offsets: offsets (in the blocks) to store the pointers to next.
* @branch: place to store the chain in.
*
* This function allocates @num blocks, zeroes out all but the last one,
* links them into chain and (if we are synchronous) writes them to disk.
* In other words, it prepares a branch that can be spliced onto the
* inode. It stores the information about that chain in the branch[], in
* the same format as ext2_get_branch() would do. We are calling it after
* we had read the existing part of chain and partial points to the last
* triple of that (one with zero ->key). Upon the exit we have the same
* picture as after the successful ext2_get_block(), except that in one
* place chain is disconnected - *branch->p is still zero (we did not
* set the last link), but branch->key contains the number that should
* be placed into *branch->p to fill that gap.
*
* If allocation fails we free all blocks we've allocated (and forget
* their buffer_heads) and return the error value the from failed
* ext2_alloc_block() (normally -ENOSPC). Otherwise we set the chain
* as described above and return 0.
*/
static int ext2_alloc_branch(struct inode *inode,
int indirect_blks, int *blks, ext2_fsblk_t goal,
int *offsets, Indirect *branch)
{
int blocksize = inode->i_sb->s_blocksize;
int i, n = 0;
int err = 0;
struct buffer_head *bh;
int num;
ext2_fsblk_t new_blocks[4];
ext2_fsblk_t current_block;
num = ext2_alloc_blocks(inode, goal, indirect_blks,
*blks, new_blocks, &err);
if (err)
return err;
branch[0].key = cpu_to_le32(new_blocks[0]);
/*
* metadata blocks and data blocks are allocated.
*/
for (n = 1; n <= indirect_blks; n++) {
/*
* Get buffer_head for parent block, zero it out
* and set the pointer to new one, then send
* parent to disk.
*/
bh = sb_getblk(inode->i_sb, new_blocks[n-1]);
if (unlikely(!bh)) {
err = -ENOMEM;
goto failed;
}
branch[n].bh = bh;
lock_buffer(bh);
memset(bh->b_data, 0, blocksize);
branch[n].p = (__le32 *) bh->b_data + offsets[n];
branch[n].key = cpu_to_le32(new_blocks[n]);
*branch[n].p = branch[n].key;
if ( n == indirect_blks) {
current_block = new_blocks[n];
/*
* End of chain, update the last new metablock of
* the chain to point to the new allocated
* data blocks numbers
*/
for (i=1; i < num; i++)
*(branch[n].p + i) = cpu_to_le32(++current_block);
}
set_buffer_uptodate(bh);
unlock_buffer(bh);
mark_buffer_dirty_inode(bh, inode);
/* We used to sync bh here if IS_SYNC(inode).
* But we now rely upon generic_write_sync()
* and b_inode_buffers. But not for directories.
*/
if (S_ISDIR(inode->i_mode) && IS_DIRSYNC(inode))
sync_dirty_buffer(bh);
}
*blks = num;
return err;
failed:
for (i = 1; i < n; i++)
bforget(branch[i].bh);
for (i = 0; i < indirect_blks; i++)
ext2_free_blocks(inode, new_blocks[i], 1);
ext2_free_blocks(inode, new_blocks[i], num);
return err;
}
/**
* ext2_splice_branch - splice the allocated branch onto inode.
* @inode: owner
* @block: (logical) number of block we are adding
* @where: location of missing link
* @num: number of indirect blocks we are adding
* @blks: number of direct blocks we are adding
*
* This function fills the missing link and does all housekeeping needed in
* inode (->i_blocks, etc.). In case of success we end up with the full
* chain to new block and return 0.
*/
static void ext2_splice_branch(struct inode *inode,
long block, Indirect *where, int num, int blks)
{
int i;
struct ext2_block_alloc_info *block_i;
ext2_fsblk_t current_block;
block_i = EXT2_I(inode)->i_block_alloc_info;
/* XXX LOCKING probably should have i_meta_lock ?*/
/* That's it */
*where->p = where->key;
/*
* Update the host buffer_head or inode to point to more just allocated
* direct blocks blocks
*/
if (num == 0 && blks > 1) {
current_block = le32_to_cpu(where->key) + 1;
for (i = 1; i < blks; i++)
*(where->p + i ) = cpu_to_le32(current_block++);
}
/*
* update the most recently allocated logical & physical block
* in i_block_alloc_info, to assist find the proper goal block for next
* allocation
*/
if (block_i) {
block_i->last_alloc_logical_block = block + blks - 1;
block_i->last_alloc_physical_block =
le32_to_cpu(where[num].key) + blks - 1;
}
/* We are done with atomic stuff, now do the rest of housekeeping */
/* had we spliced it onto indirect block? */
if (where->bh)
mark_buffer_dirty_inode(where->bh, inode);
inode->i_ctime = CURRENT_TIME_SEC;
mark_inode_dirty(inode);
}
/*
* Allocation strategy is simple: if we have to allocate something, we will
* have to go the whole way to leaf. So let's do it before attaching anything
* to tree, set linkage between the newborn blocks, write them if sync is
* required, recheck the path, free and repeat if check fails, otherwise
* set the last missing link (that will protect us from any truncate-generated
* removals - all blocks on the path are immune now) and possibly force the
* write on the parent block.
* That has a nice additional property: no special recovery from the failed
* allocations is needed - we simply release blocks and do not touch anything
* reachable from inode.
*
* `handle' can be NULL if create == 0.
*
* return > 0, # of blocks mapped or allocated.
* return = 0, if plain lookup failed.
* return < 0, error case.
*/
static int ext2_get_blocks(struct inode *inode,
sector_t iblock, unsigned long maxblocks,
struct buffer_head *bh_result,
int create)
{
int err = -EIO;
int offsets[4];
Indirect chain[4];
Indirect *partial;
ext2_fsblk_t goal;
int indirect_blks;
int blocks_to_boundary = 0;
int depth;
struct ext2_inode_info *ei = EXT2_I(inode);
int count = 0;
ext2_fsblk_t first_block = 0;
BUG_ON(maxblocks == 0);
depth = ext2_block_to_path(inode,iblock,offsets,&blocks_to_boundary);
if (depth == 0)
return (err);
partial = ext2_get_branch(inode, depth, offsets, chain, &err);
/* Simplest case - block found, no allocation needed */
if (!partial) {
first_block = le32_to_cpu(chain[depth - 1].key);
clear_buffer_new(bh_result); /* What's this do? */
count++;
/*map more blocks*/
while (count < maxblocks && count <= blocks_to_boundary) {
ext2_fsblk_t blk;
if (!verify_chain(chain, chain + depth - 1)) {
/*
* Indirect block might be removed by
* truncate while we were reading it.
* Handling of that case: forget what we've
* got now, go to reread.
*/
err = -EAGAIN;
count = 0;
break;
}
blk = le32_to_cpu(*(chain[depth-1].p + count));
if (blk == first_block + count)
count++;
else
break;
}
if (err != -EAGAIN)
goto got_it;
}
/* Next simple case - plain lookup or failed read of indirect block */
if (!create || err == -EIO)
goto cleanup;
mutex_lock(&ei->truncate_mutex);
/*
* If the indirect block is missing while we are reading
* the chain(ext2_get_branch() returns -EAGAIN err), or
* if the chain has been changed after we grab the semaphore,
* (either because another process truncated this branch, or
* another get_block allocated this branch) re-grab the chain to see if
* the request block has been allocated or not.
*
* Since we already block the truncate/other get_block
* at this point, we will have the current copy of the chain when we
* splice the branch into the tree.
*/
if (err == -EAGAIN || !verify_chain(chain, partial)) {
while (partial > chain) {
brelse(partial->bh);
partial--;
}
partial = ext2_get_branch(inode, depth, offsets, chain, &err);
if (!partial) {
count++;
mutex_unlock(&ei->truncate_mutex);
if (err)
goto cleanup;
clear_buffer_new(bh_result);
goto got_it;
}
}
/*
* Okay, we need to do block allocation. Lazily initialize the block
* allocation info here if necessary
*/
if (S_ISREG(inode->i_mode) && (!ei->i_block_alloc_info))
ext2_init_block_alloc_info(inode);
goal = ext2_find_goal(inode, iblock, partial);
/* the number of blocks need to allocate for [d,t]indirect blocks */
indirect_blks = (chain + depth) - partial - 1;
/*
* Next look up the indirect map to count the totoal number of
* direct blocks to allocate for this branch.
*/
count = ext2_blks_to_allocate(partial, indirect_blks,
maxblocks, blocks_to_boundary);
/*
* XXX ???? Block out ext2_truncate while we alter the tree
*/
err = ext2_alloc_branch(inode, indirect_blks, &count, goal,
offsets + (partial - chain), partial);
if (err) {
mutex_unlock(&ei->truncate_mutex);
goto cleanup;
}
if (IS_DAX(inode)) {
/*
* block must be initialised before we put it in the tree
* so that it's not found by another thread before it's
* initialised
*/
err = dax_clear_blocks(inode, le32_to_cpu(chain[depth-1].key),
1 << inode->i_blkbits);
if (err) {
mutex_unlock(&ei->truncate_mutex);
goto cleanup;
}
}
ext2_splice_branch(inode, iblock, partial, indirect_blks, count);
mutex_unlock(&ei->truncate_mutex);
set_buffer_new(bh_result);
got_it:
map_bh(bh_result, inode->i_sb, le32_to_cpu(chain[depth-1].key));
if (count > blocks_to_boundary)
set_buffer_boundary(bh_result);
err = count;
/* Clean up and exit */
partial = chain + depth - 1; /* the whole chain */
cleanup:
while (partial > chain) {
brelse(partial->bh);
partial--;
}
return err;
}
int ext2_get_block(struct inode *inode, sector_t iblock, struct buffer_head *bh_result, int create)
{
unsigned max_blocks = bh_result->b_size >> inode->i_blkbits;
int ret = ext2_get_blocks(inode, iblock, max_blocks,
bh_result, create);
if (ret > 0) {
bh_result->b_size = (ret << inode->i_blkbits);
ret = 0;
}
return ret;
}
int ext2_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
u64 start, u64 len)
{
return generic_block_fiemap(inode, fieinfo, start, len,
ext2_get_block);
}
static int ext2_writepage(struct page *page, struct writeback_control *wbc)
{
return block_write_full_page(page, ext2_get_block, wbc);
}
static int ext2_readpage(struct file *file, struct page *page)
{
return mpage_readpage(page, ext2_get_block);
}
static int
ext2_readpages(struct file *file, struct address_space *mapping,
struct list_head *pages, unsigned nr_pages)
{
return mpage_readpages(mapping, pages, nr_pages, ext2_get_block);
}
static int
ext2_write_begin(struct file *file, struct address_space *mapping,
loff_t pos, unsigned len, unsigned flags,
struct page **pagep, void **fsdata)
{
int ret;
ret = block_write_begin(mapping, pos, len, flags, pagep,
ext2_get_block);
if (ret < 0)
ext2_write_failed(mapping, pos + len);
return ret;
}
static int ext2_write_end(struct file *file, struct address_space *mapping,
loff_t pos, unsigned len, unsigned copied,
struct page *page, void *fsdata)
{
int ret;
ret = generic_write_end(file, mapping, pos, len, copied, page, fsdata);
if (ret < len)
ext2_write_failed(mapping, pos + len);
return ret;
}
static int
ext2_nobh_write_begin(struct file *file, struct address_space *mapping,
loff_t pos, unsigned len, unsigned flags,
struct page **pagep, void **fsdata)
{
int ret;
ret = nobh_write_begin(mapping, pos, len, flags, pagep, fsdata,
ext2_get_block);
if (ret < 0)
ext2_write_failed(mapping, pos + len);
return ret;
}
static int ext2_nobh_writepage(struct page *page,
struct writeback_control *wbc)
{
return nobh_writepage(page, ext2_get_block, wbc);
}
static sector_t ext2_bmap(struct address_space *mapping, sector_t block)
{
return generic_block_bmap(mapping,block,ext2_get_block);
}
static ssize_t
ext2_direct_IO(struct kiocb *iocb, struct iov_iter *iter, loff_t offset)
{
struct file *file = iocb->ki_filp;
struct address_space *mapping = file->f_mapping;
struct inode *inode = mapping->host;
size_t count = iov_iter_count(iter);
ssize_t ret;
if (IS_DAX(inode))
ret = dax_do_io(iocb, inode, iter, offset, ext2_get_block, NULL,
DIO_LOCKING);
else
ret = blockdev_direct_IO(iocb, inode, iter, offset,
ext2_get_block);
if (ret < 0 && iov_iter_rw(iter) == WRITE)
ext2_write_failed(mapping, offset + count);
return ret;
}
static int
ext2_writepages(struct address_space *mapping, struct writeback_control *wbc)
{
return mpage_writepages(mapping, wbc, ext2_get_block);
}
const struct address_space_operations ext2_aops = {
.readpage = ext2_readpage,
.readpages = ext2_readpages,
.writepage = ext2_writepage,
.write_begin = ext2_write_begin,
.write_end = ext2_write_end,
.bmap = ext2_bmap,
.direct_IO = ext2_direct_IO,
.writepages = ext2_writepages,
.migratepage = buffer_migrate_page,
.is_partially_uptodate = block_is_partially_uptodate,
.error_remove_page = generic_error_remove_page,
};
const struct address_space_operations ext2_nobh_aops = {
.readpage = ext2_readpage,
.readpages = ext2_readpages,
.writepage = ext2_nobh_writepage,
.write_begin = ext2_nobh_write_begin,
.write_end = nobh_write_end,
.bmap = ext2_bmap,
.direct_IO = ext2_direct_IO,
.writepages = ext2_writepages,
.migratepage = buffer_migrate_page,
.error_remove_page = generic_error_remove_page,
};
/*
* Probably it should be a library function... search for first non-zero word
* or memcmp with zero_page, whatever is better for particular architecture.
* Linus?
*/
static inline int all_zeroes(__le32 *p, __le32 *q)
{
while (p < q)
if (*p++)
return 0;
return 1;
}
/**
* ext2_find_shared - find the indirect blocks for partial truncation.
* @inode: inode in question
* @depth: depth of the affected branch
* @offsets: offsets of pointers in that branch (see ext2_block_to_path)
* @chain: place to store the pointers to partial indirect blocks
* @top: place to the (detached) top of branch
*
* This is a helper function used by ext2_truncate().
*
* When we do truncate() we may have to clean the ends of several indirect
* blocks but leave the blocks themselves alive. Block is partially
* truncated if some data below the new i_size is referred from it (and
* it is on the path to the first completely truncated data block, indeed).
* We have to free the top of that path along with everything to the right
* of the path. Since no allocation past the truncation point is possible
* until ext2_truncate() finishes, we may safely do the latter, but top
* of branch may require special attention - pageout below the truncation
* point might try to populate it.
*
* We atomically detach the top of branch from the tree, store the block
* number of its root in *@top, pointers to buffer_heads of partially
* truncated blocks - in @chain[].bh and pointers to their last elements
* that should not be removed - in @chain[].p. Return value is the pointer
* to last filled element of @chain.
*
* The work left to caller to do the actual freeing of subtrees:
* a) free the subtree starting from *@top
* b) free the subtrees whose roots are stored in
* (@chain[i].p+1 .. end of @chain[i].bh->b_data)
* c) free the subtrees growing from the inode past the @chain[0].p
* (no partially truncated stuff there).
*/
static Indirect *ext2_find_shared(struct inode *inode,
int depth,
int offsets[4],
Indirect chain[4],
__le32 *top)
{
Indirect *partial, *p;
int k, err;
*top = 0;
for (k = depth; k > 1 && !offsets[k-1]; k--)
;
partial = ext2_get_branch(inode, k, offsets, chain, &err);
if (!partial)
partial = chain + k-1;
/*
* If the branch acquired continuation since we've looked at it -
* fine, it should all survive and (new) top doesn't belong to us.
*/
write_lock(&EXT2_I(inode)->i_meta_lock);
if (!partial->key && *partial->p) {
write_unlock(&EXT2_I(inode)->i_meta_lock);
goto no_top;
}
for (p=partial; p>chain && all_zeroes((__le32*)p->bh->b_data,p->p); p--)
;
/*
* OK, we've found the last block that must survive. The rest of our
* branch should be detached before unlocking. However, if that rest
* of branch is all ours and does not grow immediately from the inode
* it's easier to cheat and just decrement partial->p.
*/
if (p == chain + k - 1 && p > chain) {
p->p--;
} else {
*top = *p->p;
*p->p = 0;
}
write_unlock(&EXT2_I(inode)->i_meta_lock);
while(partial > p)
{
brelse(partial->bh);
partial--;
}
no_top:
return partial;
}
/**
* ext2_free_data - free a list of data blocks
* @inode: inode we are dealing with
* @p: array of block numbers
* @q: points immediately past the end of array
*
* We are freeing all blocks referred from that array (numbers are
* stored as little-endian 32-bit) and updating @inode->i_blocks
* appropriately.
*/
static inline void ext2_free_data(struct inode *inode, __le32 *p, __le32 *q)
{
unsigned long block_to_free = 0, count = 0;
unsigned long nr;
for ( ; p < q ; p++) {
nr = le32_to_cpu(*p);
if (nr) {
*p = 0;
/* accumulate blocks to free if they're contiguous */
if (count == 0)
goto free_this;
else if (block_to_free == nr - count)
count++;
else {
ext2_free_blocks (inode, block_to_free, count);
mark_inode_dirty(inode);
free_this:
block_to_free = nr;
count = 1;
}
}
}
if (count > 0) {
ext2_free_blocks (inode, block_to_free, count);
mark_inode_dirty(inode);
}
}
/**
* ext2_free_branches - free an array of branches
* @inode: inode we are dealing with
* @p: array of block numbers
* @q: pointer immediately past the end of array
* @depth: depth of the branches to free
*
* We are freeing all blocks referred from these branches (numbers are
* stored as little-endian 32-bit) and updating @inode->i_blocks
* appropriately.
*/
static void ext2_free_branches(struct inode *inode, __le32 *p, __le32 *q, int depth)
{
struct buffer_head * bh;
unsigned long nr;
if (depth--) {
int addr_per_block = EXT2_ADDR_PER_BLOCK(inode->i_sb);
for ( ; p < q ; p++) {
nr = le32_to_cpu(*p);
if (!nr)
continue;
*p = 0;
bh = sb_bread(inode->i_sb, nr);
/*
* A read failure? Report error and clear slot
* (should be rare).
*/
if (!bh) {
ext2_error(inode->i_sb, "ext2_free_branches",
"Read failure, inode=%ld, block=%ld",
inode->i_ino, nr);
continue;
}
ext2_free_branches(inode,
(__le32*)bh->b_data,
(__le32*)bh->b_data + addr_per_block,
depth);
bforget(bh);
ext2_free_blocks(inode, nr, 1);
mark_inode_dirty(inode);
}
} else
ext2_free_data(inode, p, q);
}
/* dax_sem must be held when calling this function */
static void __ext2_truncate_blocks(struct inode *inode, loff_t offset)
{
__le32 *i_data = EXT2_I(inode)->i_data;
struct ext2_inode_info *ei = EXT2_I(inode);
int addr_per_block = EXT2_ADDR_PER_BLOCK(inode->i_sb);
int offsets[4];
Indirect chain[4];
Indirect *partial;
__le32 nr = 0;
int n;
long iblock;
unsigned blocksize;
blocksize = inode->i_sb->s_blocksize;
iblock = (offset + blocksize-1) >> EXT2_BLOCK_SIZE_BITS(inode->i_sb);
#ifdef CONFIG_FS_DAX
WARN_ON(!rwsem_is_locked(&ei->dax_sem));
#endif
n = ext2_block_to_path(inode, iblock, offsets, NULL);
if (n == 0)
return;
/*
* From here we block out all ext2_get_block() callers who want to
* modify the block allocation tree.
*/
mutex_lock(&ei->truncate_mutex);
if (n == 1) {
ext2_free_data(inode, i_data+offsets[0],
i_data + EXT2_NDIR_BLOCKS);
goto do_indirects;
}
partial = ext2_find_shared(inode, n, offsets, chain, &nr);
/* Kill the top of shared branch (already detached) */
if (nr) {
if (partial == chain)
mark_inode_dirty(inode);
else
mark_buffer_dirty_inode(partial->bh, inode);
ext2_free_branches(inode, &nr, &nr+1, (chain+n-1) - partial);
}
/* Clear the ends of indirect blocks on the shared branch */
while (partial > chain) {
ext2_free_branches(inode,
partial->p + 1,
(__le32*)partial->bh->b_data+addr_per_block,
(chain+n-1) - partial);
mark_buffer_dirty_inode(partial->bh, inode);
brelse (partial->bh);
partial--;
}
do_indirects:
/* Kill the remaining (whole) subtrees */
switch (offsets[0]) {
default:
nr = i_data[EXT2_IND_BLOCK];
if (nr) {
i_data[EXT2_IND_BLOCK] = 0;
mark_inode_dirty(inode);
ext2_free_branches(inode, &nr, &nr+1, 1);
}
case EXT2_IND_BLOCK:
nr = i_data[EXT2_DIND_BLOCK];
if (nr) {
i_data[EXT2_DIND_BLOCK] = 0;
mark_inode_dirty(inode);
ext2_free_branches(inode, &nr, &nr+1, 2);
}
case EXT2_DIND_BLOCK:
nr = i_data[EXT2_TIND_BLOCK];
if (nr) {
i_data[EXT2_TIND_BLOCK] = 0;
mark_inode_dirty(inode);
ext2_free_branches(inode, &nr, &nr+1, 3);
}
case EXT2_TIND_BLOCK:
;
}
ext2_discard_reservation(inode);
mutex_unlock(&ei->truncate_mutex);
}
static void ext2_truncate_blocks(struct inode *inode, loff_t offset)
{
/*
* XXX: it seems like a bug here that we don't allow
* IS_APPEND inode to have blocks-past-i_size trimmed off.
* review and fix this.
*
* Also would be nice to be able to handle IO errors and such,
* but that's probably too much to ask.
*/
if (!(S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
S_ISLNK(inode->i_mode)))
return;
if (ext2_inode_is_fast_symlink(inode))
return;
if (IS_APPEND(inode) || IS_IMMUTABLE(inode))
return;
dax_sem_down_write(EXT2_I(inode));
__ext2_truncate_blocks(inode, offset);
dax_sem_up_write(EXT2_I(inode));
}
static int ext2_setsize(struct inode *inode, loff_t newsize)
{
int error;
if (!(S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
S_ISLNK(inode->i_mode)))
return -EINVAL;
if (ext2_inode_is_fast_symlink(inode))
return -EINVAL;
if (IS_APPEND(inode) || IS_IMMUTABLE(inode))
return -EPERM;
inode_dio_wait(inode);
if (IS_DAX(inode))
error = dax_truncate_page(inode, newsize, ext2_get_block);
else if (test_opt(inode->i_sb, NOBH))
error = nobh_truncate_page(inode->i_mapping,
newsize, ext2_get_block);
else
error = block_truncate_page(inode->i_mapping,
newsize, ext2_get_block);
if (error)
return error;
dax_sem_down_write(EXT2_I(inode));
truncate_setsize(inode, newsize);
__ext2_truncate_blocks(inode, newsize);
dax_sem_up_write(EXT2_I(inode));
inode->i_mtime = inode->i_ctime = CURRENT_TIME_SEC;
if (inode_needs_sync(inode)) {
sync_mapping_buffers(inode->i_mapping);
sync_inode_metadata(inode, 1);
} else {
mark_inode_dirty(inode);
}
return 0;
}
static struct ext2_inode *ext2_get_inode(struct super_block *sb, ino_t ino,
struct buffer_head **p)
{
struct buffer_head * bh;
unsigned long block_group;
unsigned long block;
unsigned long offset;
struct ext2_group_desc * gdp;
*p = NULL;
if ((ino != EXT2_ROOT_INO && ino < EXT2_FIRST_INO(sb)) ||
ino > le32_to_cpu(EXT2_SB(sb)->s_es->s_inodes_count))
goto Einval;
block_group = (ino - 1) / EXT2_INODES_PER_GROUP(sb);
gdp = ext2_get_group_desc(sb, block_group, NULL);
if (!gdp)
goto Egdp;
/*
* Figure out the offset within the block group inode table
*/
offset = ((ino - 1) % EXT2_INODES_PER_GROUP(sb)) * EXT2_INODE_SIZE(sb);
block = le32_to_cpu(gdp->bg_inode_table) +
(offset >> EXT2_BLOCK_SIZE_BITS(sb));
if (!(bh = sb_bread(sb, block)))
goto Eio;
*p = bh;
offset &= (EXT2_BLOCK_SIZE(sb) - 1);
return (struct ext2_inode *) (bh->b_data + offset);
Einval:
ext2_error(sb, "ext2_get_inode", "bad inode number: %lu",
(unsigned long) ino);
return ERR_PTR(-EINVAL);
Eio:
ext2_error(sb, "ext2_get_inode",
"unable to read inode block - inode=%lu, block=%lu",
(unsigned long) ino, block);
Egdp:
return ERR_PTR(-EIO);
}
void ext2_set_inode_flags(struct inode *inode)
{
unsigned int flags = EXT2_I(inode)->i_flags;
inode->i_flags &= ~(S_SYNC | S_APPEND | S_IMMUTABLE | S_NOATIME |
S_DIRSYNC | S_DAX);
if (flags & EXT2_SYNC_FL)
inode->i_flags |= S_SYNC;
if (flags & EXT2_APPEND_FL)
inode->i_flags |= S_APPEND;
if (flags & EXT2_IMMUTABLE_FL)
inode->i_flags |= S_IMMUTABLE;
if (flags & EXT2_NOATIME_FL)
inode->i_flags |= S_NOATIME;
if (flags & EXT2_DIRSYNC_FL)
inode->i_flags |= S_DIRSYNC;
if (test_opt(inode->i_sb, DAX))
inode->i_flags |= S_DAX;
}
/* Propagate flags from i_flags to EXT2_I(inode)->i_flags */
void ext2_get_inode_flags(struct ext2_inode_info *ei)
{
unsigned int flags = ei->vfs_inode.i_flags;
ei->i_flags &= ~(EXT2_SYNC_FL|EXT2_APPEND_FL|
EXT2_IMMUTABLE_FL|EXT2_NOATIME_FL|EXT2_DIRSYNC_FL);
if (flags & S_SYNC)
ei->i_flags |= EXT2_SYNC_FL;
if (flags & S_APPEND)
ei->i_flags |= EXT2_APPEND_FL;
if (flags & S_IMMUTABLE)
ei->i_flags |= EXT2_IMMUTABLE_FL;
if (flags & S_NOATIME)
ei->i_flags |= EXT2_NOATIME_FL;
if (flags & S_DIRSYNC)
ei->i_flags |= EXT2_DIRSYNC_FL;
}
struct inode *ext2_iget (struct super_block *sb, unsigned long ino)
{
struct ext2_inode_info *ei;
struct buffer_head * bh;
struct ext2_inode *raw_inode;
struct inode *inode;
long ret = -EIO;
int n;
uid_t i_uid;
gid_t i_gid;
inode = iget_locked(sb, ino);
if (!inode)
return ERR_PTR(-ENOMEM);
if (!(inode->i_state & I_NEW))
return inode;
ei = EXT2_I(inode);
ei->i_block_alloc_info = NULL;
raw_inode = ext2_get_inode(inode->i_sb, ino, &bh);
if (IS_ERR(raw_inode)) {
ret = PTR_ERR(raw_inode);
goto bad_inode;
}
inode->i_mode = le16_to_cpu(raw_inode->i_mode);
i_uid = (uid_t)le16_to_cpu(raw_inode->i_uid_low);
i_gid = (gid_t)le16_to_cpu(raw_inode->i_gid_low);
if (!(test_opt (inode->i_sb, NO_UID32))) {
i_uid |= le16_to_cpu(raw_inode->i_uid_high) << 16;
i_gid |= le16_to_cpu(raw_inode->i_gid_high) << 16;
}
i_uid_write(inode, i_uid);
i_gid_write(inode, i_gid);
set_nlink(inode, le16_to_cpu(raw_inode->i_links_count));
inode->i_size = le32_to_cpu(raw_inode->i_size);
inode->i_atime.tv_sec = (signed)le32_to_cpu(raw_inode->i_atime);
inode->i_ctime.tv_sec = (signed)le32_to_cpu(raw_inode->i_ctime);
inode->i_mtime.tv_sec = (signed)le32_to_cpu(raw_inode->i_mtime);
inode->i_atime.tv_nsec = inode->i_mtime.tv_nsec = inode->i_ctime.tv_nsec = 0;
ei->i_dtime = le32_to_cpu(raw_inode->i_dtime);
/* We now have enough fields to check if the inode was active or not.
* This is needed because nfsd might try to access dead inodes
* the test is that same one that e2fsck uses
* NeilBrown 1999oct15
*/
if (inode->i_nlink == 0 && (inode->i_mode == 0 || ei->i_dtime)) {
/* this inode is deleted */
brelse (bh);
ret = -ESTALE;
goto bad_inode;
}
inode->i_blocks = le32_to_cpu(raw_inode->i_blocks);
ei->i_flags = le32_to_cpu(raw_inode->i_flags);
ei->i_faddr = le32_to_cpu(raw_inode->i_faddr);
ei->i_frag_no = raw_inode->i_frag;
ei->i_frag_size = raw_inode->i_fsize;
ei->i_file_acl = le32_to_cpu(raw_inode->i_file_acl);
ei->i_dir_acl = 0;
if (S_ISREG(inode->i_mode))
inode->i_size |= ((__u64)le32_to_cpu(raw_inode->i_size_high)) << 32;
else
ei->i_dir_acl = le32_to_cpu(raw_inode->i_dir_acl);
ei->i_dtime = 0;
inode->i_generation = le32_to_cpu(raw_inode->i_generation);
ei->i_state = 0;
ei->i_block_group = (ino - 1) / EXT2_INODES_PER_GROUP(inode->i_sb);
ei->i_dir_start_lookup = 0;
/*
* NOTE! The in-memory inode i_data array is in little-endian order
* even on big-endian machines: we do NOT byteswap the block numbers!
*/
for (n = 0; n < EXT2_N_BLOCKS; n++)
ei->i_data[n] = raw_inode->i_block[n];
if (S_ISREG(inode->i_mode)) {
inode->i_op = &ext2_file_inode_operations;
if (test_opt(inode->i_sb, NOBH)) {
inode->i_mapping->a_ops = &ext2_nobh_aops;
inode->i_fop = &ext2_file_operations;
} else {
inode->i_mapping->a_ops = &ext2_aops;
inode->i_fop = &ext2_file_operations;
}
} else if (S_ISDIR(inode->i_mode)) {
inode->i_op = &ext2_dir_inode_operations;
inode->i_fop = &ext2_dir_operations;
if (test_opt(inode->i_sb, NOBH))
inode->i_mapping->a_ops = &ext2_nobh_aops;
else
inode->i_mapping->a_ops = &ext2_aops;
} else if (S_ISLNK(inode->i_mode)) {
if (ext2_inode_is_fast_symlink(inode)) {
inode->i_link = (char *)ei->i_data;
inode->i_op = &ext2_fast_symlink_inode_operations;
nd_terminate_link(ei->i_data, inode->i_size,
sizeof(ei->i_data) - 1);
} else {
inode->i_op = &ext2_symlink_inode_operations;
if (test_opt(inode->i_sb, NOBH))
inode->i_mapping->a_ops = &ext2_nobh_aops;
else
inode->i_mapping->a_ops = &ext2_aops;
}
} else {
inode->i_op = &ext2_special_inode_operations;
if (raw_inode->i_block[0])
init_special_inode(inode, inode->i_mode,
old_decode_dev(le32_to_cpu(raw_inode->i_block[0])));
else
init_special_inode(inode, inode->i_mode,
new_decode_dev(le32_to_cpu(raw_inode->i_block[1])));
}
brelse (bh);
ext2_set_inode_flags(inode);
unlock_new_inode(inode);
return inode;
bad_inode:
iget_failed(inode);
return ERR_PTR(ret);
}
static int __ext2_write_inode(struct inode *inode, int do_sync)
{
struct ext2_inode_info *ei = EXT2_I(inode);
struct super_block *sb = inode->i_sb;
ino_t ino = inode->i_ino;
uid_t uid = i_uid_read(inode);
gid_t gid = i_gid_read(inode);
struct buffer_head * bh;
struct ext2_inode * raw_inode = ext2_get_inode(sb, ino, &bh);
int n;
int err = 0;
if (IS_ERR(raw_inode))
return -EIO;
/* For fields not not tracking in the in-memory inode,
* initialise them to zero for new inodes. */
if (ei->i_state & EXT2_STATE_NEW)
memset(raw_inode, 0, EXT2_SB(sb)->s_inode_size);
ext2_get_inode_flags(ei);
raw_inode->i_mode = cpu_to_le16(inode->i_mode);
if (!(test_opt(sb, NO_UID32))) {
raw_inode->i_uid_low = cpu_to_le16(low_16_bits(uid));
raw_inode->i_gid_low = cpu_to_le16(low_16_bits(gid));
/*
* Fix up interoperability with old kernels. Otherwise, old inodes get
* re-used with the upper 16 bits of the uid/gid intact
*/
if (!ei->i_dtime) {
raw_inode->i_uid_high = cpu_to_le16(high_16_bits(uid));
raw_inode->i_gid_high = cpu_to_le16(high_16_bits(gid));
} else {
raw_inode->i_uid_high = 0;
raw_inode->i_gid_high = 0;
}
} else {
raw_inode->i_uid_low = cpu_to_le16(fs_high2lowuid(uid));
raw_inode->i_gid_low = cpu_to_le16(fs_high2lowgid(gid));
raw_inode->i_uid_high = 0;
raw_inode->i_gid_high = 0;
}
raw_inode->i_links_count = cpu_to_le16(inode->i_nlink);
raw_inode->i_size = cpu_to_le32(inode->i_size);
raw_inode->i_atime = cpu_to_le32(inode->i_atime.tv_sec);
raw_inode->i_ctime = cpu_to_le32(inode->i_ctime.tv_sec);
raw_inode->i_mtime = cpu_to_le32(inode->i_mtime.tv_sec);
raw_inode->i_blocks = cpu_to_le32(inode->i_blocks);
raw_inode->i_dtime = cpu_to_le32(ei->i_dtime);
raw_inode->i_flags = cpu_to_le32(ei->i_flags);
raw_inode->i_faddr = cpu_to_le32(ei->i_faddr);
raw_inode->i_frag = ei->i_frag_no;
raw_inode->i_fsize = ei->i_frag_size;
raw_inode->i_file_acl = cpu_to_le32(ei->i_file_acl);
if (!S_ISREG(inode->i_mode))
raw_inode->i_dir_acl = cpu_to_le32(ei->i_dir_acl);
else {
raw_inode->i_size_high = cpu_to_le32(inode->i_size >> 32);
if (inode->i_size > 0x7fffffffULL) {
if (!EXT2_HAS_RO_COMPAT_FEATURE(sb,
EXT2_FEATURE_RO_COMPAT_LARGE_FILE) ||
EXT2_SB(sb)->s_es->s_rev_level ==
cpu_to_le32(EXT2_GOOD_OLD_REV)) {
/* If this is the first large file
* created, add a flag to the superblock.
*/
spin_lock(&EXT2_SB(sb)->s_lock);
ext2_update_dynamic_rev(sb);
EXT2_SET_RO_COMPAT_FEATURE(sb,
EXT2_FEATURE_RO_COMPAT_LARGE_FILE);
spin_unlock(&EXT2_SB(sb)->s_lock);
ext2_write_super(sb);
}
}
}
raw_inode->i_generation = cpu_to_le32(inode->i_generation);
if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
if (old_valid_dev(inode->i_rdev)) {
raw_inode->i_block[0] =
cpu_to_le32(old_encode_dev(inode->i_rdev));
raw_inode->i_block[1] = 0;
} else {
raw_inode->i_block[0] = 0;
raw_inode->i_block[1] =
cpu_to_le32(new_encode_dev(inode->i_rdev));
raw_inode->i_block[2] = 0;
}
} else for (n = 0; n < EXT2_N_BLOCKS; n++)
raw_inode->i_block[n] = ei->i_data[n];
mark_buffer_dirty(bh);
if (do_sync) {
sync_dirty_buffer(bh);
if (buffer_req(bh) && !buffer_uptodate(bh)) {
printk ("IO error syncing ext2 inode [%s:%08lx]\n",
sb->s_id, (unsigned long) ino);
err = -EIO;
}
}
ei->i_state &= ~EXT2_STATE_NEW;
brelse (bh);
return err;
}
int ext2_write_inode(struct inode *inode, struct writeback_control *wbc)
{
return __ext2_write_inode(inode, wbc->sync_mode == WB_SYNC_ALL);
}
int ext2_setattr(struct dentry *dentry, struct iattr *iattr)
{
struct inode *inode = d_inode(dentry);
int error;
error = inode_change_ok(inode, iattr);
if (error)
return error;
if (is_quota_modification(inode, iattr)) {
error = dquot_initialize(inode);
if (error)
return error;
}
if ((iattr->ia_valid & ATTR_UID && !uid_eq(iattr->ia_uid, inode->i_uid)) ||
(iattr->ia_valid & ATTR_GID && !gid_eq(iattr->ia_gid, inode->i_gid))) {
error = dquot_transfer(inode, iattr);
if (error)
return error;
}
if (iattr->ia_valid & ATTR_SIZE && iattr->ia_size != inode->i_size) {
error = ext2_setsize(inode, iattr->ia_size);
if (error)
return error;
}
setattr_copy(inode, iattr);
if (iattr->ia_valid & ATTR_MODE)
error = posix_acl_chmod(inode, inode->i_mode);
mark_inode_dirty(inode);
return error;
}
| {
"pile_set_name": "Github"
} |
<?php
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
class Google_Service_CloudSourceRepositories_PubsubConfig extends Google_Model
{
public $messageFormat;
public $serviceAccountEmail;
public $topic;
public function setMessageFormat($messageFormat)
{
$this->messageFormat = $messageFormat;
}
public function getMessageFormat()
{
return $this->messageFormat;
}
public function setServiceAccountEmail($serviceAccountEmail)
{
$this->serviceAccountEmail = $serviceAccountEmail;
}
public function getServiceAccountEmail()
{
return $this->serviceAccountEmail;
}
public function setTopic($topic)
{
$this->topic = $topic;
}
public function getTopic()
{
return $this->topic;
}
}
| {
"pile_set_name": "Github"
} |
/**
* OpenAL cross platform audio library
* Copyright (C) 2011 by authors.
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
* Or go to http://www.gnu.org/copyleft/lgpl.html
*/
#ifdef _WIN32
#ifdef __MINGW32__
#define _WIN32_IE 0x501
#else
#define _WIN32_IE 0x400
#endif
#endif
#include "config.h"
#include <algorithm>
#include <cerrno>
#include <cstdarg>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <mutex>
#include <string>
#ifdef HAVE_DIRENT_H
#include <dirent.h>
#endif
#ifdef HAVE_INTRIN_H
#include <intrin.h>
#endif
#ifdef HAVE_CPUID_H
#include <cpuid.h>
#endif
#ifdef HAVE_SSE_INTRINSICS
#include <xmmintrin.h>
#endif
#ifdef HAVE_SYS_SYSCONF_H
#include <sys/sysconf.h>
#endif
#ifdef HAVE_PROC_PIDPATH
#include <libproc.h>
#endif
#ifdef __FreeBSD__
#include <sys/types.h>
#include <sys/sysctl.h>
#endif
#ifndef _WIN32
#include <unistd.h>
#elif defined(_WIN32_IE)
#include <shlobj.h>
#endif
#include "alcmain.h"
#include "almalloc.h"
#include "alfstream.h"
#include "alspan.h"
#include "alstring.h"
#include "compat.h"
#include "cpu_caps.h"
#include "fpu_modes.h"
#include "logging.h"
#include "strutils.h"
#include "vector.h"
#if defined(HAVE_GCC_GET_CPUID) && (defined(__i386__) || defined(__x86_64__) || \
defined(_M_IX86) || defined(_M_X64))
using reg_type = unsigned int;
static inline void get_cpuid(unsigned int f, reg_type *regs)
{ __get_cpuid(f, ®s[0], ®s[1], ®s[2], ®s[3]); }
#define CAN_GET_CPUID
#elif defined(HAVE_CPUID_INTRINSIC) && (defined(__i386__) || defined(__x86_64__) || \
defined(_M_IX86) || defined(_M_X64))
using reg_type = int;
static inline void get_cpuid(unsigned int f, reg_type *regs)
{ (__cpuid)(regs, f); }
#define CAN_GET_CPUID
#endif
int CPUCapFlags = 0;
void FillCPUCaps(int capfilter)
{
int caps = 0;
/* FIXME: We really should get this for all available CPUs in case different
* CPUs have different caps (is that possible on one machine?). */
#ifdef CAN_GET_CPUID
union {
reg_type regs[4];
char str[sizeof(reg_type[4])];
} cpuinf[3]{};
get_cpuid(0, cpuinf[0].regs);
if(cpuinf[0].regs[0] == 0)
ERR("Failed to get CPUID\n");
else
{
unsigned int maxfunc = cpuinf[0].regs[0];
unsigned int maxextfunc;
get_cpuid(0x80000000, cpuinf[0].regs);
maxextfunc = cpuinf[0].regs[0];
TRACE("Detected max CPUID function: 0x%x (ext. 0x%x)\n", maxfunc, maxextfunc);
TRACE("Vendor ID: \"%.4s%.4s%.4s\"\n", cpuinf[0].str+4, cpuinf[0].str+12, cpuinf[0].str+8);
if(maxextfunc >= 0x80000004)
{
get_cpuid(0x80000002, cpuinf[0].regs);
get_cpuid(0x80000003, cpuinf[1].regs);
get_cpuid(0x80000004, cpuinf[2].regs);
TRACE("Name: \"%.16s%.16s%.16s\"\n", cpuinf[0].str, cpuinf[1].str, cpuinf[2].str);
}
if(maxfunc >= 1)
{
get_cpuid(1, cpuinf[0].regs);
if((cpuinf[0].regs[3]&(1<<25)))
caps |= CPU_CAP_SSE;
if((caps&CPU_CAP_SSE) && (cpuinf[0].regs[3]&(1<<26)))
caps |= CPU_CAP_SSE2;
if((caps&CPU_CAP_SSE2) && (cpuinf[0].regs[2]&(1<<0)))
caps |= CPU_CAP_SSE3;
if((caps&CPU_CAP_SSE3) && (cpuinf[0].regs[2]&(1<<19)))
caps |= CPU_CAP_SSE4_1;
}
}
#else
/* Assume support for whatever's supported if we can't check for it */
#if defined(HAVE_SSE4_1)
#warning "Assuming SSE 4.1 run-time support!"
caps |= CPU_CAP_SSE | CPU_CAP_SSE2 | CPU_CAP_SSE3 | CPU_CAP_SSE4_1;
#elif defined(HAVE_SSE3)
#warning "Assuming SSE 3 run-time support!"
caps |= CPU_CAP_SSE | CPU_CAP_SSE2 | CPU_CAP_SSE3;
#elif defined(HAVE_SSE2)
#warning "Assuming SSE 2 run-time support!"
caps |= CPU_CAP_SSE | CPU_CAP_SSE2;
#elif defined(HAVE_SSE)
#warning "Assuming SSE run-time support!"
caps |= CPU_CAP_SSE;
#endif
#endif
#ifdef HAVE_NEON
al::ifstream file{"/proc/cpuinfo"};
if(!file.is_open())
ERR("Failed to open /proc/cpuinfo, cannot check for NEON support\n");
else
{
std::string features;
auto getline = [](std::istream &f, std::string &output) -> bool
{
while(f.good() && f.peek() == '\n')
f.ignore();
return std::getline(f, output) && !output.empty();
};
while(getline(file, features))
{
if(features.compare(0, 10, "Features\t:", 10) == 0)
break;
}
file.close();
size_t extpos{9};
while((extpos=features.find("neon", extpos+1)) != std::string::npos)
{
if((extpos == 0 || std::isspace(features[extpos-1])) &&
(extpos+4 == features.length() || std::isspace(features[extpos+4])))
{
caps |= CPU_CAP_NEON;
break;
}
}
}
#endif
TRACE("Extensions:%s%s%s%s%s%s\n",
((capfilter&CPU_CAP_SSE) ? ((caps&CPU_CAP_SSE) ? " +SSE" : " -SSE") : ""),
((capfilter&CPU_CAP_SSE2) ? ((caps&CPU_CAP_SSE2) ? " +SSE2" : " -SSE2") : ""),
((capfilter&CPU_CAP_SSE3) ? ((caps&CPU_CAP_SSE3) ? " +SSE3" : " -SSE3") : ""),
((capfilter&CPU_CAP_SSE4_1) ? ((caps&CPU_CAP_SSE4_1) ? " +SSE4.1" : " -SSE4.1") : ""),
((capfilter&CPU_CAP_NEON) ? ((caps&CPU_CAP_NEON) ? " +NEON" : " -NEON") : ""),
((!capfilter) ? " -none-" : "")
);
CPUCapFlags = caps & capfilter;
}
FPUCtl::FPUCtl()
{
#if defined(HAVE_SSE_INTRINSICS)
this->sse_state = _mm_getcsr();
unsigned int sseState = this->sse_state;
sseState |= 0x8000; /* set flush-to-zero */
sseState |= 0x0040; /* set denormals-are-zero */
_mm_setcsr(sseState);
#elif defined(__GNUC__) && defined(HAVE_SSE)
if((CPUCapFlags&CPU_CAP_SSE))
{
__asm__ __volatile__("stmxcsr %0" : "=m" (*&this->sse_state));
unsigned int sseState = this->sse_state;
sseState |= 0x8000; /* set flush-to-zero */
if((CPUCapFlags&CPU_CAP_SSE2))
sseState |= 0x0040; /* set denormals-are-zero */
__asm__ __volatile__("ldmxcsr %0" : : "m" (*&sseState));
}
#endif
this->in_mode = true;
}
void FPUCtl::leave()
{
if(!this->in_mode) return;
#if defined(HAVE_SSE_INTRINSICS)
_mm_setcsr(this->sse_state);
#elif defined(__GNUC__) && defined(HAVE_SSE)
if((CPUCapFlags&CPU_CAP_SSE))
__asm__ __volatile__("ldmxcsr %0" : : "m" (*&this->sse_state));
#endif
this->in_mode = false;
}
#ifdef _WIN32
const PathNamePair &GetProcBinary()
{
static PathNamePair ret;
if(!ret.fname.empty() || !ret.path.empty())
return ret;
al::vector<WCHAR> fullpath(256);
DWORD len;
while((len=GetModuleFileNameW(nullptr, fullpath.data(), static_cast<DWORD>(fullpath.size()))) == fullpath.size())
fullpath.resize(fullpath.size() << 1);
if(len == 0)
{
ERR("Failed to get process name: error %lu\n", GetLastError());
return ret;
}
fullpath.resize(len);
if(fullpath.back() != 0)
fullpath.push_back(0);
auto sep = std::find(fullpath.rbegin()+1, fullpath.rend(), '\\');
sep = std::find(fullpath.rbegin()+1, sep, '/');
if(sep != fullpath.rend())
{
*sep = 0;
ret.fname = wstr_to_utf8(&*sep + 1);
ret.path = wstr_to_utf8(fullpath.data());
}
else
ret.fname = wstr_to_utf8(fullpath.data());
TRACE("Got binary: %s, %s\n", ret.path.c_str(), ret.fname.c_str());
return ret;
}
void al_print(FILE *logfile, const char *fmt, ...)
{
al::vector<char> dynmsg;
char stcmsg[256];
char *str{stcmsg};
va_list args, args2;
va_start(args, fmt);
va_copy(args2, args);
int msglen{std::vsnprintf(str, sizeof(stcmsg), fmt, args)};
if UNLIKELY(msglen >= 0 && static_cast<size_t>(msglen) >= sizeof(stcmsg))
{
dynmsg.resize(static_cast<size_t>(msglen) + 1u);
str = dynmsg.data();
msglen = std::vsnprintf(str, dynmsg.size(), fmt, args2);
}
va_end(args2);
va_end(args);
std::wstring wstr{utf8_to_wstr(str)};
fputws(wstr.c_str(), logfile);
fflush(logfile);
}
static inline int is_slash(int c)
{ return (c == '\\' || c == '/'); }
static void DirectorySearch(const char *path, const char *ext, al::vector<std::string> *const results)
{
std::string pathstr{path};
pathstr += "\\*";
pathstr += ext;
TRACE("Searching %s\n", pathstr.c_str());
std::wstring wpath{utf8_to_wstr(pathstr.c_str())};
WIN32_FIND_DATAW fdata;
HANDLE hdl{FindFirstFileW(wpath.c_str(), &fdata)};
if(hdl == INVALID_HANDLE_VALUE) return;
const auto base = results->size();
do {
results->emplace_back();
std::string &str = results->back();
str = path;
str += '\\';
str += wstr_to_utf8(fdata.cFileName);
} while(FindNextFileW(hdl, &fdata));
FindClose(hdl);
const al::span<std::string> newlist{results->data()+base, results->size()-base};
std::sort(newlist.begin(), newlist.end());
for(const auto &name : newlist)
TRACE(" got %s\n", name.c_str());
}
al::vector<std::string> SearchDataFiles(const char *ext, const char *subdir)
{
static std::mutex search_lock;
std::lock_guard<std::mutex> _{search_lock};
/* If the path is absolute, use it directly. */
al::vector<std::string> results;
if(isalpha(subdir[0]) && subdir[1] == ':' && is_slash(subdir[2]))
{
std::string path{subdir};
std::replace(path.begin(), path.end(), '/', '\\');
DirectorySearch(path.c_str(), ext, &results);
return results;
}
if(subdir[0] == '\\' && subdir[1] == '\\' && subdir[2] == '?' && subdir[3] == '\\')
{
DirectorySearch(subdir, ext, &results);
return results;
}
std::string path;
/* Search the app-local directory. */
if(auto localpath = al::getenv(L"ALSOFT_LOCAL_PATH"))
{
path = wstr_to_utf8(localpath->c_str());
if(is_slash(path.back()))
path.pop_back();
}
else if(WCHAR *cwdbuf{_wgetcwd(nullptr, 0)})
{
path = wstr_to_utf8(cwdbuf);
if(is_slash(path.back()))
path.pop_back();
free(cwdbuf);
}
else
path = ".";
std::replace(path.begin(), path.end(), '/', '\\');
DirectorySearch(path.c_str(), ext, &results);
/* Search the local and global data dirs. */
static const int ids[2]{ CSIDL_APPDATA, CSIDL_COMMON_APPDATA };
for(int id : ids)
{
WCHAR buffer[MAX_PATH];
if(SHGetSpecialFolderPathW(nullptr, buffer, id, FALSE) == FALSE)
continue;
path = wstr_to_utf8(buffer);
if(!is_slash(path.back()))
path += '\\';
path += subdir;
std::replace(path.begin(), path.end(), '/', '\\');
DirectorySearch(path.c_str(), ext, &results);
}
return results;
}
void SetRTPriority(void)
{
bool failed = false;
if(RTPrioLevel > 0)
failed = !SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
if(failed) ERR("Failed to set priority level for thread\n");
}
#else
#if defined(HAVE_PTHREAD_SETSCHEDPARAM) && !defined(__OpenBSD__)
#include <pthread.h>
#include <sched.h>
#endif
const PathNamePair &GetProcBinary()
{
static PathNamePair ret;
if(!ret.fname.empty() || !ret.path.empty())
return ret;
al::vector<char> pathname;
#ifdef __FreeBSD__
size_t pathlen;
int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1 };
if(sysctl(mib, 4, nullptr, &pathlen, nullptr, 0) == -1)
WARN("Failed to sysctl kern.proc.pathname: %s\n", strerror(errno));
else
{
pathname.resize(pathlen + 1);
sysctl(mib, 4, pathname.data(), &pathlen, nullptr, 0);
pathname.resize(pathlen);
}
#endif
#ifdef HAVE_PROC_PIDPATH
if(pathname.empty())
{
char procpath[PROC_PIDPATHINFO_MAXSIZE]{};
const pid_t pid{getpid()};
if(proc_pidpath(pid, procpath, sizeof(procpath)) < 1)
ERR("proc_pidpath(%d, ...) failed: %s\n", pid, strerror(errno));
else
pathname.insert(pathname.end(), procpath, procpath+strlen(procpath));
}
#endif
if(pathname.empty())
{
pathname.resize(256);
const char *selfname{"/proc/self/exe"};
ssize_t len{readlink(selfname, pathname.data(), pathname.size())};
if(len == -1 && errno == ENOENT)
{
selfname = "/proc/self/file";
len = readlink(selfname, pathname.data(), pathname.size());
}
if(len == -1 && errno == ENOENT)
{
selfname = "/proc/curproc/exe";
len = readlink(selfname, pathname.data(), pathname.size());
}
if(len == -1 && errno == ENOENT)
{
selfname = "/proc/curproc/file";
len = readlink(selfname, pathname.data(), pathname.size());
}
while(len > 0 && static_cast<size_t>(len) == pathname.size())
{
pathname.resize(pathname.size() << 1);
len = readlink(selfname, pathname.data(), pathname.size());
}
if(len <= 0)
{
WARN("Failed to readlink %s: %s\n", selfname, strerror(errno));
return ret;
}
pathname.resize(static_cast<size_t>(len));
}
while(!pathname.empty() && pathname.back() == 0)
pathname.pop_back();
auto sep = std::find(pathname.crbegin(), pathname.crend(), '/');
if(sep != pathname.crend())
{
ret.path = std::string(pathname.cbegin(), sep.base()-1);
ret.fname = std::string(sep.base(), pathname.cend());
}
else
ret.fname = std::string(pathname.cbegin(), pathname.cend());
TRACE("Got binary: %s, %s\n", ret.path.c_str(), ret.fname.c_str());
return ret;
}
void al_print(FILE *logfile, const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
vfprintf(logfile, fmt, ap);
va_end(ap);
fflush(logfile);
}
static void DirectorySearch(const char *path, const char *ext, al::vector<std::string> *const results)
{
TRACE("Searching %s for *%s\n", path, ext);
DIR *dir{opendir(path)};
if(!dir) return;
const auto base = results->size();
const size_t extlen{strlen(ext)};
struct dirent *dirent;
while((dirent=readdir(dir)) != nullptr)
{
if(strcmp(dirent->d_name, ".") == 0 || strcmp(dirent->d_name, "..") == 0)
continue;
const size_t len{strlen(dirent->d_name)};
if(len <= extlen) continue;
if(al::strcasecmp(dirent->d_name+len-extlen, ext) != 0)
continue;
results->emplace_back();
std::string &str = results->back();
str = path;
if(str.back() != '/')
str.push_back('/');
str += dirent->d_name;
}
closedir(dir);
const al::span<std::string> newlist{results->data()+base, results->size()-base};
std::sort(newlist.begin(), newlist.end());
for(const auto &name : newlist)
TRACE(" got %s\n", name.c_str());
}
al::vector<std::string> SearchDataFiles(const char *ext, const char *subdir)
{
static std::mutex search_lock;
std::lock_guard<std::mutex> _{search_lock};
al::vector<std::string> results;
if(subdir[0] == '/')
{
DirectorySearch(subdir, ext, &results);
return results;
}
/* Search the app-local directory. */
if(auto localpath = al::getenv("ALSOFT_LOCAL_PATH"))
DirectorySearch(localpath->c_str(), ext, &results);
else
{
al::vector<char> cwdbuf(256);
while(!getcwd(cwdbuf.data(), cwdbuf.size()))
{
if(errno != ERANGE)
{
cwdbuf.clear();
break;
}
cwdbuf.resize(cwdbuf.size() << 1);
}
if(cwdbuf.empty())
DirectorySearch(".", ext, &results);
else
{
DirectorySearch(cwdbuf.data(), ext, &results);
cwdbuf.clear();
}
}
// Search local data dir
if(auto datapath = al::getenv("XDG_DATA_HOME"))
{
std::string &path = *datapath;
if(path.back() != '/')
path += '/';
path += subdir;
DirectorySearch(path.c_str(), ext, &results);
}
else if(auto homepath = al::getenv("HOME"))
{
std::string &path = *homepath;
if(path.back() == '/')
path.pop_back();
path += "/.local/share/";
path += subdir;
DirectorySearch(path.c_str(), ext, &results);
}
// Search global data dirs
std::string datadirs{al::getenv("XDG_DATA_DIRS").value_or("/usr/local/share/:/usr/share/")};
size_t curpos{0u};
while(curpos < datadirs.size())
{
size_t nextpos{datadirs.find(':', curpos)};
std::string path{(nextpos != std::string::npos) ?
datadirs.substr(curpos, nextpos++ - curpos) : datadirs.substr(curpos)};
curpos = nextpos;
if(path.empty()) continue;
if(path.back() != '/')
path += '/';
path += subdir;
DirectorySearch(path.c_str(), ext, &results);
}
return results;
}
void SetRTPriority()
{
bool failed = false;
#if defined(HAVE_PTHREAD_SETSCHEDPARAM) && !defined(__OpenBSD__)
if(RTPrioLevel > 0)
{
struct sched_param param;
/* Use the minimum real-time priority possible for now (on Linux this
* should be 1 for SCHED_RR) */
param.sched_priority = sched_get_priority_min(SCHED_RR);
failed = !!pthread_setschedparam(pthread_self(), SCHED_RR, ¶m);
}
#else
/* Real-time priority not available */
failed = (RTPrioLevel>0);
#endif
if(failed)
ERR("Failed to set priority level for thread\n");
}
#endif
| {
"pile_set_name": "Github"
} |
#!/usr/bin/env python3
"""
numpyfilter.py [-h] inputfile
Interpret C comments as ReStructuredText, and replace them by the HTML output.
Also, add Doxygen /** and /**< syntax automatically where appropriate.
"""
import sys
import re
import os
import textwrap
from numpy.compat import pickle
CACHE_FILE = 'build/rst-cache.pck'
def main():
import argparse
parser = argparse.ArgumentParser(usage=__doc__.strip())
parser.add_argument('input_file', help='input file')
args = parser.parse_args()
comment_re = re.compile(r'(\n.*?)/\*(.*?)\*/', re.S)
cache = load_cache()
try:
with open(args.input_file, 'r') as f:
text = f.read()
text = comment_re.sub(lambda m: process_match(m, cache), text)
sys.stdout.write(text)
finally:
save_cache(cache)
def filter_comment(text):
if text.startswith('NUMPY_API'):
text = text[9:].strip()
if text.startswith('UFUNC_API'):
text = text[9:].strip()
html = render_html(text)
return html
def process_match(m, cache=None):
pre, rawtext = m.groups()
preline = pre.split("\n")[-1]
if cache is not None and rawtext in cache:
text = cache[rawtext]
else:
text = re.compile(r'^\s*\*', re.M).sub('', rawtext)
text = textwrap.dedent(text)
text = filter_comment(text)
if cache is not None:
cache[rawtext] = text
if preline.strip():
return pre + "/**< " + text + " */"
else:
return pre + "/** " + text + " */"
def load_cache():
if os.path.exists(CACHE_FILE):
with open(CACHE_FILE, 'rb') as f:
try:
cache = pickle.load(f)
except Exception:
cache = {}
else:
cache = {}
return cache
def save_cache(cache):
with open(CACHE_FILE + '.new', 'wb') as f:
pickle.dump(cache, f)
os.rename(CACHE_FILE + '.new', CACHE_FILE)
def render_html(text):
import docutils.parsers.rst
import docutils.writers.html4css1
import docutils.core
docutils.parsers.rst.roles.DEFAULT_INTERPRETED_ROLE = 'title-reference'
writer = docutils.writers.html4css1.Writer()
parts = docutils.core.publish_parts(
text,
writer=writer,
settings_overrides = dict(halt_level=5,
traceback=True,
default_reference_context='title-reference',
stylesheet_path='',
# security settings:
raw_enabled=0,
file_insertion_enabled=0,
_disable_config=1,
)
)
return parts['html_body']
if __name__ == "__main__": main()
| {
"pile_set_name": "Github"
} |
# Created by: Gea-Suan Lin <[email protected]>
# $FreeBSD$
PORTNAME= BS-Event
PORTVERSION= 0.3
PORTREVISION= 2
CATEGORIES= devel perl5
MASTER_SITES= CPAN
MASTER_SITE_SUBDIR= CPAN:ELMEX
PKGNAMEPREFIX= p5-
MAINTAINER= [email protected]
COMMENT= Class that provides an event callback interface
LICENSE= ART10 GPLv1+
LICENSE_COMB= dual
OPTIONS_DEFINE= EXAMPLES
NO_ARCH= yes
USE_PERL5= configure
USES= perl5 shebangfix
SHEBANG_FILES= samples/simple_example
perl_OLD_CMD= /opt/perl/bin/perl
post-install-EXAMPLES-on:
${MKDIR} ${STAGEDIR}${EXAMPLESDIR}/
${INSTALL_SCRIPT} ${WRKSRC}/samples/simple_example ${STAGEDIR}${EXAMPLESDIR}/
.include <bsd.port.mk>
| {
"pile_set_name": "Github"
} |
/* See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* Esri Inc. 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.
*/
using System;
using System.Collections;
using System.Drawing;
using System.IO;
using System.Resources;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Xsl;
using AGX = ESRI.ArcGISExplorer.Application;
using AGXD = ESRI.ArcGISExplorer.Data;
using AGXG = ESRI.ArcGISExplorer.Geometry;
using AGXM = ESRI.ArcGISExplorer.Mapping;
namespace com.esri.gpt.csw
{
public partial class CSWSearchDockWindow : ESRI.ArcGISExplorer.Application.DockWindow
{
private CswProfiles cswProfiles;
private CswCatalogs cswCatalogs;
private ArrayList catalogList;
private ArrayList profileList;
private bool newClicked = false;
private int cswCatalogCount = 0;
private bool _isCatalogListDirty = false;
private Hashtable addedLayer = new Hashtable();
ResourceManager resourceManager = new ResourceManager("com.esri.gpt.csw.Resources.CswResources", typeof(com.esri.gpt.csw.CSWSearchDockWindow).Assembly);
public bool showAll = false;
private static double NONEXSISTANTNUMBER = 500;
private string styledRecordResponse = null;
private String _mapServerUrl = null;
// private bool _isWriteLogs = false;
// private string _logFilePath = "";
#region "Constructor"
/// <summary>
/// Constructor
/// </summary>
/// <remarks>
/// initialize all gui components and load the search and configure catalogs
/// </remarks>
public CSWSearchDockWindow()
{
InitializeComponent();
// productBuildNoLabel.Text = resourceManager.GetString("buildVersion");
string _helpFilePath = System.IO.Path.Combine(Utils.GetSpecialFolderPath(SpecialFolder.Help), "help.htm");
// wbViewHelp.Url = new Uri(_helpFilePath);
// file path
// _xsltMetadataToHtmlFullFilePath = System.IO.Path.Combine(Utils.GetSpecialFolderPath(SpecialFolder.ConfigurationFiles), "metadata_to_html_full.xsl");
// _xsltPrepareMetadataFilePath = System.IO.Path.Combine(Utils.GetSpecialFolderPath(SpecialFolder.ConfigurationFiles), "xml_prepare.xslt");
/* String logFilePath = Utils.GetSpecialFolderPath(SpecialFolder.LogFiles);
if (logFilePath != null && logFilePath.Trim().Length > 0)
{
_isWriteLogs = true;
_logFilePath = logFilePath + "//CswSearchDockWindow.log";
Utils.setLogFile(_logFilePath);
}*/
LoadCswSearchDialog();
}
#endregion
#region "CSWSearch Dialog variables"
// private string _xsltPrepareMetadataFilePath;
// private XslCompiledTransform _xsltPrepare;
// private string _xsltMetadataToHtmlFullFilePath;
// private XslCompiledTransform _xsltFull;
private bool inited = false;
private CswManager _cswManager = new CswManager();
#endregion
/// <summary>
/// Event handler for find tab enter event.
/// </summary>
private void tabSearch_Enter(object sender, EventArgs e)
{
ArrayList alCatalogs = CswObjectsToArrayList(cswCatalogs);
if ((cswCatalogCount != alCatalogs.Count) || (_isCatalogListDirty))
{
cswCatalogCount = alCatalogs.Count;
alCatalogs.Sort();
cmbCswCatalog.DataSource = null;
cmbCswCatalog.DataSource = alCatalogs;
cmbCswCatalog.DisplayMember = "Name";
cmbCswCatalog.ValueMember = "URL";
_isCatalogListDirty = false;
}
else
{
cmbCswCatalog.Refresh();
}
}
#region "CSWSearch Configure tab"
/// <summary>
/// adding data to the catalog listbox
/// </summary>
private void adddata()
{
catalogList = CswObjectsToArrayList(cswCatalogs);
catalogList.Sort();
lstCatalog.BeginUpdate();
lstCatalog.DataSource = catalogList;
lstCatalog.DisplayMember = "Name";
lstCatalog.ValueMember = "ID";
lstCatalog.SelectedIndex = cswCatalogs.Count - 1;
lstCatalog.EndUpdate();
}
/// <summary>
/// Clearing the display and url text boxes
/// </summary>
private void cleardata()
{
txtDisplayName.Text = "";
txtURL.Text = "";
}
/// <summary>
/// Function on change of combProfile text changed event
/// </summary>
/// <param name="sender">The sender object</param>
/// <param name="e">The event arguments</param>
private void combProfile_SelectedIndexChanged(object sender, EventArgs e)
{
if (txtURL.Text.Length > 0)
{
btnSave.Enabled = true;
}
else
{
btnSave.Enabled = false;
}
}
#endregion
#region "CSWSearch Dialog UI Event Handling Function(s)"
/// <summary>
/// Function on change of SearchDialog event
/// </summary>
/// <param name="sender">The sender object</param>
/// <param name="e">The event arguments</param>
private void CswSearchDialog_Resize(object sender, EventArgs e)
{
if (!inited) { inited = LoadCswSearchDialog(); }
}
/// <summary>
/// Function on click of find button
/// </summary>
/// <param name="sender">The sender object</param>
/// <param name="e">The event arguments</param>
private void btnSearch_Click(object sender, EventArgs e)
{
try
{
if (cmbCswCatalog.SelectedIndex == -1)
{
MessageBox.Show(resourceManager.GetString("catalogNotSelected"), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
CswCatalog catalog = (CswCatalog)cmbCswCatalog.SelectedItem;
if (catalog == null) { throw new NullReferenceException(resourceManager.GetString("catalogNotSpecified")); }
if (!catalog.IsConnected())
{
string errMsg = "";
try { catalog.Connect(); }
catch (Exception ex) { errMsg = ex.ToString(); }
if (!catalog.IsConnected())
{
MessageBox.Show(resourceManager.GetString("catalogConnectFailed"), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
// clear up result list
lstSearchResults.DataSource = null;
Cursor.Current = Cursors.WaitCursor;
// genrate search criteria
CswSearchCriteria searchCriteria = new CswSearchCriteria();
searchCriteria.SearchText = txtSearchPhrase.Text;
searchCriteria.StartPosition = 1;
searchCriteria.MaxRecords = (int)nudNumOfResults.Value; ;
searchCriteria.LiveDataAndMapOnly = (chkLiveDataAndMapOnly.CheckState == CheckState.Checked);
searchCriteria.Envelope = null; // place holder
CswSearchRequest searchRequest = new CswSearchRequest();
searchRequest.Catalog = catalog;
searchRequest.Criteria = searchCriteria;
searchRequest.Search();
CswSearchResponse response = searchRequest.GetResponse();
ArrayList alRecords = CswObjectsToArrayList(response.Records);
if (alRecords.Count == 0)
{
MessageBox.Show(resourceManager.GetString("noRecordFound"), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
if (alRecords.Count > 0)
{
lstSearchResults.DataSource = alRecords;
lstSearchResults.DisplayMember = "Title";
lstSearchResults.ValueMember = "ID";
showAllFootPrintTSBtn.Enabled = catalog.Profile.SupportSpatialBoundary;
clearAllFootPrintTSBtn.Enabled = catalog.Profile.SupportSpatialBoundary;
displayFootPrintTSBtn.Enabled = catalog.Profile.SupportSpatialBoundary;
zoomToFootPrintTSBtn.Enabled = catalog.Profile.SupportSpatialBoundary;
showAll = true;
}
lblResult.Text = resourceManager.GetString("resultTxt") + " (" + alRecords.Count + ")";
}
catch (Exception ex)
{
MessageBox.Show(resourceManager.GetString("searchFailed"), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
Cursor.Current = Cursors.Default;
}
}
/// <summary>
/// Function on change of search results
/// </summary>
/// <param name="sender">The sender object</param>
/// <param name="e">The event arguments</param>
private void lstSearchResults_SelectedIndexChanged(object sender, EventArgs e)
{
Cursor.Current = Cursors.WaitCursor;
CswRecord record = (CswRecord)lstSearchResults.SelectedItem;
if (record == null)
{
//display abstract
txtAbstract.Text = "";
// GUI update for buttons
tsbAddToMap.Enabled = false;
tsbViewMetadata.Enabled = false;
tsbDownloadMetadata.Enabled = false;
}
else
{
txtAbstract.Text = record.Abstract;
tsbAddToMap.Enabled = record.IsLiveDataOrMap;
tsbViewMetadata.Enabled = true;
tsbDownloadMetadata.Enabled = true;
}
Cursor.Current = Cursors.Default;
}
/// <summary>
/// Function to reset the maximum number of results
/// </summary>
/// <param name="sender">The sender object</param>
/// <param name="e">The event arguments</param>
private void nudNumOfResults_Leave(object sender, EventArgs e)
{
// reset the NumOfResult to integer value
nudNumOfResults.Value = (int)nudNumOfResults.Value;
}
/// <summary>
/// Function on click of view metadata button or menu
/// </summary>
/// <param name="sender">The sender object</param>
/// <param name="e">The event arguments</param>
private void tsbViewMetadata_Click(object sender, EventArgs e)
{
ViewMetadata_Clicked();
}
/// <summary>
/// Function on click of download metadata button or menu
/// </summary>
/// <param name="sender">The sender object</param>
/// <param name="e">The event arguments</param>
private void tsbDownloadMetadata_Click(object sender, EventArgs e)
{
DownloadMetadata_Clicked();
}
/// <summary>
/// Function on click of add to map button or menu
/// </summary>
/// <param name="sender">The sender object</param>
/// <param name="e">The event arguments</param>
private void tsbAddToMap_Click(object sender, EventArgs e)
{
AddToMap_Clicked();
}
#endregion
#region "CSWSearch Dialog Function(s)"
/// <summary>
/// Constructor loads profile and catalogs
/// </summary>
private bool LoadCswSearchDialog()
{
// load CSW Profiles
try
{
cswProfiles = _cswManager.loadProfile();
if (cswProfiles == null) { throw new NullReferenceException(resourceManager.GetString("loadProfileFailed")); }
// populate profiles
profileList = CswObjectsToArrayList(cswProfiles);
combProfile.BeginUpdate();
combProfile.DataSource = profileList;
combProfile.DisplayMember = "Name";
combProfile.ValueMember = "ID";
combProfile.SelectedIndex = -1;
combProfile.EndUpdate();
}
catch (Exception ex)
{
MessageBox.Show(resourceManager.GetString("loadProfileFailed"), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
// load CSW Catalogs
try
{
cswCatalogs = _cswManager.loadCatalog();
if (cswCatalogs == null) { throw new NullReferenceException("Failed to load catalogs. _cswCatalogs is null."); }
ArrayList alCatalogs = CswObjectsToArrayList(cswCatalogs);
cswCatalogCount = alCatalogs.Count;
alCatalogs.Sort();
lblCatalogs.Text = resourceManager.GetString("catalogsTxt") + " (" + alCatalogs.Count + ")";
cmbCswCatalog.DataSource = alCatalogs;
cmbCswCatalog.DisplayMember = "Name";
cmbCswCatalog.ValueMember = "URL";
//populate lst box for configure tab
lstCatalog.DataSource = alCatalogs;
lstCatalog.DisplayMember = "Name";
lstCatalog.ValueMember = "ID";
lstCatalog.SelectedIndex = cswCatalogs.Count - 1;
}
catch (Exception ex)
{
MessageBox.Show(resourceManager.GetString("loadCatalogFailed"), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
return true;
}
/// <summary>
/// prepare metadata. Metadata xml is transformed to an intermediate format.
/// Map service information shall be generated and put in <Esri></Esri> tags.
/// </summary>
/// <param name="xmlDoc">Metadata XML document</param>
/// <returns>Transformed XML document</returns>
/* private XmlDocument PrepareMetadata(XmlDocument xmlDoc) {
try {
if (xmlDoc == null) { throw new ArgumentNullException(); }
//load the Xsl if necessary
/* if (_xsltPrepare == null) {
_xsltPrepare = new XslCompiledTransform();
try { _xsltPrepare.Load(_xsltPrepareMetadataFilePath); }
catch (Exception ex) {
ShowErrorMessageBox(resourceManager.GetString("LoadMetadataPreparationStylesheetFailed"));
return null;
}
}*/
// todo: clean metadata xml. remove namespaces (to be consistant with the behavior on Portal) (?)
// transform
/* StringWriter strWriter = new StringWriter();
_xsltPrepare.Transform(new XmlNodeReader(xmlDoc), null, (TextWriter)strWriter);
strWriter.Close();
XmlDocument newXmlDoc = new XmlDocument();
newXmlDoc.LoadXml(strWriter.ToString());
return newXmlDoc;
}
catch (Exception ex) {
ShowErrorMessageBox(resourceManager.GetString("PrepareMetadataFailed"));
return null;
}
}*/
/// <summary>
/// Display an error message dialog with the provided message string, with default caption, button and icon
/// </summary>
/// <param name="ErrorMessage">Error message to be displayed</param>
private void ShowErrorMessageBox(string ErrorMessage)
{
MessageBox.Show(ErrorMessage, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
/// <summary>
/// Retrieves the selected metadata (in search result listbox) from CSW catalog.
/// It handles including GUI validation and metadata retrieveal.
/// </summary>
/// <remarks>
/// Reused in View Summary, View Detail, and Download buttons.
/// </remarks>
/// <returns>A XMLDocument object if successfully retrieved metadata. Null if otherwise.</returns>
private XmlDocument RetrieveSelectedMetadataFromCatalog(bool bApplyTransform)
{
if (cmbCswCatalog.SelectedIndex == -1)
{
MessageBox.Show(resourceManager.GetString("catalogNotSelected"), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return null;
}
CswCatalog catalog = (CswCatalog)cmbCswCatalog.SelectedItem;
if (catalog == null) { throw new NullReferenceException(resourceManager.GetString("catalogNotSpecified")); }
CswRecord record = (CswRecord)lstSearchResults.SelectedItem;
if (record == null) throw new NullReferenceException(resourceManager.GetString("searchNotSelected"));
// connect to catalog if not connected already
if (!catalog.IsConnected())
{
string errMsg = "";
try { catalog.Connect(); }
catch (Exception ex) { errMsg = ex.ToString(); }
if (!catalog.IsConnected())
{
MessageBox.Show(resourceManager.GetString("catalogConnectFailed"), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return null;
}
}
bool isTransformed = false;
// retrieve metadata doc by its ID
CswSearchRequest searchRequest = new CswSearchRequest();
searchRequest.Catalog = catalog;
try
{
//MessageBox.Show(record.ID);
isTransformed = searchRequest.GetMetadataByID(record.ID, bApplyTransform);
_mapServerUrl = searchRequest.GetMapServerUrl();
//MessageBox.Show(record.FullMetadata);
}
catch (Exception ex)
{
FormMessageBox frmMessageBox = new FormMessageBox();
frmMessageBox.Init("Failed to retrieve metadata from service: " + ex.Message,
"Response from CSW service:\r\n" + searchRequest.GetResponse().ResponseXML,
"Error");
frmMessageBox.ShowDialog(this);
return null;
}
CswSearchResponse response = searchRequest.GetResponse();
CswRecord recordMetadata = response.Records[0];
if (!isTransformed)
{
XmlDocument xmlDoc = new XmlDocument();
try { xmlDoc.LoadXml(recordMetadata.FullMetadata); }
catch (XmlException xmlEx)
{
MessageBox.Show(resourceManager.GetString("loadXMLException"), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return null;
}
return xmlDoc;
}
else
{
styledRecordResponse = recordMetadata.FullMetadata;
return null;
}
}
/// <summary>
/// Retrieves the selected metadata (in search result listbox) from CSW catalog. Exception shall be thrown.
/// </summary>
/// <remarks>
/// Called in View Metadata, Download Metadata, and Add to Map
/// </remarks>
/// <returns>A XMLDocument object if metadata was retrieved successfully. Null if otherwise.</returns>
private void RetrieveAddToMapInfoFromCatalog()
{
try
{
// validate
if (cmbCswCatalog.SelectedIndex == -1)
{
MessageBox.Show(resourceManager.GetString("catalogNotSelected"), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (lstSearchResults.SelectedIndex == -1) { throw new Exception(resourceManager.GetString("searchNotSelected")); }
CswCatalog catalog = (CswCatalog)cmbCswCatalog.SelectedItem;
if (catalog == null) { throw new NullReferenceException(resourceManager.GetString("catalogNotSpecified")); }
CswRecord record = (CswRecord)lstSearchResults.SelectedItem;
if (record == null) throw new NullReferenceException(resourceManager.GetString("searchNotSelected"));
// connect to catalog if needed
if (!catalog.IsConnected())
{
string errMsg = "";
try { catalog.Connect(); }
catch (Exception ex) { errMsg = ex.Message; }
// exit if still not connected
if (!catalog.IsConnected())
{
MessageBox.Show(resourceManager.GetString("catalogConnectFailed"), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
CswSearchRequest searchRequest = new CswSearchRequest();
searchRequest.Catalog = catalog;
try
{
searchRequest.GetAddToMapInfoByID(record.ID);
_mapServerUrl = searchRequest.GetMapServerUrl();
}
catch (Exception ex)
{
FormMessageBox frmMessageBox = new FormMessageBox();
frmMessageBox.Init("Failed to retrieve metadata from service: " + ex.Message,
"Response from CSW service:\r\n" + searchRequest.GetResponse().ResponseXML,
"Error");
frmMessageBox.ShowDialog(this);
}
}
catch (Exception ex)
{
MessageBox.Show(resourceManager.GetString("loadXMLException"), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
#endregion
#region "Utils"
/// <summary>
/// convert cswobjects to arraylist
/// </summary>
/// <remarks>
/// will phase out once CswObjects implements IList interface.
/// </remarks>
/// <param name="cswObjs">CSWObjects to be converted</param>
/// <returns>ArrayList that contains a list of CSW objects.</returns>
private ArrayList CswObjectsToArrayList(CswObjects cswObjs)
{
ArrayList alCswObjects = new ArrayList();
for (int i = 0; i < cswObjs.Count; i++)
{
alCswObjects.Add(cswObjs[i]);
}
return alCswObjects;
}
/// <summary>
/// Genearate temporary filename
/// </summary>
/// <remarks>
/// Generate temporary filename with specified prefix and surfix.
/// It uses current windows user's temp folder by default.
/// </remarks>
/// <param name="param1">Desription of the First Param</param>
/// <returns>Description of the return value.</returns>
private string GenerateTempFilename(string prefix, string surfix)
{
//string tempPath = System.IO.Path.GetTempPath();
//return GenerateTempFilename(prefix, surfix, tempPath, false);
return System.IO.Path.GetTempFileName();
}
/// <summary>
/// Generates temp file name with prefix and suffix
/// </summary>
/// <param name="prefix">file prefix</param>
/// <param name="surfix">file suffix</param>
/// <param name="directory">folder</param>
/// <param name="overwrite">can be overwritten ?</param>
/// <returns></returns>
private string GenerateTempFilename(string prefix, string surfix, string directory, Boolean overwrite)
{
// todo: need to generate number and check if file already exist
return (directory + "~" + prefix + "Temp" + "." + surfix);
}
private string AppendQuestionOrAmpersandToUrlString(string urlString)
{
string finalChar = urlString.Substring(urlString.Length - 1, 1); // final char
if (!finalChar.Equals("?") && !finalChar.Equals("&"))
{
if (urlString.LastIndexOf("=") > -1) { urlString = urlString + "&"; }
else { urlString = urlString + "?"; }
}
return urlString;
}
/// <summary>
/// Gets application path
/// </summary>
/// <returns></returns>
private string GetApplicationPath()
{
return System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
}
#endregion
#region "Private Functions"
/// <summary>
/// Function to view metadata
/// </summary>
private void ViewMetadata_Clicked()
{
try
{
Cursor.Current = Cursors.WaitCursor;
XmlDocument xmlDoc = RetrieveSelectedMetadataFromCatalog(true);
if (xmlDoc == null && styledRecordResponse == null) return;
// prepare metadata for service info
/* xmlDoc = PrepareMetadata(xmlDoc);
if (xmlDoc == null) return;
// transform metadata using style sheet
//load the Xsl if necessary
if (_xsltFull == null) {
_xsltFull = new XslCompiledTransform();
try { _xsltFull.Load(_xsltMetadataToHtmlFullFilePath);
//MessageBox.Show(_xsltFull.ToString() + _xsltMetadataToHtmlFullFilePath);
}
catch { throw new Exception(resourceManager.GetString("loadMetadataException")); }
}*/
/* string tmpFilePath = GenerateTempFilename("Meta", "html");
XmlWriter xmlWriter = new XmlTextWriter(tmpFilePath, Encoding.UTF8);
_xsltFull.Transform(new XmlNodeReader(xmlDoc), xmlWriter);
xmlWriter.Close(); */
string tmpFilePath = "";
if (xmlDoc != null && styledRecordResponse == null)
{
// display metadata in XML format
tmpFilePath = GenerateTempFilename("Meta", "xml");
XmlWriter xmlWriter = new XmlTextWriter(tmpFilePath, Encoding.UTF8);
XmlNode binaryNode = xmlDoc.GetElementsByTagName("Binary")[0];
if (binaryNode != null)
{
XmlNode enclosureNode = xmlDoc.GetElementsByTagName("Enclosure")[0];
if (enclosureNode != null)
binaryNode.RemoveChild(enclosureNode);
}
String outputStr = xmlDoc.InnerXml.Replace("utf-16", "utf-8");
xmlWriter.WriteRaw(outputStr);
xmlWriter.Close();
}
else if (xmlDoc == null && styledRecordResponse != null
&& styledRecordResponse.Trim().Length > 0)
{
// display metadata in XML format
tmpFilePath = GenerateTempFilename("Meta", "html");
FileInfo fileInfo = new FileInfo(tmpFilePath);
System.IO.FileStream fileStream = fileInfo.Create();
StreamWriter sr = new StreamWriter(fileStream);
sr.Write(styledRecordResponse);
sr.Close();
fileStream.Close();
styledRecordResponse = null;
}
// pop up a window displaying the summary HTML
FormViewMetadata frmViewMetadata = new FormViewMetadata();
//tmp
CswRecord record = (CswRecord)(lstSearchResults.SelectedItem);
frmViewMetadata.MetadataTitle = record.Title;
//tmp
frmViewMetadata.Navigate(tmpFilePath);
frmViewMetadata.Show();
frmViewMetadata.Activate();
return;
}
catch (Exception ex)
{
MessageBox.Show(resourceManager.GetString("viewMetadataFailed"), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
styledRecordResponse = null;
Cursor.Current = Cursors.Default;
}
}
/// <summary>
/// Normalize a string for filename.
/// </summary>
/// <param name="filename">File name string to be normalized</param>
/// <returns>Normalized file name string</returns>
private string NormalizeFilename(string filename)
{
// Get a list of invalid file characters.
char[] invalidFilenameChars = System.IO.Path.GetInvalidFileNameChars();
// replace invalid characters with ' ' char
for (int i = 0; i < invalidFilenameChars.GetLength(0); i++)
{
filename = filename.Replace(invalidFilenameChars[i], ' ');
}
return filename;
}
/// <summary>
/// Function to download metadata
/// </summary>
private void DownloadMetadata_Clicked()
{
try
{
Cursor.Current = Cursors.WaitCursor;
// retrieve metadata
XmlDocument xmlDoc = RetrieveSelectedMetadataFromCatalog(false);
if (xmlDoc == null) return;
// save to file
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "XML Files|*.xml";
saveFileDialog.FileName = NormalizeFilename(((CswRecord)lstSearchResults.SelectedItem).Title);
saveFileDialog.DefaultExt = "xml";
saveFileDialog.Title = resourceManager.GetString("downloadXMLFile");
saveFileDialog.CheckFileExists = false;
saveFileDialog.OverwritePrompt = true;
if (saveFileDialog.ShowDialog(this) == DialogResult.Cancel) return;
if (saveFileDialog.FileName.Length > 0)
{
Cursor.Current = Cursors.WaitCursor;
try
{
XmlNode binaryNode = xmlDoc.GetElementsByTagName("Binary")[0];
if (binaryNode != null)
{
XmlNode enclosureNode = xmlDoc.GetElementsByTagName("Enclosure")[0];
if (enclosureNode != null)
binaryNode.RemoveChild(enclosureNode);
}
xmlDoc.Save(saveFileDialog.FileName);
MessageBox.Show(resourceManager.GetString("fileSaved"), "Download Metadata", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(resourceManager.GetString("fileSavedFailed"), "Download Metadata", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
finally
{
Cursor.Current = Cursors.Default;
}
}
}
catch (Exception ex)
{
MessageBox.Show(resourceManager.GetString("downloadMetadataFailed"), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
Cursor.Current = Cursors.Default;
}
}
/// <summary>
/// Function to add to map
/// </summary>
private void AddToMap_Clicked()
{
try
{
/* if (addedLayer[lstSearchResults.SelectedItem.GetHashCode()] != null) {
AGXM.ServiceLayer resultLayer = (AGXM.ServiceLayer)addedLayer[lstSearchResults.SelectedItem.GetHashCode()];
try {
if (resultLayer.Extent.GetEnvelope() != null) {
MessageBox.Show(resourceManager.GetString("layerAdded"), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception e) {
addedLayer.Remove(lstSearchResults.SelectedItem.GetHashCode());
}
}*/
// if (addedLayer[lstSearchResults.SelectedItem.GetHashCode()] == null) {
Cursor.Current = Cursors.WaitCursor;
// retrieve metadata
CswRecord record = (CswRecord)lstSearchResults.SelectedItem;
if (record == null) throw new NullReferenceException("CswRecord is null.");
if (record.MapServerURL == null || record.MapServerURL.Trim().Length == 0)
{
// retrieve metadata
RetrieveAddToMapInfoFromCatalog();
}
else
{
_mapServerUrl = record.MapServerURL;
}
// if (xmlDoc == null) return;
// prepare metadata for service info
// xmlDoc = PrepareMetadata(xmlDoc);
// if (xmlDoc == null) return;
if (_mapServerUrl != null && _mapServerUrl.Trim().Length > 0)
{
String serviceType = record.ServiceType;
if (serviceType == null || serviceType.Length == 0)
{
serviceType = CswProfile.getServiceType(_mapServerUrl);
}
if (serviceType.Equals("ags"))
{
if (_mapServerUrl.ToLower().Contains("arcgis/rest"))
{
_mapServerUrl = _mapServerUrl + "?f=nmf";
CswClient client = new CswClient();
AddAGSService(client.SubmitHttpRequest("DOWNLOAD", _mapServerUrl, ""));
}
else
{
AddAGSService(_mapServerUrl);
}
}
else if (serviceType.Equals("wms") || serviceType.Equals("aims"))
{
try
{
MapServiceInfo msinfo = new MapServiceInfo();
msinfo.Server = record.MapServerURL;
msinfo.Service = record.ServiceName;
msinfo.ServiceType = record.ServiceType;
CswProfile.ParseServiceInfoFromUrl(msinfo, _mapServerUrl, serviceType);
addMapServiceLayer(msinfo);
}
catch (Exception e)
{
AddAGSService(_mapServerUrl);
}
}
}
else
{
MapServiceInfo msi = new MapServiceInfo();
// parse out service information
// ParseServiceInfoFromMetadata(xmlDoc, ref msi);
if (msi.IsMapService())
{
addMapServiceLayer(msi);
}
else
{
MessageBox.Show(resourceManager.GetString("invalidService"), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
// }
}
catch (Exception ex)
{
MessageBox.Show(resourceManager.GetString("addMapFailed"), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
Cursor.Current = Cursors.Default;
}
}
/// <summary>
/// Function to add to map serivce both IMS and WMS
/// </summary>
///<param name="msi">The map service info</param>
private void addMapServiceLayer(MapServiceInfo msi)
{
if (msi.ServiceType.Equals("wms", StringComparison.OrdinalIgnoreCase))
{
if (!addLayerWMS2(msi, false))
addLayerWMS(msi, false);
// MessageBox.Show("WMS service not supported in this version.", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
addLayerArcIMS(msi);
// MessageBox.Show("ArcIMS service not supported in this version.", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
/// <summary>
/// Adds WMS layer to map
/// </summary>
/// <param name="msi">map service information</param>
/// <param name="fromServerUrl">service url</param>
/// <returns></returns>
private bool addLayerWMS2(MapServiceInfo msi, Boolean fromServerUrl)
{
bool flag = false;
if (msi == null) { throw new ArgumentNullException("msi"); }
string service = msi.Service;
string url = AppendQuestionOrAmpersandToUrlString(msi.Server);
// append serviceParam to server url?
if (msi.ServiceParam.Length > 0 && !fromServerUrl)
{
url = url + msi.ServiceParam;
url = AppendQuestionOrAmpersandToUrlString(url);
}
CswClient client = new CswClient();
string response = client.SubmitHttpRequest("GET", url + "request=GetCapabilities&service=WMS", "");
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(response);
XmlNamespaceManager xmlnsManager = new XmlNamespaceManager(xmlDoc.NameTable);
xmlnsManager.AddNamespace("wms", "http://www.opengis.net/wms");
XmlNodeList nl = null;
if (xmlDoc.SelectSingleNode("//wms:Layer", xmlnsManager) != null)
{
nl = xmlDoc.SelectNodes("/wms:WMS_Capabilities/wms:Capability/wms:Layer/wms:Layer/wms:Title", xmlnsManager);
}
if (nl != null)
{
flag = true;
for (int i = nl.Count - 1; i >= 0; i--)
{
AGXD.ServiceConnectionProperties conn = new AGXD.ServiceConnectionProperties
(AGXD.ServiceType.Wms,
new Uri(url),
"", nl.Item(i).InnerText);
AGXM.ServiceLayer sl = new AGXM.ServiceLayer(conn);
bool connected = sl.Connect();
if (connected)
{
addLayer(sl);
addedLayer.Add(DateTime.Now.Millisecond, sl);
}
}
}
return flag;
}
/// <summary>
/// Parse out service information (such as service type, server name, service name, etc) from metadta document
/// </summary>
/// <param name="xmlDoc">xml metadata doc to be parsed</param>
/// <param name="msi">MapServiceInfo object as output</param>
private void ParseServiceInfoFromMetadata(XmlDocument xmlDoc, ref MapServiceInfo msi)
{
// todo: service info as an object?
// also, what about service param and isSecured?
if (xmlDoc == null) { throw new ArgumentNullException("xmlDoc"); }
msi = new MapServiceInfo();
XmlNamespaceManager xmlNamespaceManager = new XmlNamespaceManager(xmlDoc.NameTable);
xmlNamespaceManager.AddNamespace("cat", "http://www.esri.com/metadata/csw/");
xmlNamespaceManager.AddNamespace("csw", "http://www.opengis.net/cat/csw");
XmlNode nodeMetadata = xmlDoc.SelectSingleNode("//metadata|//cat:metadata|//csw:metadata", xmlNamespaceManager);
if (nodeMetadata == null) { throw new Exception("No metadata node was found in the XML"); }
// parse out service information
XmlNode nodeEsri = nodeMetadata.SelectSingleNode("Esri");
if (nodeEsri == null) throw new Exception("<Esri> node missing");
// server
XmlNode node = nodeEsri.SelectSingleNode("Server");
if (node == null) throw new Exception("'//Esri/Server' node missing");
msi.Server = node.InnerText;
// service
node = nodeEsri.SelectSingleNode("Service");
if (node != null) { msi.Service = node.InnerText; }
// service type
node = nodeEsri.SelectSingleNode("ServiceType");
if (node != null) { msi.ServiceType = node.InnerText; }
// service param
node = nodeEsri.SelectSingleNode("ServiceParam");
if (node != null) { msi.ServiceParam = node.InnerText; }
// issecured
node = nodeEsri.SelectSingleNode("issecured");
if (node != null) { msi.IsSecured = (node.InnerText.Equals("True", StringComparison.OrdinalIgnoreCase)); }
return;
}
/// <summary>
/// Function to add WMS map serivce
/// </summary>
///<param name="msi">The map service info</param>
///<param name="fromServerUrl">from server url</param>
private void addLayerWMS(MapServiceInfo msi, Boolean fromServerUrl)
{
if (msi == null) { throw new ArgumentNullException("msi"); }
string service = msi.Service;
string url = AppendQuestionOrAmpersandToUrlString(msi.Server);
// append serviceParam to server url?
if (msi.ServiceParam.Length > 0 && !fromServerUrl)
{
url = url + msi.ServiceParam;
url = AppendQuestionOrAmpersandToUrlString(url);
}
// connect to wms service
try
{
AGXD.ServiceConnectionProperties sc = new AGXD.ServiceConnectionProperties();
sc.ServiceType = (AGXD.ServiceType)Enum.Parse(typeof(AGXD.ServiceType), "Wms");
AGXM.ServiceLayer resultLayer = new AGXM.ServiceLayer();
if (msi.Service != null && msi.Service.Trim().Length > 0)
sc.ServiceName = msi.Service;
else
sc.ServiceName = "Unknown Service Name";
sc.SubServiceName = "";
sc.Url = new System.Uri(url);
// sc.Username = "";
// sc.Password = "";
resultLayer.Visible = true;
resultLayer.ServiceConnectionProperties = sc;
resultLayer.Connect();
addLayer(resultLayer);
addedLayer.Add(DateTime.Now, resultLayer);
}
catch (Exception ex)
{
throw new Exception(resourceManager.GetString("failedWMSService"), ex);
}
return;
}
/// <summary>
/// Adds layer to current map display
/// </summary>
/// <param name="layer"></param>
private void addLayer(AGXM.ServiceLayer layer)
{
AGXM.MapDisplay md = AGX.Application.ActiveMapDisplay;
if (!layer.IsConnected)
{
layer.Connect();
}
md.Map.ChildItems.Add(layer);
}
/// <summary>
/// Function to add ArcIMS map serivce
/// </summary>
///<param name="msi">The map service info</param>
private void addLayerArcIMS(MapServiceInfo msi)
{
if (msi == null) { throw new ArgumentNullException("msi"); }
//IIMSConnection imsConnection;
try
{
AGXD.ServiceConnectionProperties sc = new AGXD.ServiceConnectionProperties();
sc.ServiceType = (AGXD.ServiceType)Enum.Parse(typeof(AGXD.ServiceType), "Ims");
AGXM.ServiceLayer resultLayer = new AGXM.ServiceLayer();
sc.ServiceName = msi.Service;
sc.SubServiceName = "";
sc.Url = new System.Uri(msi.Server);
// resultLayer.Username = "";
// resultLayer.Password = "";
//resultLayer.Name = "Layer";
// resultLayer.Copyright = "";
resultLayer.Visible = true;
resultLayer.ServiceConnectionProperties = sc;
resultLayer.Connect();
addLayer(resultLayer);
addedLayer.Add(DateTime.Now, resultLayer);
}
catch (Exception ex)
{
throw new Exception(resourceManager.GetString("failedIMSService"), ex);
}
return;
}
/// <summary>
/// Event handler for label place holder
/// </summary>
/// <param name="sender">The sender object</param>
/// <param name="e">The event arguments</param>
private void labelPlaceHolder_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
if (e.KeyCode == Keys.Tab)
{
this.GetNextControl(this.ActiveControl, true).Focus();
}
}
/// <summary>
/// Event handler for list search results mouse move.
/// </summary>
/// <param name="sender">The sender object</param>
/// <param name="e">The event arguments</param>
private void lstSearchResults_MouseMove(object sender, MouseEventArgs e)
{
int idx = lstSearchResults.IndexFromPoint(e.Location);
if ((idx >= 0) && (idx < lstSearchResults.Items.Count))
{
CswRecord record = (CswRecord)lstSearchResults.SelectedItem;
string msg = record.Abstract;
if (msg.Length > 200) msg = msg.Substring(0, 200);
toolTip.SetToolTip(lstSearchResults, msg);
}
}
/// <summary>
/// Event handler for catalog list selected index changed.
/// </summary>
/// <param name="sender">The sender object</param>
/// <param name="e">The event arguments</param>
private void lstCatalog_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
btnDelete.Enabled = true;
CswCatalog catalog = (CswCatalog)lstCatalog.SelectedItem;
combProfile.SelectedItem = catalog.Profile;
txtURL.Text = catalog.URL;
txtDisplayName.Text = catalog.Name;
txtURL.BackColor = Color.White;
btnSave.Enabled = false;
}
catch (Exception ex)
{
MessageBox.Show(resourceManager.GetString("selectedIndexChanged"), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
/// <summary>
/// Event handler for configure tab delete button.
/// </summary>
/// <param name="sender">The sender object</param>
/// <param name="e">The event arguments</param>
private void btnDelete_Click(object sender, EventArgs e)
{
int index = lstCatalog.SelectedIndex;
cleardata();
adddata();
lstCatalog.SelectedIndex = index;
try
{
if (lstCatalog.SelectedItem == null)
{
MessageBox.Show(resourceManager.GetString("resultNotSelected"), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
CswCatalog catalog = (CswCatalog)lstCatalog.SelectedItem;
if (MessageBox.Show(resourceManager.GetString("deleteConfirm"), "Confirm delete", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
catalogList.Remove(catalog);
lstCatalog.Update();
_cswManager.deleteCatalog(catalog);
cleardata();
adddata();
lblCatalogs.Text = resourceManager.GetString("catalogsTxt") + " (" + lstCatalog.Items.Count + ")";
}
}
}
catch (Exception ex)
{
MessageBox.Show(resourceManager.GetString("deleteFailed"), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
/// <summary>
/// Event handler for configure tab add button.
/// </summary>
/// <param name="sender">The sender object</param>
/// <param name="e">The event arguments</param>
private void btnAdd_Click(object sender, EventArgs e)
{
try
{
cleardata();
newClicked = true;
btnDelete.Enabled = false;
btnSave.Enabled = false;
combProfile.SelectedItem = combProfile.Items[0];
txtURL.BackColor = Color.White;
}
catch (Exception ex)
{
MessageBox.Show(resourceManager.GetString("addCatalogFailed"), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
/// <summary>
/// Event handler for configure tab save button.
/// </summary>
/// <param name="sender">The sender object</param>
/// <param name="e">The event arguments</param>
private void btnSave_Click(object sender, EventArgs e)
{
try
{
if (newClicked == true)
{
newClicked = false;
CswProfile profile = combProfile.SelectedItem as CswProfile;
string url = "";
url = txtURL.Text.Trim();
string name = "";
name = txtDisplayName.Text.Trim();
if (url.Length == 0)
{
MessageBox.Show(resourceManager.GetString("urlEmptyError"), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
CswCatalog catalog = new CswCatalog(url, name, profile);
_cswManager.addCatalog(catalog);
MessageBox.Show(resourceManager.GetString("catalogAdded"), "Success", MessageBoxButtons.OK, MessageBoxIcon.None);
cleardata();
adddata();
catalog.resetConnection();
lblCatalogs.Text = resourceManager.GetString("catalogsTxt") + " (" + lstCatalog.Items.Count + ")";
_isCatalogListDirty = true;
}
}
else if (lstCatalog.SelectedItem == null)
{
MessageBox.Show(resourceManager.GetString("resultNotSelected"));
}
else
{
CswCatalog catalog = (CswCatalog)lstCatalog.SelectedItem;
int index = lstCatalog.SelectedIndex;
CswProfile profile = combProfile.SelectedItem as CswProfile;
_cswManager.updateCatalog(catalog, txtDisplayName.Text, txtURL.Text, profile);
cleardata();
adddata();
catalog.resetConnection();
lstCatalog.SelectedIndex = index;
MessageBox.Show(resourceManager.GetString("dataSaved"), "Success", MessageBoxButtons.OK, MessageBoxIcon.None);
_isCatalogListDirty = true;
}
}
catch (Exception ex)
{
MessageBox.Show(resourceManager.GetString("dataSavedFailed"), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
#endregion
/// <summary>
/// Event handler for link labeled event.
/// </summary>
/// <param name="sender">The sender object</param>
/// <param name="e">The event arguments</param>
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
System.Diagnostics.Process.Start("IExplore", " http://www.esri.com");
}
/// <summary>
/// Event handler for add to map context menu clicked.
/// </summary>
/// <param name="param1">The sender object</param>
/// <param name="param1">The event arguments</param>
/* private void addToMapToolStripMenuItem_Click(object sender, EventArgs e) {
if (lstSearchResults.Items.Count == 0) {
MessageBox.Show(resourceManager.GetString("layerNotFound"), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
AddToMap_Clicked();
}*/
/// <summary>
/// Event handler for remove from map context menu clicked.
/// </summary>
/// <param name="param1">The sender object</param>
/// <param name="param1">The event arguments</param>
/* private void removeFromMapToolStripMenuItem_Click(object sender, EventArgs e) {
RemoveFromMap_Clicked();
}*/
/// <summary>
/// Function to remove layer from map.
/// </summary>
private void RemoveFromMap_Clicked()
{
if (lstSearchResults.Items.Count == 0)
{
MessageBox.Show(resourceManager.GetString("layerNotFoundToRemove"), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
try
{
Cursor.Current = Cursors.WaitCursor;
AGXM.ServiceLayer resultLayer = (AGXM.ServiceLayer)addedLayer[lstSearchResults.SelectedItem.GetHashCode()];
if (resultLayer == null)
{
MessageBox.Show(resourceManager.GetString("layerNotAdded"));
}
else if (resultLayer.IsConnected)
{
addedLayer.Remove(lstSearchResults.SelectedItem.GetHashCode());
// View3D currView = (View3D)taskUI.E2.CurrentView; ////
// currView.RemoveLayer(resultLayer); // TODO
}
else
{
//nothing
}
}
catch (Exception ex)
{
throw new Exception(resourceManager.GetString("layerNotAdded"), ex);
}
finally
{
Cursor.Current = Cursors.Default;
}
}
/// <summary>
/// Event handler for remove from map clicked.
/// </summary>
/// <param name="param1">The sender object</param>
/// <param name="param1">The event arguments</param>
/* private void zoomToLayerToolStripMenuItem1_Click(object sender, EventArgs e) {
ZoomToLayer_Clicked();
}*/
/// <summary>
/// Function to zoom to layer from map.
/// </summary>
private void ZoomToLayer_Clicked()
{
if (lstSearchResults.Items.Count == 0)
{
MessageBox.Show(resourceManager.GetString("layerNotAdded"), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
try
{
AGXM.ServiceLayer resultLayer = (AGXM.ServiceLayer)addedLayer[lstSearchResults.SelectedItem.GetHashCode()];
if (resultLayer == null)
{
MessageBox.Show(resourceManager.GetString("layerNotfoundToZoom"), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else if (resultLayer.IsConnected)
{
AGXG.Envelope envelope = new AGXG.Envelope();
envelope.XMin = resultLayer.Extent.XMin;
envelope.YMin = resultLayer.Extent.YMin;
envelope.XMax = resultLayer.Extent.XMax;
envelope.YMax = resultLayer.Extent.YMax;
// View3D currView = (View3D)taskUI.E2.CurrentView;
// currView.DoActionOnGeometry(esriE2GeometryAction.Zoom, envelope); TODO
AGXM.MapDisplay md = AGX.Application.ActiveMapDisplay;
md.ZoomTo(envelope);
}
else
{
//nothing
}
}
catch (Exception ex)
{
MessageBox.Show(resourceManager.GetString("layerZoomFailed"), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
Cursor.Current = Cursors.Default;
}
}
/// <summary>
/// Adds ArcGIS service endpoint to map
/// </summary>
/// <param name="fileName">service url or layer filename</param>
private void AddAGSService(string fileName)
{
try
{
if (fileName.ToLower().Contains("http") && !fileName.ToLower().Contains("arcgis/rest"))
{
if (fileName.EndsWith("MapServer"))
fileName = fileName.Remove(fileName.LastIndexOf("MapServer"));
if (fileName.EndsWith("GlobeServer"))
{
ShowErrorMessageBox("AddArcGISLayerFailed" + "\r\n" + "Adding Globe Server service not supported");
return;
}
String[] s = fileName.Split(new String[] { "/services" }, StringSplitOptions.RemoveEmptyEntries);
AGXD.ServiceConnectionProperties sc = new AGXD.ServiceConnectionProperties();
AGXM.ServiceLayer mapServerLayer = new AGXM.ServiceLayer();
sc.Url = new System.Uri(s[0] + "/services");
sc.ServiceType = AGXD.ServiceType.MapServer;
String[] s1 = null;
if (s.Length > 1)
{
s1 = s[1].Split('?');
}
else
return;
String[] s2 = null;
if (s1 != null)
{
s2 = s1[0].ToLower().Split(new String[] { "/mapserver" }, StringSplitOptions.RemoveEmptyEntries);
}
else
return;
String[] serviceName = null;
if (s2 != null)
serviceName = s2[0].Split(new String[] { "/" }, StringSplitOptions.RemoveEmptyEntries);
else
return;
if (serviceName != null)
mapServerLayer.Name = serviceName[serviceName.Length - 1];
else
return;
sc.ServiceName = s2[0];
mapServerLayer.CachePolicy = AGXM.LayerCachePolicy.RemoveOnApplicationExit; // esriE2LayerCacheType.Session;
try
{
mapServerLayer.Connect();
}
catch (Exception e) { }
if (mapServerLayer.IsConnected)
{
addLayer(mapServerLayer);
addedLayer.Add(DateTime.Now, mapServerLayer);
}
}
else
{
System.IO.StreamReader fStream = System.IO.File.OpenText(fileName);
string xml = fStream.ReadToEnd().Trim();
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
XmlNodeList layersNode = doc.GetElementsByTagName("E2Layers");
foreach (XmlNode xmlnode in layersNode)
{
XmlNodeList layerNodes = xmlnode.ChildNodes;
foreach (XmlNode node in layerNodes)
{
if (node.HasChildNodes && node.Attributes.Item(0).Value.Equals("esri:E2ServerLayer"))
{
AGXD.ServiceConnectionProperties sc = new AGXD.ServiceConnectionProperties();
AGXM.ServiceLayer svrLyr = new AGXM.ServiceLayer();
foreach (XmlNode childNode in node)
{
if (childNode.Name.Equals("DisplayName"))
svrLyr.Name = childNode.InnerText;
else if (childNode.Name.Equals("ServerType"))
sc.ServiceType = (AGXD.ServiceType)Int16.Parse(childNode.InnerText);
else if (childNode.Name.Equals("Url"))
sc.Url = new System.Uri(childNode.InnerText);
else if (childNode.Name.Equals("ServiceName"))
sc.ServiceName = childNode.InnerText;
else if (childNode.Name.Equals("SubserviceName"))
sc.SubServiceName = childNode.InnerText;
}
svrLyr.ServiceConnectionProperties = sc;
svrLyr.Connect();
if (svrLyr.IsConnected)
{
addLayer(svrLyr);
addedLayer.Add(DateTime.Now, svrLyr);
}
}
}
}
}
}
catch (Exception ex)
{
ShowErrorMessageBox("AddArcGISLayerFailed" + "\r\n" + ex.Message);
}
}
/// <summary>
/// Zooms to selected record footprint
/// </summary>
/// <param name="sender">Event sender</param>
/// <param name="e">Event arguments</param>
private void zoomToFootPrintTSBtn_Click(object sender, EventArgs e)
{
CswRecord record = (CswRecord)lstSearchResults.SelectedItem;
AGXM.MapDisplay md = AGX.Application.ActiveMapDisplay;
md.ZoomTo(makeFootPrint(record).GetEnvelope());
}
/// <summary>
/// Displays all footprints in map
/// </summary>
/// <param name="sender">Event sender</param>
/// <param name="e">Event arguments</param>
private void showAllFootPrintTSBtn_Click(object sender, EventArgs e)
{
try
{
Cursor.Current = Cursors.WaitCursor;
AGXM.MapDisplay md = AGX.Application.ActiveMapDisplay;
if (showAll)
{
showAll = false;
showAllFootPrintTSBtn.ToolTipText = "Hide All Footprints";
showAllFootPrintTSBtn.Image = (Image)this.resourceManager.GetObject("hideAll");
foreach (Object obj in lstSearchResults.Items)
{
CswRecord record = (CswRecord)obj;
if (record.BoundingBox.Maxx != NONEXSISTANTNUMBER)
{
AGXM.Graphic pointGraphic = makeFootPrintGraphic(record);
//Create a new Note to hold the graphic
AGXM.Note newNote = new AGXM.Note(record.Title, pointGraphic.Geometry, pointGraphic.Symbol);
//Add the Result to the map
md.Map.ChildItems.Add(newNote);
}
}
}
else
{
// md.Map.ChildItems.Clear();
clearFootprints();
}
}
catch (Exception ex)
{
ShowErrorMessageBox(ex.Message);
}
finally
{
Cursor.Current = Cursors.Default;
}
}
/// <summary>
/// Clear all footprint displayed on map
/// </summary>
private void clearFootprints()
{
showAll = true;
showAllFootPrintTSBtn.ToolTipText = "Show All Footprints";
showAllFootPrintTSBtn.Image = (Image)this.resourceManager.GetObject("showAll");
AGXM.MapDisplay md = AGX.Application.ActiveMapDisplay;
foreach (Object obj in lstSearchResults.Items)
{
CswRecord record = (CswRecord)obj;
if (record.BoundingBox.Maxx != NONEXSISTANTNUMBER)
{
AGXM.MapItemCollection mic = md.Map.ChildItems;
IEnumerator e = mic.GetEnumerator();
while (e.MoveNext())
{
AGXM.MapItem mi = (AGXM.MapItem)e.Current;
if (mi.Name == record.Title)
{
md.Map.ChildItems.Remove(mi);
break;
}
}
}
/* if (record.BoundingBox.Maxx != NONEXSISTANTNUMBER)
{
AGXM.Graphic pointGraphic = makeFootPrintGraphic(record);
//Create a new Note to hold the graphic
AGXM.Note newNote = new AGXM.Note(record.Title, pointGraphic.Geometry, pointGraphic.Symbol);
//Add the Result to the map
md.Map.ChildItems.Remove(newNote);
}*/
}
}
/// <summary>
/// Handles clears all footprints event
/// </summary>
/// <param name="sender">Event sender</param>
/// <param name="e">Event arguments</param>
private void clearAllFootPrintTSBtn_Click(object sender, EventArgs e)
{
clearFootprints();
}
/// <summary>
/// Handles display footprints event
/// </summary>
/// <param name="sender">Event sender</param>
/// <param name="e">Event arguments</param>
private void displayFootPrintTSBtn_Click(object sender, EventArgs e)
{
CswRecord record = (CswRecord)lstSearchResults.SelectedItem;
try
{
AGXM.Graphic pointGraphic = makeFootPrintGraphic(record);
//Create a new Note to hold the graphic
AGXM.Note newNote = new AGXM.Note(record.Title, pointGraphic.Geometry, pointGraphic.Symbol);
AGXM.MapDisplay md = AGX.Application.ActiveMapDisplay;
//Add the Result to the map
md.Map.ChildItems.Add(newNote);
}
catch (Exception ex)
{
string msg = ex.Message;
}
}
/// <summary>
/// Makes footprint envelope for a metadata record
/// </summary>
/// <param name="record">CswRecord object</param>
/// <returns>envelope polygon</returns>
private AGXG.Polygon makeFootPrint(CswRecord record)
{
AGXG.Envelope envelope = new AGXG.Envelope();
try
{
envelope.XMax = record.BoundingBox.Maxx;
envelope.YMax = record.BoundingBox.Maxy;
envelope.XMin = record.BoundingBox.Minx;
envelope.YMin = record.BoundingBox.Miny;
}
catch (System.ArgumentException e)
{
try
{
envelope.XMax = record.BoundingBox.Minx;
envelope.YMax = record.BoundingBox.Maxy;
envelope.XMin = record.BoundingBox.Maxx;
envelope.YMin = record.BoundingBox.Miny;
}
catch (System.ArgumentException e1)
{
try
{
envelope.XMax = record.BoundingBox.Minx;
envelope.YMax = record.BoundingBox.Miny;
envelope.XMin = record.BoundingBox.Maxx;
envelope.YMin = record.BoundingBox.Maxy;
}
catch (System.ArgumentException e2)
{
envelope.XMax = record.BoundingBox.Maxx;
envelope.YMax = record.BoundingBox.Miny;
envelope.XMin = record.BoundingBox.Minx;
envelope.YMin = record.BoundingBox.Maxy;
}
}
}
AGXG.Point p1 = new AGXG.Point();
p1.SetCoordinates(record.BoundingBox.Maxx, record.BoundingBox.Maxy);
AGXG.Point p2 = new AGXG.Point();
p2.SetCoordinates(record.BoundingBox.Maxx, record.BoundingBox.Miny);
AGXG.Point p3 = new AGXG.Point();
p3.SetCoordinates(record.BoundingBox.Minx, record.BoundingBox.Miny);
AGXG.Point p4 = new AGXG.Point();
p4.SetCoordinates(record.BoundingBox.Minx, record.BoundingBox.Maxy);
AGXG.Polygon footPrint = new AGXG.Polygon();
footPrint.AddPoint(p1);
footPrint.AddPoint(p2);
footPrint.AddPoint(p3);
footPrint.AddPoint(p4);
footPrint.AddPoint(p1);
return footPrint;
}
/// <summary>
/// Makes graphic to display footprint
/// </summary>
/// <param name="record"></param>
/// <returns></returns>
private AGXM.Graphic makeFootPrintGraphic(CswRecord record)
{
AGXG.Polygon footPrint = makeFootPrint(record);
//Turn the Polygon in to a Graphic
AGXM.Graphic graphic = new AGXM.Graphic(footPrint);
//Set the Graphic's symbol
// graphic.Symbol = AGXM.Symbol.Fill.Outline.Yellow;
graphic.Symbol.OutlineColor = Color.Yellow;
graphic.Symbol.Color = Color.Transparent;
// graphic.Symbol.Size = 100;
return graphic;
}
/// <summary>
/// Handles Help link click event
/// </summary>
/// <param name="sender">Event sender</param>
/// <param name="e">Event arguments</param>
private void linkLblHelp_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
System.Diagnostics.Process.Start("IExplore", CswResources.helpUrl);
}
/// <summary>
/// Handles About link click event
/// </summary>
/// <param name="sender">Event sender</param>
/// <param name="e">Event arguments</param>
private void linkLblAbt_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
System.Diagnostics.Process.Start("IExplore", CswResources.abtUrl);
}
/// <summary>
/// Handles url text changed event
/// </summary>
/// <param name="sender">Event sender</param>
/// <param name="e">Event arguments</param>
private void txtURL_TextChanged(object sender, EventArgs e)
{
if (txtURL.Text.Length > 0)
{
btnSave.Enabled = true;
}
else
{
btnSave.Enabled = false;
}
}
/// <summary>
/// Handles name changed event
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void txtDisplayName_TextChanged(object sender, EventArgs e)
{
if (txtURL.Text.Length > 0)
{
btnSave.Enabled = true;
}
else
{
btnSave.Enabled = false;
}
}
/// <summary>
/// Function on click of search phrase
/// </summary>
/// <param name="param1">The sender object</param>
/// <param name="param1">The event arguments</param>
private void txtSearchPhrase_TextChanged(object sender, EventArgs e)
{
btnSearch.Enabled = true;
}
/// <summary>
/// Function to reset the maximum number of results
/// </summary>
/// <param name="param1">The sender object</param>
/// <param name="param1">The event arguments</param>
private void cmbCswCatalog_SelectedIndexChanged(object sender, EventArgs e)
{
lstSearchResults.DataSource = null;
// reset GUI
txtAbstract.Text = "";
tsbAddToMap.Enabled = false;
tsbViewMetadata.Enabled = false;
tsbDownloadMetadata.Enabled = false;
if (cmbCswCatalog.SelectedIndex == -1)
{
cmbCswCatalog.SelectedIndex = 0;
}
CswCatalog catalog = (CswCatalog)cmbCswCatalog.SelectedItem;
if (catalog == null)
{
throw new NullReferenceException(resourceManager.GetString("catalogNotSpecified"));
}
if (catalog.Profile.SupportContentTypeQuery)
{
chkLiveDataAndMapOnly.Enabled = true;
}
else
{
chkLiveDataAndMapOnly.Enabled = false;
}
}
/// <summary>
/// Set the maximum number of results to integer value
/// </summary>
/// <param name="sender">event sender</param>
/// <param name="e">event args</param>
private void nudNumOfResults_ValueChanged(object sender, EventArgs e)
{
if (nudNumOfResults.Value > 500)
{
nudNumOfResults.Value = 500;
}
}
}
}
| {
"pile_set_name": "Github"
} |
{
"extends": "@microsoft/sp-tslint-rules/base-tslint.json",
"rules": {
"class-name": false,
"export-name": false,
"forin": false,
"label-position": false,
"member-access": true,
"no-arg": false,
"no-console": false,
"no-construct": false,
"no-duplicate-variable": true,
"no-eval": false,
"no-function-expression": true,
"no-internal-module": true,
"no-shadowed-variable": true,
"no-switch-case-fall-through": true,
"no-unnecessary-semicolons": true,
"no-unused-expression": true,
"no-use-before-declare": true,
"no-with-statement": true,
"semicolon": true,
"trailing-comma": false,
"typedef": false,
"typedef-whitespace": false,
"use-named-parameter": true,
"variable-name": false,
"whitespace": false
}
} | {
"pile_set_name": "Github"
} |
// MESSAGE VOLT_SENSOR PACKING
#define MAVLINK_MSG_ID_VOLT_SENSOR 191
MAVPACKED(
typedef struct __mavlink_volt_sensor_t {
uint16_t voltage; /*< Voltage in uS of PWM. 0 uS = 0V, 20 uS = 21.5V */
uint16_t reading2; /*< Depends on the value of r2Type (0) Current consumption in uS of PWM, 20 uS = 90Amp (1) Distance in cm (2) Distance in cm (3) Absolute value*/
uint8_t r2Type; /*< It is the value of reading 2: 0 - Current, 1 - Foreward Sonar, 2 - Back Sonar, 3 - RPM*/
}) mavlink_volt_sensor_t;
#define MAVLINK_MSG_ID_VOLT_SENSOR_LEN 5
#define MAVLINK_MSG_ID_VOLT_SENSOR_MIN_LEN 5
#define MAVLINK_MSG_ID_191_LEN 5
#define MAVLINK_MSG_ID_191_MIN_LEN 5
#define MAVLINK_MSG_ID_VOLT_SENSOR_CRC 17
#define MAVLINK_MSG_ID_191_CRC 17
#if MAVLINK_COMMAND_24BIT
#define MAVLINK_MESSAGE_INFO_VOLT_SENSOR { \
191, \
"VOLT_SENSOR", \
3, \
{ { "voltage", NULL, MAVLINK_TYPE_UINT16_T, 0, 0, offsetof(mavlink_volt_sensor_t, voltage) }, \
{ "reading2", NULL, MAVLINK_TYPE_UINT16_T, 0, 2, offsetof(mavlink_volt_sensor_t, reading2) }, \
{ "r2Type", NULL, MAVLINK_TYPE_UINT8_T, 0, 4, offsetof(mavlink_volt_sensor_t, r2Type) }, \
} \
}
#else
#define MAVLINK_MESSAGE_INFO_VOLT_SENSOR { \
"VOLT_SENSOR", \
3, \
{ { "voltage", NULL, MAVLINK_TYPE_UINT16_T, 0, 0, offsetof(mavlink_volt_sensor_t, voltage) }, \
{ "reading2", NULL, MAVLINK_TYPE_UINT16_T, 0, 2, offsetof(mavlink_volt_sensor_t, reading2) }, \
{ "r2Type", NULL, MAVLINK_TYPE_UINT8_T, 0, 4, offsetof(mavlink_volt_sensor_t, r2Type) }, \
} \
}
#endif
/**
* @brief Pack a volt_sensor message
* @param system_id ID of this system
* @param component_id ID of this component (e.g. 200 for IMU)
* @param msg The MAVLink message to compress the data into
*
* @param r2Type It is the value of reading 2: 0 - Current, 1 - Foreward Sonar, 2 - Back Sonar, 3 - RPM
* @param voltage Voltage in uS of PWM. 0 uS = 0V, 20 uS = 21.5V
* @param reading2 Depends on the value of r2Type (0) Current consumption in uS of PWM, 20 uS = 90Amp (1) Distance in cm (2) Distance in cm (3) Absolute value
* @return length of the message in bytes (excluding serial stream start sign)
*/
static inline uint16_t mavlink_msg_volt_sensor_pack(uint8_t system_id, uint8_t component_id, mavlink_message_t* msg,
uint8_t r2Type, uint16_t voltage, uint16_t reading2)
{
#if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS
char buf[MAVLINK_MSG_ID_VOLT_SENSOR_LEN];
_mav_put_uint16_t(buf, 0, voltage);
_mav_put_uint16_t(buf, 2, reading2);
_mav_put_uint8_t(buf, 4, r2Type);
memcpy(_MAV_PAYLOAD_NON_CONST(msg), buf, MAVLINK_MSG_ID_VOLT_SENSOR_LEN);
#else
mavlink_volt_sensor_t packet;
packet.voltage = voltage;
packet.reading2 = reading2;
packet.r2Type = r2Type;
memcpy(_MAV_PAYLOAD_NON_CONST(msg), &packet, MAVLINK_MSG_ID_VOLT_SENSOR_LEN);
#endif
msg->msgid = MAVLINK_MSG_ID_VOLT_SENSOR;
return mavlink_finalize_message(msg, system_id, component_id, MAVLINK_MSG_ID_VOLT_SENSOR_MIN_LEN, MAVLINK_MSG_ID_VOLT_SENSOR_LEN, MAVLINK_MSG_ID_VOLT_SENSOR_CRC);
}
/**
* @brief Pack a volt_sensor message on a channel
* @param system_id ID of this system
* @param component_id ID of this component (e.g. 200 for IMU)
* @param chan The MAVLink channel this message will be sent over
* @param msg The MAVLink message to compress the data into
* @param r2Type It is the value of reading 2: 0 - Current, 1 - Foreward Sonar, 2 - Back Sonar, 3 - RPM
* @param voltage Voltage in uS of PWM. 0 uS = 0V, 20 uS = 21.5V
* @param reading2 Depends on the value of r2Type (0) Current consumption in uS of PWM, 20 uS = 90Amp (1) Distance in cm (2) Distance in cm (3) Absolute value
* @return length of the message in bytes (excluding serial stream start sign)
*/
static inline uint16_t mavlink_msg_volt_sensor_pack_chan(uint8_t system_id, uint8_t component_id, uint8_t chan,
mavlink_message_t* msg,
uint8_t r2Type,uint16_t voltage,uint16_t reading2)
{
#if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS
char buf[MAVLINK_MSG_ID_VOLT_SENSOR_LEN];
_mav_put_uint16_t(buf, 0, voltage);
_mav_put_uint16_t(buf, 2, reading2);
_mav_put_uint8_t(buf, 4, r2Type);
memcpy(_MAV_PAYLOAD_NON_CONST(msg), buf, MAVLINK_MSG_ID_VOLT_SENSOR_LEN);
#else
mavlink_volt_sensor_t packet;
packet.voltage = voltage;
packet.reading2 = reading2;
packet.r2Type = r2Type;
memcpy(_MAV_PAYLOAD_NON_CONST(msg), &packet, MAVLINK_MSG_ID_VOLT_SENSOR_LEN);
#endif
msg->msgid = MAVLINK_MSG_ID_VOLT_SENSOR;
return mavlink_finalize_message_chan(msg, system_id, component_id, chan, MAVLINK_MSG_ID_VOLT_SENSOR_MIN_LEN, MAVLINK_MSG_ID_VOLT_SENSOR_LEN, MAVLINK_MSG_ID_VOLT_SENSOR_CRC);
}
/**
* @brief Encode a volt_sensor struct
*
* @param system_id ID of this system
* @param component_id ID of this component (e.g. 200 for IMU)
* @param msg The MAVLink message to compress the data into
* @param volt_sensor C-struct to read the message contents from
*/
static inline uint16_t mavlink_msg_volt_sensor_encode(uint8_t system_id, uint8_t component_id, mavlink_message_t* msg, const mavlink_volt_sensor_t* volt_sensor)
{
return mavlink_msg_volt_sensor_pack(system_id, component_id, msg, volt_sensor->r2Type, volt_sensor->voltage, volt_sensor->reading2);
}
/**
* @brief Encode a volt_sensor struct on a channel
*
* @param system_id ID of this system
* @param component_id ID of this component (e.g. 200 for IMU)
* @param chan The MAVLink channel this message will be sent over
* @param msg The MAVLink message to compress the data into
* @param volt_sensor C-struct to read the message contents from
*/
static inline uint16_t mavlink_msg_volt_sensor_encode_chan(uint8_t system_id, uint8_t component_id, uint8_t chan, mavlink_message_t* msg, const mavlink_volt_sensor_t* volt_sensor)
{
return mavlink_msg_volt_sensor_pack_chan(system_id, component_id, chan, msg, volt_sensor->r2Type, volt_sensor->voltage, volt_sensor->reading2);
}
/**
* @brief Send a volt_sensor message
* @param chan MAVLink channel to send the message
*
* @param r2Type It is the value of reading 2: 0 - Current, 1 - Foreward Sonar, 2 - Back Sonar, 3 - RPM
* @param voltage Voltage in uS of PWM. 0 uS = 0V, 20 uS = 21.5V
* @param reading2 Depends on the value of r2Type (0) Current consumption in uS of PWM, 20 uS = 90Amp (1) Distance in cm (2) Distance in cm (3) Absolute value
*/
#ifdef MAVLINK_USE_CONVENIENCE_FUNCTIONS
static inline void mavlink_msg_volt_sensor_send(mavlink_channel_t chan, uint8_t r2Type, uint16_t voltage, uint16_t reading2)
{
#if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS
char buf[MAVLINK_MSG_ID_VOLT_SENSOR_LEN];
_mav_put_uint16_t(buf, 0, voltage);
_mav_put_uint16_t(buf, 2, reading2);
_mav_put_uint8_t(buf, 4, r2Type);
_mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_VOLT_SENSOR, buf, MAVLINK_MSG_ID_VOLT_SENSOR_MIN_LEN, MAVLINK_MSG_ID_VOLT_SENSOR_LEN, MAVLINK_MSG_ID_VOLT_SENSOR_CRC);
#else
mavlink_volt_sensor_t packet;
packet.voltage = voltage;
packet.reading2 = reading2;
packet.r2Type = r2Type;
_mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_VOLT_SENSOR, (const char *)&packet, MAVLINK_MSG_ID_VOLT_SENSOR_MIN_LEN, MAVLINK_MSG_ID_VOLT_SENSOR_LEN, MAVLINK_MSG_ID_VOLT_SENSOR_CRC);
#endif
}
/**
* @brief Send a volt_sensor message
* @param chan MAVLink channel to send the message
* @param struct The MAVLink struct to serialize
*/
static inline void mavlink_msg_volt_sensor_send_struct(mavlink_channel_t chan, const mavlink_volt_sensor_t* volt_sensor)
{
#if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS
mavlink_msg_volt_sensor_send(chan, volt_sensor->r2Type, volt_sensor->voltage, volt_sensor->reading2);
#else
_mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_VOLT_SENSOR, (const char *)volt_sensor, MAVLINK_MSG_ID_VOLT_SENSOR_MIN_LEN, MAVLINK_MSG_ID_VOLT_SENSOR_LEN, MAVLINK_MSG_ID_VOLT_SENSOR_CRC);
#endif
}
#if MAVLINK_MSG_ID_VOLT_SENSOR_LEN <= MAVLINK_MAX_PAYLOAD_LEN
/*
This varient of _send() can be used to save stack space by re-using
memory from the receive buffer. The caller provides a
mavlink_message_t which is the size of a full mavlink message. This
is usually the receive buffer for the channel, and allows a reply to an
incoming message with minimum stack space usage.
*/
static inline void mavlink_msg_volt_sensor_send_buf(mavlink_message_t *msgbuf, mavlink_channel_t chan, uint8_t r2Type, uint16_t voltage, uint16_t reading2)
{
#if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS
char *buf = (char *)msgbuf;
_mav_put_uint16_t(buf, 0, voltage);
_mav_put_uint16_t(buf, 2, reading2);
_mav_put_uint8_t(buf, 4, r2Type);
_mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_VOLT_SENSOR, buf, MAVLINK_MSG_ID_VOLT_SENSOR_MIN_LEN, MAVLINK_MSG_ID_VOLT_SENSOR_LEN, MAVLINK_MSG_ID_VOLT_SENSOR_CRC);
#else
mavlink_volt_sensor_t *packet = (mavlink_volt_sensor_t *)msgbuf;
packet->voltage = voltage;
packet->reading2 = reading2;
packet->r2Type = r2Type;
_mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_VOLT_SENSOR, (const char *)packet, MAVLINK_MSG_ID_VOLT_SENSOR_MIN_LEN, MAVLINK_MSG_ID_VOLT_SENSOR_LEN, MAVLINK_MSG_ID_VOLT_SENSOR_CRC);
#endif
}
#endif
#endif
// MESSAGE VOLT_SENSOR UNPACKING
/**
* @brief Get field r2Type from volt_sensor message
*
* @return It is the value of reading 2: 0 - Current, 1 - Foreward Sonar, 2 - Back Sonar, 3 - RPM
*/
static inline uint8_t mavlink_msg_volt_sensor_get_r2Type(const mavlink_message_t* msg)
{
return _MAV_RETURN_uint8_t(msg, 4);
}
/**
* @brief Get field voltage from volt_sensor message
*
* @return Voltage in uS of PWM. 0 uS = 0V, 20 uS = 21.5V
*/
static inline uint16_t mavlink_msg_volt_sensor_get_voltage(const mavlink_message_t* msg)
{
return _MAV_RETURN_uint16_t(msg, 0);
}
/**
* @brief Get field reading2 from volt_sensor message
*
* @return Depends on the value of r2Type (0) Current consumption in uS of PWM, 20 uS = 90Amp (1) Distance in cm (2) Distance in cm (3) Absolute value
*/
static inline uint16_t mavlink_msg_volt_sensor_get_reading2(const mavlink_message_t* msg)
{
return _MAV_RETURN_uint16_t(msg, 2);
}
/**
* @brief Decode a volt_sensor message into a struct
*
* @param msg The message to decode
* @param volt_sensor C-struct to decode the message contents into
*/
static inline void mavlink_msg_volt_sensor_decode(const mavlink_message_t* msg, mavlink_volt_sensor_t* volt_sensor)
{
#if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS
volt_sensor->voltage = mavlink_msg_volt_sensor_get_voltage(msg);
volt_sensor->reading2 = mavlink_msg_volt_sensor_get_reading2(msg);
volt_sensor->r2Type = mavlink_msg_volt_sensor_get_r2Type(msg);
#else
uint8_t len = msg->len < MAVLINK_MSG_ID_VOLT_SENSOR_LEN? msg->len : MAVLINK_MSG_ID_VOLT_SENSOR_LEN;
memset(volt_sensor, 0, MAVLINK_MSG_ID_VOLT_SENSOR_LEN);
memcpy(volt_sensor, _MAV_PAYLOAD(msg), len);
#endif
}
| {
"pile_set_name": "Github"
} |
const express = require("express");
const app = express();
const { resolve } = require("path");
// Replace if using a different env file or config
const env = require("dotenv").config({ path: "./.env" });
const stripe = require("stripe")(process.env.STRIPE_SECRET_KEY);
app.use(express.static(process.env.STATIC_DIR));
app.use(express.json());
app.get("/", (req, res) => {
// Display checkout page
const path = resolve(process.env.STATIC_DIR + "/index.html");
res.sendFile(path);
});
app.get("/stripe-key", (req, res) => {
res.send({ publishableKey: process.env.STRIPE_PUBLISHABLE_KEY });
});
const calculateOrderAmount = items => {
// Replace this constant with a calculation of the order's amount
// You should always calculate the order total on the server to prevent
// people from directly manipulating the amount on the client
return 1400;
};
app.post("/pay", async (req, res) => {
const { paymentMethodId, paymentIntentId, items, currency, useStripeSdk } = req.body;
const orderAmount = calculateOrderAmount(items);
try {
let intent;
if (paymentMethodId) {
// Create new PaymentIntent with a PaymentMethod ID from the client.
intent = await stripe.paymentIntents.create({
amount: orderAmount,
currency: currency,
payment_method: paymentMethodId,
confirmation_method: "manual",
confirm: true,
// If a mobile client passes `useStripeSdk`, set `use_stripe_sdk=true`
// to take advantage of new authentication features in mobile SDKs
use_stripe_sdk: useStripeSdk,
});
// After create, if the PaymentIntent's status is succeeded, fulfill the order.
} else if (paymentIntentId) {
// Confirm the PaymentIntent to finalize payment after handling a required action
// on the client.
intent = await stripe.paymentIntents.confirm(paymentIntentId);
// After confirm, if the PaymentIntent's status is succeeded, fulfill the order.
}
res.send(generateResponse(intent));
} catch (e) {
// Handle "hard declines" e.g. insufficient funds, expired card, etc
// See https://stripe.com/docs/declines/codes for more
res.send({ error: e.message });
}
});
const generateResponse = intent => {
// Generate a response based on the intent's status
switch (intent.status) {
case "requires_action":
case "requires_source_action":
// Card requires authentication
return {
requiresAction: true,
clientSecret: intent.client_secret
};
case "requires_payment_method":
case "requires_source":
// Card was not properly authenticated, suggest a new payment method
return {
error: "Your card was denied, please provide a new payment method"
};
case "succeeded":
// Payment is complete, authentication not required
// To cancel the payment after capture you will need to issue a Refund (https://stripe.com/docs/api/refunds)
console.log("💰 Payment received!");
return { clientSecret: intent.client_secret };
}
};
app.listen(4242, () => console.log(`Node server listening on port ${4242}!`));
| {
"pile_set_name": "Github"
} |
//
// WalletBackupDelegate.swift
// Blockchain
//
// Created by kevinwu on 5/18/18.
// Copyright © 2018 Blockchain Luxembourg S.A. All rights reserved.
//
import Foundation
@objc protocol WalletBackupDelegate: class {
/// Method invoked when backup sequence is completed
func didBackupWallet()
/// Method invoked when backup attempt fails
func didFailBackupWallet()
}
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="gb2312"?>
<VisualStudioProject
ProjectType="Visual C++"
Version="9.00"
Name="mmGhostR3"
ProjectGUID="{42C8E7CE-82C8-46FF-90A5-5648710C8ADB}"
RootNamespace="mmGhostR3"
Keyword="Win32Proj"
TargetFrameworkVersion="196613"
>
<Platforms>
<Platform
Name="Win32"
/>
</Platforms>
<ToolFiles>
</ToolFiles>
<Configurations>
<Configuration
Name="Debug|Win32"
OutputDirectory="O:\_obj\$(solutionName)\$(ConfigurationName)\$(ProjectName)\"
IntermediateDirectory="O:\_obj\$(solutionName)\$(ConfigurationName)\$(ProjectName)\"
ConfigurationType="2"
UseOfMFC="0"
CharacterSet="2"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
/>
<Tool
Name="VCCLCompilerTool"
Optimization="0"
PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_USRDLL;MMGHOSTR3_EXPORTS"
MinimalRebuild="true"
ExceptionHandling="2"
BasicRuntimeChecks="3"
RuntimeLibrary="1"
UsePrecompiledHeader="2"
WarningLevel="3"
DebugInformationFormat="4"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLinkerTool"
AdditionalOptions="/SAFESEH:NO"
OutputFile="$(SolutionDir)\_Obj\libs\$(ProjectName).dll"
LinkIncremental="2"
GenerateDebugInformation="true"
SubSystem="2"
TargetMachine="1"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCAppVerifierTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
<Configuration
Name="Release|Win32"
OutputDirectory="O:\_obj\$(solutionName)\$(ConfigurationName)\$(ProjectName)\"
IntermediateDirectory="O:\_obj\$(solutionName)\$(ConfigurationName)\$(ProjectName)\"
ConfigurationType="2"
UseOfMFC="0"
CharacterSet="2"
WholeProgramOptimization="1"
>
<Tool
Name="VCPreBuildEventTool"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
/>
<Tool
Name="VCCLCompilerTool"
Optimization="2"
EnableIntrinsicFunctions="true"
FavorSizeOrSpeed="1"
OmitFramePointers="true"
PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_USRDLL;MMGHOSTR3_EXPORTS"
ExceptionHandling="2"
RuntimeLibrary="0"
BufferSecurityCheck="true"
EnableFunctionLevelLinking="true"
UsePrecompiledHeader="2"
WarningLevel="3"
DebugInformationFormat="0"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
/>
<Tool
Name="VCLinkerTool"
AdditionalOptions="/SAFESEH:NO"
OutputFile="$(SolutionDir)\_Obj\libs\$(ProjectName).dll"
LinkIncremental="1"
GenerateManifest="false"
SubSystem="2"
OptimizeReferences="2"
EnableCOMDATFolding="2"
SetChecksum="true"
RandomizedBaseAddress="1"
FixedBaseAddress="1"
DataExecutionPrevention="0"
TargetMachine="1"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCManifestTool"
/>
<Tool
Name="VCXDCMakeTool"
/>
<Tool
Name="VCBscMakeTool"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCAppVerifierTool"
/>
<Tool
Name="VCPostBuildEventTool"
/>
</Configuration>
</Configurations>
<References>
</References>
<Files>
<Filter
Name="源文件"
Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"
>
<File
RelativePath=".\Console.cpp"
>
</File>
<File
RelativePath=".\DbgFunction.cpp"
>
</File>
<File
RelativePath=".\dllmain.cpp"
>
<FileConfiguration
Name="Debug|Win32"
>
<Tool
Name="VCCLCompilerTool"
UsePrecompiledHeader="0"
CompileAsManaged="0"
/>
</FileConfiguration>
<FileConfiguration
Name="Release|Win32"
>
<Tool
Name="VCCLCompilerTool"
UsePrecompiledHeader="0"
CompileAsManaged="0"
/>
</FileConfiguration>
</File>
<File
RelativePath=".\mmGhostR3.cpp"
>
</File>
<File
RelativePath=".\PipeCore.cpp"
>
</File>
<File
RelativePath=".\stdafx.cpp"
>
<FileConfiguration
Name="Debug|Win32"
>
<Tool
Name="VCCLCompilerTool"
UsePrecompiledHeader="1"
/>
</FileConfiguration>
<FileConfiguration
Name="Release|Win32"
>
<Tool
Name="VCCLCompilerTool"
UsePrecompiledHeader="1"
/>
</FileConfiguration>
</File>
<File
RelativePath=".\WorkCore.cpp"
>
</File>
</Filter>
<Filter
Name="头文件"
Filter="h;hpp;hxx;hm;inl;inc;xsd"
UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"
>
<File
RelativePath=".\Console.h"
>
</File>
<File
RelativePath=".\DbgFunction.h"
>
</File>
<File
RelativePath=".\DbgStruct.h"
>
</File>
<File
RelativePath=".\mmGhostR3.h"
>
</File>
<File
RelativePath=".\PipeCore.h"
>
</File>
<File
RelativePath=".\stdafx.h"
>
</File>
<File
RelativePath=".\targetver.h"
>
</File>
<File
RelativePath=".\WorkCore.h"
>
</File>
</Filter>
</Files>
<Globals>
</Globals>
</VisualStudioProject>
| {
"pile_set_name": "Github"
} |
// Before
class ExampleComponent extends React.Component {
// highlight-range{1-10}
componentWillMount() {
this.setState({
subscribedValue: this.props.dataSource.value,
});
// This is not safe; it can leak!
this.props.dataSource.subscribe(
this.handleSubscriptionChange
);
}
componentWillUnmount() {
this.props.dataSource.unsubscribe(
this.handleSubscriptionChange
);
}
handleSubscriptionChange = dataSource => {
this.setState({
subscribedValue: dataSource.value,
});
};
}
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="ISO-8859-1" ?>
<?xml-stylesheet type="text/xsl" href=""?>
<plugin>
<name>testPluginPackage</name>
<creationDate>2008-02-19</creationDate>
<author>Monique Szpak</author>
<authorEmail>[email protected]</authorEmail>
<authorUrl>http://www.openx.org</authorUrl>
<license>license.txt</license>
<description>testPlugin Package for OpenX</description>
<version>0.0.1</version>
<type>package</type>
<install>
<files>
<file path="{PLUGINPATH}">testPluginPackage.readme.txt</file>
</files>
<contents>
<group name="testPlugin">1</group>
<group name="testDepends">2</group>
</contents>
</install>
</plugin>
| {
"pile_set_name": "Github"
} |
// © 2018 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
#include "unicode/utypes.h"
#if !UCONFIG_NO_FORMATTING
#ifndef __SOURCE_NUMRANGE_TYPES_H__
#define __SOURCE_NUMRANGE_TYPES_H__
#include "unicode/numberformatter.h"
#include "unicode/numberrangeformatter.h"
#include "unicode/simpleformatter.h"
#include "number_types.h"
#include "number_decimalquantity.h"
#include "number_formatimpl.h"
#include "formatted_string_builder.h"
#include "formattedval_impl.h"
#include "pluralranges.h"
U_NAMESPACE_BEGIN namespace number {
namespace impl {
/**
* Class similar to UFormattedNumberData.
*
* Has incomplete magic number logic that will need to be finished
* if this is to be exposed as C API in the future.
*
* Possible magic number: 0x46445200
* Reads in ASCII as "FDR" (FormatteDnumberRange with room at the end)
*/
class UFormattedNumberRangeData : public FormattedValueStringBuilderImpl {
public:
UFormattedNumberRangeData() : FormattedValueStringBuilderImpl(kUndefinedField) {}
virtual ~UFormattedNumberRangeData();
DecimalQuantity quantity1;
DecimalQuantity quantity2;
UNumberRangeIdentityResult identityResult = UNUM_IDENTITY_RESULT_COUNT;
};
class NumberRangeFormatterImpl : public UMemory {
public:
NumberRangeFormatterImpl(const RangeMacroProps& macros, UErrorCode& status);
void format(UFormattedNumberRangeData& data, bool equalBeforeRounding, UErrorCode& status) const;
private:
NumberFormatterImpl formatterImpl1;
NumberFormatterImpl formatterImpl2;
bool fSameFormatters;
UNumberRangeCollapse fCollapse;
UNumberRangeIdentityFallback fIdentityFallback;
SimpleFormatter fRangeFormatter;
SimpleModifier fApproximatelyModifier;
StandardPluralRanges fPluralRanges;
void formatSingleValue(UFormattedNumberRangeData& data,
MicroProps& micros1, MicroProps& micros2,
UErrorCode& status) const;
void formatApproximately(UFormattedNumberRangeData& data,
MicroProps& micros1, MicroProps& micros2,
UErrorCode& status) const;
void formatRange(UFormattedNumberRangeData& data,
MicroProps& micros1, MicroProps& micros2,
UErrorCode& status) const;
const Modifier& resolveModifierPlurals(const Modifier& first, const Modifier& second) const;
};
/** Helper function used in upluralrules.cpp */
const UFormattedNumberRangeData* validateUFormattedNumberRange(
const UFormattedNumberRange* uresult, UErrorCode& status);
} // namespace impl
} // namespace number
U_NAMESPACE_END
#endif //__SOURCE_NUMRANGE_TYPES_H__
#endif /* #if !UCONFIG_NO_FORMATTING */
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.jfr.consumer;
import java.util.List;
import jdk.jfr.ValueDescriptor;
import jdk.jfr.internal.Type;
/**
* A recorded thread.
*
* @since 8
*/
public final class RecordedThread extends RecordedObject {
static ObjectFactory<RecordedThread> createFactory(Type type, TimeConverter timeConverter) {
return new ObjectFactory<RecordedThread>(type) {
@Override
RecordedThread createTyped(List<ValueDescriptor> desc, long id, Object[] object) {
return new RecordedThread(desc, id, object, timeConverter);
}
};
}
private final long uniqueId;
private RecordedThread(List<ValueDescriptor> descriptors, long id, Object[] values, TimeConverter timeConverter) {
super(descriptors, values, timeConverter);
this.uniqueId = id;
}
/**
* Returns the thread name used by the operating system.
*
* @return the OS thread name, or {@code null} if doesn't exist
*/
public String getOSName() {
return getTyped("osName", String.class, null);
}
/**
* Returns the thread ID used by the operating system.
*
* @return The Java thread ID, or {@code -1} if doesn't exist
*/
public long getOSThreadId() {
Long l = getTyped("osThreadId", Long.class, -1L);
return l.longValue();
}
/**
* Returns the Java thread group, if available.
*
* @return the thread group, or {@code null} if doesn't exist
*/
public RecordedThreadGroup getThreadGroup() {
return getTyped("group", RecordedThreadGroup.class, null);
}
/**
* Returns the Java thread name, or {@code null} if if doesn't exist.
* <p>
* Returns {@code java.lang.Thread.getName()} if the thread has a Java
* representation. {@code null} otherwise.
*
* @return the Java thread name, or {@code null} if doesn't exist
*/
public String getJavaName() {
return getTyped("javaName", String.class, null);
}
/**
* Returns the Java thread ID, or {@code -1} if it's not a Java thread.
*
* @return the Java thread ID, or {@code -1} if it's not a Java thread
*/
public long getJavaThreadId() {
Long l = getTyped("javaThreadId", Long.class, -1L);
return l.longValue();
}
/**
* Returns a unique ID for both native threads and Java threads that can't be
* reused within the lifespan of the JVM.
* <p>
* See {@link #getJavaThreadId()} for the ID that is returned by
* {@code java.lang.Thread.getId()}
*
* @return a unique ID for the thread
*/
public long getId() {
return uniqueId;
}
}
| {
"pile_set_name": "Github"
} |
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Author: [email protected] (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
//
// DynamicMessage is implemented by constructing a data structure which
// has roughly the same memory layout as a generated message would have.
// Then, we use Reflection to implement our reflection interface. All
// the other operations we need to implement (e.g. parsing, copying,
// etc.) are already implemented in terms of Reflection, so the rest is
// easy.
//
// The up side of this strategy is that it's very efficient. We don't
// need to use hash_maps or generic representations of fields. The
// down side is that this is a low-level memory management hack which
// can be tricky to get right.
//
// As mentioned in the header, we only expose a DynamicMessageFactory
// publicly, not the DynamicMessage class itself. This is because
// GenericMessageReflection wants to have a pointer to a "default"
// copy of the class, with all fields initialized to their default
// values. We only want to construct one of these per message type,
// so DynamicMessageFactory stores a cache of default messages for
// each type it sees (each unique Descriptor pointer). The code
// refers to the "default" copy of the class as the "prototype".
//
// Note on memory allocation: This module often calls "operator new()"
// to allocate untyped memory, rather than calling something like
// "new uint8[]". This is because "operator new()" means "Give me some
// space which I can use as I please." while "new uint8[]" means "Give
// me an array of 8-bit integers.". In practice, the later may return
// a pointer that is not aligned correctly for general use. I believe
// Item 8 of "More Effective C++" discusses this in more detail, though
// I don't have the book on me right now so I'm not sure.
#include <algorithm>
#include <memory>
#include <unordered_map>
#include <google/protobuf/stubs/hash.h>
#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/dynamic_message.h>
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/arenastring.h>
#include <google/protobuf/extension_set.h>
#include <google/protobuf/map_field.h>
#include <google/protobuf/map_field_inl.h>
#include <google/protobuf/map_type_handler.h>
#include <google/protobuf/reflection_ops.h>
#include <google/protobuf/repeated_field.h>
#include <google/protobuf/wire_format.h>
namespace google {
namespace protobuf {
using internal::DynamicMapField;
using internal::ExtensionSet;
using internal::InternalMetadataWithArena;
using internal::MapField;
using internal::ArenaStringPtr;
// ===================================================================
// Some helper tables and functions...
namespace {
bool IsMapFieldInApi(const FieldDescriptor* field) { return field->is_map(); }
// Compute the byte size of the in-memory representation of the field.
int FieldSpaceUsed(const FieldDescriptor* field) {
typedef FieldDescriptor FD; // avoid line wrapping
if (field->label() == FD::LABEL_REPEATED) {
switch (field->cpp_type()) {
case FD::CPPTYPE_INT32:
return sizeof(RepeatedField<int32>);
case FD::CPPTYPE_INT64:
return sizeof(RepeatedField<int64>);
case FD::CPPTYPE_UINT32:
return sizeof(RepeatedField<uint32>);
case FD::CPPTYPE_UINT64:
return sizeof(RepeatedField<uint64>);
case FD::CPPTYPE_DOUBLE:
return sizeof(RepeatedField<double>);
case FD::CPPTYPE_FLOAT:
return sizeof(RepeatedField<float>);
case FD::CPPTYPE_BOOL:
return sizeof(RepeatedField<bool>);
case FD::CPPTYPE_ENUM:
return sizeof(RepeatedField<int>);
case FD::CPPTYPE_MESSAGE:
if (IsMapFieldInApi(field)) {
return sizeof(DynamicMapField);
} else {
return sizeof(RepeatedPtrField<Message>);
}
case FD::CPPTYPE_STRING:
switch (field->options().ctype()) {
default: // TODO(kenton): Support other string reps.
case FieldOptions::STRING:
return sizeof(RepeatedPtrField<std::string>);
}
break;
}
} else {
switch (field->cpp_type()) {
case FD::CPPTYPE_INT32:
return sizeof(int32);
case FD::CPPTYPE_INT64:
return sizeof(int64);
case FD::CPPTYPE_UINT32:
return sizeof(uint32);
case FD::CPPTYPE_UINT64:
return sizeof(uint64);
case FD::CPPTYPE_DOUBLE:
return sizeof(double);
case FD::CPPTYPE_FLOAT:
return sizeof(float);
case FD::CPPTYPE_BOOL:
return sizeof(bool);
case FD::CPPTYPE_ENUM:
return sizeof(int);
case FD::CPPTYPE_MESSAGE:
return sizeof(Message*);
case FD::CPPTYPE_STRING:
switch (field->options().ctype()) {
default: // TODO(kenton): Support other string reps.
case FieldOptions::STRING:
return sizeof(ArenaStringPtr);
}
break;
}
}
GOOGLE_LOG(DFATAL) << "Can't get here.";
return 0;
}
// Compute the byte size of in-memory representation of the oneof fields
// in default oneof instance.
int OneofFieldSpaceUsed(const FieldDescriptor* field) {
typedef FieldDescriptor FD; // avoid line wrapping
switch (field->cpp_type()) {
case FD::CPPTYPE_INT32:
return sizeof(int32);
case FD::CPPTYPE_INT64:
return sizeof(int64);
case FD::CPPTYPE_UINT32:
return sizeof(uint32);
case FD::CPPTYPE_UINT64:
return sizeof(uint64);
case FD::CPPTYPE_DOUBLE:
return sizeof(double);
case FD::CPPTYPE_FLOAT:
return sizeof(float);
case FD::CPPTYPE_BOOL:
return sizeof(bool);
case FD::CPPTYPE_ENUM:
return sizeof(int);
case FD::CPPTYPE_MESSAGE:
return sizeof(Message*);
case FD::CPPTYPE_STRING:
switch (field->options().ctype()) {
default:
case FieldOptions::STRING:
return sizeof(ArenaStringPtr);
}
break;
}
GOOGLE_LOG(DFATAL) << "Can't get here.";
return 0;
}
inline int DivideRoundingUp(int i, int j) { return (i + (j - 1)) / j; }
static const int kSafeAlignment = sizeof(uint64);
static const int kMaxOneofUnionSize = sizeof(uint64);
inline int AlignTo(int offset, int alignment) {
return DivideRoundingUp(offset, alignment) * alignment;
}
// Rounds the given byte offset up to the next offset aligned such that any
// type may be stored at it.
inline int AlignOffset(int offset) { return AlignTo(offset, kSafeAlignment); }
#define bitsizeof(T) (sizeof(T) * 8)
} // namespace
// ===================================================================
class DynamicMessage : public Message {
public:
struct TypeInfo {
int size;
int has_bits_offset;
int oneof_case_offset;
int internal_metadata_offset;
int extensions_offset;
// Not owned by the TypeInfo.
DynamicMessageFactory* factory; // The factory that created this object.
const DescriptorPool* pool; // The factory's DescriptorPool.
const Descriptor* type; // Type of this DynamicMessage.
// Warning: The order in which the following pointers are defined is
// important (the prototype must be deleted *before* the offsets).
std::unique_ptr<uint32[]> offsets;
std::unique_ptr<uint32[]> has_bits_indices;
std::unique_ptr<const Reflection> reflection;
// Don't use a unique_ptr to hold the prototype: the destructor for
// DynamicMessage needs to know whether it is the prototype, and does so by
// looking back at this field. This would assume details about the
// implementation of unique_ptr.
const DynamicMessage* prototype;
int weak_field_map_offset; // The offset for the weak_field_map;
TypeInfo() : prototype(NULL) {}
~TypeInfo() { delete prototype; }
};
DynamicMessage(const TypeInfo* type_info);
// This should only be used by GetPrototypeNoLock() to avoid dead lock.
DynamicMessage(TypeInfo* type_info, bool lock_factory);
~DynamicMessage();
// Called on the prototype after construction to initialize message fields.
void CrossLinkPrototypes();
// implements Message ----------------------------------------------
Message* New() const override;
Message* New(Arena* arena) const override;
Arena* GetArena() const override { return arena_; }
int GetCachedSize() const override;
void SetCachedSize(int size) const override;
Metadata GetMetadata() const override;
// We actually allocate more memory than sizeof(*this) when this
// class's memory is allocated via the global operator new. Thus, we need to
// manually call the global operator delete. Calling the destructor is taken
// care of for us. This makes DynamicMessage compatible with -fsized-delete.
// It doesn't work for MSVC though.
#ifndef _MSC_VER
static void operator delete(void* ptr) { ::operator delete(ptr); }
#endif // !_MSC_VER
private:
DynamicMessage(const TypeInfo* type_info, Arena* arena);
void SharedCtor(bool lock_factory);
inline bool is_prototype() const {
return type_info_->prototype == this ||
// If type_info_->prototype is NULL, then we must be constructing
// the prototype now, which means we must be the prototype.
type_info_->prototype == NULL;
}
inline void* OffsetToPointer(int offset) {
return reinterpret_cast<uint8*>(this) + offset;
}
inline const void* OffsetToPointer(int offset) const {
return reinterpret_cast<const uint8*>(this) + offset;
}
const TypeInfo* type_info_;
Arena* const arena_;
mutable std::atomic<int> cached_byte_size_;
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(DynamicMessage);
};
DynamicMessage::DynamicMessage(const TypeInfo* type_info)
: type_info_(type_info), arena_(NULL), cached_byte_size_(0) {
SharedCtor(true);
}
DynamicMessage::DynamicMessage(const TypeInfo* type_info, Arena* arena)
: type_info_(type_info), arena_(arena), cached_byte_size_(0) {
SharedCtor(true);
}
DynamicMessage::DynamicMessage(TypeInfo* type_info, bool lock_factory)
: type_info_(type_info), arena_(NULL), cached_byte_size_(0) {
// The prototype in type_info has to be set before creating the prototype
// instance on memory. e.g., message Foo { map<int32, Foo> a = 1; }. When
// creating prototype for Foo, prototype of the map entry will also be
// created, which needs the address of the prototype of Foo (the value in
// map). To break the cyclic dependency, we have to assign the address of
// prototype into type_info first.
type_info->prototype = this;
SharedCtor(lock_factory);
}
void DynamicMessage::SharedCtor(bool lock_factory) {
// We need to call constructors for various fields manually and set
// default values where appropriate. We use placement new to call
// constructors. If you haven't heard of placement new, I suggest Googling
// it now. We use placement new even for primitive types that don't have
// constructors for consistency. (In theory, placement new should be used
// any time you are trying to convert untyped memory to typed memory, though
// in practice that's not strictly necessary for types that don't have a
// constructor.)
const Descriptor* descriptor = type_info_->type;
// Initialize oneof cases.
for (int i = 0; i < descriptor->oneof_decl_count(); ++i) {
new (OffsetToPointer(type_info_->oneof_case_offset + sizeof(uint32) * i))
uint32(0);
}
new (OffsetToPointer(type_info_->internal_metadata_offset))
InternalMetadataWithArena(arena_);
if (type_info_->extensions_offset != -1) {
new (OffsetToPointer(type_info_->extensions_offset)) ExtensionSet(arena_);
}
for (int i = 0; i < descriptor->field_count(); i++) {
const FieldDescriptor* field = descriptor->field(i);
void* field_ptr = OffsetToPointer(type_info_->offsets[i]);
if (field->containing_oneof()) {
continue;
}
switch (field->cpp_type()) {
#define HANDLE_TYPE(CPPTYPE, TYPE) \
case FieldDescriptor::CPPTYPE_##CPPTYPE: \
if (!field->is_repeated()) { \
new (field_ptr) TYPE(field->default_value_##TYPE()); \
} else { \
new (field_ptr) RepeatedField<TYPE>(arena_); \
} \
break;
HANDLE_TYPE(INT32, int32);
HANDLE_TYPE(INT64, int64);
HANDLE_TYPE(UINT32, uint32);
HANDLE_TYPE(UINT64, uint64);
HANDLE_TYPE(DOUBLE, double);
HANDLE_TYPE(FLOAT, float);
HANDLE_TYPE(BOOL, bool);
#undef HANDLE_TYPE
case FieldDescriptor::CPPTYPE_ENUM:
if (!field->is_repeated()) {
new (field_ptr) int(field->default_value_enum()->number());
} else {
new (field_ptr) RepeatedField<int>(arena_);
}
break;
case FieldDescriptor::CPPTYPE_STRING:
switch (field->options().ctype()) {
default: // TODO(kenton): Support other string reps.
case FieldOptions::STRING:
if (!field->is_repeated()) {
const std::string* default_value;
if (is_prototype()) {
default_value = &field->default_value_string();
} else {
default_value = &(reinterpret_cast<const ArenaStringPtr*>(
type_info_->prototype->OffsetToPointer(
type_info_->offsets[i]))
->Get());
}
ArenaStringPtr* asp = new (field_ptr) ArenaStringPtr();
asp->UnsafeSetDefault(default_value);
} else {
new (field_ptr) RepeatedPtrField<std::string>(arena_);
}
break;
}
break;
case FieldDescriptor::CPPTYPE_MESSAGE: {
if (!field->is_repeated()) {
new (field_ptr) Message*(NULL);
} else {
if (IsMapFieldInApi(field)) {
// We need to lock in most cases to avoid data racing. Only not lock
// when the constructor is called inside GetPrototype(), in which
// case we have already locked the factory.
if (lock_factory) {
if (arena_ != NULL) {
new (field_ptr) DynamicMapField(
type_info_->factory->GetPrototype(field->message_type()),
arena_);
} else {
new (field_ptr) DynamicMapField(
type_info_->factory->GetPrototype(field->message_type()));
}
} else {
if (arena_ != NULL) {
new (field_ptr)
DynamicMapField(type_info_->factory->GetPrototypeNoLock(
field->message_type()),
arena_);
} else {
new (field_ptr)
DynamicMapField(type_info_->factory->GetPrototypeNoLock(
field->message_type()));
}
}
} else {
new (field_ptr) RepeatedPtrField<Message>(arena_);
}
}
break;
}
}
}
}
DynamicMessage::~DynamicMessage() {
const Descriptor* descriptor = type_info_->type;
reinterpret_cast<InternalMetadataWithArena*>(
OffsetToPointer(type_info_->internal_metadata_offset))
->~InternalMetadataWithArena();
if (type_info_->extensions_offset != -1) {
reinterpret_cast<ExtensionSet*>(
OffsetToPointer(type_info_->extensions_offset))
->~ExtensionSet();
}
// We need to manually run the destructors for repeated fields and strings,
// just as we ran their constructors in the DynamicMessage constructor.
// We also need to manually delete oneof fields if it is set and is string
// or message.
// Additionally, if any singular embedded messages have been allocated, we
// need to delete them, UNLESS we are the prototype message of this type,
// in which case any embedded messages are other prototypes and shouldn't
// be touched.
for (int i = 0; i < descriptor->field_count(); i++) {
const FieldDescriptor* field = descriptor->field(i);
if (field->containing_oneof()) {
void* field_ptr =
OffsetToPointer(type_info_->oneof_case_offset +
sizeof(uint32) * field->containing_oneof()->index());
if (*(reinterpret_cast<const uint32*>(field_ptr)) == field->number()) {
field_ptr = OffsetToPointer(
type_info_->offsets[descriptor->field_count() +
field->containing_oneof()->index()]);
if (field->cpp_type() == FieldDescriptor::CPPTYPE_STRING) {
switch (field->options().ctype()) {
default:
case FieldOptions::STRING: {
const std::string* default_value =
&(reinterpret_cast<const ArenaStringPtr*>(
reinterpret_cast<const uint8*>(type_info_->prototype) +
type_info_->offsets[i])
->Get());
reinterpret_cast<ArenaStringPtr*>(field_ptr)->Destroy(
default_value, NULL);
break;
}
}
} else if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
delete *reinterpret_cast<Message**>(field_ptr);
}
}
continue;
}
void* field_ptr = OffsetToPointer(type_info_->offsets[i]);
if (field->is_repeated()) {
switch (field->cpp_type()) {
#define HANDLE_TYPE(UPPERCASE, LOWERCASE) \
case FieldDescriptor::CPPTYPE_##UPPERCASE: \
reinterpret_cast<RepeatedField<LOWERCASE>*>(field_ptr) \
->~RepeatedField<LOWERCASE>(); \
break
HANDLE_TYPE(INT32, int32);
HANDLE_TYPE(INT64, int64);
HANDLE_TYPE(UINT32, uint32);
HANDLE_TYPE(UINT64, uint64);
HANDLE_TYPE(DOUBLE, double);
HANDLE_TYPE(FLOAT, float);
HANDLE_TYPE(BOOL, bool);
HANDLE_TYPE(ENUM, int);
#undef HANDLE_TYPE
case FieldDescriptor::CPPTYPE_STRING:
switch (field->options().ctype()) {
default: // TODO(kenton): Support other string reps.
case FieldOptions::STRING:
reinterpret_cast<RepeatedPtrField<std::string>*>(field_ptr)
->~RepeatedPtrField<std::string>();
break;
}
break;
case FieldDescriptor::CPPTYPE_MESSAGE:
if (IsMapFieldInApi(field)) {
reinterpret_cast<DynamicMapField*>(field_ptr)->~DynamicMapField();
} else {
reinterpret_cast<RepeatedPtrField<Message>*>(field_ptr)
->~RepeatedPtrField<Message>();
}
break;
}
} else if (field->cpp_type() == FieldDescriptor::CPPTYPE_STRING) {
switch (field->options().ctype()) {
default: // TODO(kenton): Support other string reps.
case FieldOptions::STRING: {
const std::string* default_value =
&(reinterpret_cast<const ArenaStringPtr*>(
type_info_->prototype->OffsetToPointer(
type_info_->offsets[i]))
->Get());
reinterpret_cast<ArenaStringPtr*>(field_ptr)->Destroy(default_value,
NULL);
break;
}
}
} else if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) {
if (!is_prototype()) {
Message* message = *reinterpret_cast<Message**>(field_ptr);
if (message != NULL) {
delete message;
}
}
}
}
}
void DynamicMessage::CrossLinkPrototypes() {
// This should only be called on the prototype message.
GOOGLE_CHECK(is_prototype());
DynamicMessageFactory* factory = type_info_->factory;
const Descriptor* descriptor = type_info_->type;
// Cross-link default messages.
for (int i = 0; i < descriptor->field_count(); i++) {
const FieldDescriptor* field = descriptor->field(i);
void* field_ptr = OffsetToPointer(type_info_->offsets[i]);
if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE &&
!field->is_repeated()) {
// For fields with message types, we need to cross-link with the
// prototype for the field's type.
// For singular fields, the field is just a pointer which should
// point to the prototype.
*reinterpret_cast<const Message**>(field_ptr) =
factory->GetPrototypeNoLock(field->message_type());
}
}
}
Message* DynamicMessage::New() const { return New(NULL); }
Message* DynamicMessage::New(Arena* arena) const {
if (arena != NULL) {
void* new_base = Arena::CreateArray<char>(arena, type_info_->size);
memset(new_base, 0, type_info_->size);
return new (new_base) DynamicMessage(type_info_, arena);
} else {
void* new_base = operator new(type_info_->size);
memset(new_base, 0, type_info_->size);
return new (new_base) DynamicMessage(type_info_);
}
}
int DynamicMessage::GetCachedSize() const {
return cached_byte_size_.load(std::memory_order_relaxed);
}
void DynamicMessage::SetCachedSize(int size) const {
cached_byte_size_.store(size, std::memory_order_relaxed);
}
Metadata DynamicMessage::GetMetadata() const {
Metadata metadata;
metadata.descriptor = type_info_->type;
metadata.reflection = type_info_->reflection.get();
return metadata;
}
// ===================================================================
struct DynamicMessageFactory::PrototypeMap {
typedef std::unordered_map<const Descriptor*, const DynamicMessage::TypeInfo*>
Map;
Map map_;
};
DynamicMessageFactory::DynamicMessageFactory()
: pool_(NULL),
delegate_to_generated_factory_(false),
prototypes_(new PrototypeMap) {}
DynamicMessageFactory::DynamicMessageFactory(const DescriptorPool* pool)
: pool_(pool),
delegate_to_generated_factory_(false),
prototypes_(new PrototypeMap) {}
DynamicMessageFactory::~DynamicMessageFactory() {
for (PrototypeMap::Map::iterator iter = prototypes_->map_.begin();
iter != prototypes_->map_.end(); ++iter) {
DeleteDefaultOneofInstance(iter->second->type, iter->second->offsets.get(),
iter->second->prototype);
delete iter->second;
}
}
const Message* DynamicMessageFactory::GetPrototype(const Descriptor* type) {
MutexLock lock(&prototypes_mutex_);
return GetPrototypeNoLock(type);
}
const Message* DynamicMessageFactory::GetPrototypeNoLock(
const Descriptor* type) {
if (delegate_to_generated_factory_ &&
type->file()->pool() == DescriptorPool::generated_pool()) {
return MessageFactory::generated_factory()->GetPrototype(type);
}
const DynamicMessage::TypeInfo** target = &prototypes_->map_[type];
if (*target != NULL) {
// Already exists.
return (*target)->prototype;
}
DynamicMessage::TypeInfo* type_info = new DynamicMessage::TypeInfo;
*target = type_info;
type_info->type = type;
type_info->pool = (pool_ == NULL) ? type->file()->pool() : pool_;
type_info->factory = this;
// We need to construct all the structures passed to Reflection's constructor.
// This includes:
// - A block of memory that contains space for all the message's fields.
// - An array of integers indicating the byte offset of each field within
// this block.
// - A big bitfield containing a bit for each field indicating whether
// or not that field is set.
// Compute size and offsets.
uint32* offsets = new uint32[type->field_count() + type->oneof_decl_count()];
type_info->offsets.reset(offsets);
// Decide all field offsets by packing in order.
// We place the DynamicMessage object itself at the beginning of the allocated
// space.
int size = sizeof(DynamicMessage);
size = AlignOffset(size);
// Next the has_bits, which is an array of uint32s.
if (type->file()->syntax() == FileDescriptor::SYNTAX_PROTO3) {
type_info->has_bits_offset = -1;
} else {
type_info->has_bits_offset = size;
int has_bits_array_size =
DivideRoundingUp(type->field_count(), bitsizeof(uint32));
size += has_bits_array_size * sizeof(uint32);
size = AlignOffset(size);
uint32* has_bits_indices = new uint32[type->field_count()];
for (int i = 0; i < type->field_count(); i++) {
has_bits_indices[i] = i;
}
type_info->has_bits_indices.reset(has_bits_indices);
}
// The oneof_case, if any. It is an array of uint32s.
if (type->oneof_decl_count() > 0) {
type_info->oneof_case_offset = size;
size += type->oneof_decl_count() * sizeof(uint32);
size = AlignOffset(size);
}
// The ExtensionSet, if any.
if (type->extension_range_count() > 0) {
type_info->extensions_offset = size;
size += sizeof(ExtensionSet);
size = AlignOffset(size);
} else {
// No extensions.
type_info->extensions_offset = -1;
}
// All the fields.
//
// TODO(b/31226269): Optimize the order of fields to minimize padding.
int num_weak_fields = 0;
for (int i = 0; i < type->field_count(); i++) {
// Make sure field is aligned to avoid bus errors.
// Oneof fields do not use any space.
if (!type->field(i)->containing_oneof()) {
int field_size = FieldSpaceUsed(type->field(i));
size = AlignTo(size, std::min(kSafeAlignment, field_size));
offsets[i] = size;
size += field_size;
}
}
// The oneofs.
for (int i = 0; i < type->oneof_decl_count(); i++) {
size = AlignTo(size, kSafeAlignment);
offsets[type->field_count() + i] = size;
size += kMaxOneofUnionSize;
}
// Add the InternalMetadataWithArena to the end.
size = AlignOffset(size);
type_info->internal_metadata_offset = size;
size += sizeof(InternalMetadataWithArena);
type_info->weak_field_map_offset = -1;
// Align the final size to make sure no clever allocators think that
// alignment is not necessary.
type_info->size = size;
// Construct the reflection object.
if (type->oneof_decl_count() > 0) {
// Compute the size of default oneof instance and offsets of default
// oneof fields.
for (int i = 0; i < type->oneof_decl_count(); i++) {
for (int j = 0; j < type->oneof_decl(i)->field_count(); j++) {
const FieldDescriptor* field = type->oneof_decl(i)->field(j);
int field_size = OneofFieldSpaceUsed(field);
size = AlignTo(size, std::min(kSafeAlignment, field_size));
offsets[field->index()] = size;
size += field_size;
}
}
}
size = AlignOffset(size);
// Allocate the prototype + oneof fields.
void* base = operator new(size);
memset(base, 0, size);
// We have already locked the factory so we should not lock in the constructor
// of dynamic message to avoid dead lock.
DynamicMessage* prototype = new (base) DynamicMessage(type_info, false);
if (type->oneof_decl_count() > 0 || num_weak_fields > 0) {
// Construct default oneof instance.
ConstructDefaultOneofInstance(type_info->type, type_info->offsets.get(),
prototype);
}
internal::ReflectionSchema schema = {type_info->prototype,
type_info->offsets.get(),
type_info->has_bits_indices.get(),
type_info->has_bits_offset,
type_info->internal_metadata_offset,
type_info->extensions_offset,
type_info->oneof_case_offset,
type_info->size,
type_info->weak_field_map_offset};
type_info->reflection.reset(
new Reflection(type_info->type, schema, type_info->pool, this));
// Cross link prototypes.
prototype->CrossLinkPrototypes();
return prototype;
}
void DynamicMessageFactory::ConstructDefaultOneofInstance(
const Descriptor* type, const uint32 offsets[],
void* default_oneof_or_weak_instance) {
for (int i = 0; i < type->oneof_decl_count(); i++) {
for (int j = 0; j < type->oneof_decl(i)->field_count(); j++) {
const FieldDescriptor* field = type->oneof_decl(i)->field(j);
void* field_ptr =
reinterpret_cast<uint8*>(default_oneof_or_weak_instance) +
offsets[field->index()];
switch (field->cpp_type()) {
#define HANDLE_TYPE(CPPTYPE, TYPE) \
case FieldDescriptor::CPPTYPE_##CPPTYPE: \
new (field_ptr) TYPE(field->default_value_##TYPE()); \
break;
HANDLE_TYPE(INT32, int32);
HANDLE_TYPE(INT64, int64);
HANDLE_TYPE(UINT32, uint32);
HANDLE_TYPE(UINT64, uint64);
HANDLE_TYPE(DOUBLE, double);
HANDLE_TYPE(FLOAT, float);
HANDLE_TYPE(BOOL, bool);
#undef HANDLE_TYPE
case FieldDescriptor::CPPTYPE_ENUM:
new (field_ptr) int(field->default_value_enum()->number());
break;
case FieldDescriptor::CPPTYPE_STRING:
switch (field->options().ctype()) {
default:
case FieldOptions::STRING:
ArenaStringPtr* asp = new (field_ptr) ArenaStringPtr();
asp->UnsafeSetDefault(&field->default_value_string());
break;
}
break;
case FieldDescriptor::CPPTYPE_MESSAGE: {
new (field_ptr) Message*(NULL);
break;
}
}
}
}
}
void DynamicMessageFactory::DeleteDefaultOneofInstance(
const Descriptor* type, const uint32 offsets[],
const void* default_oneof_instance) {
for (int i = 0; i < type->oneof_decl_count(); i++) {
for (int j = 0; j < type->oneof_decl(i)->field_count(); j++) {
const FieldDescriptor* field = type->oneof_decl(i)->field(j);
if (field->cpp_type() == FieldDescriptor::CPPTYPE_STRING) {
switch (field->options().ctype()) {
default:
case FieldOptions::STRING:
break;
}
}
}
}
}
} // namespace protobuf
} // namespace google
| {
"pile_set_name": "Github"
} |
{
"@type" : "g:P",
"@value" : {
"predicate" : "without",
"value" : [ {
"@type" : "g:Int32",
"@value" : 1
}, {
"@type" : "g:Int32",
"@value" : 2
} ]
}
} | {
"pile_set_name": "Github"
} |
#!/usr/bin/perl
## ====================================================================
##
## Copyright (c) 1996-2000 Carnegie Mellon University. All rights
## reserved.
##
## Redistribution and use in source and binary forms, with or without
## modification, are permitted provided that the following conditions
## are met:
##
## 1. Redistributions of source code must retain the above copyright
## notice, this list of conditions and the following disclaimer.
##
## 2. Redistributions in binary form must reproduce the above copyright
## notice, this list of conditions and the following disclaimer in
## the documentation and/or other materials provided with the
## distribution.
##
## This work was supported in part by funding from the Defense Advanced
## Research Projects Agency and the National Science Foundation of the
## United States of America, and the CMU Sphinx Speech Consortium.
##
## THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND
## ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
## THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
## PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY
## NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
##
## ====================================================================
##
## Author: Ricky Houghton
##
use strict;
use File::Copy;
use File::Basename;
use File::Spec::Functions;
use File::Path;
use lib catdir(dirname($0), updir(), 'lib');
use SphinxTrain::Config;
use SphinxTrain::Util;
#*****************************************************************************
# Baum-welch is done in several parts. This script gathers the results of
# all those parts and then computes the discrete probability distributions
# associated with all the states. It also computes the transition matrices.
#****************************************************************************
$| = 1; # Turn on autoflushing
die "USAGE: $0 <iter> [<ngau>]" if @ARGV < 1;
my ($iter, $n_gau) = @ARGV;
$n_gau = 1 unless defined($n_gau);
use vars qw($MLLT_FILE $MODEL_TYPE);
$MLLT_FILE = catfile($ST::CFG_MODEL_DIR, "${ST::CFG_EXPTNAME}.mllt");
$MODEL_TYPE = 'falign_ci';
my $modelname="${ST::CFG_EXPTNAME}.falign_ci_${ST::CFG_DIRLABEL}";
my $processpart="10.falign_ci_hmm";
opendir(ACCUMDIR, $ST::CFG_BWACCUM_DIR)
or die "Could not open $ST::CFG_BWACCUM_DIR: $!";
my @bwaccumdirs = map catdir($ST::CFG_BWACCUM_DIR, $_),
grep /^\Q${ST::CFG_EXPTNAME}_buff_/, readdir(ACCUMDIR);
closedir(ACCUMDIR);
my $hmmdir = "${ST::CFG_BASE_DIR}/model_parameters/$modelname";
mkdir ($hmmdir,0777);
my $means = "$hmmdir/means";
my $variances = "$hmmdir/variances";
my $mixture_weights = "$hmmdir/mixture_weights";
my $transition_matrices = "$hmmdir/transition_matrices";
if ($iter == 1) {
my $mdeffile = catfile($ST::CFG_BASE_DIR, 'model_architecture',
"${ST::CFG_EXPTNAME}.falign_ci.mdef");
# Copy the mdef and fillerdict files into the new HMM directory
copy($mdeffile, catfile($hmmdir, 'mdef'))
or die "Failed to copy $mdeffile to $hmmdir/mdef: $!";
copy($ST::CFG_FILLERDICT, catfile($hmmdir, 'noisedict'))
or die "Failed to copy $ST::CFG_FILLERDICT to $hmmdir/noisedict: $!";
# Create the feat.params file in the new HMM directory
SubstParams($ST::CFG_FEATPARAMS, catfile($hmmdir, 'feat.params'));
# Copy a feature space transform if any
if (-r $MLLT_FILE) {
copy($MLLT_FILE, catfile($hmmdir, 'feature_transform'));
}
}
my $logdir = "${ST::CFG_LOG_DIR}/$processpart";
mkdir ($logdir,0777);
my $logfile = "$logdir/${ST::CFG_EXPTNAME}.${n_gau}.${iter}.norm.log";
Log("Normalization for iteration: $iter", 'result');
my $return_value = RunTool
('norm', $logfile, 0,
-accumdir => @bwaccumdirs,
-mixwfn => $mixture_weights,
-tmatfn => $transition_matrices,
-meanfn => $means,
-varfn => $variances,
-fullvar => $ST::CFG_FULLVAR
);
if ($return_value) {
LogError ("Failed to start norm");
}
exit ($return_value);
| {
"pile_set_name": "Github"
} |
.class public Lcom/tencent/mm/plugin/sns/ui/ClassifyHeader;
.super Landroid/widget/LinearLayout;
.source "SourceFile"
# instance fields
.field private cuI:Landroid/widget/TextView;
.field private fiz:Landroid/widget/ImageView;
.field private mContext:Landroid/content/Context;
# direct methods
.method public constructor <init>(Landroid/content/Context;Landroid/util/AttributeSet;)V
.locals 0
.prologue
.line 28
invoke-direct {p0, p1, p2}, Landroid/widget/LinearLayout;-><init>(Landroid/content/Context;Landroid/util/AttributeSet;)V
.line 29
invoke-direct {p0, p1}, Lcom/tencent/mm/plugin/sns/ui/ClassifyHeader;->init(Landroid/content/Context;)V
.line 30
return-void
.end method
.method public constructor <init>(Landroid/content/Context;Landroid/util/AttributeSet;I)V
.locals 0
.annotation build Landroid/annotation/TargetApi;
value = 0xb
.end annotation
.prologue
.line 23
invoke-direct {p0, p1, p2, p3}, Landroid/widget/LinearLayout;-><init>(Landroid/content/Context;Landroid/util/AttributeSet;I)V
.line 24
invoke-direct {p0, p1}, Lcom/tencent/mm/plugin/sns/ui/ClassifyHeader;->init(Landroid/content/Context;)V
.line 25
return-void
.end method
.method private init(Landroid/content/Context;)V
.locals 2
.prologue
.line 38
iput-object p1, p0, Lcom/tencent/mm/plugin/sns/ui/ClassifyHeader;->mContext:Landroid/content/Context;
.line 39
iget-object v0, p0, Lcom/tencent/mm/plugin/sns/ui/ClassifyHeader;->mContext:Landroid/content/Context;
const v1, 0x7f030136
invoke-static {v0, v1, p0}, Landroid/view/View;->inflate(Landroid/content/Context;ILandroid/view/ViewGroup;)Landroid/view/View;
move-result-object v1
.line 40
const v0, 0x7f100497
invoke-virtual {v1, v0}, Landroid/view/View;->findViewById(I)Landroid/view/View;
move-result-object v0
check-cast v0, Landroid/widget/ImageView;
iput-object v0, p0, Lcom/tencent/mm/plugin/sns/ui/ClassifyHeader;->fiz:Landroid/widget/ImageView;
.line 41
const v0, 0x7f100498
invoke-virtual {v1, v0}, Landroid/view/View;->findViewById(I)Landroid/view/View;
move-result-object v0
check-cast v0, Landroid/widget/TextView;
iput-object v0, p0, Lcom/tencent/mm/plugin/sns/ui/ClassifyHeader;->cuI:Landroid/widget/TextView;
.line 42
return-void
.end method
| {
"pile_set_name": "Github"
} |
// Copyright (c) 2014 Arista Networks, Inc. All rights reserved.
// Arista Networks, Inc. Confidential and Proprietary.
#include <cassert>
#include "eos/subintf.h"
#include "impl.h"
namespace eos {
class subintf_mgr_impl : public subintf_mgr {
public:
subintf_mgr_impl() {
}
subintf_iter_t subintf_iter() const {
subintf_iter_t * nop = 0;
return *nop; // TODO: No op impl.
}
bool exists(intf_id_t) const {
return false;
}
vlan_id_t vlan_tag(intf_id_t) const {
return 0; // TODO: No-op impl.
}
void vlan_tag_is(intf_id_t, vlan_id_t) {
// TODO: No-op impl.
}
intf_id_t parent_intf(intf_id_t) const {
return intf_id_t(); // TODO: No-op impl.
}
void subintf_is(intf_id_t) {
// TODO: No-op impl.
}
void subintf_is(intf_id_t, vlan_id_t) {
// TODO: No-op impl.
}
void subintf_del(intf_id_t) {
return; // TODO: No-op impl.
}
subintf_t subintf(intf_id_t) const {
subintf_t * nop = 0;
return *nop; // TODO: No op impl.
}
};
DEFINE_STUB_MGR_CTOR(subintf_mgr)
}
| {
"pile_set_name": "Github"
} |
<?php declare(strict_types=1);
namespace Shopware\Core\Content\Test\Product;
use Doctrine\DBAL\Connection;
use PHPUnit\Framework\TestCase;
use Shopware\Core\Content\Product\Aggregate\ProductVisibility\ProductVisibilityDefinition;
use Shopware\Core\Defaults;
use Shopware\Core\Framework\Context;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
use Shopware\Core\Framework\Test\TestCaseBase\SalesChannelFunctionalTestBehaviour;
use Shopware\Core\Framework\Uuid\Uuid;
use Shopware\Core\PlatformRequest;
class ProductControllerTest extends TestCase
{
use SalesChannelFunctionalTestBehaviour;
/**
* @var EntityRepositoryInterface
*/
private $productRepository;
/**
* @var Connection
*/
private $connection;
protected function setUp(): void
{
$this->productRepository = $this->getContainer()->get('product.repository');
$this->connection = $this->getContainer()->get(Connection::class);
}
public function testProductList(): void
{
$manufacturerId = Uuid::randomHex();
$taxId = Uuid::randomHex();
$client = $this->getSalesChannelBrowser();
$salesChannelId = $this->salesChannelIds[count($this->salesChannelIds) - 1];
$this->productRepository->create([
[
'id' => Uuid::randomHex(),
'productNumber' => Uuid::randomHex(),
'stock' => 1,
'name' => 'Test',
'price' => [['currencyId' => Defaults::CURRENCY, 'gross' => 10, 'net' => 9, 'linked' => false]],
'manufacturer' => ['id' => $manufacturerId, 'name' => 'test'],
'tax' => ['id' => $taxId, 'taxRate' => 17, 'name' => 'with id'],
'visibilities' => [
['salesChannelId' => $salesChannelId, 'visibility' => ProductVisibilityDefinition::VISIBILITY_ALL],
],
],
], Context::createDefaultContext());
$client->request('GET', '/sales-channel-api/v' . PlatformRequest::API_VERSION . '/product');
static::assertSame(200, $client->getResponse()->getStatusCode(), $client->getResponse()->getContent());
$content = json_decode($client->getResponse()->getContent(), true);
static::assertNotEmpty($content);
static::assertArrayHasKey('total', $content);
static::assertArrayHasKey('data', $content);
static::assertGreaterThan(0, $content['total']);
static::assertNotEmpty($content['data']);
foreach ($content['data'] as $product) {
static::assertArrayHasKey('calculatedListingPrice', $product);
static::assertArrayHasKey('calculatedPrices', $product);
static::assertArrayHasKey('calculatedPrice', $product);
static::assertArrayNotHasKey('price', $product);
static::assertArrayHasKey('name', $product);
static::assertArrayHasKey('id', $product);
}
}
public function testProductDetail(): void
{
$productId = Uuid::randomHex();
$manufacturerId = Uuid::randomHex();
$taxId = Uuid::randomHex();
$client = $this->getSalesChannelBrowser();
$salesChannelId = $this->salesChannelIds[count($this->salesChannelIds) - 1];
$this->productRepository->create([
[
'id' => $productId,
'productNumber' => Uuid::randomHex(),
'stock' => 1,
'name' => 'Test',
'price' => [['currencyId' => Defaults::CURRENCY, 'gross' => 10, 'net' => 9, 'linked' => false]],
'manufacturer' => ['id' => $manufacturerId, 'name' => 'test'],
'tax' => ['id' => $taxId, 'taxRate' => 17, 'name' => 'with id'],
'visibilities' => [
['salesChannelId' => $salesChannelId, 'visibility' => ProductVisibilityDefinition::VISIBILITY_ALL],
],
],
], Context::createDefaultContext());
$client->request('GET', '/sales-channel-api/v' . PlatformRequest::API_VERSION . '/product/' . $productId);
static::assertSame(200, $client->getResponse()->getStatusCode(), $client->getResponse()->getContent());
$content = json_decode($client->getResponse()->getContent(), true);
static::assertEquals($productId, $content['data']['id']);
static::assertEquals(10, $content['data']['calculatedPrice']['totalPrice']);
static::assertEquals('with id', $content['data']['tax']['name']);
static::assertEquals(17, $content['data']['tax']['taxRate']);
}
public function testProductDetailWithInactiveProduct(): void
{
$productId = Uuid::randomHex();
$manufacturerId = Uuid::randomHex();
$taxId = Uuid::randomHex();
$client = $this->getSalesChannelBrowser();
$salesChannelId = $this->salesChannelIds[count($this->salesChannelIds) - 1];
$this->productRepository->create([
[
'id' => $productId,
'productNumber' => Uuid::randomHex(),
'name' => 'Test',
'stock' => 1,
'active' => false,
'price' => [['currencyId' => Defaults::CURRENCY, 'gross' => 10, 'net' => 9, 'linked' => false]],
'manufacturer' => ['id' => $manufacturerId, 'name' => 'test'],
'tax' => ['id' => $taxId, 'taxRate' => 17, 'name' => 'with id'],
'visibilities' => [
['salesChannelId' => $salesChannelId, 'visibility' => ProductVisibilityDefinition::VISIBILITY_ALL],
],
],
], Context::createDefaultContext());
$client->request('GET', '/sales-channel-api/v' . PlatformRequest::API_VERSION . '/product/' . $productId);
static::assertSame(404, $client->getResponse()->getStatusCode(), $client->getResponse()->getContent());
}
}
| {
"pile_set_name": "Github"
} |
/*
tda18271-common.c - driver for the Philips / NXP TDA18271 silicon tuner
Copyright (C) 2007, 2008 Michael Krufky <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "tda18271-priv.h"
static int tda18271_i2c_gate_ctrl(struct dvb_frontend *fe, int enable)
{
struct tda18271_priv *priv = fe->tuner_priv;
enum tda18271_i2c_gate gate;
int ret = 0;
switch (priv->gate) {
case TDA18271_GATE_DIGITAL:
case TDA18271_GATE_ANALOG:
gate = priv->gate;
break;
case TDA18271_GATE_AUTO:
default:
switch (priv->mode) {
case TDA18271_DIGITAL:
gate = TDA18271_GATE_DIGITAL;
break;
case TDA18271_ANALOG:
default:
gate = TDA18271_GATE_ANALOG;
break;
}
}
switch (gate) {
case TDA18271_GATE_ANALOG:
if (fe->ops.analog_ops.i2c_gate_ctrl)
ret = fe->ops.analog_ops.i2c_gate_ctrl(fe, enable);
break;
case TDA18271_GATE_DIGITAL:
if (fe->ops.i2c_gate_ctrl)
ret = fe->ops.i2c_gate_ctrl(fe, enable);
break;
default:
ret = -EINVAL;
break;
}
return ret;
};
/*---------------------------------------------------------------------*/
static void tda18271_dump_regs(struct dvb_frontend *fe, int extended)
{
struct tda18271_priv *priv = fe->tuner_priv;
unsigned char *regs = priv->tda18271_regs;
tda_reg("=== TDA18271 REG DUMP ===\n");
tda_reg("ID_BYTE = 0x%02x\n", 0xff & regs[R_ID]);
tda_reg("THERMO_BYTE = 0x%02x\n", 0xff & regs[R_TM]);
tda_reg("POWER_LEVEL_BYTE = 0x%02x\n", 0xff & regs[R_PL]);
tda_reg("EASY_PROG_BYTE_1 = 0x%02x\n", 0xff & regs[R_EP1]);
tda_reg("EASY_PROG_BYTE_2 = 0x%02x\n", 0xff & regs[R_EP2]);
tda_reg("EASY_PROG_BYTE_3 = 0x%02x\n", 0xff & regs[R_EP3]);
tda_reg("EASY_PROG_BYTE_4 = 0x%02x\n", 0xff & regs[R_EP4]);
tda_reg("EASY_PROG_BYTE_5 = 0x%02x\n", 0xff & regs[R_EP5]);
tda_reg("CAL_POST_DIV_BYTE = 0x%02x\n", 0xff & regs[R_CPD]);
tda_reg("CAL_DIV_BYTE_1 = 0x%02x\n", 0xff & regs[R_CD1]);
tda_reg("CAL_DIV_BYTE_2 = 0x%02x\n", 0xff & regs[R_CD2]);
tda_reg("CAL_DIV_BYTE_3 = 0x%02x\n", 0xff & regs[R_CD3]);
tda_reg("MAIN_POST_DIV_BYTE = 0x%02x\n", 0xff & regs[R_MPD]);
tda_reg("MAIN_DIV_BYTE_1 = 0x%02x\n", 0xff & regs[R_MD1]);
tda_reg("MAIN_DIV_BYTE_2 = 0x%02x\n", 0xff & regs[R_MD2]);
tda_reg("MAIN_DIV_BYTE_3 = 0x%02x\n", 0xff & regs[R_MD3]);
/* only dump extended regs if DBG_ADV is set */
if (!(tda18271_debug & DBG_ADV))
return;
/* W indicates write-only registers.
* Register dump for write-only registers shows last value written. */
tda_reg("EXTENDED_BYTE_1 = 0x%02x\n", 0xff & regs[R_EB1]);
tda_reg("EXTENDED_BYTE_2 = 0x%02x\n", 0xff & regs[R_EB2]);
tda_reg("EXTENDED_BYTE_3 = 0x%02x\n", 0xff & regs[R_EB3]);
tda_reg("EXTENDED_BYTE_4 = 0x%02x\n", 0xff & regs[R_EB4]);
tda_reg("EXTENDED_BYTE_5 = 0x%02x\n", 0xff & regs[R_EB5]);
tda_reg("EXTENDED_BYTE_6 = 0x%02x\n", 0xff & regs[R_EB6]);
tda_reg("EXTENDED_BYTE_7 = 0x%02x\n", 0xff & regs[R_EB7]);
tda_reg("EXTENDED_BYTE_8 = 0x%02x\n", 0xff & regs[R_EB8]);
tda_reg("EXTENDED_BYTE_9 W = 0x%02x\n", 0xff & regs[R_EB9]);
tda_reg("EXTENDED_BYTE_10 = 0x%02x\n", 0xff & regs[R_EB10]);
tda_reg("EXTENDED_BYTE_11 = 0x%02x\n", 0xff & regs[R_EB11]);
tda_reg("EXTENDED_BYTE_12 = 0x%02x\n", 0xff & regs[R_EB12]);
tda_reg("EXTENDED_BYTE_13 = 0x%02x\n", 0xff & regs[R_EB13]);
tda_reg("EXTENDED_BYTE_14 = 0x%02x\n", 0xff & regs[R_EB14]);
tda_reg("EXTENDED_BYTE_15 = 0x%02x\n", 0xff & regs[R_EB15]);
tda_reg("EXTENDED_BYTE_16 W = 0x%02x\n", 0xff & regs[R_EB16]);
tda_reg("EXTENDED_BYTE_17 W = 0x%02x\n", 0xff & regs[R_EB17]);
tda_reg("EXTENDED_BYTE_18 = 0x%02x\n", 0xff & regs[R_EB18]);
tda_reg("EXTENDED_BYTE_19 W = 0x%02x\n", 0xff & regs[R_EB19]);
tda_reg("EXTENDED_BYTE_20 W = 0x%02x\n", 0xff & regs[R_EB20]);
tda_reg("EXTENDED_BYTE_21 = 0x%02x\n", 0xff & regs[R_EB21]);
tda_reg("EXTENDED_BYTE_22 = 0x%02x\n", 0xff & regs[R_EB22]);
tda_reg("EXTENDED_BYTE_23 = 0x%02x\n", 0xff & regs[R_EB23]);
}
int tda18271_read_regs(struct dvb_frontend *fe)
{
struct tda18271_priv *priv = fe->tuner_priv;
unsigned char *regs = priv->tda18271_regs;
unsigned char buf = 0x00;
int ret;
struct i2c_msg msg[] = {
{ .addr = priv->i2c_props.addr, .flags = 0,
.buf = &buf, .len = 1 },
{ .addr = priv->i2c_props.addr, .flags = I2C_M_RD,
.buf = regs, .len = 16 }
};
tda18271_i2c_gate_ctrl(fe, 1);
/* read all registers */
ret = i2c_transfer(priv->i2c_props.adap, msg, 2);
tda18271_i2c_gate_ctrl(fe, 0);
if (ret != 2)
tda_err("ERROR: i2c_transfer returned: %d\n", ret);
if (tda18271_debug & DBG_REG)
tda18271_dump_regs(fe, 0);
return (ret == 2 ? 0 : ret);
}
int tda18271_read_extended(struct dvb_frontend *fe)
{
struct tda18271_priv *priv = fe->tuner_priv;
unsigned char *regs = priv->tda18271_regs;
unsigned char regdump[TDA18271_NUM_REGS];
unsigned char buf = 0x00;
int ret, i;
struct i2c_msg msg[] = {
{ .addr = priv->i2c_props.addr, .flags = 0,
.buf = &buf, .len = 1 },
{ .addr = priv->i2c_props.addr, .flags = I2C_M_RD,
.buf = regdump, .len = TDA18271_NUM_REGS }
};
tda18271_i2c_gate_ctrl(fe, 1);
/* read all registers */
ret = i2c_transfer(priv->i2c_props.adap, msg, 2);
tda18271_i2c_gate_ctrl(fe, 0);
if (ret != 2)
tda_err("ERROR: i2c_transfer returned: %d\n", ret);
for (i = 0; i < TDA18271_NUM_REGS; i++) {
/* don't update write-only registers */
if ((i != R_EB9) &&
(i != R_EB16) &&
(i != R_EB17) &&
(i != R_EB19) &&
(i != R_EB20))
regs[i] = regdump[i];
}
if (tda18271_debug & DBG_REG)
tda18271_dump_regs(fe, 1);
return (ret == 2 ? 0 : ret);
}
static int __tda18271_write_regs(struct dvb_frontend *fe, int idx, int len,
bool lock_i2c)
{
struct tda18271_priv *priv = fe->tuner_priv;
unsigned char *regs = priv->tda18271_regs;
unsigned char buf[TDA18271_NUM_REGS + 1];
struct i2c_msg msg = { .addr = priv->i2c_props.addr, .flags = 0,
.buf = buf };
int i, ret = 1, max;
BUG_ON((len == 0) || (idx + len > sizeof(buf)));
switch (priv->small_i2c) {
case TDA18271_03_BYTE_CHUNK_INIT:
max = 3;
break;
case TDA18271_08_BYTE_CHUNK_INIT:
max = 8;
break;
case TDA18271_16_BYTE_CHUNK_INIT:
max = 16;
break;
case TDA18271_39_BYTE_CHUNK_INIT:
default:
max = 39;
}
/*
* If lock_i2c is true, it will take the I2C bus for tda18271 private
* usage during the entire write ops, as otherwise, bad things could
* happen.
* During device init, several write operations will happen. So,
* tda18271_init_regs controls the I2C lock directly,
* disabling lock_i2c here.
*/
if (lock_i2c) {
tda18271_i2c_gate_ctrl(fe, 1);
i2c_lock_adapter(priv->i2c_props.adap);
}
while (len) {
if (max > len)
max = len;
buf[0] = idx;
for (i = 1; i <= max; i++)
buf[i] = regs[idx - 1 + i];
msg.len = max + 1;
/* write registers */
ret = __i2c_transfer(priv->i2c_props.adap, &msg, 1);
if (ret != 1)
break;
idx += max;
len -= max;
}
if (lock_i2c) {
i2c_unlock_adapter(priv->i2c_props.adap);
tda18271_i2c_gate_ctrl(fe, 0);
}
if (ret != 1)
tda_err("ERROR: idx = 0x%x, len = %d, i2c_transfer returned: %d\n",
idx, max, ret);
return (ret == 1 ? 0 : ret);
}
int tda18271_write_regs(struct dvb_frontend *fe, int idx, int len)
{
return __tda18271_write_regs(fe, idx, len, true);
}
/*---------------------------------------------------------------------*/
static int __tda18271_charge_pump_source(struct dvb_frontend *fe,
enum tda18271_pll pll, int force,
bool lock_i2c)
{
struct tda18271_priv *priv = fe->tuner_priv;
unsigned char *regs = priv->tda18271_regs;
int r_cp = (pll == TDA18271_CAL_PLL) ? R_EB7 : R_EB4;
regs[r_cp] &= ~0x20;
regs[r_cp] |= ((force & 1) << 5);
return __tda18271_write_regs(fe, r_cp, 1, lock_i2c);
}
int tda18271_charge_pump_source(struct dvb_frontend *fe,
enum tda18271_pll pll, int force)
{
return __tda18271_charge_pump_source(fe, pll, force, true);
}
int tda18271_init_regs(struct dvb_frontend *fe)
{
struct tda18271_priv *priv = fe->tuner_priv;
unsigned char *regs = priv->tda18271_regs;
tda_dbg("initializing registers for device @ %d-%04x\n",
i2c_adapter_id(priv->i2c_props.adap),
priv->i2c_props.addr);
/*
* Don't let any other I2C transfer to happen at adapter during init,
* as those could cause bad things
*/
tda18271_i2c_gate_ctrl(fe, 1);
i2c_lock_adapter(priv->i2c_props.adap);
/* initialize registers */
switch (priv->id) {
case TDA18271HDC1:
regs[R_ID] = 0x83;
break;
case TDA18271HDC2:
regs[R_ID] = 0x84;
break;
}
regs[R_TM] = 0x08;
regs[R_PL] = 0x80;
regs[R_EP1] = 0xc6;
regs[R_EP2] = 0xdf;
regs[R_EP3] = 0x16;
regs[R_EP4] = 0x60;
regs[R_EP5] = 0x80;
regs[R_CPD] = 0x80;
regs[R_CD1] = 0x00;
regs[R_CD2] = 0x00;
regs[R_CD3] = 0x00;
regs[R_MPD] = 0x00;
regs[R_MD1] = 0x00;
regs[R_MD2] = 0x00;
regs[R_MD3] = 0x00;
switch (priv->id) {
case TDA18271HDC1:
regs[R_EB1] = 0xff;
break;
case TDA18271HDC2:
regs[R_EB1] = 0xfc;
break;
}
regs[R_EB2] = 0x01;
regs[R_EB3] = 0x84;
regs[R_EB4] = 0x41;
regs[R_EB5] = 0x01;
regs[R_EB6] = 0x84;
regs[R_EB7] = 0x40;
regs[R_EB8] = 0x07;
regs[R_EB9] = 0x00;
regs[R_EB10] = 0x00;
regs[R_EB11] = 0x96;
switch (priv->id) {
case TDA18271HDC1:
regs[R_EB12] = 0x0f;
break;
case TDA18271HDC2:
regs[R_EB12] = 0x33;
break;
}
regs[R_EB13] = 0xc1;
regs[R_EB14] = 0x00;
regs[R_EB15] = 0x8f;
regs[R_EB16] = 0x00;
regs[R_EB17] = 0x00;
switch (priv->id) {
case TDA18271HDC1:
regs[R_EB18] = 0x00;
break;
case TDA18271HDC2:
regs[R_EB18] = 0x8c;
break;
}
regs[R_EB19] = 0x00;
regs[R_EB20] = 0x20;
switch (priv->id) {
case TDA18271HDC1:
regs[R_EB21] = 0x33;
break;
case TDA18271HDC2:
regs[R_EB21] = 0xb3;
break;
}
regs[R_EB22] = 0x48;
regs[R_EB23] = 0xb0;
__tda18271_write_regs(fe, 0x00, TDA18271_NUM_REGS, false);
/* setup agc1 gain */
regs[R_EB17] = 0x00;
__tda18271_write_regs(fe, R_EB17, 1, false);
regs[R_EB17] = 0x03;
__tda18271_write_regs(fe, R_EB17, 1, false);
regs[R_EB17] = 0x43;
__tda18271_write_regs(fe, R_EB17, 1, false);
regs[R_EB17] = 0x4c;
__tda18271_write_regs(fe, R_EB17, 1, false);
/* setup agc2 gain */
if ((priv->id) == TDA18271HDC1) {
regs[R_EB20] = 0xa0;
__tda18271_write_regs(fe, R_EB20, 1, false);
regs[R_EB20] = 0xa7;
__tda18271_write_regs(fe, R_EB20, 1, false);
regs[R_EB20] = 0xe7;
__tda18271_write_regs(fe, R_EB20, 1, false);
regs[R_EB20] = 0xec;
__tda18271_write_regs(fe, R_EB20, 1, false);
}
/* image rejection calibration */
/* low-band */
regs[R_EP3] = 0x1f;
regs[R_EP4] = 0x66;
regs[R_EP5] = 0x81;
regs[R_CPD] = 0xcc;
regs[R_CD1] = 0x6c;
regs[R_CD2] = 0x00;
regs[R_CD3] = 0x00;
regs[R_MPD] = 0xcd;
regs[R_MD1] = 0x77;
regs[R_MD2] = 0x08;
regs[R_MD3] = 0x00;
__tda18271_write_regs(fe, R_EP3, 11, false);
if ((priv->id) == TDA18271HDC2) {
/* main pll cp source on */
__tda18271_charge_pump_source(fe, TDA18271_MAIN_PLL, 1, false);
msleep(1);
/* main pll cp source off */
__tda18271_charge_pump_source(fe, TDA18271_MAIN_PLL, 0, false);
}
msleep(5); /* pll locking */
/* launch detector */
__tda18271_write_regs(fe, R_EP1, 1, false);
msleep(5); /* wanted low measurement */
regs[R_EP5] = 0x85;
regs[R_CPD] = 0xcb;
regs[R_CD1] = 0x66;
regs[R_CD2] = 0x70;
__tda18271_write_regs(fe, R_EP3, 7, false);
msleep(5); /* pll locking */
/* launch optimization algorithm */
__tda18271_write_regs(fe, R_EP2, 1, false);
msleep(30); /* image low optimization completion */
/* mid-band */
regs[R_EP5] = 0x82;
regs[R_CPD] = 0xa8;
regs[R_CD2] = 0x00;
regs[R_MPD] = 0xa9;
regs[R_MD1] = 0x73;
regs[R_MD2] = 0x1a;
__tda18271_write_regs(fe, R_EP3, 11, false);
msleep(5); /* pll locking */
/* launch detector */
__tda18271_write_regs(fe, R_EP1, 1, false);
msleep(5); /* wanted mid measurement */
regs[R_EP5] = 0x86;
regs[R_CPD] = 0xa8;
regs[R_CD1] = 0x66;
regs[R_CD2] = 0xa0;
__tda18271_write_regs(fe, R_EP3, 7, false);
msleep(5); /* pll locking */
/* launch optimization algorithm */
__tda18271_write_regs(fe, R_EP2, 1, false);
msleep(30); /* image mid optimization completion */
/* high-band */
regs[R_EP5] = 0x83;
regs[R_CPD] = 0x98;
regs[R_CD1] = 0x65;
regs[R_CD2] = 0x00;
regs[R_MPD] = 0x99;
regs[R_MD1] = 0x71;
regs[R_MD2] = 0xcd;
__tda18271_write_regs(fe, R_EP3, 11, false);
msleep(5); /* pll locking */
/* launch detector */
__tda18271_write_regs(fe, R_EP1, 1, false);
msleep(5); /* wanted high measurement */
regs[R_EP5] = 0x87;
regs[R_CD1] = 0x65;
regs[R_CD2] = 0x50;
__tda18271_write_regs(fe, R_EP3, 7, false);
msleep(5); /* pll locking */
/* launch optimization algorithm */
__tda18271_write_regs(fe, R_EP2, 1, false);
msleep(30); /* image high optimization completion */
/* return to normal mode */
regs[R_EP4] = 0x64;
__tda18271_write_regs(fe, R_EP4, 1, false);
/* synchronize */
__tda18271_write_regs(fe, R_EP1, 1, false);
i2c_unlock_adapter(priv->i2c_props.adap);
tda18271_i2c_gate_ctrl(fe, 0);
return 0;
}
/*---------------------------------------------------------------------*/
/*
* Standby modes, EP3 [7:5]
*
* | SM || SM_LT || SM_XT || mode description
* |=====\\=======\\=======\\===================================
* | 0 || 0 || 0 || normal mode
* |-----||-------||-------||-----------------------------------
* | || || || standby mode w/ slave tuner output
* | 1 || 0 || 0 || & loop thru & xtal oscillator on
* |-----||-------||-------||-----------------------------------
* | 1 || 1 || 0 || standby mode w/ xtal oscillator on
* |-----||-------||-------||-----------------------------------
* | 1 || 1 || 1 || power off
*
*/
int tda18271_set_standby_mode(struct dvb_frontend *fe,
int sm, int sm_lt, int sm_xt)
{
struct tda18271_priv *priv = fe->tuner_priv;
unsigned char *regs = priv->tda18271_regs;
if (tda18271_debug & DBG_ADV)
tda_dbg("sm = %d, sm_lt = %d, sm_xt = %d\n", sm, sm_lt, sm_xt);
regs[R_EP3] &= ~0xe0; /* clear sm, sm_lt, sm_xt */
regs[R_EP3] |= (sm ? (1 << 7) : 0) |
(sm_lt ? (1 << 6) : 0) |
(sm_xt ? (1 << 5) : 0);
return tda18271_write_regs(fe, R_EP3, 1);
}
/*---------------------------------------------------------------------*/
int tda18271_calc_main_pll(struct dvb_frontend *fe, u32 freq)
{
/* sets main post divider & divider bytes, but does not write them */
struct tda18271_priv *priv = fe->tuner_priv;
unsigned char *regs = priv->tda18271_regs;
u8 d, pd;
u32 div;
int ret = tda18271_lookup_pll_map(fe, MAIN_PLL, &freq, &pd, &d);
if (tda_fail(ret))
goto fail;
regs[R_MPD] = (0x7f & pd);
div = ((d * (freq / 1000)) << 7) / 125;
regs[R_MD1] = 0x7f & (div >> 16);
regs[R_MD2] = 0xff & (div >> 8);
regs[R_MD3] = 0xff & div;
fail:
return ret;
}
int tda18271_calc_cal_pll(struct dvb_frontend *fe, u32 freq)
{
/* sets cal post divider & divider bytes, but does not write them */
struct tda18271_priv *priv = fe->tuner_priv;
unsigned char *regs = priv->tda18271_regs;
u8 d, pd;
u32 div;
int ret = tda18271_lookup_pll_map(fe, CAL_PLL, &freq, &pd, &d);
if (tda_fail(ret))
goto fail;
regs[R_CPD] = pd;
div = ((d * (freq / 1000)) << 7) / 125;
regs[R_CD1] = 0x7f & (div >> 16);
regs[R_CD2] = 0xff & (div >> 8);
regs[R_CD3] = 0xff & div;
fail:
return ret;
}
/*---------------------------------------------------------------------*/
int tda18271_calc_bp_filter(struct dvb_frontend *fe, u32 *freq)
{
/* sets bp filter bits, but does not write them */
struct tda18271_priv *priv = fe->tuner_priv;
unsigned char *regs = priv->tda18271_regs;
u8 val;
int ret = tda18271_lookup_map(fe, BP_FILTER, freq, &val);
if (tda_fail(ret))
goto fail;
regs[R_EP1] &= ~0x07; /* clear bp filter bits */
regs[R_EP1] |= (0x07 & val);
fail:
return ret;
}
int tda18271_calc_km(struct dvb_frontend *fe, u32 *freq)
{
/* sets K & M bits, but does not write them */
struct tda18271_priv *priv = fe->tuner_priv;
unsigned char *regs = priv->tda18271_regs;
u8 val;
int ret = tda18271_lookup_map(fe, RF_CAL_KMCO, freq, &val);
if (tda_fail(ret))
goto fail;
regs[R_EB13] &= ~0x7c; /* clear k & m bits */
regs[R_EB13] |= (0x7c & val);
fail:
return ret;
}
int tda18271_calc_rf_band(struct dvb_frontend *fe, u32 *freq)
{
/* sets rf band bits, but does not write them */
struct tda18271_priv *priv = fe->tuner_priv;
unsigned char *regs = priv->tda18271_regs;
u8 val;
int ret = tda18271_lookup_map(fe, RF_BAND, freq, &val);
if (tda_fail(ret))
goto fail;
regs[R_EP2] &= ~0xe0; /* clear rf band bits */
regs[R_EP2] |= (0xe0 & (val << 5));
fail:
return ret;
}
int tda18271_calc_gain_taper(struct dvb_frontend *fe, u32 *freq)
{
/* sets gain taper bits, but does not write them */
struct tda18271_priv *priv = fe->tuner_priv;
unsigned char *regs = priv->tda18271_regs;
u8 val;
int ret = tda18271_lookup_map(fe, GAIN_TAPER, freq, &val);
if (tda_fail(ret))
goto fail;
regs[R_EP2] &= ~0x1f; /* clear gain taper bits */
regs[R_EP2] |= (0x1f & val);
fail:
return ret;
}
int tda18271_calc_ir_measure(struct dvb_frontend *fe, u32 *freq)
{
/* sets IR Meas bits, but does not write them */
struct tda18271_priv *priv = fe->tuner_priv;
unsigned char *regs = priv->tda18271_regs;
u8 val;
int ret = tda18271_lookup_map(fe, IR_MEASURE, freq, &val);
if (tda_fail(ret))
goto fail;
regs[R_EP5] &= ~0x07;
regs[R_EP5] |= (0x07 & val);
fail:
return ret;
}
int tda18271_calc_rf_cal(struct dvb_frontend *fe, u32 *freq)
{
/* sets rf cal byte (RFC_Cprog), but does not write it */
struct tda18271_priv *priv = fe->tuner_priv;
unsigned char *regs = priv->tda18271_regs;
u8 val;
int ret = tda18271_lookup_map(fe, RF_CAL, freq, &val);
/* The TDA18271HD/C1 rf_cal map lookup is expected to go out of range
* for frequencies above 61.1 MHz. In these cases, the internal RF
* tracking filters calibration mechanism is used.
*
* There is no need to warn the user about this.
*/
if (ret < 0)
goto fail;
regs[R_EB14] = val;
fail:
return ret;
}
void _tda_printk(struct tda18271_priv *state, const char *level,
const char *func, const char *fmt, ...)
{
struct va_format vaf;
va_list args;
va_start(args, fmt);
vaf.fmt = fmt;
vaf.va = &args;
if (state)
printk("%s%s: [%d-%04x|%c] %pV",
level, func, i2c_adapter_id(state->i2c_props.adap),
state->i2c_props.addr,
(state->role == TDA18271_MASTER) ? 'M' : 'S',
&vaf);
else
printk("%s%s: %pV", level, func, &vaf);
va_end(args);
}
| {
"pile_set_name": "Github"
} |
# Original taken and modified from:
# https://github.com/ihowson/Teensy-Raw-HID-in-Python/blob/master/teensy_loader_cli/49-teensy.rules
#
# This file must be placed at:
#
# /etc/udev/rules.d/ArduinoRawHID.rules (preferred location)
# or
# /lib/udev/rules.d/ArduinoRawHID.rules (req'd on some broken systems)
#
# SUBSYSTEMS=="usb", ATTRS{idVendor}=="0x2341", ATTRS{idProduct}=="0x8036", MODE:="0666"
#
# Reload udev rules:
# udevadm control --reload && udevadm trigger
#
#
# Arduino devices (leonardo only, or all Arduino devices):
#SUBSYSTEMS=="usb", ATTRS{idVendor}=="2341", ATTRS{idProduct}=="8036", MODE:="0666"
SUBSYSTEMS=="usb", ATTRS{idVendor}=="2341", MODE:="0666"
#
#
#SUBSYSTEMS=="usb", ATTRS{idVendor}=="16c0", ATTRS{idProduct}=="04[789]?", MODE:="0666"
#SUBSYSTEMS=="usb", ATTRS{idVendor}=="16c0", ATTRS{idProduct}=="8000", MODE:="0666"
#KERNEL=="ttyACM*", ATTRS{idVendor}=="16c0", ATTRS{idProduct}=="04[789]?", SYMLINK+="ttyUSB00%n", MODE:="0666", ENV{ID_MM_DEVICE_IGNORE}="1"
#
# If you share your linux system with other users, or just don't like the
# idea of write permission for everybody, you can replace MODE:="0666" with
# OWNER:="yourusername" to create the device owned by you, or with
# GROUP:="somegroupname" and mange access using standard unix groups.
#
#
# If using USB Serial you get a new device each time (Ubuntu 9.10)
# eg: /dev/ttyACM0, ttyACM1, ttyACM2, ttyACM3, ttyACM4, etc
# apt-get remove --purge modemmanager (reboot may be necessary)
#
#
# Older modem proding (eg, Ubuntu 9.04) caused very slow serial device detection.
# To fix, add this near top of /lib/udev/rules.d/77-nm-probe-modem-capabilities.rules
# SUBSYSTEMS=="usb", ATTRS{idVendor}=="16c0", ATTRS{idProduct}=="04[789]?", GOTO="nm_modem_probe_end"
#
#
# (old udev rules)
#SUBSYSTEMS=="usb", ATTRS{idVendor}=="16c0", ATTRS{idProduct}=="047[78]", MODE:="0666"
#SUBSYSTEMS=="usb", ATTRS{idVendor}=="16c0", ATTRS{idProduct}=="048[02]", MODE:="0666"
#KERNEL=="ttyACM*", SYMLINK+="ttyUSB00%n", MODE:="0666"
| {
"pile_set_name": "Github"
} |
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package icmp
import "syscall"
func init() {
freebsdVersion, _ = syscall.SysctlUint32("kern.osreldate")
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package codegen.enum.companionObject
import kotlin.test.*
enum class Game {
ROCK,
PAPER,
SCISSORS;
companion object {
fun foo() = ROCK
val bar = PAPER
val values2 = values()
val scissors = valueOf("SCISSORS")
}
}
fun box(): String {
if (Game.foo() != Game.ROCK) return "Fail 1"
if (Game.bar != Game.PAPER) return "Fail 2: ${Game.bar}"
if (Game.values().size != 3) return "Fail 3"
if (Game.valueOf("SCISSORS") != Game.SCISSORS) return "Fail 4"
if (Game.values2.size != 3) return "Fail 5"
if (Game.scissors != Game.SCISSORS) return "Fail 6"
return "OK"
}
@Test fun runTest() = println(box()) | {
"pile_set_name": "Github"
} |
// Copyright (c) 2012 Ecma International. All rights reserved.
// Ecma International makes this code available under the terms and conditions set
// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
// "Use Terms"). Any redistribution of this code must retain the above
// copyright and this notice and otherwise comply with the Use Terms.
/*---
es5id: 15.2.3.6-3-83
description: >
Object.defineProperty - 'configurable' property in 'Attributes' is
own accessor property without a get function (8.10.5 step 4.a)
includes: [runTestCase.js]
---*/
function testcase() {
var obj = { };
var attr = {};
Object.defineProperty(attr, "configurable", {
set : function () { }
});
Object.defineProperty(obj, "property", attr);
var beforeDeleted = obj.hasOwnProperty("property");
delete obj.property;
var afterDeleted = obj.hasOwnProperty("property") && typeof (obj.property) === "undefined";
return beforeDeleted === true && afterDeleted === true;
}
runTestCase(testcase);
| {
"pile_set_name": "Github"
} |
0.023220 0.023220 3
0.394739 0.394739 4
1.010068 1.010068 1
1.683447 1.683447 2
2.240726 2.240726 3
2.763175 2.763175 4
3.378503 3.378503 1
3.993832 3.993832 2
4.632381 4.632381 3
5.259320 5.259320 4
5.932698 5.932698 1
6.606077 6.606077 2
7.267846 7.267846 3
7.918005 7.918005 4
8.579773 8.579773 1
9.241542 9.241542 2
9.891701 9.891701 3
10.553469 10.553469 4
11.192018 11.192018 1
11.865397 11.865397 2
12.527166 12.527166 3
13.188934 13.188934 4
13.827483 13.827483 1
14.512472 14.512472 2
15.162630 15.162630 3
15.824399 15.824399 4
16.474558 16.474558 1
17.124717 17.124717 2
17.798095 17.798095 3
18.448254 18.448254 4
19.110023 19.110023 1
19.783401 19.783401 2
20.433560 20.433560 3
21.106939 21.106939 4
21.757098 21.757098 1
22.430476 22.430476 2
23.080635 23.080635 3
23.754014 23.754014 4
24.392562 24.392562 1
25.054331 25.054331 2
25.716100 25.716100 3
26.366259 26.366259 4
27.028027 27.028027 1
27.701406 27.701406 2
28.386395 28.386395 3
29.071383 29.071383 4
29.767982 29.767982 1
30.441361 30.441361 2
31.103129 31.103129 3
31.753288 31.753288 4
32.449887 32.449887 1
33.111655 33.111655 2
33.773424 33.773424 3
34.435193 34.435193 4
35.120181 35.120181 1
35.770340 35.770340 2
36.420499 36.420499 3
37.070658 37.070658 4
37.732426 37.732426 1
38.405805 38.405805 2
39.044354 39.044354 3
39.717732 39.717732 4
40.391111 40.391111 1
41.041270 41.041270 2
41.691429 41.691429 3
42.353197 42.353197 4
43.003356 43.003356 1
43.665125 43.665125 2
44.326893 44.326893 3
44.988662 44.988662 4
45.650431 45.650431 1
46.300590 46.300590 2
46.950748 46.950748 3
47.600907 47.600907 4
48.262676 48.262676 1
48.924444 48.924444 2
49.574603 49.574603 3
50.224762 50.224762 4
50.898141 50.898141 1
51.548299 51.548299 2
52.198458 52.198458 3
52.860227 52.860227 4
53.521995 53.521995 1
54.206984 54.206984 2
54.857143 54.857143 3
55.530522 55.530522 4
56.192290 56.192290 1
56.854059 56.854059 2
57.527438 57.527438 3
58.200816 58.200816 4
58.874195 58.874195 1
59.559184 59.559184 2
60.220952 60.220952 3
60.871111 60.871111 4
61.544490 61.544490 1
62.194649 62.194649 2
62.856417 62.856417 3
63.518186 63.518186 4
64.168345 64.168345 1
64.818503 64.818503 2
65.480272 65.480272 3
66.142041 66.142041 4
66.803810 66.803810 1
67.477188 67.477188 2
68.127347 68.127347 3
68.789116 68.789116 4
69.439274 69.439274 1
70.112653 70.112653 2
70.774422 70.774422 3
71.424580 71.424580 4
72.074739 72.074739 1
72.748118 72.748118 2
73.398277 73.398277 3
74.048435 74.048435 4
74.710204 74.710204 1
75.383583 75.383583 2
76.056961 76.056961 3
76.730340 76.730340 4
77.392109 77.392109 1
78.065488 78.065488 2
78.738866 78.738866 3
79.423855 79.423855 4
80.097234 80.097234 1
80.770612 80.770612 2
81.443991 81.443991 3
82.105760 82.105760 4
82.767528 82.767528 1
83.417687 83.417687 2
84.067846 84.067846 3
84.706395 84.706395 4
85.368163 85.368163 1
86.018322 86.018322 2
86.668481 86.668481 3
87.330249 87.330249 4
87.980408 87.980408 1
88.642177 88.642177 2
89.292336 89.292336 3
89.942494 89.942494 4
90.604263 90.604263 1
91.266032 91.266032 2
91.916190 91.916190 3
92.566349 92.566349 4
93.216508 93.216508 1
93.878277 93.878277 2
94.528435 94.528435 3
95.178594 95.178594 4
95.840363 95.840363 1
96.513741 96.513741 2
97.175510 97.175510 3
97.825669 97.825669 4
98.487438 98.487438 1
99.137596 99.137596 2
99.799365 99.799365 3
100.449524 100.449524 4
101.111293 101.111293 1
101.784671 101.784671 2
102.446440 102.446440 3
103.119819 103.119819 4
103.793197 103.793197 1
104.466576 104.466576 2
105.139955 105.139955 3
105.801723 105.801723 4
106.451882 106.451882 1
107.032381 107.032381 2
107.624490 107.624490 3
108.239819 108.239819 4
108.843537 108.843537 1
109.458866 109.458866 2
110.097415 110.097415 3
110.724354 110.724354 4
111.374512 111.374512 1
112.024671 112.024671 2
112.674830 112.674830 3
113.336599 113.336599 4
114.009977 114.009977 1
114.671746 114.671746 2
115.310295 115.310295 3
115.960454 115.960454 4
116.633832 116.633832 1
117.283991 117.283991 2
117.934150 117.934150 3
118.595918 118.595918 4
119.246077 119.246077 1
119.896236 119.896236 2
120.546395 120.546395 3
121.208163 121.208163 4
121.869932 121.869932 1
122.520091 122.520091 2
123.181859 123.181859 3
123.843628 123.843628 4
124.493787 124.493787 1
125.143946 125.143946 2
125.805714 125.805714 3
126.467483 126.467483 4
127.129252 127.129252 1
127.802630 127.802630 2
128.452789 128.452789 3
129.114558 129.114558 4
129.764717 129.764717 1
130.414875 130.414875 2
131.076644 131.076644 3
131.738413 131.738413 4
132.400181 132.400181 1
133.050340 133.050340 2
133.700499 133.700499 3
134.373878 134.373878 4
135.035646 135.035646 1
135.674195 135.674195 2
136.347574 136.347574 3
136.997732 136.997732 4
137.659501 137.659501 1
138.321270 138.321270 2
138.983039 138.983039 3
139.644807 139.644807 4
140.306576 140.306576 1
140.956735 140.956735 2
141.630113 141.630113 3
142.280272 142.280272 4
142.942041 142.942041 1
143.615420 143.615420 2
144.253968 144.253968 3
144.892517 144.892517 4
145.542676 145.542676 1
146.204444 146.204444 2
146.842993 146.842993 3
147.493152 147.493152 4
148.131701 148.131701 1
148.793469 148.793469 2
149.443628 149.443628 3
150.093787 150.093787 4
150.743946 150.743946 1
151.417324 151.417324 2
152.067483 152.067483 3
152.706032 152.706032 4
153.356190 153.356190 1
154.017959 154.017959 2
154.668118 154.668118 3
155.318277 155.318277 4
155.968435 155.968435 1
156.630204 156.630204 2
157.280363 157.280363 3
157.953741 157.953741 4
158.603900 158.603900 1
159.254059 159.254059 2
159.904218 159.904218 3
160.554376 160.554376 4
161.204535 161.204535 1
161.866304 161.866304 2
162.516463 162.516463 3
163.178231 163.178231 4
163.840000 163.840000 1
164.490159 164.490159 2
165.128707 165.128707 3
165.790476 165.790476 4
166.440635 166.440635 1
167.090794 167.090794 2
167.740952 167.740952 3
168.391111 168.391111 4
169.052880 169.052880 1
169.714649 169.714649 2
170.353197 170.353197 3
170.991746 170.991746 4
171.630295 171.630295 1
172.268844 172.268844 2
172.919002 172.919002 3
173.557551 173.557551 4
174.219320 174.219320 1
174.869478 174.869478 2
175.508027 175.508027 3
176.158186 176.158186 4
176.796735 176.796735 1
177.470113 177.470113 2
178.120272 178.120272 3
178.758821 178.758821 4
179.408980 179.408980 1
180.070748 180.070748 2
180.732517 180.732517 3
181.382676 181.382676 4
182.032834 182.032834 1
182.671383 182.671383 2
183.344762 183.344762 3
183.994921 183.994921 4
184.633469 184.633469 1
185.295238 185.295238 2
185.957007 185.957007 3
186.618776 186.618776 4
187.280544 187.280544 1
187.930703 187.930703 2
188.580862 188.580862 3
189.254240 189.254240 4
189.904399 189.904399 1
190.566168 190.566168 2
191.216327 191.216327 3
191.878095 191.878095 4
192.574694 192.574694 1
193.259683 193.259683 2
193.909841 193.909841 3
194.560000 194.560000 4
195.210159 195.210159 1
195.871927 195.871927 2
196.533696 196.533696 3
197.207075 197.207075 4
197.857234 197.857234 1
198.507392 198.507392 2
199.157551 199.157551 3
199.819320 199.819320 4
200.481088 200.481088 1
201.131247 201.131247 2
201.781406 201.781406 3
202.443175 202.443175 4
203.104943 203.104943 1
203.755102 203.755102 2
204.405261 204.405261 3
205.055420 205.055420 4
205.717188 205.717188 1
206.367347 206.367347 2
207.029116 207.029116 3
207.656054 207.656054 4
208.306213 208.306213 1
208.944762 208.944762 2
209.606531 209.606531 3
210.268299 210.268299 4
210.930068 210.930068 1
211.568617 211.568617 2
212.230385 212.230385 3
212.880544 212.880544 4
213.530703 213.530703 1
214.192472 214.192472 2
214.842630 214.842630 3
215.504399 215.504399 4
216.142948 216.142948 1
216.793107 216.793107 2
217.454875 217.454875 3
218.105034 218.105034 4
218.766803 218.766803 1
219.416961 219.416961 2
220.067120 220.067120 3
220.717279 220.717279 4
221.367438 221.367438 1
222.029206 222.029206 2
222.667755 222.667755 3
223.317914 223.317914 4
223.968073 223.968073 1
224.641451 224.641451 2
225.291610 225.291610 3
225.953379 225.953379 4
226.603537 226.603537 1
227.265306 227.265306 2
227.915465 227.915465 3
228.577234 228.577234 4
229.227392 229.227392 1
229.877551 229.877551 2
230.527710 230.527710 3
231.189478 231.189478 4
231.839637 231.839637 1
232.501406 232.501406 2
233.151565 233.151565 3
233.813333 233.813333 4
234.463492 234.463492 1
235.113651 235.113651 2
235.775420 235.775420 3
236.437188 236.437188 4
237.087347 237.087347 1
237.749116 237.749116 2
238.422494 238.422494 3
239.072653 239.072653 4
239.722812 239.722812 1
240.396190 240.396190 2
241.057959 241.057959 3
241.708118 241.708118 4
242.369887 242.369887 1
243.008435 243.008435 2
243.658594 243.658594 3
244.308753 244.308753 4
244.970522 244.970522 1
245.632290 245.632290 2
246.270839 246.270839 3
246.909388 246.909388 4
247.547937 247.547937 1
248.209705 248.209705 2
248.871474 248.871474 3
249.510023 249.510023 4
250.171791 250.171791 1
250.810340 250.810340 2
251.460499 251.460499 3
252.110658 252.110658 4
252.760816 252.760816 1
253.422585 253.422585 2
254.072744 254.072744 3
254.722902 254.722902 4
255.361451 255.361451 1
256.023220 256.023220 2
256.673379 256.673379 3
257.323537 257.323537 4
257.973696 257.973696 1
258.612245 258.612245 2
259.239184 259.239184 3
259.877732 259.877732 4
260.527891 260.527891 1
261.189660 261.189660 2
261.828209 261.828209 3
262.489977 262.489977 4
263.116916 263.116916 1
263.778685 263.778685 2
264.428844 264.428844 3
265.090612 265.090612 4
265.740771 265.740771 1
266.390930 266.390930 2
267.041088 267.041088 3
267.702857 267.702857 4
268.364626 268.364626 1
269.003175 269.003175 2
269.653333 269.653333 3
270.303492 270.303492 4
270.953651 270.953651 1
271.615420 271.615420 2
272.265578 272.265578 3
272.904127 272.904127 4
273.542676 273.542676 1
274.158005 274.158005 2
274.784943 274.784943 3
275.423492 275.423492 4
276.062041 276.062041 1
| {
"pile_set_name": "Github"
} |
cmd_Release/obj.target/libsass/src/libsass/src/memory/SharedPtr.o := c++ '-DNODE_GYP_MODULE_NAME=libsass' '-DUSING_UV_SHARED=1' '-DUSING_V8_SHARED=1' '-DV8_DEPRECATION_WARNINGS=1' '-D_DARWIN_USE_64_BIT_INODE=1' '-D_LARGEFILE_SOURCE' '-D_FILE_OFFSET_BITS=64' '-DLIBSASS_VERSION="3.5.4"' -I/Users/leonard.gonsalves/.node-gyp/11.3.0/include/node -I/Users/leonard.gonsalves/.node-gyp/11.3.0/src -I/Users/leonard.gonsalves/.node-gyp/11.3.0/deps/openssl/config -I/Users/leonard.gonsalves/.node-gyp/11.3.0/deps/openssl/openssl/include -I/Users/leonard.gonsalves/.node-gyp/11.3.0/deps/uv/include -I/Users/leonard.gonsalves/.node-gyp/11.3.0/deps/zlib -I/Users/leonard.gonsalves/.node-gyp/11.3.0/deps/v8/include -I../src/libsass/include -Os -gdwarf-2 -mmacosx-version-min=10.7 -arch x86_64 -Wall -Wendif-labels -W -Wno-unused-parameter -std=c++11 -stdlib=libc++ -fno-strict-aliasing -MMD -MF ./Release/.deps/Release/obj.target/libsass/src/libsass/src/memory/SharedPtr.o.d.raw -c -o Release/obj.target/libsass/src/libsass/src/memory/SharedPtr.o ../src/libsass/src/memory/SharedPtr.cpp
Release/obj.target/libsass/src/libsass/src/memory/SharedPtr.o: \
../src/libsass/src/memory/SharedPtr.cpp \
../src/libsass/src/memory/../sass.hpp \
../src/libsass/include/sass/base.h \
../src/libsass/src/memory/SharedPtr.hpp \
../src/libsass/src/memory/../ast_fwd_decl.hpp \
../src/libsass/src/memory/../memory/SharedPtr.hpp \
../src/libsass/include/sass/functions.h
../src/libsass/src/memory/SharedPtr.cpp:
../src/libsass/src/memory/../sass.hpp:
../src/libsass/include/sass/base.h:
../src/libsass/src/memory/SharedPtr.hpp:
../src/libsass/src/memory/../ast_fwd_decl.hpp:
../src/libsass/src/memory/../memory/SharedPtr.hpp:
../src/libsass/include/sass/functions.h:
| {
"pile_set_name": "Github"
} |
/*
** FAAD2 - Freeware Advanced Audio (AAC) Decoder including SBR decoding
** Copyright (C) 2003-2004 M. Bakker, Ahead Software AG, http://www.nero.com
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
**
** Any non-GPL usage of this software or parts of this software is strictly
** forbidden.
**
** Commercial non-GPL licensing of this software is possible.
** For more info contact Ahead Software through [email protected].
**
** $Id: sbr_huff.h,v 1.2 2009-02-11 21:19:30 dave Exp $
**/
#ifndef __SBR_HUFF_H__
#define __SBR_HUFF_H__
#ifdef __cplusplus
extern "C" {
#endif
void sbr_envelope(bitfile *ld, sbr_info *sbr, uint8_t ch);
void sbr_noise(bitfile *ld, sbr_info *sbr, uint8_t ch);
#ifdef __cplusplus
}
#endif
#endif
| {
"pile_set_name": "Github"
} |
2107 1565597572115 httpcache-v1
Method: POST
URL: https://www.notion.so/api/v3/getRecordValues
Body:+110
{
"requests": [
{
"id": "ad5565a3-c036-48c6-ab91-13a461a71835",
"table": "block"
}
]
}
Response:+1907
{
"results": [
{
"role": "comment_only",
"value": {
"alive": true,
"content": [
"fbcc00fb-7f44-4f6f-a644-482e73cd33b3",
"9047299c-8753-416a-aea8-6d7bf62f856a",
"e9eb8298-7d71-4ab0-bfdf-25db390ad74f",
"165cc8aa-d2b6-42a7-a917-dcb0de3276ea",
"fac6efa8-ee61-4ba1-b035-6e43a3d289dc",
"4b227b86-8bb9-44a0-88d6-b87594b00cfa",
"aa05a5b8-5d89-4178-b3ab-aa7e0cc4a038",
"9fb27cd9-41fe-48f2-86bd-87e64c1f6458",
"8dbd4774-4876-4d79-977b-aa03fb6801df",
"2be21f73-426b-4e4e-92e4-e15cd525e252",
"4f1e7a9f-ad17-40fb-85a0-1a57b0ea8d9f",
"5545d447-266e-4811-80b7-e07001a2c4aa",
"6ed9b7ce-da9d-4a19-95b2-d68919664bd1",
"6be19234-b37a-42ec-8f63-3d3bb2f7be0e",
"223d7495-1bb3-4167-bb52-e493945f3a22",
"24200e3a-a614-40f4-8ee1-bb2630c541d6",
"cc237566-fb77-404b-908b-c732c4cf75db",
"93a3c562-706a-40f0-9e62-a6394389d198",
"b2674bcd-760c-4740-a21b-b12adb6862c3",
"be1899d6-151f-4a90-af74-84b5474e4ad9",
"24bfd5e1-341b-4251-971b-dd6647eead45",
"ceb6048a-3be2-4b9a-9a12-d58a569e65c0"
],
"created_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
"created_time": 1552022241310,
"format": {
"page_full_width": true,
"page_small_text": true
},
"id": "ad5565a3-c036-48c6-ab91-13a461a71835",
"ignore_block_count": true,
"last_edited_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
"last_edited_time": 1552022241310,
"parent_id": "eb584d64-0967-460c-a9f1-9d66ff8697ea",
"parent_table": "block",
"properties": {
"title": [
[
"array reduce"
]
]
},
"type": "page",
"version": 3
}
}
]
}
32187 1565597572117 httpcache-v1
Method: POST
URL: https://www.notion.so/api/v3/loadPageChunk
Body:+152
{
"chunkNumber": 0,
"cursor": {
"stack": []
},
"limit": 50,
"pageId": "ad5565a3-c036-48c6-ab91-13a461a71835",
"verticalColumns": false
}
Response:+31946
{
"cursor": {
"stack": []
},
"recordMap": {
"block": {
"165cc8aa-d2b6-42a7-a917-dcb0de3276ea": {
"role": "comment_only",
"value": {
"alive": true,
"created_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
"created_time": 1552022241307,
"id": "165cc8aa-d2b6-42a7-a917-dcb0de3276ea",
"ignore_block_count": true,
"last_edited_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
"last_edited_time": 1552022241307,
"parent_id": "ad5565a3-c036-48c6-ab91-13a461a71835",
"parent_table": "block",
"properties": {
"title": [
[
"$item is the value of current position in the array."
]
]
},
"type": "bulleted_list",
"version": 1
}
},
"223d7495-1bb3-4167-bb52-e493945f3a22": {
"role": "comment_only",
"value": {
"alive": true,
"created_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
"created_time": 1552022241309,
"id": "223d7495-1bb3-4167-bb52-e493945f3a22",
"ignore_block_count": true,
"last_edited_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
"last_edited_time": 1552022241309,
"parent_id": "ad5565a3-c036-48c6-ab91-13a461a71835",
"parent_table": "block",
"properties": {
"language": [
[
"Plain Text"
]
],
"title": [
[
"$result = array_reduce([101, 230, 21, 341, 251], function($carry, $item){\n return $carry || $item \u003c 100;\n}, false);//default value must set false"
]
]
},
"type": "code",
"version": 1
}
},
"24200e3a-a614-40f4-8ee1-bb2630c541d6": {
"role": "comment_only",
"value": {
"alive": true,
"created_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
"created_time": 1552022241309,
"id": "24200e3a-a614-40f4-8ee1-bb2630c541d6",
"ignore_block_count": true,
"last_edited_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
"last_edited_time": 1552022241309,
"parent_id": "ad5565a3-c036-48c6-ab91-13a461a71835",
"parent_table": "block",
"properties": {
"title": [
[
"result:"
],
[
"true",
[
[
"c"
]
]
]
]
},
"type": "text",
"version": 1
}
},
"24bfd5e1-341b-4251-971b-dd6647eead45": {
"role": "comment_only",
"value": {
"alive": true,
"created_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
"created_time": 1552022241310,
"id": "24bfd5e1-341b-4251-971b-dd6647eead45",
"ignore_block_count": true,
"last_edited_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
"last_edited_time": 1552022241310,
"parent_id": "ad5565a3-c036-48c6-ab91-13a461a71835",
"parent_table": "block",
"properties": {
"language": [
[
"Plain Text"
]
],
"title": [
[
"function implode_method($array, $piece){\n return array_reduce($array, function($carry, $item) use ($piece) {\n return !$carry ? $item : ($carry . $piece . $item);\n });\n}\n\n$result = implode_method([\"hello\", \"world\", \"PHP\", \"language\"], \"-\");"
]
]
},
"type": "code",
"version": 1
}
},
"2be21f73-426b-4e4e-92e4-e15cd525e252": {
"role": "comment_only",
"value": {
"alive": true,
"created_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
"created_time": 1552022241308,
"id": "2be21f73-426b-4e4e-92e4-e15cd525e252",
"ignore_block_count": true,
"last_edited_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
"last_edited_time": 1552022241308,
"parent_id": "ad5565a3-c036-48c6-ab91-13a461a71835",
"parent_table": "block",
"properties": {
"title": [
[
"result:"
],
[
"211",
[
[
"c"
]
]
]
]
},
"type": "text",
"version": 1
}
},
"4b227b86-8bb9-44a0-88d6-b87594b00cfa": {
"role": "comment_only",
"value": {
"alive": true,
"created_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
"created_time": 1552022241308,
"id": "4b227b86-8bb9-44a0-88d6-b87594b00cfa",
"ignore_block_count": true,
"last_edited_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
"last_edited_time": 1552022241308,
"parent_id": "ad5565a3-c036-48c6-ab91-13a461a71835",
"parent_table": "block",
"properties": {
"language": [
[
"Plain Text"
]
],
"title": [
[
"$result = array_reduce([1, 2, 3, 4, 5], function($carry, $item){\n return $carry + $item;\n});"
]
]
},
"type": "code",
"version": 1
}
},
"4f1e7a9f-ad17-40fb-85a0-1a57b0ea8d9f": {
"role": "comment_only",
"value": {
"alive": true,
"created_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
"created_time": 1552022241309,
"id": "4f1e7a9f-ad17-40fb-85a0-1a57b0ea8d9f",
"ignore_block_count": true,
"last_edited_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
"last_edited_time": 1552022241309,
"parent_id": "ad5565a3-c036-48c6-ab91-13a461a71835",
"parent_table": "block",
"properties": {
"title": [
[
"Is all item more than 100",
[
[
"b"
]
]
]
]
},
"type": "text",
"version": 1
}
},
"5545d447-266e-4811-80b7-e07001a2c4aa": {
"role": "comment_only",
"value": {
"alive": true,
"created_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
"created_time": 1552022241309,
"id": "5545d447-266e-4811-80b7-e07001a2c4aa",
"ignore_block_count": true,
"last_edited_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
"last_edited_time": 1552022241309,
"parent_id": "ad5565a3-c036-48c6-ab91-13a461a71835",
"parent_table": "block",
"properties": {
"language": [
[
"Plain Text"
]
],
"title": [
[
"$result = array_reduce([101, 230, 210, 341, 251], function($carry, $item){\n return $carry \u0026\u0026 $item \u003e 100;\n}, true); //default value must set true"
]
]
},
"type": "code",
"version": 1
}
},
"6be19234-b37a-42ec-8f63-3d3bb2f7be0e": {
"role": "comment_only",
"value": {
"alive": true,
"created_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
"created_time": 1552022241309,
"id": "6be19234-b37a-42ec-8f63-3d3bb2f7be0e",
"ignore_block_count": true,
"last_edited_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
"last_edited_time": 1552022241309,
"parent_id": "ad5565a3-c036-48c6-ab91-13a461a71835",
"parent_table": "block",
"properties": {
"title": [
[
"Is any item less than 100",
[
[
"b"
]
]
]
]
},
"type": "text",
"version": 1
}
},
"6ed9b7ce-da9d-4a19-95b2-d68919664bd1": {
"role": "comment_only",
"value": {
"alive": true,
"created_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
"created_time": 1552022241309,
"id": "6ed9b7ce-da9d-4a19-95b2-d68919664bd1",
"ignore_block_count": true,
"last_edited_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
"last_edited_time": 1552022241309,
"parent_id": "ad5565a3-c036-48c6-ab91-13a461a71835",
"parent_table": "block",
"properties": {
"title": [
[
"result:"
],
[
"true",
[
[
"c"
]
]
]
]
},
"type": "text",
"version": 1
}
},
"8dbd4774-4876-4d79-977b-aa03fb6801df": {
"role": "comment_only",
"value": {
"alive": true,
"created_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
"created_time": 1552022241308,
"id": "8dbd4774-4876-4d79-977b-aa03fb6801df",
"ignore_block_count": true,
"last_edited_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
"last_edited_time": 1552022241308,
"parent_id": "ad5565a3-c036-48c6-ab91-13a461a71835",
"parent_table": "block",
"properties": {
"language": [
[
"Plain Text"
]
],
"title": [
[
"$result = array_reduce([10, 23, 211, 34, 25], function($carry, $item){\n return $item \u003e $carry ? $item : $carry;\n});"
]
]
},
"type": "code",
"version": 1
}
},
"9047299c-8753-416a-aea8-6d7bf62f856a": {
"role": "comment_only",
"value": {
"alive": true,
"created_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
"created_time": 1552022241307,
"id": "9047299c-8753-416a-aea8-6d7bf62f856a",
"ignore_block_count": true,
"last_edited_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
"last_edited_time": 1552022241307,
"parent_id": "ad5565a3-c036-48c6-ab91-13a461a71835",
"parent_table": "block",
"properties": {
"title": [
[
"Usage: "
],
[
"array_reduce ($array, function($carry, $item){...}, $defaul_value_of_first_carry)",
[
[
"c"
]
]
]
]
},
"type": "text",
"version": 1
}
},
"93a3c562-706a-40f0-9e62-a6394389d198": {
"role": "comment_only",
"value": {
"alive": true,
"created_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
"created_time": 1552022241309,
"id": "93a3c562-706a-40f0-9e62-a6394389d198",
"ignore_block_count": true,
"last_edited_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
"last_edited_time": 1552022241309,
"parent_id": "ad5565a3-c036-48c6-ab91-13a461a71835",
"parent_table": "block",
"properties": {
"language": [
[
"Plain Text"
]
],
"title": [
[
"$result = array_reduce([\"hello\", \"world\", \"PHP\", \"language\"], function($carry, $item){\n return !$carry ? $item : $carry . \"-\" . $item ;\n});"
]
]
},
"type": "code",
"version": 1
}
},
"9fb27cd9-41fe-48f2-86bd-87e64c1f6458": {
"role": "comment_only",
"value": {
"alive": true,
"created_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
"created_time": 1552022241308,
"id": "9fb27cd9-41fe-48f2-86bd-87e64c1f6458",
"ignore_block_count": true,
"last_edited_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
"last_edited_time": 1552022241308,
"parent_id": "ad5565a3-c036-48c6-ab91-13a461a71835",
"parent_table": "block",
"properties": {
"title": [
[
"The largest number in array",
[
[
"b"
]
]
]
]
},
"type": "text",
"version": 1
}
},
"aa05a5b8-5d89-4178-b3ab-aa7e0cc4a038": {
"role": "comment_only",
"value": {
"alive": true,
"created_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
"created_time": 1552022241308,
"id": "aa05a5b8-5d89-4178-b3ab-aa7e0cc4a038",
"ignore_block_count": true,
"last_edited_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
"last_edited_time": 1552022241308,
"parent_id": "ad5565a3-c036-48c6-ab91-13a461a71835",
"parent_table": "block",
"properties": {
"title": [
[
"result:"
],
[
"15",
[
[
"c"
]
]
]
]
},
"type": "text",
"version": 1
}
},
"ad5565a3-c036-48c6-ab91-13a461a71835": {
"role": "comment_only",
"value": {
"alive": true,
"content": [
"fbcc00fb-7f44-4f6f-a644-482e73cd33b3",
"9047299c-8753-416a-aea8-6d7bf62f856a",
"e9eb8298-7d71-4ab0-bfdf-25db390ad74f",
"165cc8aa-d2b6-42a7-a917-dcb0de3276ea",
"fac6efa8-ee61-4ba1-b035-6e43a3d289dc",
"4b227b86-8bb9-44a0-88d6-b87594b00cfa",
"aa05a5b8-5d89-4178-b3ab-aa7e0cc4a038",
"9fb27cd9-41fe-48f2-86bd-87e64c1f6458",
"8dbd4774-4876-4d79-977b-aa03fb6801df",
"2be21f73-426b-4e4e-92e4-e15cd525e252",
"4f1e7a9f-ad17-40fb-85a0-1a57b0ea8d9f",
"5545d447-266e-4811-80b7-e07001a2c4aa",
"6ed9b7ce-da9d-4a19-95b2-d68919664bd1",
"6be19234-b37a-42ec-8f63-3d3bb2f7be0e",
"223d7495-1bb3-4167-bb52-e493945f3a22",
"24200e3a-a614-40f4-8ee1-bb2630c541d6",
"cc237566-fb77-404b-908b-c732c4cf75db",
"93a3c562-706a-40f0-9e62-a6394389d198",
"b2674bcd-760c-4740-a21b-b12adb6862c3",
"be1899d6-151f-4a90-af74-84b5474e4ad9",
"24bfd5e1-341b-4251-971b-dd6647eead45",
"ceb6048a-3be2-4b9a-9a12-d58a569e65c0"
],
"created_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
"created_time": 1552022241310,
"format": {
"page_full_width": true,
"page_small_text": true
},
"id": "ad5565a3-c036-48c6-ab91-13a461a71835",
"ignore_block_count": true,
"last_edited_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
"last_edited_time": 1552022241310,
"parent_id": "eb584d64-0967-460c-a9f1-9d66ff8697ea",
"parent_table": "block",
"properties": {
"title": [
[
"array reduce"
]
]
},
"type": "page",
"version": 3
}
},
"b2674bcd-760c-4740-a21b-b12adb6862c3": {
"role": "comment_only",
"value": {
"alive": true,
"created_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
"created_time": 1552022241310,
"id": "b2674bcd-760c-4740-a21b-b12adb6862c3",
"ignore_block_count": true,
"last_edited_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
"last_edited_time": 1552022241310,
"parent_id": "ad5565a3-c036-48c6-ab91-13a461a71835",
"parent_table": "block",
"properties": {
"title": [
[
"result:"
],
[
"\"hello-world-PHP-language\"",
[
[
"c"
]
]
]
]
},
"type": "text",
"version": 1
}
},
"b64d2e8d-06e0-4dbe-a37e-6e7d0e06bb48": {
"role": "comment_only",
"value": {
"alive": true,
"content": [
"517c8074-a37c-44fd-8a9c-fb9f3eae1dcb",
"494832a4-8019-450b-b43e-04be9e23957c",
"eb584d64-0967-460c-a9f1-9d66ff8697ea",
"6427ea2b-9d2c-4408-a6ff-9721a6dc9cdc",
"78acf98d-751b-413c-b0ef-3d520c041518",
"feed5453-5dd0-4311-9546-05916acc717b",
"c21e2838-bb88-4a0b-8677-7fd7990427b3",
"388890af-6e2d-48b5-8627-8159740b2534",
"3df608de-d7c1-4570-8555-90ad35d2817a",
"dd3184e6-59de-418c-9116-ab565faa8a55",
"3f08c649-08b2-4a97-b43f-ac884356a505",
"caabd093-67a6-454d-8e67-b40f2303905b",
"1f2707b9-a751-475a-ba82-519f75e3c8bd",
"7ea927a4-8c64-45ba-9d71-d5d5796e1b71",
"5d759c32-1671-4b6c-9cc1-ad59c031c78c",
"d2ac9d43-0e3b-4077-a4f0-344ab77dce28",
"8e344e73-ab23-422f-9bc5-1b7a660edb69",
"a3705b2a-2c83-4e42-b51b-b58874cdba41",
"8b30ba45-a57e-44b5-b6c2-501af4626d35",
"6feefd3b-c9d8-4156-84d1-a7c4286028c7",
"7862f22e-1011-4a4b-8afd-26b9317e46e3",
"27de0930-be0d-4503-9a9b-05150c7d754e",
"fcd7e413-e4c3-42f0-b0c5-7a7685e669ee",
"37215ea5-9547-43fb-89a7-dc17d26d5671",
"10044815-3b9e-4513-8fa0-812a9957a6cc",
"73d52685-2f50-4a6a-b764-7a1742062923",
"2aee6dcb-0989-4be0-82bb-e36362381d91",
"a5af103b-d852-4d05-b5ed-007e9bc6dac6",
"0f9ca6e7-305f-414a-9ea4-796bcec6a74b",
"640a427d-f7cc-4181-99da-abc56c0ee5c7",
"6358c964-0c94-4f8a-a8f5-0b120eed603b",
"a2437364-c680-4790-94d6-bb7afe6bbac0",
"2a04f54f-cf44-4cd5-bb37-8dc6b9f2f1bd",
"98823712-1c98-4a43-8727-0a1d762add3b",
"d5ddf8b7-ebe7-43b3-ab49-22492b9f0565",
"80fa00b7-710d-4ce0-a406-927876f8600b",
"1f9d9197-defa-432c-bc3d-187124d72a2f",
"dac99271-1f4b-46ca-8985-d6ddd65e5190",
"8c42d3d9-a3bc-48da-bce0-bdcb3b7ce79c",
"b27336d9-e12f-4163-b64c-0f3bd43d13e4",
"ee791784-c85f-4e7b-a57d-79d4a1fcce89",
"ca285753-71c7-41a9-b880-7bf2da161416",
"75659e2f-e309-433d-9258-b76662aeb4fb",
"9507d5d1-9e19-423b-bb30-e7776757fd1a",
"c2cfe994-4a4e-42a5-a1f3-29b806f5c459",
"60c1d051-8c78-4c95-aa4e-d6680ae7e1ed",
"39389e18-4435-40d2-be30-84d806209e25",
"0eabffb2-1a8c-43e6-b5d0-24c02329f9d1",
"c09beb38-7179-42f3-a2d1-f4b433238aa0",
"e738bef3-04ad-47b8-abdb-d2ff70319024",
"20bc9dce-d534-40ff-a8c3-c05e75afd5f6",
"4bba2444-204c-4803-8e80-ee10663d08c2",
"0a6069ee-9200-41b9-b90f-af0e866b3798",
"8aad07a8-ece6-477b-8cf0-8ad575a906a8",
"f0aa9c04-6b09-48e8-9f6d-39195ed864c6",
"cfd0d40b-7b07-441c-bde3-a5be0d2be41b",
"d4c8c201-7f26-48eb-a78f-b18c68723b03",
"f49c9bfd-2029-4200-9a4b-8089d428dd89",
"0fddad86-8858-4ff5-84b9-18129c56229f",
"34fff563-be44-4c2d-9eb5-6171986332d6",
"6ba36b23-f2c3-4c8b-a9cc-1cf9cb37def5",
"0dddc90f-f179-4221-bf9c-4b41d349abb0",
"beea7707-e1f5-4975-b2c8-ded58a7e3771",
"98e7c9aa-afb7-47fa-8982-4cbc37642c6c",
"19d3a490-e861-442a-bbf8-30380bc306b7",
"d8cdf9b0-ae04-41c2-ba75-67fe799b9269",
"d5631366-098b-4c90-b10a-4c27cda07738",
"50dc657c-d5c2-4a7b-9bac-a72649a034bc",
"fd667c80-db70-416a-827b-b1c047fdcd5a",
"681c5601-034f-4549-9a89-5da2da43ed1e",
"7bb5ac60-6cd4-4c77-b217-3d3c51d66ecc",
"057eb94f-bb82-4152-b310-dbb929c85b35",
"5c659a09-6a5a-44b5-88cd-2ab2cf5e69de",
"7c52c9fa-ae12-4339-a606-1e3e64a5e440",
"cee10c4b-aca3-4ae1-bef8-0e0c7958d06b",
"8790e424-131f-482d-9f67-2821001d711f",
"e4e32393-007a-4cd6-b1f8-27b0cb8545c5",
"a7c4d158-bfc6-4651-b97b-cf5908cb435e",
"0933ee85-f73c-456d-a664-05037c9050a2",
"fdac48d7-3a67-46af-8280-cb49d3eb2900",
"1ee62efb-a132-4463-ad88-13047e39701a",
"3bb8f2d9-3a30-426a-90e4-c8d89d2b2785",
"e0331f63-7a2f-4805-a18a-faecbe9cbd66",
"3e614d87-5020-40dc-9e8e-4af5ace88042",
"68a6b5ab-d251-4ea1-82a1-afa23f2b4071",
"99767f42-6259-4914-8dc4-5d6b25fdc196",
"8d36e04e-03e7-4133-81d8-8932cbbd4bc0",
"f74395f5-0fb4-4a16-adfe-cd4f56f1c218",
"82837995-7012-4d5d-a90f-fdf5f95771a1",
"88347a4f-4632-4e18-a9bb-6ff61df8922d",
"bd21e71f-9d9e-48dc-be35-e136a9a8c144",
"742d5ccb-5b6b-4d47-bb6c-9800fd80a6d3",
"92dec6b9-c8e9-44be-866a-e1b7eb1d9074",
"b8e79283-d1b6-4848-b988-973df27cf924",
"a6892b0f-5fd3-4ff3-8ab1-0f05027fe043",
"310dc1a9-743f-4997-aa0b-041e5451e745",
"29536388-77ef-4997-9c01-5894e8dbf0b6",
"09eab12d-0e6a-4f5d-981a-e20def142720",
"7b8f9cbd-f897-407c-94d7-825654c81800",
"8f27b6c2-32e0-46fe-9052-1bece702489a",
"f2cbf97f-76bf-4894-b8a7-9b36dbdaa986",
"c2d0558a-e174-47cc-b309-c640ed3984b2",
"1765cb3f-cdf2-4b3e-941e-3d64128527a6",
"9272c5f6-725a-4a1d-9d6a-bcf68f821ab7",
"14002421-cb79-46f2-bd72-40d37b882ed2",
"24526f5c-fac3-443f-911e-e2c72b4c6749",
"3665ae32-4323-4b83-a8e7-dc3122f82218",
"a00936a6-0a0a-4bf3-9db5-563f85e34db0",
"6b2e4928-558c-43b9-8be4-fe720bf21677"
],
"created_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
"created_time": 1552022174667,
"format": {
"page_full_width": true,
"page_small_text": true
},
"id": "b64d2e8d-06e0-4dbe-a37e-6e7d0e06bb48",
"last_edited_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
"last_edited_time": 1553725920000,
"parent_id": "8be972f2-13d4-403a-b7f8-c74e60f7639f",
"parent_table": "block",
"permissions": [
{
"allow_search_engine_indexing": false,
"role": "comment_only",
"type": "public_permission"
}
],
"properties": {
"title": [
[
"Essential PHP"
]
]
},
"type": "page",
"version": 170
}
},
"be1899d6-151f-4a90-af74-84b5474e4ad9": {
"role": "comment_only",
"value": {
"alive": true,
"created_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
"created_time": 1552022241310,
"id": "be1899d6-151f-4a90-af74-84b5474e4ad9",
"ignore_block_count": true,
"last_edited_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
"last_edited_time": 1552022241310,
"parent_id": "ad5565a3-c036-48c6-ab91-13a461a71835",
"parent_table": "block",
"properties": {
"title": [
[
"if make a implode method, the source code will be :"
]
]
},
"type": "text",
"version": 1
}
},
"cc237566-fb77-404b-908b-c732c4cf75db": {
"role": "comment_only",
"value": {
"alive": true,
"created_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
"created_time": 1552022241309,
"id": "cc237566-fb77-404b-908b-c732c4cf75db",
"ignore_block_count": true,
"last_edited_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
"last_edited_time": 1552022241309,
"parent_id": "ad5565a3-c036-48c6-ab91-13a461a71835",
"parent_table": "block",
"properties": {
"title": [
[
"Like implode($array, $piece)",
[
[
"b"
]
]
]
]
},
"type": "text",
"version": 1
}
},
"ceb6048a-3be2-4b9a-9a12-d58a569e65c0": {
"role": "comment_only",
"value": {
"alive": true,
"created_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
"created_time": 1552022241310,
"id": "ceb6048a-3be2-4b9a-9a12-d58a569e65c0",
"ignore_block_count": true,
"last_edited_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
"last_edited_time": 1552022241310,
"parent_id": "ad5565a3-c036-48c6-ab91-13a461a71835",
"parent_table": "block",
"properties": {
"title": [
[
"result:"
],
[
"\"hello-world-PHP-language\"",
[
[
"c"
]
]
]
]
},
"type": "text",
"version": 1
}
},
"e9eb8298-7d71-4ab0-bfdf-25db390ad74f": {
"role": "comment_only",
"value": {
"alive": true,
"created_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
"created_time": 1552022241307,
"id": "e9eb8298-7d71-4ab0-bfdf-25db390ad74f",
"ignore_block_count": true,
"last_edited_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
"last_edited_time": 1552022241307,
"parent_id": "ad5565a3-c036-48c6-ab91-13a461a71835",
"parent_table": "block",
"properties": {
"title": [
[
"$carry is the result from the last round of iteration."
]
]
},
"type": "bulleted_list",
"version": 1
}
},
"eb584d64-0967-460c-a9f1-9d66ff8697ea": {
"role": "comment_only",
"value": {
"alive": true,
"content": [
"251fa25c-766e-46e9-a3ac-a75cd976c839",
"d2d6d384-c9cd-473e-815b-40bdc1eaecbd",
"b88ba8d3-76c3-4505-b697-8d2640a622a2",
"f381ba42-bebd-4a54-84b7-c19c72c0830c",
"7645aaaa-44e2-40d4-94a3-eb504d93cd82",
"03c6dbda-0b82-49a6-a506-43b502e30a14",
"5be1fb18-f6ef-4265-b69e-bdb6c7b86a64",
"fc44eedb-d34d-4ba3-9744-831936154de2",
"d66b4550-8fd0-40dc-b7f7-c25d46b45364",
"d7292e5e-bb03-415c-92cb-8d0e7569b66f",
"e641c963-c933-4033-8197-aadf5f54312d",
"778a7987-9ef0-45fc-8953-8dc8c9e07813",
"231b8cd1-e446-489f-9506-4b7d83466a8c",
"e1e98474-edd7-4837-a49b-ccd77a0b082c",
"21ecda2f-c72e-4efd-8b25-3470f043185b",
"ddd2b3f7-5360-4b3d-91cf-c1475ad67e5d",
"adf6fbb4-3ac0-47bf-b9e8-ff74d34ab1aa",
"a0644b35-0e61-41db-8203-d13873c1da8a",
"e846192c-8ea6-46d4-9e7c-f2cd8d9ad110",
"fa6d7267-f9cc-4897-acf7-df463d641324",
"433d843c-3cda-483a-8a5e-2c3de099b8c2",
"ad5565a3-c036-48c6-ab91-13a461a71835",
"77eadb7e-e30b-4f12-b1ed-5832d4b49415"
],
"created_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
"created_time": 1552022220000,
"format": {
"page_full_width": true,
"page_small_text": true
},
"id": "eb584d64-0967-460c-a9f1-9d66ff8697ea",
"last_edited_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
"last_edited_time": 1552022520000,
"parent_id": "b64d2e8d-06e0-4dbe-a37e-6e7d0e06bb48",
"parent_table": "block",
"permissions": [
{
"role": "editor",
"type": "user_permission",
"user_id": "bb760e2d-d679-4b64-b2a9-03005b21870a"
}
],
"properties": {
"title": [
[
"Arrays"
]
]
},
"type": "page",
"version": 38
}
},
"fac6efa8-ee61-4ba1-b035-6e43a3d289dc": {
"role": "comment_only",
"value": {
"alive": true,
"created_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
"created_time": 1552022241308,
"id": "fac6efa8-ee61-4ba1-b035-6e43a3d289dc",
"ignore_block_count": true,
"last_edited_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
"last_edited_time": 1552022241308,
"parent_id": "ad5565a3-c036-48c6-ab91-13a461a71835",
"parent_table": "block",
"properties": {
"title": [
[
"Sum of array",
[
[
"b"
]
]
]
]
},
"type": "text",
"version": 1
}
},
"fbcc00fb-7f44-4f6f-a644-482e73cd33b3": {
"role": "comment_only",
"value": {
"alive": true,
"created_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
"created_time": 1552022241304,
"id": "fbcc00fb-7f44-4f6f-a644-482e73cd33b3",
"ignore_block_count": true,
"last_edited_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
"last_edited_time": 1552022241304,
"parent_id": "ad5565a3-c036-48c6-ab91-13a461a71835",
"parent_table": "block",
"properties": {
"title": [
[
"array_reduce",
[
[
"c"
]
]
],
[
" reduces array into a single value. Basically, The "
],
[
"array_reduce",
[
[
"c"
]
]
],
[
" will go through every item with the result from last iteration and produce new value to the next iteration."
]
]
},
"type": "text",
"version": 1
}
}
},
"notion_user": {
"bb760e2d-d679-4b64-b2a9-03005b21870a": {
"role": "reader",
"value": {
"clipper_onboarding_completed": true,
"email": "[email protected]",
"family_name": "Kowalczyk",
"given_name": "Krzysztof",
"id": "bb760e2d-d679-4b64-b2a9-03005b21870a",
"mobile_onboarding_completed": true,
"onboarding_completed": true,
"profile_photo": "https://s3-us-west-2.amazonaws.com/public.notion-static.com/2dcaa66c-7674-4ff6-9924-601785b63561/head-bw-640x960.png",
"version": 179
}
}
},
"space": {}
}
}
| {
"pile_set_name": "Github"
} |
use super::{L2rUser, Options, Result};
use super::{PeerConstructor, ProgramState};
use std;
use std::cell::RefCell;
use std::rc::Rc;
pub enum ClassMessageBoundaryStatus {
StreamOriented,
MessageOriented,
MessageBoundaryStatusDependsOnInnerType,
}
pub enum ClassMulticonnectStatus {
MultiConnect,
SingleConnect,
MulticonnectnessDependsOnInnerType,
}
/// A trait for a each specified type's accompanying object
///
/// Don't forget to register each instance at the `list_of_all_specifier_classes` macro.
pub trait SpecifierClass: std::fmt::Debug {
/// The primary name of the class
fn get_name(&self) -> &'static str;
/// Names to match command line parameters against, with a `:` colon if needed
fn get_prefixes(&self) -> Vec<&'static str>;
/// --long-help snippet about this specifier
fn help(&self) -> &'static str;
/// Given the command line text, construct the specifier
/// arg is what comes after the colon (e.g. `//echo.websocket.org` in `ws://echo.websocket.org`)
fn construct(&self, arg: &str) -> Result<Rc<dyn Specifier>>;
/// Given the inner specifier, construct this specifier.
fn construct_overlay(&self, inner: Rc<dyn Specifier>) -> Result<Rc<dyn Specifier>>;
/// Returns if this specifier is an overlay
fn is_overlay(&self) -> bool;
/// True if it is not expected to preserve message boundaries on reads
fn message_boundary_status(&self) -> ClassMessageBoundaryStatus;
fn multiconnect_status(&self) -> ClassMulticonnectStatus;
/// If it is Some then is_overlay, construct and most other things are ignored and prefix get replaced...
fn alias_info(&self) -> Option<&'static str>;
}
macro_rules! specifier_alias {
(name=$n:ident,
prefixes=[$($p:expr),*],
alias=$x:expr,
help=$h:expr) => {
#[derive(Debug,Default)]
pub struct $n;
impl $crate::SpecifierClass for $n {
fn get_name(&self) -> &'static str { stringify!($n) }
fn get_prefixes(&self) -> Vec<&'static str> { vec![$($p),*] }
fn help(&self) -> &'static str { $h }
fn message_boundary_status(&self) -> $crate::ClassMessageBoundaryStatus {
panic!("Error: message_boundary_status called on alias class")
}
fn multiconnect_status(&self) -> $crate::ClassMulticonnectStatus {
panic!("Error: multiconnect_status called on alias class")
}
fn is_overlay(&self) -> bool {
false
}
fn construct(&self, _arg:&str) -> $crate::Result<Rc<dyn Specifier>> {
panic!("Error: construct called on alias class")
}
fn construct_overlay(&self, _inner : Rc<dyn Specifier>) -> $crate::Result<Rc<dyn Specifier>> {
panic!("Error: construct_overlay called on alias class")
}
fn alias_info(&self) -> Option<&'static str> { Some($x) }
}
};
}
macro_rules! specifier_class {
(name=$n:ident,
target=$t:ident,
prefixes=[$($p:expr),*],
arg_handling=$c:tt,
overlay=$o:expr,
$so:expr,
$ms:expr,
help=$h:expr) => {
#[derive(Debug,Default)]
pub struct $n;
impl $crate::SpecifierClass for $n {
fn get_name(&self) -> &'static str { stringify!($n) }
fn get_prefixes(&self) -> Vec<&'static str> { vec![$($p),*] }
fn help(&self) -> &'static str { $h }
fn message_boundary_status(&self) -> $crate::ClassMessageBoundaryStatus {
use $crate::ClassMessageBoundaryStatus::*;
$so
}
fn multiconnect_status(&self) -> $crate::ClassMulticonnectStatus {
use $crate::ClassMulticonnectStatus::*;
$ms
}
fn is_overlay(&self) -> bool {
$o
}
specifier_class!(construct target=$t $c);
}
};
(construct target=$t:ident noarg) => {
fn construct(&self, just_arg:&str) -> $crate::Result<Rc<dyn Specifier>> {
if just_arg != "" {
Err(format!("{}-specifer requires no parameters. `{}` is not needed",
self.get_name(), just_arg))?;
}
Ok(Rc::new($t))
}
fn construct_overlay(&self, _inner : Rc<dyn Specifier>) -> $crate::Result<Rc<dyn Specifier>> {
panic!("Error: construct_overlay called on non-overlay specifier class")
}
fn alias_info(&self) -> Option<&'static str> { None }
};
(construct target=$t:ident into) => {
fn construct(&self, just_arg:&str) -> $crate::Result<Rc<dyn Specifier>> {
Ok(Rc::new($t(just_arg.into())))
}
fn construct_overlay(&self, _inner : Rc<dyn Specifier>) -> $crate::Result<Rc<dyn Specifier>> {
panic!("Error: construct_overlay called on non-overlay specifier class")
}
fn alias_info(&self) -> Option<&'static str> { None }
};
(construct target=$t:ident parse) => {
fn construct(&self, just_arg:&str) -> $crate::Result<Rc<dyn Specifier>> {
Ok(Rc::new($t(just_arg.parse()?)))
}
fn construct_overlay(&self, _inner : Rc<dyn Specifier>) -> $crate::Result<Rc<dyn Specifier>> {
panic!("Error: construct_overlay called on non-overlay specifier class")
}
fn alias_info(&self) -> Option<&'static str> { None }
};
(construct target=$t:ident parseresolve) => {
fn construct(&self, just_arg:&str) -> $crate::Result<Rc<dyn Specifier>> {
use std::net::ToSocketAddrs;
info!("Resolving hostname to IP addresses");
let addrs : Vec<std::net::SocketAddr> = just_arg.to_socket_addrs()?.collect();
if addrs.is_empty() {
Err("Failed to resolve this hostname to IP")?;
}
for addr in &addrs {
info!("Got IP: {}", addr);
}
Ok(Rc::new($t(addrs)))
}
fn construct_overlay(&self, _inner : Rc<dyn Specifier>) -> $crate::Result<Rc<dyn Specifier>> {
panic!("Error: construct_overlay called on non-overlay specifier class")
}
fn alias_info(&self) -> Option<&'static str> { None }
};
(construct target=$t:ident subspec) => {
fn construct(&self, just_arg:&str) -> $crate::Result<Rc<dyn Specifier>> {
Ok(Rc::new($t($crate::spec(just_arg)?)))
}
fn construct_overlay(&self, _inner : Rc<dyn Specifier>) -> $crate::Result<Rc<dyn Specifier>> {
Ok(Rc::new($t(_inner)))
}
fn alias_info(&self) -> Option<&'static str> { None }
};
(construct target=$t:ident {$($x:tt)*}) => {
$($x)*
fn alias_info(&self) -> Option<&'static str> { None }
};
}
#[derive(Debug)]
pub struct SpecifierNode {
pub cls: Rc<dyn SpecifierClass>,
//pub opt: Rc<std::any::Any>,
}
#[derive(Debug)]
pub struct SpecifierStack {
pub addr: String,
pub addrtype: SpecifierNode,
pub overlays: Vec<SpecifierNode>,
}
#[derive(Clone)]
pub struct ConstructParams {
pub global_state: Rc<RefCell<ProgramState>>,
pub program_options: Rc<Options>,
pub left_to_right: L2rUser,
}
/// All of those methods are about left_to_right mechanism
impl ConstructParams {
/// Reset left_to_right to default value.
pub fn reset_l2r(&mut self) {
match self.left_to_right {
L2rUser::FillIn(ref mut x) => {
*x.borrow_mut() = Default::default();
//*x = Rc::new(RefCell::new(Default::default()));
}
L2rUser::ReadFrom(_) => panic!("ConstructParams::reset_l2r called wrong"),
}
}
/// Clones ConstructParams, changing FillIn to ReadFrom in left_to_right field
/// and also disassociating it from the original RefCell.
///
/// Panics when called on object with left_to_right set to ReadFrom.
pub fn reply(&self) -> Self {
let l2r = match self.left_to_right {
L2rUser::FillIn(ref x) => Rc::new(x.borrow().clone()),
L2rUser::ReadFrom(_) => panic!("ConstructParams::reply called wrong"),
};
ConstructParams {
global_state: self.global_state.clone(),
program_options: self.program_options.clone(),
left_to_right: L2rUser::ReadFrom(l2r),
}
}
pub fn deep_clone(&self) -> Self {
let l2r = match self.left_to_right {
L2rUser::FillIn(ref x) => L2rUser::FillIn(Rc::new(RefCell::new(x.borrow().clone()))),
L2rUser::ReadFrom(_) => {
panic!(
"You are not supposed to use ConstructParams::deep_clone on ReadFrom things"
);
}
};
ConstructParams {
global_state: self.global_state.clone(),
program_options: self.program_options.clone(),
left_to_right: l2r,
}
}
/// Access specified-specific global (singleton) data
pub fn global<T:std::any::Any, F>(&self, def:F) -> std::cell::RefMut<T>
where F : FnOnce()->T
{
std::cell::RefMut::map(
self.global_state.borrow_mut(),
|x|{
x.0.entry().or_insert(def())
}
)
}
}
/// A parsed command line argument.
/// For example, `ws-listen:tcp-l:127.0.0.1:8080` gets parsed into
/// a `WsUpgrade(TcpListen(SocketAddr))`.
pub trait Specifier: std::fmt::Debug {
/// Apply the specifier for constructing a "socket" or other connecting device.
fn construct(&self, p: ConstructParams) -> PeerConstructor;
// Specified by `specifier_boilerplate!`:
fn is_multiconnect(&self) -> bool;
fn uses_global_state(&self) -> bool;
}
impl Specifier for Rc<dyn Specifier> {
fn construct(&self, p: ConstructParams) -> PeerConstructor {
(**self).construct(p)
}
fn is_multiconnect(&self) -> bool {
(**self).is_multiconnect()
}
fn uses_global_state(&self) -> bool {
(**self).uses_global_state()
}
}
macro_rules! specifier_boilerplate {
(singleconnect $($e:tt)*) => {
fn is_multiconnect(&self) -> bool { false }
specifier_boilerplate!($($e)*);
};
(multiconnect $($e:tt)*) => {
fn is_multiconnect(&self) -> bool { true }
specifier_boilerplate!($($e)*);
};
(no_subspec $($e:tt)*) => {
specifier_boilerplate!($($e)*);
};
(has_subspec $($e:tt)*) => {
specifier_boilerplate!($($e)*);
};
() => {
};
(globalstate $($e:tt)*) => {
fn uses_global_state(&self) -> bool { true }
specifier_boilerplate!($($e)*);
};
(noglobalstate $($e:tt)*) => {
fn uses_global_state(&self) -> bool { false }
specifier_boilerplate!($($e)*);
};
}
macro_rules! self_0_is_subspecifier {
(...) => {
// removed with old linter
};
(proxy_is_multiconnect) => {
self_0_is_subspecifier!(...);
fn is_multiconnect(&self) -> bool { self.0.is_multiconnect() }
};
}
| {
"pile_set_name": "Github"
} |
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactInjection
*/
'use strict';
var DOMProperty = require('DOMProperty');
var EventPluginHub = require('EventPluginHub');
var ReactComponentEnvironment = require('ReactComponentEnvironment');
var ReactClass = require('ReactClass');
var ReactEmptyComponent = require('ReactEmptyComponent');
var ReactBrowserEventEmitter = require('ReactBrowserEventEmitter');
var ReactNativeComponent = require('ReactNativeComponent');
var ReactDOMComponent = require('ReactDOMComponent');
var ReactPerf = require('ReactPerf');
var ReactRootIndex = require('ReactRootIndex');
var ReactUpdates = require('ReactUpdates');
var ReactInjection = {
Component: ReactComponentEnvironment.injection,
Class: ReactClass.injection,
DOMComponent: ReactDOMComponent.injection,
DOMProperty: DOMProperty.injection,
EmptyComponent: ReactEmptyComponent.injection,
EventPluginHub: EventPluginHub.injection,
EventEmitter: ReactBrowserEventEmitter.injection,
NativeComponent: ReactNativeComponent.injection,
Perf: ReactPerf.injection,
RootIndex: ReactRootIndex.injection,
Updates: ReactUpdates.injection,
};
module.exports = ReactInjection;
| {
"pile_set_name": "Github"
} |
项目地址:https://github.com/skratchdot/open-golang<br>
项目作用:代码直接打开浏览器、文件等。<br>
使用方式:
```go
open.Run("https://github.com/xmge/gonote")
etc...
``` | {
"pile_set_name": "Github"
} |
from envi.archs.z80.regs import *
from envi.archs.z80.const import *
# (patrn,mask), mnem, o1type, o1info, o2type, o2info, oplen, immoff, iflags
z80table = [
(('00', 'ff'), 'nop', None, None, None, None, 1, 0, 0),
(('010000', 'ff0000'), 'ld', OPTYPE_Reg, REG_BC, OPTYPE_imm16, None, 3, 1, 0),
(('02', 'ff'), 'ld', OPTYPE_RegMem, REG_BC, OPTYPE_Reg, REG_A, 1, 0, 0),
(('03', 'ff'), 'inc', OPTYPE_Reg, REG_BC, None, None, 1, 0, 0),
(('04', 'ff'), 'inc', OPTYPE_Reg, REG_B, None, None, 1, 0, 0),
(('05', 'ff'), 'dec', OPTYPE_Reg, REG_B, None, None, 1, 0, 0),
(('0600', 'ff00'), 'ld', OPTYPE_Reg, REG_B, OPTYPE_imm8, None, 2, 1, 0),
(('07', 'ff'), 'rlca', None, None, None, None, 1, 0, 0),
(('08', 'ff'), 'ex', OPTYPE_Reg, REG_AF, OPTYPE_RegAlt, REG_AF, 1, 0, 0),
(('09', 'ff'), 'add', OPTYPE_Reg, REG_HL, OPTYPE_Reg, REG_BC, 1, 0, 0),
(('0a', 'ff'), 'ld', OPTYPE_Reg, REG_A, OPTYPE_RegMem, REG_BC, 1, 0, 0),
(('0b', 'ff'), 'dec', OPTYPE_Reg, REG_BC, None, None, 1, 0, 0),
(('0c', 'ff'), 'inc', OPTYPE_Reg, REG_C, None, None, 1, 0, 0),
(('0d', 'ff'), 'dec', OPTYPE_Reg, REG_C, None, None, 1, 0, 0),
(('0e00', 'ff00'), 'ld', OPTYPE_Reg, REG_C, OPTYPE_imm8, None, 2, 1, 0),
(('0f', 'ff'), 'rrca', None, None, None, None, 1, 0, 0),
(('1000', 'ff00'), 'djnz', OPTYPE_Ind, None, None, None, 2, 1, 0),
(('110000', 'ff0000'), 'ld', OPTYPE_Reg, REG_DE, OPTYPE_imm16, None, 3, 1, 0),
(('12', 'ff'), 'ld', OPTYPE_RegMem, REG_DE, OPTYPE_Reg, REG_A, 1, 0, 0),
(('13', 'ff'), 'inc', OPTYPE_Reg, REG_DE, None, None, 1, 0, 0),
(('14', 'ff'), 'inc', OPTYPE_Reg, REG_D, None, None, 1, 0, 0),
(('15', 'ff'), 'dec', OPTYPE_Reg, REG_D, None, None, 1, 0, 0),
(('1600', 'ff00'), 'ld', OPTYPE_Reg, REG_D, OPTYPE_imm8, None, 2, 1, 0),
(('17', 'ff'), 'rla', None, None, None, None, 1, 0, 0),
(('1800', 'ff00'), 'jr', OPTYPE_Ind, None, None, None, 2, 1, 0),
(('19', 'ff'), 'add', OPTYPE_Reg, REG_HL, OPTYPE_Reg, REG_DE, 1, 0, 0),
(('1a', 'ff'), 'ld', OPTYPE_Reg, REG_A, OPTYPE_RegMem, REG_DE, 1, 0, 0),
(('1b', 'ff'), 'dec', OPTYPE_Reg, REG_DE, None, None, 1, 0, 0),
(('1c', 'ff'), 'inc', OPTYPE_Reg, REG_E, None, None, 1, 0, 0),
(('1d', 'ff'), 'dec', OPTYPE_Reg, REG_E, None, None, 1, 0, 0),
(('1e00', 'ff00'), 'ld', OPTYPE_Reg, REG_E, OPTYPE_imm8, None, 2, 1, 0),
(('1f', 'ff'), 'rra', None, None, None, None, 1, 0, 0),
(('2000', 'ff00'), 'jr', OPTYPE_Cond, COND_NZ, OPTYPE_Ind, None, 2, 1, 0),
(('210000', 'ff0000'), 'ld', OPTYPE_Reg, REG_HL, OPTYPE_imm16, None, 3, 1, 0),
(('220000', 'ff0000'), 'ld', OPTYPE_immmem16, None, OPTYPE_Reg, REG_HL, 3, 1, 0),
(('23', 'ff'), 'inc', OPTYPE_Reg, REG_HL, None, None, 1, 0, 0),
(('24', 'ff'), 'inc', OPTYPE_Reg, REG_H, None, None, 1, 0, 0),
(('25', 'ff'), 'dec', OPTYPE_Reg, REG_H, None, None, 1, 0, 0),
(('2600', 'ff00'), 'ld', OPTYPE_Reg, REG_H, OPTYPE_imm8, None, 2, 1, 0),
(('27', 'ff'), 'daa', None, None, None, None, 1, 0, 0),
(('2800', 'ff00'), 'jr', OPTYPE_Cond, COND_Z, OPTYPE_Ind, None, 2, 1, 0),
(('29', 'ff'), 'add', OPTYPE_Reg, REG_HL, OPTYPE_Reg, REG_HL, 1, 0, 0),
(('2a0000', 'ff0000'), 'ld', OPTYPE_Reg, REG_HL, OPTYPE_immmem16, None, 3, 1, 0),
(('2b', 'ff'), 'dec', OPTYPE_Reg, REG_HL, None, None, 1, 0, 0),
(('2c', 'ff'), 'inc', OPTYPE_Reg, REG_L, None, None, 1, 0, 0),
(('2d', 'ff'), 'dec', OPTYPE_Reg, REG_L, None, None, 1, 0, 0),
(('2e00', 'ff00'), 'ld', OPTYPE_Reg, REG_L, OPTYPE_imm8, None, 2, 1, 0),
(('2f', 'ff'), 'cpl', None, None, None, None, 1, 0, 0),
(('3000', 'ff00'), 'jr', OPTYPE_Cond, COND_NC, OPTYPE_Ind, None, 2, 1, 0),
(('310000', 'ff0000'), 'ld', OPTYPE_Reg, REG_SP, OPTYPE_imm16, None, 3, 1, 0),
(('320000', 'ff0000'), 'ld', OPTYPE_immmem16, None, OPTYPE_Reg, REG_A, 3, 1, 0),
(('33', 'ff'), 'inc', OPTYPE_Reg, REG_SP, None, None, 1, 0, 0),
(('34', 'ff'), 'inc', OPTYPE_RegMem, REG_HL, None, None, 1, 0, 0),
(('35', 'ff'), 'dec', OPTYPE_RegMem, REG_HL, None, None, 1, 0, 0),
(('3600', 'ff00'), 'ld', OPTYPE_RegMem, REG_HL, OPTYPE_imm8, None, 2, 1, 0),
(('37', 'ff'), 'scf', None, None, None, None, 1, 0, 0),
(('3800', 'ff00'), 'jr', OPTYPE_Cond, COND_C, OPTYPE_Ind, None, 2, 1, 0),
(('39', 'ff'), 'add', OPTYPE_Reg, REG_HL, OPTYPE_Reg, REG_SP, 1, 0, 0),
(('3a0000', 'ff0000'), 'ld', OPTYPE_Reg, REG_A, OPTYPE_immmem16, None, 3, 1, 0),
(('3b', 'ff'), 'dec', OPTYPE_Reg, REG_SP, None, None, 1, 0, 0),
(('3c', 'ff'), 'inc', OPTYPE_Reg, REG_A, None, None, 1, 0, 0),
(('3d', 'ff'), 'dec', OPTYPE_Reg, REG_A, None, None, 1, 0, 0),
(('3e00', 'ff00'), 'ld', OPTYPE_Reg, REG_A, OPTYPE_imm8, None, 2, 1, 0),
(('3f', 'ff'), 'ccf', None, None, None, None, 1, 0, 0),
(('40', 'ff'), 'ld', OPTYPE_Reg, REG_B, OPTYPE_Reg, REG_B, 1, 0, 0),
(('41', 'ff'), 'ld', OPTYPE_Reg, REG_B, OPTYPE_Reg, REG_C, 1, 0, 0),
(('42', 'ff'), 'ld', OPTYPE_Reg, REG_B, OPTYPE_Reg, REG_D, 1, 0, 0),
(('43', 'ff'), 'ld', OPTYPE_Reg, REG_B, OPTYPE_Reg, REG_E, 1, 0, 0),
(('44', 'ff'), 'ld', OPTYPE_Reg, REG_B, OPTYPE_Reg, REG_H, 1, 0, 0),
(('45', 'ff'), 'ld', OPTYPE_Reg, REG_B, OPTYPE_Reg, REG_L, 1, 0, 0),
(('46', 'ff'), 'ld', OPTYPE_Reg, REG_B, OPTYPE_RegMem, REG_HL, 1, 0, 0),
(('47', 'ff'), 'ld', OPTYPE_Reg, REG_B, OPTYPE_Reg, REG_A, 1, 0, 0),
(('48', 'ff'), 'ld', OPTYPE_Reg, REG_C, OPTYPE_Reg, REG_B, 1, 0, 0),
(('49', 'ff'), 'ld', OPTYPE_Reg, REG_C, OPTYPE_Reg, REG_C, 1, 0, 0),
(('4a', 'ff'), 'ld', OPTYPE_Reg, REG_C, OPTYPE_Reg, REG_D, 1, 0, 0),
(('4b', 'ff'), 'ld', OPTYPE_Reg, REG_C, OPTYPE_Reg, REG_E, 1, 0, 0),
(('4c', 'ff'), 'ld', OPTYPE_Reg, REG_C, OPTYPE_Reg, REG_H, 1, 0, 0),
(('4d', 'ff'), 'ld', OPTYPE_Reg, REG_C, OPTYPE_Reg, REG_L, 1, 0, 0),
(('4e', 'ff'), 'ld', OPTYPE_Reg, REG_C, OPTYPE_RegMem, REG_HL, 1, 0, 0),
(('4f', 'ff'), 'ld', OPTYPE_Reg, REG_C, OPTYPE_Reg, REG_A, 1, 0, 0),
(('50', 'ff'), 'ld', OPTYPE_Reg, REG_D, OPTYPE_Reg, REG_B, 1, 0, 0),
(('51', 'ff'), 'ld', OPTYPE_Reg, REG_D, OPTYPE_Reg, REG_C, 1, 0, 0),
(('52', 'ff'), 'ld', OPTYPE_Reg, REG_D, OPTYPE_Reg, REG_D, 1, 0, 0),
(('53', 'ff'), 'ld', OPTYPE_Reg, REG_D, OPTYPE_Reg, REG_E, 1, 0, 0),
(('54', 'ff'), 'ld', OPTYPE_Reg, REG_D, OPTYPE_Reg, REG_H, 1, 0, 0),
(('55', 'ff'), 'ld', OPTYPE_Reg, REG_D, OPTYPE_Reg, REG_L, 1, 0, 0),
(('56', 'ff'), 'ld', OPTYPE_Reg, REG_D, OPTYPE_RegMem, REG_HL, 1, 0, 0),
(('57', 'ff'), 'ld', OPTYPE_Reg, REG_D, OPTYPE_Reg, REG_A, 1, 0, 0),
(('58', 'ff'), 'ld', OPTYPE_Reg, REG_E, OPTYPE_Reg, REG_B, 1, 0, 0),
(('59', 'ff'), 'ld', OPTYPE_Reg, REG_E, OPTYPE_Reg, REG_C, 1, 0, 0),
(('5a', 'ff'), 'ld', OPTYPE_Reg, REG_E, OPTYPE_Reg, REG_D, 1, 0, 0),
(('5b', 'ff'), 'ld', OPTYPE_Reg, REG_E, OPTYPE_Reg, REG_E, 1, 0, 0),
(('5c', 'ff'), 'ld', OPTYPE_Reg, REG_E, OPTYPE_Reg, REG_H, 1, 0, 0),
(('5d', 'ff'), 'ld', OPTYPE_Reg, REG_E, OPTYPE_Reg, REG_L, 1, 0, 0),
(('5e', 'ff'), 'ld', OPTYPE_Reg, REG_E, OPTYPE_RegMem, REG_HL, 1, 0, 0),
(('5f', 'ff'), 'ld', OPTYPE_Reg, REG_E, OPTYPE_Reg, REG_A, 1, 0, 0),
(('60', 'ff'), 'ld', OPTYPE_Reg, REG_H, OPTYPE_Reg, REG_B, 1, 0, 0),
(('61', 'ff'), 'ld', OPTYPE_Reg, REG_H, OPTYPE_Reg, REG_C, 1, 0, 0),
(('62', 'ff'), 'ld', OPTYPE_Reg, REG_H, OPTYPE_Reg, REG_D, 1, 0, 0),
(('63', 'ff'), 'ld', OPTYPE_Reg, REG_H, OPTYPE_Reg, REG_E, 1, 0, 0),
(('64', 'ff'), 'ld', OPTYPE_Reg, REG_H, OPTYPE_Reg, REG_H, 1, 0, 0),
(('65', 'ff'), 'ld', OPTYPE_Reg, REG_H, OPTYPE_Reg, REG_L, 1, 0, 0),
(('66', 'ff'), 'ld', OPTYPE_Reg, REG_H, OPTYPE_RegMem, REG_HL, 1, 0, 0),
(('67', 'ff'), 'ld', OPTYPE_Reg, REG_H, OPTYPE_Reg, REG_A, 1, 0, 0),
(('68', 'ff'), 'ld', OPTYPE_Reg, REG_L, OPTYPE_Reg, REG_B, 1, 0, 0),
(('69', 'ff'), 'ld', OPTYPE_Reg, REG_L, OPTYPE_Reg, REG_C, 1, 0, 0),
(('6a', 'ff'), 'ld', OPTYPE_Reg, REG_L, OPTYPE_Reg, REG_D, 1, 0, 0),
(('6b', 'ff'), 'ld', OPTYPE_Reg, REG_L, OPTYPE_Reg, REG_E, 1, 0, 0),
(('6c', 'ff'), 'ld', OPTYPE_Reg, REG_L, OPTYPE_Reg, REG_H, 1, 0, 0),
(('6d', 'ff'), 'ld', OPTYPE_Reg, REG_L, OPTYPE_Reg, REG_L, 1, 0, 0),
(('6e', 'ff'), 'ld', OPTYPE_Reg, REG_L, OPTYPE_RegMem, REG_HL, 1, 0, 0),
(('6f', 'ff'), 'ld', OPTYPE_Reg, REG_L, OPTYPE_Reg, REG_A, 1, 0, 0),
(('70', 'ff'), 'ld', OPTYPE_RegMem, REG_HL, OPTYPE_Reg, REG_B, 1, 0, 0),
(('71', 'ff'), 'ld', OPTYPE_RegMem, REG_HL, OPTYPE_Reg, REG_C, 1, 0, 0),
(('72', 'ff'), 'ld', OPTYPE_RegMem, REG_HL, OPTYPE_Reg, REG_D, 1, 0, 0),
(('73', 'ff'), 'ld', OPTYPE_RegMem, REG_HL, OPTYPE_Reg, REG_E, 1, 0, 0),
(('74', 'ff'), 'ld', OPTYPE_RegMem, REG_HL, OPTYPE_Reg, REG_H, 1, 0, 0),
(('75', 'ff'), 'ld', OPTYPE_RegMem, REG_HL, OPTYPE_Reg, REG_L, 1, 0, 0),
(('76', 'ff'), 'halt', None, None, None, None, 1, 0, 0),
(('77', 'ff'), 'ld', OPTYPE_RegMem, REG_HL, OPTYPE_Reg, REG_A, 1, 0, 0),
(('78', 'ff'), 'ld', OPTYPE_Reg, REG_A, OPTYPE_Reg, REG_B, 1, 0, 0),
(('79', 'ff'), 'ld', OPTYPE_Reg, REG_A, OPTYPE_Reg, REG_C, 1, 0, 0),
(('7a', 'ff'), 'ld', OPTYPE_Reg, REG_A, OPTYPE_Reg, REG_D, 1, 0, 0),
(('7b', 'ff'), 'ld', OPTYPE_Reg, REG_A, OPTYPE_Reg, REG_E, 1, 0, 0),
(('7c', 'ff'), 'ld', OPTYPE_Reg, REG_A, OPTYPE_Reg, REG_H, 1, 0, 0),
(('7d', 'ff'), 'ld', OPTYPE_Reg, REG_A, OPTYPE_Reg, REG_L, 1, 0, 0),
(('7e', 'ff'), 'ld', OPTYPE_Reg, REG_A, OPTYPE_RegMem, REG_HL, 1, 0, 0),
(('7f', 'ff'), 'ld', OPTYPE_Reg, REG_A, OPTYPE_Reg, REG_A, 1, 0, 0),
(('80', 'ff'), 'add', OPTYPE_Reg, REG_A, OPTYPE_Reg, REG_B, 1, 0, 0),
(('81', 'ff'), 'add', OPTYPE_Reg, REG_A, OPTYPE_Reg, REG_C, 1, 0, 0),
(('82', 'ff'), 'add', OPTYPE_Reg, REG_A, OPTYPE_Reg, REG_D, 1, 0, 0),
(('83', 'ff'), 'add', OPTYPE_Reg, REG_A, OPTYPE_Reg, REG_E, 1, 0, 0),
(('84', 'ff'), 'add', OPTYPE_Reg, REG_A, OPTYPE_Reg, REG_H, 1, 0, 0),
(('85', 'ff'), 'add', OPTYPE_Reg, REG_A, OPTYPE_Reg, REG_L, 1, 0, 0),
(('86', 'ff'), 'add', OPTYPE_Reg, REG_A, OPTYPE_RegMem, REG_HL, 1, 0, 0),
(('87', 'ff'), 'add', OPTYPE_Reg, REG_A, OPTYPE_Reg, REG_A, 1, 0, 0),
(('88', 'ff'), 'adc', OPTYPE_Reg, REG_A, OPTYPE_Reg, REG_B, 1, 0, 0),
(('89', 'ff'), 'adc', OPTYPE_Reg, REG_A, OPTYPE_Reg, REG_C, 1, 0, 0),
(('8a', 'ff'), 'adc', OPTYPE_Reg, REG_A, OPTYPE_Reg, REG_D, 1, 0, 0),
(('8b', 'ff'), 'adc', OPTYPE_Reg, REG_A, OPTYPE_Reg, REG_E, 1, 0, 0),
(('8c', 'ff'), 'adc', OPTYPE_Reg, REG_A, OPTYPE_Reg, REG_H, 1, 0, 0),
(('8d', 'ff'), 'adc', OPTYPE_Reg, REG_A, OPTYPE_Reg, REG_L, 1, 0, 0),
(('8e', 'ff'), 'adc', OPTYPE_Reg, REG_A, OPTYPE_RegMem, REG_HL, 1, 0, 0),
(('8f', 'ff'), 'adc', OPTYPE_Reg, REG_A, OPTYPE_Reg, REG_A, 1, 0, 0),
(('90', 'ff'), 'sub', OPTYPE_Reg, REG_B, None, None, 1, 0, 0),
(('91', 'ff'), 'sub', OPTYPE_Reg, REG_C, None, None, 1, 0, 0),
(('92', 'ff'), 'sub', OPTYPE_Reg, REG_D, None, None, 1, 0, 0),
(('93', 'ff'), 'sub', OPTYPE_Reg, REG_E, None, None, 1, 0, 0),
(('94', 'ff'), 'sub', OPTYPE_Reg, REG_H, None, None, 1, 0, 0),
(('95', 'ff'), 'sub', OPTYPE_Reg, REG_L, None, None, 1, 0, 0),
(('96', 'ff'), 'sub', OPTYPE_RegMem, REG_HL, None, None, 1, 0, 0),
(('97', 'ff'), 'sub', OPTYPE_Reg, REG_A, None, None, 1, 0, 0),
(('98', 'ff'), 'sbc', OPTYPE_Reg, REG_B, None, None, 1, 0, 0),
(('99', 'ff'), 'sbc', OPTYPE_Reg, REG_C, None, None, 1, 0, 0),
(('9a', 'ff'), 'sbc', OPTYPE_Reg, REG_D, None, None, 1, 0, 0),
(('9b', 'ff'), 'sbc', OPTYPE_Reg, REG_E, None, None, 1, 0, 0),
(('9c', 'ff'), 'sbc', OPTYPE_Reg, REG_H, None, None, 1, 0, 0),
(('9d', 'ff'), 'sbc', OPTYPE_Reg, REG_L, None, None, 1, 0, 0),
(('9e', 'ff'), 'sbc', OPTYPE_RegMem, REG_HL, None, None, 1, 0, 0),
(('9f', 'ff'), 'sbc', OPTYPE_Reg, REG_A, None, None, 1, 0, 0),
(('a0', 'ff'), 'and', OPTYPE_Reg, REG_B, None, None, 1, 0, 0),
(('a1', 'ff'), 'and', OPTYPE_Reg, REG_C, None, None, 1, 0, 0),
(('a2', 'ff'), 'and', OPTYPE_Reg, REG_D, None, None, 1, 0, 0),
(('a3', 'ff'), 'and', OPTYPE_Reg, REG_E, None, None, 1, 0, 0),
(('a4', 'ff'), 'and', OPTYPE_Reg, REG_H, None, None, 1, 0, 0),
(('a5', 'ff'), 'and', OPTYPE_Reg, REG_L, None, None, 1, 0, 0),
(('a6', 'ff'), 'and', OPTYPE_RegMem, REG_HL, None, None, 1, 0, 0),
(('a7', 'ff'), 'and', OPTYPE_Reg, REG_A, None, None, 1, 0, 0),
(('a8', 'ff'), 'xor', OPTYPE_Reg, REG_B, None, None, 1, 0, 0),
(('a9', 'ff'), 'xor', OPTYPE_Reg, REG_C, None, None, 1, 0, 0),
(('aa', 'ff'), 'xor', OPTYPE_Reg, REG_D, None, None, 1, 0, 0),
(('ab', 'ff'), 'xor', OPTYPE_Reg, REG_E, None, None, 1, 0, 0),
(('ac', 'ff'), 'xor', OPTYPE_Reg, REG_H, None, None, 1, 0, 0),
(('ad', 'ff'), 'xor', OPTYPE_Reg, REG_L, None, None, 1, 0, 0),
(('ae', 'ff'), 'xor', OPTYPE_RegMem, REG_HL, None, None, 1, 0, 0),
(('af', 'ff'), 'xor', OPTYPE_Reg, REG_A, None, None, 1, 0, 0),
(('b0', 'ff'), 'or', OPTYPE_Reg, REG_B, None, None, 1, 0, 0),
(('b1', 'ff'), 'or', OPTYPE_Reg, REG_C, None, None, 1, 0, 0),
(('b2', 'ff'), 'or', OPTYPE_Reg, REG_D, None, None, 1, 0, 0),
(('b3', 'ff'), 'or', OPTYPE_Reg, REG_E, None, None, 1, 0, 0),
(('b4', 'ff'), 'or', OPTYPE_Reg, REG_H, None, None, 1, 0, 0),
(('b5', 'ff'), 'or', OPTYPE_Reg, REG_L, None, None, 1, 0, 0),
(('b6', 'ff'), 'or', OPTYPE_RegMem, REG_HL, None, None, 1, 0, 0),
(('b7', 'ff'), 'or', OPTYPE_Reg, REG_A, None, None, 1, 0, 0),
(('b8', 'ff'), 'cp', OPTYPE_Reg, REG_B, None, None, 1, 0, 0),
(('b9', 'ff'), 'cp', OPTYPE_Reg, REG_C, None, None, 1, 0, 0),
(('ba', 'ff'), 'cp', OPTYPE_Reg, REG_D, None, None, 1, 0, 0),
(('bb', 'ff'), 'cp', OPTYPE_Reg, REG_E, None, None, 1, 0, 0),
(('bc', 'ff'), 'cp', OPTYPE_Reg, REG_H, None, None, 1, 0, 0),
(('bd', 'ff'), 'cp', OPTYPE_Reg, REG_L, None, None, 1, 0, 0),
(('be', 'ff'), 'cp', OPTYPE_RegMem, REG_HL, None, None, 1, 0, 0),
(('bf', 'ff'), 'cp', OPTYPE_Reg, REG_A, None, None, 1, 0, 0),
(('c0', 'ff'), 'ret', OPTYPE_Cond, COND_NZ, None, None, 1, 0, 0),
(('c1', 'ff'), 'pop', OPTYPE_Reg, REG_BC, None, None, 1, 0, 0),
(('c2', 'ff'), 'jp', OPTYPE_Cond, COND_NZ, OPTYPE_Ind, None, 1, 0, 0),
(('c3', 'ff'), 'jp', OPTYPE_imm16, None, None, None, 3, 1, 0),
(('c40000', 'ff0000'), 'call', OPTYPE_Cond, COND_NZ, OPTYPE_imm16, None, 3, 1, 0),
(('c5', 'ff'), 'push', OPTYPE_Reg, REG_BC, None, None, 1, 0, 0),
(('c600', 'ff00'), 'add', OPTYPE_Reg, REG_A, OPTYPE_imm8, None, 2, 1, 0),
(('c7', 'ff'), 'rst', OPTYPE_const, 0, None, None, 1, 0, 0),
(('c8', 'ff'), 'ret', OPTYPE_Cond, COND_Z, None, None, 1, 0, 0),
(('c9', 'ff'), 'ret', None, None, None, None, 1, 0, 0),
(('ca', 'ff'), 'jp', OPTYPE_Cond, COND_Z, OPTYPE_Ind, None, 1, 0, 0),
(('cb00', 'ffff'), 'rlc', OPTYPE_Reg, REG_B, None, None, 2, 0, 0),
(('cb01', 'ffff'), 'rlc', OPTYPE_Reg, REG_C, None, None, 2, 0, 0),
(('cb02', 'ffff'), 'rlc', OPTYPE_Reg, REG_D, None, None, 2, 0, 0),
(('cb03', 'ffff'), 'rlc', OPTYPE_Reg, REG_E, None, None, 2, 0, 0),
(('cb04', 'ffff'), 'rlc', OPTYPE_Reg, REG_H, None, None, 2, 0, 0),
(('cb05', 'ffff'), 'rlc', OPTYPE_Reg, REG_L, None, None, 2, 0, 0),
(('cb06', 'ffff'), 'rlc', OPTYPE_RegMem, REG_HL, None, None, 2, 0, 0),
(('cb07', 'ffff'), 'rlc', OPTYPE_Reg, REG_A, None, None, 2, 0, 0),
(('cb08', 'ffff'), 'rrc', OPTYPE_Reg, REG_B, None, None, 2, 0, 0),
(('cb09', 'ffff'), 'rrc', OPTYPE_Reg, REG_C, None, None, 2, 0, 0),
(('cb0a', 'ffff'), 'rrc', OPTYPE_Reg, REG_D, None, None, 2, 0, 0),
(('cb0b', 'ffff'), 'rrc', OPTYPE_Reg, REG_E, None, None, 2, 0, 0),
(('cb0c', 'ffff'), 'rrc', OPTYPE_Reg, REG_H, None, None, 2, 0, 0),
(('cb0d', 'ffff'), 'rrc', OPTYPE_Reg, REG_L, None, None, 2, 0, 0),
(('cb0e', 'ffff'), 'rrc', OPTYPE_RegMem, REG_HL, None, None, 2, 0, 0),
(('cb0f', 'ffff'), 'rrc', OPTYPE_Reg, REG_A, None, None, 2, 0, 0),
(('cb10', 'ffff'), 'rl', OPTYPE_Reg, REG_B, None, None, 2, 0, 0),
(('cb11', 'ffff'), 'rl', OPTYPE_Reg, REG_C, None, None, 2, 0, 0),
(('cb12', 'ffff'), 'rl', OPTYPE_Reg, REG_D, None, None, 2, 0, 0),
(('cb13', 'ffff'), 'rl', OPTYPE_Reg, REG_E, None, None, 2, 0, 0),
(('cb14', 'ffff'), 'rl', OPTYPE_Reg, REG_H, None, None, 2, 0, 0),
(('cb15', 'ffff'), 'rl', OPTYPE_Reg, REG_L, None, None, 2, 0, 0),
(('cb16', 'ffff'), 'rl', OPTYPE_RegMem, REG_HL, None, None, 2, 0, 0),
(('cb17', 'ffff'), 'rl', OPTYPE_Reg, REG_A, None, None, 2, 0, 0),
(('cb18', 'ffff'), 'rr', OPTYPE_Reg, REG_B, None, None, 2, 0, 0),
(('cb19', 'ffff'), 'rr', OPTYPE_Reg, REG_C, None, None, 2, 0, 0),
(('cb1a', 'ffff'), 'rr', OPTYPE_Reg, REG_D, None, None, 2, 0, 0),
(('cb1b', 'ffff'), 'rr', OPTYPE_Reg, REG_E, None, None, 2, 0, 0),
(('cb1c', 'ffff'), 'rr', OPTYPE_Reg, REG_H, None, None, 2, 0, 0),
(('cb1d', 'ffff'), 'rr', OPTYPE_Reg, REG_L, None, None, 2, 0, 0),
(('cb1e', 'ffff'), 'rr', OPTYPE_RegMem, REG_HL, None, None, 2, 0, 0),
(('cb1f', 'ffff'), 'rr', OPTYPE_Reg, REG_A, None, None, 2, 0, 0),
(('cb20', 'ffff'), 'sla', OPTYPE_Reg, REG_B, None, None, 2, 0, 0),
(('cb21', 'ffff'), 'sla', OPTYPE_Reg, REG_C, None, None, 2, 0, 0),
(('cb22', 'ffff'), 'sla', OPTYPE_Reg, REG_D, None, None, 2, 0, 0),
(('cb23', 'ffff'), 'sla', OPTYPE_Reg, REG_E, None, None, 2, 0, 0),
(('cb24', 'ffff'), 'sla', OPTYPE_Reg, REG_H, None, None, 2, 0, 0),
(('cb25', 'ffff'), 'sla', OPTYPE_Reg, REG_L, None, None, 2, 0, 0),
(('cb26', 'ffff'), 'sla', OPTYPE_RegMem, REG_HL, None, None, 2, 0, 0),
(('cb27', 'ffff'), 'sla', OPTYPE_Reg, REG_A, None, None, 2, 0, 0),
(('cb28', 'ffff'), 'sra', OPTYPE_Reg, REG_B, None, None, 2, 0, 0),
(('cb29', 'ffff'), 'sra', OPTYPE_Reg, REG_C, None, None, 2, 0, 0),
(('cb2a', 'ffff'), 'sra', OPTYPE_Reg, REG_D, None, None, 2, 0, 0),
(('cb2b', 'ffff'), 'sra', OPTYPE_Reg, REG_E, None, None, 2, 0, 0),
(('cb2c', 'ffff'), 'sra', OPTYPE_Reg, REG_H, None, None, 2, 0, 0),
(('cb2d', 'ffff'), 'sra', OPTYPE_Reg, REG_L, None, None, 2, 0, 0),
(('cb2e', 'ffff'), 'sra', OPTYPE_RegMem, REG_HL, None, None, 2, 0, 0),
(('cb2f', 'ffff'), 'sra', OPTYPE_Reg, REG_A, None, None, 2, 0, 0),
(('cb38', 'ffff'), 'srl', OPTYPE_Reg, REG_B, None, None, 2, 0, 0),
(('cb39', 'ffff'), 'srl', OPTYPE_Reg, REG_C, None, None, 2, 0, 0),
(('cb3a', 'ffff'), 'srl', OPTYPE_Reg, REG_D, None, None, 2, 0, 0),
(('cb3b', 'ffff'), 'srl', OPTYPE_Reg, REG_E, None, None, 2, 0, 0),
(('cb3c', 'ffff'), 'srl', OPTYPE_Reg, REG_H, None, None, 2, 0, 0),
(('cb3d', 'ffff'), 'srl', OPTYPE_Reg, REG_L, None, None, 2, 0, 0),
(('cb3e', 'ffff'), 'srl', OPTYPE_RegMem, REG_HL, None, None, 2, 0, 0),
(('cb3f', 'ffff'), 'srl', OPTYPE_Reg, REG_A, None, None, 2, 0, 0),
(('cb40', 'ffff'), 'bit', OPTYPE_const, 0, OPTYPE_Reg, REG_B, 2, 0, 0),
(('cb41', 'ffff'), 'bit', OPTYPE_const, 0, OPTYPE_Reg, REG_C, 2, 0, 0),
(('cb42', 'ffff'), 'bit', OPTYPE_const, 0, OPTYPE_Reg, REG_D, 2, 0, 0),
(('cb43', 'ffff'), 'bit', OPTYPE_const, 0, OPTYPE_Reg, REG_E, 2, 0, 0),
(('cb44', 'ffff'), 'bit', OPTYPE_const, 0, OPTYPE_Reg, REG_H, 2, 0, 0),
(('cb45', 'ffff'), 'bit', OPTYPE_const, 0, OPTYPE_Reg, REG_L, 2, 0, 0),
(('cb46', 'ffff'), 'bit', OPTYPE_const, 0, OPTYPE_RegMem, REG_HL, 2, 0, 0),
(('cb47', 'ffff'), 'bit', OPTYPE_const, 0, OPTYPE_Reg, REG_A, 2, 0, 0),
(('cb48', 'ffff'), 'bit', OPTYPE_const, 1, OPTYPE_Reg, REG_B, 2, 0, 0),
(('cb49', 'ffff'), 'bit', OPTYPE_const, 1, OPTYPE_Reg, REG_C, 2, 0, 0),
(('cb4a', 'ffff'), 'bit', OPTYPE_const, 1, OPTYPE_Reg, REG_D, 2, 0, 0),
(('cb4b', 'ffff'), 'bit', OPTYPE_const, 1, OPTYPE_Reg, REG_E, 2, 0, 0),
(('cb4c', 'ffff'), 'bit', OPTYPE_const, 1, OPTYPE_Reg, REG_H, 2, 0, 0),
(('cb4d', 'ffff'), 'bit', OPTYPE_const, 1, OPTYPE_Reg, REG_L, 2, 0, 0),
(('cb4e', 'ffff'), 'bit', OPTYPE_const, 1, OPTYPE_RegMem, REG_HL, 2, 0, 0),
(('cb4f', 'ffff'), 'bit', OPTYPE_const, 1, OPTYPE_Reg, REG_A, 2, 0, 0),
(('cb50', 'ffff'), 'bit', OPTYPE_const, 2, OPTYPE_Reg, REG_B, 2, 0, 0),
(('cb51', 'ffff'), 'bit', OPTYPE_const, 2, OPTYPE_Reg, REG_C, 2, 0, 0),
(('cb52', 'ffff'), 'bit', OPTYPE_const, 2, OPTYPE_Reg, REG_D, 2, 0, 0),
(('cb53', 'ffff'), 'bit', OPTYPE_const, 2, OPTYPE_Reg, REG_E, 2, 0, 0),
(('cb54', 'ffff'), 'bit', OPTYPE_const, 2, OPTYPE_Reg, REG_H, 2, 0, 0),
(('cb55', 'ffff'), 'bit', OPTYPE_const, 2, OPTYPE_Reg, REG_L, 2, 0, 0),
(('cb56', 'ffff'), 'bit', OPTYPE_const, 2, OPTYPE_RegMem, REG_HL, 2, 0, 0),
(('cb57', 'ffff'), 'bit', OPTYPE_const, 2, OPTYPE_Reg, REG_A, 2, 0, 0),
(('cb58', 'ffff'), 'bit', OPTYPE_const, 3, OPTYPE_Reg, REG_B, 2, 0, 0),
(('cb59', 'ffff'), 'bit', OPTYPE_const, 3, OPTYPE_Reg, REG_C, 2, 0, 0),
(('cb5a', 'ffff'), 'bit', OPTYPE_const, 3, OPTYPE_Reg, REG_D, 2, 0, 0),
(('cb5b', 'ffff'), 'bit', OPTYPE_const, 3, OPTYPE_Reg, REG_E, 2, 0, 0),
(('cb5c', 'ffff'), 'bit', OPTYPE_const, 3, OPTYPE_Reg, REG_H, 2, 0, 0),
(('cb5d', 'ffff'), 'bit', OPTYPE_const, 3, OPTYPE_Reg, REG_L, 2, 0, 0),
(('cb5e', 'ffff'), 'bit', OPTYPE_const, 3, OPTYPE_RegMem, REG_HL, 2, 0, 0),
(('cb5f', 'ffff'), 'bit', OPTYPE_const, 3, OPTYPE_Reg, REG_A, 2, 0, 0),
(('cb60', 'ffff'), 'bit', OPTYPE_const, 4, OPTYPE_Reg, REG_B, 2, 0, 0),
(('cb61', 'ffff'), 'bit', OPTYPE_const, 4, OPTYPE_Reg, REG_C, 2, 0, 0),
(('cb62', 'ffff'), 'bit', OPTYPE_const, 4, OPTYPE_Reg, REG_D, 2, 0, 0),
(('cb63', 'ffff'), 'bit', OPTYPE_const, 4, OPTYPE_Reg, REG_E, 2, 0, 0),
(('cb64', 'ffff'), 'bit', OPTYPE_const, 4, OPTYPE_Reg, REG_H, 2, 0, 0),
(('cb65', 'ffff'), 'bit', OPTYPE_const, 4, OPTYPE_Reg, REG_L, 2, 0, 0),
(('cb66', 'ffff'), 'bit', OPTYPE_const, 4, OPTYPE_RegMem, REG_HL, 2, 0, 0),
(('cb67', 'ffff'), 'bit', OPTYPE_const, 4, OPTYPE_Reg, REG_A, 2, 0, 0),
(('cb68', 'ffff'), 'bit', OPTYPE_const, 5, OPTYPE_Reg, REG_B, 2, 0, 0),
(('cb69', 'ffff'), 'bit', OPTYPE_const, 5, OPTYPE_Reg, REG_C, 2, 0, 0),
(('cb6a', 'ffff'), 'bit', OPTYPE_const, 5, OPTYPE_Reg, REG_D, 2, 0, 0),
(('cb6b', 'ffff'), 'bit', OPTYPE_const, 5, OPTYPE_Reg, REG_E, 2, 0, 0),
(('cb6c', 'ffff'), 'bit', OPTYPE_const, 5, OPTYPE_Reg, REG_H, 2, 0, 0),
(('cb6d', 'ffff'), 'bit', OPTYPE_const, 5, OPTYPE_Reg, REG_L, 2, 0, 0),
(('cb6e', 'ffff'), 'bit', OPTYPE_const, 5, OPTYPE_RegMem, REG_HL, 2, 0, 0),
(('cb6f', 'ffff'), 'bit', OPTYPE_const, 5, OPTYPE_Reg, REG_A, 2, 0, 0),
(('cb70', 'ffff'), 'bit', OPTYPE_const, 6, OPTYPE_Reg, REG_B, 2, 0, 0),
(('cb71', 'ffff'), 'bit', OPTYPE_const, 6, OPTYPE_Reg, REG_C, 2, 0, 0),
(('cb72', 'ffff'), 'bit', OPTYPE_const, 6, OPTYPE_Reg, REG_D, 2, 0, 0),
(('cb73', 'ffff'), 'bit', OPTYPE_const, 6, OPTYPE_Reg, REG_E, 2, 0, 0),
(('cb74', 'ffff'), 'bit', OPTYPE_const, 6, OPTYPE_Reg, REG_H, 2, 0, 0),
(('cb75', 'ffff'), 'bit', OPTYPE_const, 6, OPTYPE_Reg, REG_L, 2, 0, 0),
(('cb76', 'ffff'), 'bit', OPTYPE_const, 6, OPTYPE_RegMem, REG_HL, 2, 0, 0),
(('cb77', 'ffff'), 'bit', OPTYPE_const, 6, OPTYPE_Reg, REG_A, 2, 0, 0),
(('cb78', 'ffff'), 'bit', OPTYPE_const, 7, OPTYPE_Reg, REG_B, 2, 0, 0),
(('cb79', 'ffff'), 'bit', OPTYPE_const, 7, OPTYPE_Reg, REG_C, 2, 0, 0),
(('cb7a', 'ffff'), 'bit', OPTYPE_const, 7, OPTYPE_Reg, REG_D, 2, 0, 0),
(('cb7b', 'ffff'), 'bit', OPTYPE_const, 7, OPTYPE_Reg, REG_E, 2, 0, 0),
(('cb7c', 'ffff'), 'bit', OPTYPE_const, 7, OPTYPE_Reg, REG_H, 2, 0, 0),
(('cb7d', 'ffff'), 'bit', OPTYPE_const, 7, OPTYPE_Reg, REG_L, 2, 0, 0),
(('cb7e', 'ffff'), 'bit', OPTYPE_const, 7, OPTYPE_RegMem, REG_HL, 2, 0, 0),
(('cb7f', 'ffff'), 'bit', OPTYPE_const, 7, OPTYPE_Reg, REG_A, 2, 0, 0),
(('cb80', 'ffff'), 'res', OPTYPE_const, 0, OPTYPE_Reg, REG_B, 2, 0, 0),
(('cb81', 'ffff'), 'res', OPTYPE_const, 0, OPTYPE_Reg, REG_C, 2, 0, 0),
(('cb82', 'ffff'), 'res', OPTYPE_const, 0, OPTYPE_Reg, REG_D, 2, 0, 0),
(('cb83', 'ffff'), 'res', OPTYPE_const, 0, OPTYPE_Reg, REG_E, 2, 0, 0),
(('cb84', 'ffff'), 'res', OPTYPE_const, 0, OPTYPE_Reg, REG_H, 2, 0, 0),
(('cb85', 'ffff'), 'res', OPTYPE_const, 0, OPTYPE_Reg, REG_L, 2, 0, 0),
(('cb86', 'ffff'), 'res', OPTYPE_const, 0, OPTYPE_RegMem, REG_HL, 2, 0, 0),
(('cb87', 'ffff'), 'res', OPTYPE_const, 0, OPTYPE_Reg, REG_A, 2, 0, 0),
(('cb88', 'ffff'), 'res', OPTYPE_const, 1, OPTYPE_Reg, REG_B, 2, 0, 0),
(('cb89', 'ffff'), 'res', OPTYPE_const, 1, OPTYPE_Reg, REG_C, 2, 0, 0),
(('cb8a', 'ffff'), 'res', OPTYPE_const, 1, OPTYPE_Reg, REG_D, 2, 0, 0),
(('cb8b', 'ffff'), 'res', OPTYPE_const, 1, OPTYPE_Reg, REG_E, 2, 0, 0),
(('cb8c', 'ffff'), 'res', OPTYPE_const, 1, OPTYPE_Reg, REG_H, 2, 0, 0),
(('cb8d', 'ffff'), 'res', OPTYPE_const, 1, OPTYPE_Reg, REG_L, 2, 0, 0),
(('cb8e', 'ffff'), 'res', OPTYPE_const, 1, OPTYPE_RegMem, REG_HL, 2, 0, 0),
(('cb8f', 'ffff'), 'res', OPTYPE_const, 1, OPTYPE_Reg, REG_A, 2, 0, 0),
(('cb90', 'ffff'), 'res', OPTYPE_const, 2, OPTYPE_Reg, REG_B, 2, 0, 0),
(('cb91', 'ffff'), 'res', OPTYPE_const, 2, OPTYPE_Reg, REG_C, 2, 0, 0),
(('cb92', 'ffff'), 'res', OPTYPE_const, 2, OPTYPE_Reg, REG_D, 2, 0, 0),
(('cb93', 'ffff'), 'res', OPTYPE_const, 2, OPTYPE_Reg, REG_E, 2, 0, 0),
(('cb94', 'ffff'), 'res', OPTYPE_const, 2, OPTYPE_Reg, REG_H, 2, 0, 0),
(('cb95', 'ffff'), 'res', OPTYPE_const, 2, OPTYPE_Reg, REG_L, 2, 0, 0),
(('cb96', 'ffff'), 'res', OPTYPE_const, 2, OPTYPE_RegMem, REG_HL, 2, 0, 0),
(('cb97', 'ffff'), 'res', OPTYPE_const, 2, OPTYPE_Reg, REG_A, 2, 0, 0),
(('cb98', 'ffff'), 'res', OPTYPE_const, 3, OPTYPE_Reg, REG_B, 2, 0, 0),
(('cb99', 'ffff'), 'res', OPTYPE_const, 3, OPTYPE_Reg, REG_C, 2, 0, 0),
(('cb9a', 'ffff'), 'res', OPTYPE_const, 3, OPTYPE_Reg, REG_D, 2, 0, 0),
(('cb9b', 'ffff'), 'res', OPTYPE_const, 3, OPTYPE_Reg, REG_E, 2, 0, 0),
(('cb9c', 'ffff'), 'res', OPTYPE_const, 3, OPTYPE_Reg, REG_H, 2, 0, 0),
(('cb9d', 'ffff'), 'res', OPTYPE_const, 3, OPTYPE_Reg, REG_L, 2, 0, 0),
(('cb9e', 'ffff'), 'res', OPTYPE_const, 3, OPTYPE_RegMem, REG_HL, 2, 0, 0),
(('cb9f', 'ffff'), 'res', OPTYPE_const, 3, OPTYPE_Reg, REG_A, 2, 0, 0),
(('cba0', 'ffff'), 'res', OPTYPE_const, 4, OPTYPE_Reg, REG_B, 2, 0, 0),
(('cba1', 'ffff'), 'res', OPTYPE_const, 4, OPTYPE_Reg, REG_C, 2, 0, 0),
(('cba2', 'ffff'), 'res', OPTYPE_const, 4, OPTYPE_Reg, REG_D, 2, 0, 0),
(('cba3', 'ffff'), 'res', OPTYPE_const, 4, OPTYPE_Reg, REG_E, 2, 0, 0),
(('cba4', 'ffff'), 'res', OPTYPE_const, 4, OPTYPE_Reg, REG_H, 2, 0, 0),
(('cba5', 'ffff'), 'res', OPTYPE_const, 4, OPTYPE_Reg, REG_L, 2, 0, 0),
(('cba6', 'ffff'), 'res', OPTYPE_const, 4, OPTYPE_RegMem, REG_HL, 2, 0, 0),
(('cba7', 'ffff'), 'res', OPTYPE_const, 4, OPTYPE_Reg, REG_A, 2, 0, 0),
(('cba8', 'ffff'), 'res', OPTYPE_const, 5, OPTYPE_Reg, REG_B, 2, 0, 0),
(('cba9', 'ffff'), 'res', OPTYPE_const, 5, OPTYPE_Reg, REG_C, 2, 0, 0),
(('cbaa', 'ffff'), 'res', OPTYPE_const, 5, OPTYPE_Reg, REG_D, 2, 0, 0),
(('cbab', 'ffff'), 'res', OPTYPE_const, 5, OPTYPE_Reg, REG_E, 2, 0, 0),
(('cbac', 'ffff'), 'res', OPTYPE_const, 5, OPTYPE_Reg, REG_H, 2, 0, 0),
(('cbad', 'ffff'), 'res', OPTYPE_const, 5, OPTYPE_Reg, REG_L, 2, 0, 0),
(('cbae', 'ffff'), 'res', OPTYPE_const, 5, OPTYPE_RegMem, REG_HL, 2, 0, 0),
(('cbaf', 'ffff'), 'res', OPTYPE_const, 5, OPTYPE_Reg, REG_A, 2, 0, 0),
(('cbb0', 'ffff'), 'res', OPTYPE_const, 6, OPTYPE_Reg, REG_B, 2, 0, 0),
(('cbb1', 'ffff'), 'res', OPTYPE_const, 6, OPTYPE_Reg, REG_C, 2, 0, 0),
(('cbb2', 'ffff'), 'res', OPTYPE_const, 6, OPTYPE_Reg, REG_D, 2, 0, 0),
(('cbb3', 'ffff'), 'res', OPTYPE_const, 6, OPTYPE_Reg, REG_E, 2, 0, 0),
(('cbb4', 'ffff'), 'res', OPTYPE_const, 6, OPTYPE_Reg, REG_H, 2, 0, 0),
(('cbb5', 'ffff'), 'res', OPTYPE_const, 6, OPTYPE_Reg, REG_L, 2, 0, 0),
(('cbb6', 'ffff'), 'res', OPTYPE_const, 6, OPTYPE_RegMem, REG_HL, 2, 0, 0),
(('cbb7', 'ffff'), 'res', OPTYPE_const, 6, OPTYPE_Reg, REG_A, 2, 0, 0),
(('cbb8', 'ffff'), 'res', OPTYPE_const, 7, OPTYPE_Reg, REG_B, 2, 0, 0),
(('cbb9', 'ffff'), 'res', OPTYPE_const, 7, OPTYPE_Reg, REG_C, 2, 0, 0),
(('cbba', 'ffff'), 'res', OPTYPE_const, 7, OPTYPE_Reg, REG_D, 2, 0, 0),
(('cbbb', 'ffff'), 'res', OPTYPE_const, 7, OPTYPE_Reg, REG_E, 2, 0, 0),
(('cbbc', 'ffff'), 'res', OPTYPE_const, 7, OPTYPE_Reg, REG_H, 2, 0, 0),
(('cbbd', 'ffff'), 'res', OPTYPE_const, 7, OPTYPE_Reg, REG_L, 2, 0, 0),
(('cbbe', 'ffff'), 'res', OPTYPE_const, 7, OPTYPE_RegMem, REG_HL, 2, 0, 0),
(('cbbf', 'ffff'), 'res', OPTYPE_const, 7, OPTYPE_Reg, REG_A, 2, 0, 0),
(('cbc0', 'ffff'), 'set', OPTYPE_const, 0, OPTYPE_Reg, REG_B, 2, 0, 0),
(('cbc1', 'ffff'), 'set', OPTYPE_const, 0, OPTYPE_Reg, REG_C, 2, 0, 0),
(('cbc2', 'ffff'), 'set', OPTYPE_const, 0, OPTYPE_Reg, REG_D, 2, 0, 0),
(('cbc3', 'ffff'), 'set', OPTYPE_const, 0, OPTYPE_Reg, REG_E, 2, 0, 0),
(('cbc4', 'ffff'), 'set', OPTYPE_const, 0, OPTYPE_Reg, REG_H, 2, 0, 0),
(('cbc5', 'ffff'), 'set', OPTYPE_const, 0, OPTYPE_Reg, REG_L, 2, 0, 0),
(('cbc6', 'ffff'), 'set', OPTYPE_const, 0, OPTYPE_RegMem, REG_HL, 2, 0, 0),
(('cbc7', 'ffff'), 'set', OPTYPE_const, 0, OPTYPE_Reg, REG_A, 2, 0, 0),
(('cbc8', 'ffff'), 'set', OPTYPE_const, 1, OPTYPE_Reg, REG_B, 2, 0, 0),
(('cbc9', 'ffff'), 'set', OPTYPE_const, 1, OPTYPE_Reg, REG_C, 2, 0, 0),
(('cbca', 'ffff'), 'set', OPTYPE_const, 1, OPTYPE_Reg, REG_D, 2, 0, 0),
(('cbcb', 'ffff'), 'set', OPTYPE_const, 1, OPTYPE_Reg, REG_E, 2, 0, 0),
(('cbcc', 'ffff'), 'set', OPTYPE_const, 1, OPTYPE_Reg, REG_H, 2, 0, 0),
(('cbcd', 'ffff'), 'set', OPTYPE_const, 1, OPTYPE_Reg, REG_L, 2, 0, 0),
(('cbce', 'ffff'), 'set', OPTYPE_const, 1, OPTYPE_RegMem, REG_HL, 2, 0, 0),
(('cbcf', 'ffff'), 'set', OPTYPE_const, 1, OPTYPE_Reg, REG_A, 2, 0, 0),
(('cbd0', 'ffff'), 'set', OPTYPE_const, 2, OPTYPE_Reg, REG_B, 2, 0, 0),
(('cbd1', 'ffff'), 'set', OPTYPE_const, 2, OPTYPE_Reg, REG_C, 2, 0, 0),
(('cbd2', 'ffff'), 'set', OPTYPE_const, 2, OPTYPE_Reg, REG_D, 2, 0, 0),
(('cbd3', 'ffff'), 'set', OPTYPE_const, 2, OPTYPE_Reg, REG_E, 2, 0, 0),
(('cbd4', 'ffff'), 'set', OPTYPE_const, 2, OPTYPE_Reg, REG_H, 2, 0, 0),
(('cbd5', 'ffff'), 'set', OPTYPE_const, 2, OPTYPE_Reg, REG_L, 2, 0, 0),
(('cbd6', 'ffff'), 'set', OPTYPE_const, 2, OPTYPE_RegMem, REG_HL, 2, 0, 0),
(('cbd7', 'ffff'), 'set', OPTYPE_const, 2, OPTYPE_Reg, REG_A, 2, 0, 0),
(('cbd8', 'ffff'), 'set', OPTYPE_const, 3, OPTYPE_Reg, REG_B, 2, 0, 0),
(('cbd9', 'ffff'), 'set', OPTYPE_const, 3, OPTYPE_Reg, REG_C, 2, 0, 0),
(('cbda', 'ffff'), 'set', OPTYPE_const, 3, OPTYPE_Reg, REG_D, 2, 0, 0),
(('cbdb', 'ffff'), 'set', OPTYPE_const, 3, OPTYPE_Reg, REG_E, 2, 0, 0),
(('cbdc', 'ffff'), 'set', OPTYPE_const, 3, OPTYPE_Reg, REG_H, 2, 0, 0),
(('cbdd', 'ffff'), 'set', OPTYPE_const, 3, OPTYPE_Reg, REG_L, 2, 0, 0),
(('cbde', 'ffff'), 'set', OPTYPE_const, 3, OPTYPE_RegMem, REG_HL, 2, 0, 0),
(('cbdf', 'ffff'), 'set', OPTYPE_const, 3, OPTYPE_Reg, REG_A, 2, 0, 0),
(('cbe0', 'ffff'), 'set', OPTYPE_const, 4, OPTYPE_Reg, REG_B, 2, 0, 0),
(('cbe1', 'ffff'), 'set', OPTYPE_const, 4, OPTYPE_Reg, REG_C, 2, 0, 0),
(('cbe2', 'ffff'), 'set', OPTYPE_const, 4, OPTYPE_Reg, REG_D, 2, 0, 0),
(('cbe3', 'ffff'), 'set', OPTYPE_const, 4, OPTYPE_Reg, REG_E, 2, 0, 0),
(('cbe4', 'ffff'), 'set', OPTYPE_const, 4, OPTYPE_Reg, REG_H, 2, 0, 0),
(('cbe5', 'ffff'), 'set', OPTYPE_const, 4, OPTYPE_Reg, REG_L, 2, 0, 0),
(('cbe6', 'ffff'), 'set', OPTYPE_const, 4, OPTYPE_RegMem, REG_HL, 2, 0, 0),
(('cbe7', 'ffff'), 'set', OPTYPE_const, 4, OPTYPE_Reg, REG_A, 2, 0, 0),
(('cbe8', 'ffff'), 'set', OPTYPE_const, 5, OPTYPE_Reg, REG_B, 2, 0, 0),
(('cbe9', 'ffff'), 'set', OPTYPE_const, 5, OPTYPE_Reg, REG_C, 2, 0, 0),
(('cbea', 'ffff'), 'set', OPTYPE_const, 5, OPTYPE_Reg, REG_D, 2, 0, 0),
(('cbeb', 'ffff'), 'set', OPTYPE_const, 5, OPTYPE_Reg, REG_E, 2, 0, 0),
(('cbec', 'ffff'), 'set', OPTYPE_const, 5, OPTYPE_Reg, REG_H, 2, 0, 0),
(('cbed', 'ffff'), 'set', OPTYPE_const, 5, OPTYPE_Reg, REG_L, 2, 0, 0),
(('cbee', 'ffff'), 'set', OPTYPE_const, 5, OPTYPE_RegMem, REG_HL, 2, 0, 0),
(('cbef', 'ffff'), 'set', OPTYPE_const, 5, OPTYPE_Reg, REG_A, 2, 0, 0),
(('cbf0', 'ffff'), 'set', OPTYPE_const, 6, OPTYPE_Reg, REG_B, 2, 0, 0),
(('cbf1', 'ffff'), 'set', OPTYPE_const, 6, OPTYPE_Reg, REG_C, 2, 0, 0),
(('cbf2', 'ffff'), 'set', OPTYPE_const, 6, OPTYPE_Reg, REG_D, 2, 0, 0),
(('cbf3', 'ffff'), 'set', OPTYPE_const, 6, OPTYPE_Reg, REG_E, 2, 0, 0),
(('cbf4', 'ffff'), 'set', OPTYPE_const, 6, OPTYPE_Reg, REG_H, 2, 0, 0),
(('cbf5', 'ffff'), 'set', OPTYPE_const, 6, OPTYPE_Reg, REG_L, 2, 0, 0),
(('cbf6', 'ffff'), 'set', OPTYPE_const, 6, OPTYPE_RegMem, REG_HL, 2, 0, 0),
(('cbf7', 'ffff'), 'set', OPTYPE_const, 6, OPTYPE_Reg, REG_A, 2, 0, 0),
(('cbf8', 'ffff'), 'set', OPTYPE_const, 7, OPTYPE_Reg, REG_B, 2, 0, 0),
(('cbf9', 'ffff'), 'set', OPTYPE_const, 7, OPTYPE_Reg, REG_C, 2, 0, 0),
(('cbfa', 'ffff'), 'set', OPTYPE_const, 7, OPTYPE_Reg, REG_D, 2, 0, 0),
(('cbfb', 'ffff'), 'set', OPTYPE_const, 7, OPTYPE_Reg, REG_E, 2, 0, 0),
(('cbfc', 'ffff'), 'set', OPTYPE_const, 7, OPTYPE_Reg, REG_H, 2, 0, 0),
(('cbfd', 'ffff'), 'set', OPTYPE_const, 7, OPTYPE_Reg, REG_L, 2, 0, 0),
(('cbfe', 'ffff'), 'set', OPTYPE_const, 7, OPTYPE_RegMem, REG_HL, 2, 0, 0),
(('cbff', 'ffff'), 'set', OPTYPE_const, 7, OPTYPE_Reg, REG_A, 2, 0, 0),
(('cc0000', 'ff0000'), 'call', OPTYPE_Cond, COND_Z, OPTYPE_imm16, None, 3, 1, 0),
(('cd0000', 'ff0000'), 'call', OPTYPE_imm16, None, None, None, 3, 1, 0),
(('ce00', 'ff00'), 'adc', OPTYPE_Reg, REG_A, OPTYPE_imm8, None, 2, 1, 0),
(('cf', 'ff'), 'rst', OPTYPE_const, 8, None, None, 1, 0, 0),
(('d0', 'ff'), 'ret', OPTYPE_Cond, COND_NC, None, None, 1, 0, 0),
(('d1', 'ff'), 'pop', OPTYPE_Reg, REG_DE, None, None, 1, 0, 0),
(('d2', 'ff'), 'jp', OPTYPE_Cond, COND_NC, OPTYPE_Ind, None, 1, 0, 0),
(('d300', 'ff00'), 'out', OPTYPE_immmem8, None, OPTYPE_Reg, REG_A, 2, 1, 0),
(('d40000', 'ff0000'), 'call', OPTYPE_Cond, COND_NC, OPTYPE_imm16, None, 3, 1, 0),
(('d40000', 'ff0000'), 'call', OPTYPE_Cond, COND_NC, OPTYPE_imm16, None, 3, 1, 0),
(('d5', 'ff'), 'push', OPTYPE_Reg, REG_DE, None, None, 1, 0, 0),
(('d600', 'ff00'), 'sub', OPTYPE_imm8, None, None, None, 2, 1, 0),
(('d7', 'ff'), 'rst', OPTYPE_const, 16, None, None, 1, 0, 0),
(('d8', 'ff'), 'ret', OPTYPE_Reg, REG_C, None, None, 1, 0, 0),
(('d9', 'ff'), 'exx', None, None, None, None, 1, 0, 0),
(('da', 'ff'), 'jp', OPTYPE_Reg, REG_C, OPTYPE_Ind, None, 1, 0, 0),
(('db00', 'ff00'), 'in', OPTYPE_Reg, REG_A, OPTYPE_immmem8, None, 2, 1, 0),
(('dc0000', 'ff0000'), 'call', OPTYPE_Reg, REG_C, OPTYPE_imm16, None, 3, 1, 0),
(('dd09', 'ffff'), 'add', OPTYPE_Reg, REG_IX, OPTYPE_Reg, REG_BC, 2, 0, 0),
(('dd19', 'ffff'), 'add', OPTYPE_Reg, REG_IX, OPTYPE_Reg, REG_DE, 2, 0, 0),
(('dd210000', 'ffff0000'), 'ld', OPTYPE_Reg, REG_IX, OPTYPE_imm16, None, 4, 2, 0),
(('dd220000', 'ffff0000'), 'ld', OPTYPE_immmem16, None, OPTYPE_Reg, REG_IX, 4, 2, 0),
(('dd23', 'ffff'), 'inc', OPTYPE_Reg, REG_IX, None, None, 2, 0, 0),
(('dd29', 'ffff'), 'add', OPTYPE_Reg, REG_IX, OPTYPE_Reg, REG_IX, 2, 0, 0),
(('dd2a0000', 'ffff0000'), 'ld', OPTYPE_Reg, REG_IX, OPTYPE_immmem16, None, 4, 2, 0),
(('dd2b', 'ffff'), 'dec', OPTYPE_Reg, REG_IX, None, None, 2, 0, 0),
(('dd3400', 'ffff00'), 'inc', OPTYPE_RegMemDisp, REG_IX, None, None, 3, 2, 0),
(('dd3500', 'ffff00'), 'dec', OPTYPE_RegMemDisp, REG_IX, None, None, 3, 2, 0),
(('dd360000', 'ffff0000'), 'ld', OPTYPE_RegMemDisp, REG_IX, OPTYPE_imm8, None, 4, 2, 0),
(('dd39', 'ffff'), 'add', OPTYPE_Reg, REG_IX, OPTYPE_Reg, REG_SP, 2, 0, 0),
(('dd4600', 'ffff00'), 'ld', OPTYPE_Reg, REG_B, OPTYPE_RegMemDisp, REG_IX, 3, 2, 0),
(('dd4e00', 'ffff00'), 'ld', OPTYPE_Reg, REG_C, OPTYPE_RegMemDisp, REG_IX, 3, 2, 0),
(('dd5600', 'ffff00'), 'ld', OPTYPE_Reg, REG_D, OPTYPE_RegMemDisp, REG_IX, 3, 2, 0),
(('dd5e00', 'ffff00'), 'ld', OPTYPE_Reg, REG_E, OPTYPE_RegMemDisp, REG_IX, 3, 2, 0),
(('dd6600', 'ffff00'), 'ld', OPTYPE_Reg, REG_H, OPTYPE_RegMemDisp, REG_IX, 3, 2, 0),
(('dd6e00', 'ffff00'), 'ld', OPTYPE_Reg, REG_L, OPTYPE_RegMemDisp, REG_IX, 3, 2, 0),
(('dd7000', 'ffff00'), 'ld', OPTYPE_RegMemDisp, REG_IX, OPTYPE_Reg, REG_B, 3, 2, 0),
(('dd7100', 'ffff00'), 'ld', OPTYPE_RegMemDisp, REG_IX, OPTYPE_Reg, REG_C, 3, 2, 0),
(('dd7200', 'ffff00'), 'ld', OPTYPE_RegMemDisp, REG_IX, OPTYPE_Reg, REG_D, 3, 2, 0),
(('dd7300', 'ffff00'), 'ld', OPTYPE_RegMemDisp, REG_IX, OPTYPE_Reg, REG_E, 3, 2, 0),
(('dd7400', 'ffff00'), 'ld', OPTYPE_RegMemDisp, REG_IX, OPTYPE_Reg, REG_H, 3, 2, 0),
(('dd7500', 'ffff00'), 'ld', OPTYPE_RegMemDisp, REG_IX, OPTYPE_Reg, REG_L, 3, 2, 0),
(('dd7700', 'ffff00'), 'ld', OPTYPE_RegMemDisp, REG_IX, OPTYPE_Reg, REG_A, 3, 2, 0),
(('dd7e00', 'ffff00'), 'ld', OPTYPE_Reg, REG_A, OPTYPE_RegMemDisp, REG_IX, 3, 2, 0),
(('dd8600', 'ffff00'), 'add', OPTYPE_Reg, REG_A, OPTYPE_RegMemDisp, REG_IX, 3, 2, 0),
(('dd8e00', 'ffff00'), 'adc', OPTYPE_Reg, REG_A, OPTYPE_RegMemDisp, REG_IX, 3, 2, 0),
(('dd9600', 'ffff00'), 'sub', OPTYPE_RegMemDisp, REG_IX, None, None, 3, 2, 0),
(('dd9e00', 'ffff00'), 'sbc', OPTYPE_Reg, REG_A, OPTYPE_RegMemDisp, REG_IX, 3, 2, 0),
(('dda600', 'ffff00'), 'and', OPTYPE_RegMemDisp, REG_IX, None, None, 3, 2, 0),
(('ddae00', 'ffff00'), 'xor', OPTYPE_RegMemDisp, REG_IX, None, None, 3, 2, 0),
(('ddb600', 'ffff00'), 'or', OPTYPE_RegMemDisp, REG_IX, None, None, 3, 2, 0),
(('ddbe00', 'ffff00'), 'cp', OPTYPE_RegMemDisp, REG_IX, None, None, 3, 2, 0),
(('ddcb0006', 'ffff00ff'), 'rlc', OPTYPE_RegMemDisp, REG_IX, None, None, 4, 2, 0),
(('ddcb000e', 'ffff00ff'), 'rrc', OPTYPE_RegMemDisp, REG_IX, None, None, 4, 2, 0),
(('ddcb0016', 'ffff00ff'), 'rl', OPTYPE_RegMemDisp, REG_IX, None, None, 4, 2, 0),
(('ddcb001e', 'ffff00ff'), 'rr', OPTYPE_RegMemDisp, REG_IX, None, None, 4, 2, 0),
(('ddcb0026', 'ffff00ff'), 'sla', OPTYPE_RegMemDisp, REG_IX, None, None, 4, 2, 0),
(('ddcb002e', 'ffff00ff'), 'sra', OPTYPE_RegMemDisp, REG_IX, None, None, 4, 2, 0),
(('ddcb0046', 'ffff00ff'), 'bit', OPTYPE_const, 0, OPTYPE_RegMemDisp, REG_IX, 4, 2, 0),
(('ddcb004e', 'ffff00ff'), 'bit', OPTYPE_const, 1, OPTYPE_RegMemDisp, REG_IX, 4, 2, 0),
(('ddcb0056', 'ffff00ff'), 'bit', OPTYPE_const, 2, OPTYPE_RegMemDisp, REG_IX, 4, 2, 0),
(('ddcb005e', 'ffff00ff'), 'bit', OPTYPE_const, 3, OPTYPE_RegMemDisp, REG_IX, 4, 2, 0),
(('ddcb0066', 'ffff00ff'), 'bit', OPTYPE_const, 4, OPTYPE_RegMemDisp, REG_IX, 4, 2, 0),
(('ddcb006e', 'ffff00ff'), 'bit', OPTYPE_const, 5, OPTYPE_RegMemDisp, REG_IX, 4, 2, 0),
(('ddcb0076', 'ffff00ff'), 'bit', OPTYPE_const, 6, OPTYPE_RegMemDisp, REG_IX, 4, 2, 0),
(('ddcb007e', 'ffff00ff'), 'bit', OPTYPE_const, 7, OPTYPE_RegMemDisp, REG_IX, 4, 2, 0),
(('ddcb0086', 'ffff00ff'), 'res', OPTYPE_const, 0, OPTYPE_RegMemDisp, REG_IX, 4, 2, 0),
(('ddcb008e', 'ffff00ff'), 'res', OPTYPE_const, 1, OPTYPE_RegMemDisp, REG_IX, 4, 2, 0),
(('ddcb0096', 'ffff00ff'), 'res', OPTYPE_const, 2, OPTYPE_RegMemDisp, REG_IX, 4, 2, 0),
(('ddcb009e', 'ffff00ff'), 'res', OPTYPE_const, 3, OPTYPE_RegMemDisp, REG_IX, 4, 2, 0),
(('ddcb00a6', 'ffff00ff'), 'res', OPTYPE_const, 4, OPTYPE_RegMemDisp, REG_IX, 4, 2, 0),
(('ddcb00ae', 'ffff00ff'), 'res', OPTYPE_const, 5, OPTYPE_RegMemDisp, REG_IX, 4, 2, 0),
(('ddcb00b6', 'ffff00ff'), 'res', OPTYPE_const, 6, OPTYPE_RegMemDisp, REG_IX, 4, 2, 0),
(('ddcb00be', 'ffff00ff'), 'res', OPTYPE_const, 7, OPTYPE_RegMemDisp, REG_IX, 4, 2, 0),
(('ddcb00c6', 'ffff00ff'), 'set', OPTYPE_const, 0, OPTYPE_RegMemDisp, REG_IX, 4, 2, 0),
(('ddcb00ce', 'ffff00ff'), 'set', OPTYPE_const, 1, OPTYPE_RegMemDisp, REG_IX, 4, 2, 0),
(('ddcb00d6', 'ffff00ff'), 'set', OPTYPE_const, 2, OPTYPE_RegMemDisp, REG_IX, 4, 2, 0),
(('ddcb00de', 'ffff00ff'), 'set', OPTYPE_const, 3, OPTYPE_RegMemDisp, REG_IX, 4, 2, 0),
(('ddcb00e6', 'ffff00ff'), 'set', OPTYPE_const, 4, OPTYPE_RegMemDisp, REG_IX, 4, 2, 0),
(('ddcb00ee', 'ffff00ff'), 'set', OPTYPE_const, 5, OPTYPE_RegMemDisp, REG_IX, 4, 2, 0),
(('ddcb00f6', 'ffff00ff'), 'set', OPTYPE_const, 6, OPTYPE_RegMemDisp, REG_IX, 4, 2, 0),
(('ddcb00fe', 'ffff00ff'), 'set', OPTYPE_const, 7, OPTYPE_RegMemDisp, REG_IX, 4, 2, 0),
(('dde1', 'ffff'), 'pop', OPTYPE_Reg, REG_IX, None, None, 2, 0, 0),
(('dde3', 'ffff'), 'ex', OPTYPE_RegMem, REG_SP, OPTYPE_Reg, REG_IX, 2, 0, 0),
(('dde5', 'ffff'), 'push', OPTYPE_Reg, REG_IX, None, None, 2, 0, 0),
(('dde9', 'ffff'), 'jp', OPTYPE_RegMem, REG_IX, None, None, 2, 0, 0),
(('ddf9', 'ffff'), 'ld', OPTYPE_Reg, REG_SP, OPTYPE_Reg, REG_IX, 2, 0, 0),
(('de00', 'ff00'), 'sbc', OPTYPE_Reg, REG_A, OPTYPE_imm8, None, 2, 1, 0),
(('df', 'ff'), 'rst', OPTYPE_const, 24, None, None, 1, 0, 0),
(('e0', 'ff'), 'ret', OPTYPE_Cond, COND_PO, None, None, 1, 0, 0),
(('e1', 'ff'), 'pop', OPTYPE_Reg, REG_HL, None, None, 1, 0, 0),
(('e2', 'ff'), 'jp', OPTYPE_Cond, COND_PO, OPTYPE_Ind, None, 1, 0, 0),
(('e3', 'ff'), 'ex', OPTYPE_RegMem, REG_SP, OPTYPE_Reg, REG_HL, 1, 0, 0),
(('e40000', 'ff0000'), 'call', OPTYPE_Cond, COND_PO, OPTYPE_imm16, None, 3, 1, 0),
(('e5', 'ff'), 'push', OPTYPE_Reg, REG_HL, None, None, 1, 0, 0),
(('e600', 'ff00'), 'and', OPTYPE_imm8, None, None, None, 2, 1, 0),
(('e7', 'ff'), 'rst', OPTYPE_const, 32, None, None, 1, 0, 0),
(('e8', 'ff'), 'ret', OPTYPE_Cond, COND_PE, None, None, 1, 0, 0),
(('e9', 'ff'), 'jp', OPTYPE_RegMem, REG_HL, None, None, 1, 0, 0),
(('ea', 'ff'), 'jp', OPTYPE_Cond, COND_PE, OPTYPE_Ind, None, 1, 0, 0),
(('eb', 'ff'), 'ex', OPTYPE_Reg, REG_DE, OPTYPE_Reg, REG_HL, 1, 0, 0),
(('ec0000', 'ff0000'), 'call', OPTYPE_Cond, COND_PE, OPTYPE_imm16, None, 3, 1, 0),
(('ed40', 'ffff'), 'in', OPTYPE_Reg, REG_B, OPTYPE_RegMem, REG_C, 2, 0, 0),
(('ed41', 'ffff'), 'out', OPTYPE_RegMem, REG_C, OPTYPE_Reg, REG_B, 2, 0, 0),
(('ed42', 'ffff'), 'sbc', OPTYPE_Reg, REG_HL, OPTYPE_Reg, REG_BC, 2, 0, 0),
(('ed430000', 'ffff0000'), 'ld', OPTYPE_immmem16, None, OPTYPE_Reg, REG_BC, 4, 2, 0),
(('ed44', 'ffff'), 'neg', None, None, None, None, 2, 0, 0),
(('ed45', 'ffff'), 'retn', None, None, None, None, 2, 0, 0),
(('ed46', 'ffff'), 'im', OPTYPE_const, 0, None, None, 2, 0, 0),
(('ed47', 'ffff'), 'ld', OPTYPE_Reg, REG_I, OPTYPE_Reg, REG_A, 2, 0, 0),
(('ed48', 'ffff'), 'in', OPTYPE_Reg, REG_C, OPTYPE_RegMem, REG_C, 2, 0, 0),
(('ed49', 'ffff'), 'out', OPTYPE_RegMem, REG_C, OPTYPE_Reg, REG_C, 2, 0, 0),
(('ed4a', 'ffff'), 'adc', OPTYPE_Reg, REG_HL, OPTYPE_Reg, REG_BC, 2, 0, 0),
(('ed4b0000', 'ffff0000'), 'ld', OPTYPE_Reg, REG_BC, OPTYPE_immmem16, None, 4, 2, 0),
(('ed4d', 'ffff'), 'reti', None, None, None, None, 2, 0, 0),
(('ed50', 'ffff'), 'in', OPTYPE_Reg, REG_D, OPTYPE_RegMem, REG_C, 2, 0, 0),
(('ed51', 'ffff'), 'out', OPTYPE_RegMem, REG_C, OPTYPE_Reg, REG_D, 2, 0, 0),
(('ed52', 'ffff'), 'sbc', OPTYPE_Reg, REG_HL, OPTYPE_Reg, REG_DE, 2, 0, 0),
(('ed530000', 'ffff0000'), 'ld', OPTYPE_immmem16, None, OPTYPE_Reg, REG_DE, 4, 2, 0),
(('ed56', 'ffff'), 'im', OPTYPE_const, 1, None, None, 2, 0, 0),
(('ed57', 'ffff'), 'ld', OPTYPE_Reg, REG_A, OPTYPE_Reg, REG_I, 2, 0, 0),
(('ed58', 'ffff'), 'in', OPTYPE_Reg, REG_E, OPTYPE_RegMem, REG_C, 2, 0, 0),
(('ed59', 'ffff'), 'out', OPTYPE_RegMem, REG_C, OPTYPE_Reg, REG_E, 2, 0, 0),
(('ed5a', 'ffff'), 'adc', OPTYPE_Reg, REG_HL, OPTYPE_Reg, REG_DE, 2, 0, 0),
(('ed5b0000', 'ffff0000'), 'ld', OPTYPE_Reg, REG_DE, OPTYPE_immmem16, None, 4, 2, 0),
(('ed5e', 'ffff'), 'im', OPTYPE_const, 2, None, None, 2, 0, 0),
(('ed60', 'ffff'), 'in', OPTYPE_Reg, REG_H, OPTYPE_RegMem, REG_C, 2, 0, 0),
(('ed61', 'ffff'), 'out', OPTYPE_RegMem, REG_C, OPTYPE_Reg, REG_H, 2, 0, 0),
(('ed62', 'ffff'), 'sbc', OPTYPE_Reg, REG_HL, OPTYPE_Reg, REG_HL, 2, 0, 0),
(('ed67', 'ffff'), 'rrd', None, None, None, None, 2, 0, 0),
(('ed68', 'ffff'), 'in', OPTYPE_Reg, REG_L, OPTYPE_RegMem, REG_C, 2, 0, 0),
(('ed69', 'ffff'), 'out', OPTYPE_RegMem, REG_C, OPTYPE_Reg, REG_L, 2, 0, 0),
(('ed6a', 'ffff'), 'adc', OPTYPE_Reg, REG_HL, OPTYPE_Reg, REG_HL, 2, 0, 0),
(('ed6f', 'ffff'), 'rld', None, None, None, None, 2, 0, 0),
(('ed72', 'ffff'), 'sbc', OPTYPE_Reg, REG_HL, OPTYPE_Reg, REG_SP, 2, 0, 0),
(('ed730000', 'ffff0000'), 'ld', OPTYPE_immmem16, None, OPTYPE_Reg, REG_SP, 4, 2, 0),
(('ed78', 'ffff'), 'in', OPTYPE_Reg, REG_A, OPTYPE_RegMem, REG_C, 2, 0, 0),
(('ed79', 'ffff'), 'out', OPTYPE_RegMem, REG_C, OPTYPE_Reg, REG_A, 2, 0, 0),
(('ed7a', 'ffff'), 'adc', OPTYPE_Reg, REG_HL, OPTYPE_Reg, REG_SP, 2, 0, 0),
(('ed7b0000', 'ffff0000'), 'ld', OPTYPE_Reg, REG_SP, OPTYPE_immmem16, None, 4, 2, 0),
(('eda0', 'ffff'), 'ldi', None, None, None, None, 2, 0, 0),
(('eda1', 'ffff'), 'cpi', None, None, None, None, 2, 0, 0),
(('eda2', 'ffff'), 'ini', None, None, None, None, 2, 0, 0),
(('eda3', 'ffff'), 'outi', None, None, None, None, 2, 0, 0),
(('eda8', 'ffff'), 'ldd', None, None, None, None, 2, 0, 0),
(('eda9', 'ffff'), 'cpd', None, None, None, None, 2, 0, 0),
(('edaa', 'ffff'), 'ind', None, None, None, None, 2, 0, 0),
(('edab', 'ffff'), 'outd', None, None, None, None, 2, 0, 0),
(('edb0', 'ffff'), 'ldir', None, None, None, None, 2, 0, 0),
(('edb1', 'ffff'), 'cpir', None, None, None, None, 2, 0, 0),
(('edb2', 'ffff'), 'inir', None, None, None, None, 2, 0, 0),
(('edb3', 'ffff'), 'otir', None, None, None, None, 2, 0, 0),
(('edb8', 'ffff'), 'lddr', None, None, None, None, 2, 0, 0),
(('edb9', 'ffff'), 'cpdr', None, None, None, None, 2, 0, 0),
(('edba', 'ffff'), 'indr', None, None, None, None, 2, 0, 0),
(('edbb', 'ffff'), 'otdr', None, None, None, None, 2, 0, 0),
(('ee00', 'ff00'), 'xor', OPTYPE_imm8, None, None, None, 2, 1, 0),
(('ef', 'ff'), 'rst', OPTYPE_const, 40, None, None, 1, 0, 0),
(('f0', 'ff'), 'ret', OPTYPE_Cond, COND_P, None, None, 1, 0, 0),
(('f1', 'ff'), 'pop', OPTYPE_Reg, REG_AF, None, None, 1, 0, 0),
(('f2', 'ff'), 'jp', OPTYPE_Cond, COND_P, OPTYPE_Ind, None, 1, 0, 0),
(('f3', 'ff'), 'di', None, None, None, None, 1, 0, 0),
(('f40000', 'ff0000'), 'call', OPTYPE_Cond, COND_P, OPTYPE_imm16, None, 3, 1, 0),
(('f5', 'ff'), 'push', OPTYPE_Reg, REG_AF, None, None, 1, 0, 0),
(('f600', 'ff00'), 'or', OPTYPE_imm8, None, None, None, 2, 1, 0),
(('f7', 'ff'), 'rst', OPTYPE_const, 48, None, None, 1, 0, 0),
(('f8', 'ff'), 'ret', OPTYPE_Cond, COND_M, None, None, 1, 0, 0),
(('f9', 'ff'), 'ld', OPTYPE_Reg, REG_SP, OPTYPE_Reg, REG_HL, 1, 0, 0),
(('fa', 'ff'), 'jp', OPTYPE_Cond, COND_M, OPTYPE_Ind, None, 1, 0, 0),
(('fb', 'ff'), 'ei', None, None, None, None, 1, 0, 0),
(('fc0000', 'ff0000'), 'call', OPTYPE_Cond, COND_M, OPTYPE_imm16, None, 3, 1, 0),
(('fd09', 'ffff'), 'add', OPTYPE_Reg, REG_IY, OPTYPE_Reg, REG_BC, 2, 0, 0),
(('fd19', 'ffff'), 'add', OPTYPE_Reg, REG_IY, OPTYPE_Reg, REG_DE, 2, 0, 0),
(('fd210000', 'ffff0000'), 'ld', OPTYPE_Reg, REG_IY, OPTYPE_imm16, None, 4, 2, 0),
(('fd220000', 'ffff0000'), 'ld', OPTYPE_immmem16, None, OPTYPE_Reg, REG_IY, 4, 2, 0),
(('fd23', 'ffff'), 'inc', OPTYPE_Reg, REG_IY, None, None, 2, 0, 0),
(('fd29', 'ffff'), 'add', OPTYPE_Reg, REG_IY, OPTYPE_Reg, REG_IY, 2, 0, 0),
(('fd2a0000', 'ffff0000'), 'ld', OPTYPE_Reg, REG_IY, OPTYPE_immmem16, None, 4, 2, 0),
(('fd2b', 'ffff'), 'dec', OPTYPE_Reg, REG_IY, None, None, 2, 0, 0),
(('fd3400', 'ffff00'), 'inc', OPTYPE_RegMemDisp, REG_IY, None, None, 3, 2, 0),
(('fd3500', 'ffff00'), 'dec', OPTYPE_RegMemDisp, REG_IY, None, None, 3, 2, 0),
(('fd360000', 'ffff0000'), 'ld', OPTYPE_RegMemDisp, REG_IY, OPTYPE_imm8, None, 4, 2, 0),
(('fd39', 'ffff'), 'add', OPTYPE_Reg, REG_IY, OPTYPE_Reg, REG_SP, 2, 0, 0),
(('fd4600', 'ffff00'), 'ld', OPTYPE_Reg, REG_B, OPTYPE_RegMemDisp, REG_IY, 3, 2, 0),
(('fd4e00', 'ffff00'), 'ld', OPTYPE_Reg, REG_C, OPTYPE_RegMemDisp, REG_IY, 3, 2, 0),
(('fd5600', 'ffff00'), 'ld', OPTYPE_Reg, REG_D, OPTYPE_RegMemDisp, REG_IY, 3, 2, 0),
(('fd5e00', 'ffff00'), 'ld', OPTYPE_Reg, REG_E, OPTYPE_RegMemDisp, REG_IY, 3, 2, 0),
(('fd6600', 'ffff00'), 'ld', OPTYPE_Reg, REG_H, OPTYPE_RegMemDisp, REG_IY, 3, 2, 0),
(('fd6e00', 'ffff00'), 'ld', OPTYPE_Reg, REG_L, OPTYPE_RegMemDisp, REG_IY, 3, 2, 0),
(('fd7000', 'ffff00'), 'ld', OPTYPE_RegMemDisp, REG_IY, OPTYPE_Reg, REG_B, 3, 2, 0),
(('fd7100', 'ffff00'), 'ld', OPTYPE_RegMemDisp, REG_IY, OPTYPE_Reg, REG_C, 3, 2, 0),
(('fd7200', 'ffff00'), 'ld', OPTYPE_RegMemDisp, REG_IY, OPTYPE_Reg, REG_D, 3, 2, 0),
(('fd7300', 'ffff00'), 'ld', OPTYPE_RegMemDisp, REG_IY, OPTYPE_Reg, REG_E, 3, 2, 0),
(('fd7400', 'ffff00'), 'ld', OPTYPE_RegMemDisp, REG_IY, OPTYPE_Reg, REG_H, 3, 2, 0),
(('fd7500', 'ffff00'), 'ld', OPTYPE_RegMemDisp, REG_IY, OPTYPE_Reg, REG_L, 3, 2, 0),
(('fd7700', 'ffff00'), 'ld', OPTYPE_RegMemDisp, REG_IY, OPTYPE_Reg, REG_A, 3, 2, 0),
(('fd7e00', 'ffff00'), 'ld', OPTYPE_Reg, REG_A, OPTYPE_RegMemDisp, REG_IY, 3, 2, 0),
(('fd8600', 'ffff00'), 'add', OPTYPE_Reg, REG_A, OPTYPE_RegMemDisp, REG_IY, 3, 2, 0),
(('fd8e00', 'ffff00'), 'adc', OPTYPE_Reg, REG_A, OPTYPE_RegMemDisp, REG_IY, 3, 2, 0),
(('fd9600', 'ffff00'), 'sub', OPTYPE_RegMemDisp, REG_IY, None, None, 3, 2, 0),
(('fd9e00', 'ffff00'), 'sbc', OPTYPE_Reg, REG_A, OPTYPE_RegMemDisp, REG_IY, 3, 2, 0),
(('fda600', 'ffff00'), 'and', OPTYPE_RegMemDisp, REG_IY, None, None, 3, 2, 0),
(('fdae00', 'ffff00'), 'xor', OPTYPE_RegMemDisp, REG_IY, None, None, 3, 2, 0),
(('fdb600', 'ffff00'), 'or', OPTYPE_RegMemDisp, REG_IY, None, None, 3, 2, 0),
(('fdbe00', 'ffff00'), 'cp', OPTYPE_RegMemDisp, REG_IY, None, None, 3, 2, 0),
(('fdcb0006', 'ffff00ff'), 'rlc', OPTYPE_RegMemDisp, REG_IY, None, None, 4, 2, 0),
(('fdcb000e', 'ffff00ff'), 'rrc', OPTYPE_RegMemDisp, REG_IY, None, None, 4, 2, 0),
(('fdcb0016', 'ffff00ff'), 'rl', OPTYPE_RegMemDisp, REG_IY, None, None, 4, 2, 0),
(('fdcb001e', 'ffff00ff'), 'rr', OPTYPE_RegMemDisp, REG_IY, None, None, 4, 2, 0),
(('fdcb0026', 'ffff00ff'), 'sla', OPTYPE_RegMemDisp, REG_IY, None, None, 4, 2, 0),
(('fdcb002e', 'ffff00ff'), 'sra', OPTYPE_RegMemDisp, REG_IY, None, None, 4, 2, 0),
(('fdcb0046', 'ffff00ff'), 'bit', OPTYPE_const, 0, OPTYPE_RegMemDisp, REG_IY, 4, 2, 0),
(('fdcb004e', 'ffff00ff'), 'bit', OPTYPE_const, 1, OPTYPE_RegMemDisp, REG_IY, 4, 2, 0),
(('fdcb0056', 'ffff00ff'), 'bit', OPTYPE_const, 2, OPTYPE_RegMemDisp, REG_IY, 4, 2, 0),
(('fdcb005e', 'ffff00ff'), 'bit', OPTYPE_const, 3, OPTYPE_RegMemDisp, REG_IY, 4, 2, 0),
(('fdcb0066', 'ffff00ff'), 'bit', OPTYPE_const, 4, OPTYPE_RegMemDisp, REG_IY, 4, 2, 0),
(('fdcb006e', 'ffff00ff'), 'bit', OPTYPE_const, 5, OPTYPE_RegMemDisp, REG_IY, 4, 2, 0),
(('fdcb0076', 'ffff00ff'), 'bit', OPTYPE_const, 6, OPTYPE_RegMemDisp, REG_IY, 4, 2, 0),
(('fdcb007e', 'ffff00ff'), 'bit', OPTYPE_const, 7, OPTYPE_RegMemDisp, REG_IY, 4, 2, 0),
(('fdcb0086', 'ffff00ff'), 'res', OPTYPE_const, 0, OPTYPE_RegMemDisp, REG_IY, 4, 2, 0),
(('fdcb008e', 'ffff00ff'), 'res', OPTYPE_const, 1, OPTYPE_RegMemDisp, REG_IY, 4, 2, 0),
(('fdcb0096', 'ffff00ff'), 'res', OPTYPE_const, 2, OPTYPE_RegMemDisp, REG_IY, 4, 2, 0),
(('fdcb009e', 'ffff00ff'), 'res', OPTYPE_const, 3, OPTYPE_RegMemDisp, REG_IY, 4, 2, 0),
(('fdcb00a6', 'ffff00ff'), 'res', OPTYPE_const, 4, OPTYPE_RegMemDisp, REG_IY, 4, 2, 0),
(('fdcb00ae', 'ffff00ff'), 'res', OPTYPE_const, 5, OPTYPE_RegMemDisp, REG_IY, 4, 2, 0),
(('fdcb00b6', 'ffff00ff'), 'res', OPTYPE_const, 6, OPTYPE_RegMemDisp, REG_IY, 4, 2, 0),
(('fdcb00be', 'ffff00ff'), 'res', OPTYPE_const, 7, OPTYPE_RegMemDisp, REG_IY, 4, 2, 0),
(('fdcb00c6', 'ffff00ff'), 'set', OPTYPE_const, 0, OPTYPE_RegMemDisp, REG_IY, 4, 2, 0),
(('fdcb00ce', 'ffff00ff'), 'set', OPTYPE_const, 1, OPTYPE_RegMemDisp, REG_IY, 4, 2, 0),
(('fdcb00d6', 'ffff00ff'), 'set', OPTYPE_const, 2, OPTYPE_RegMemDisp, REG_IY, 4, 2, 0),
(('fdcb00de', 'ffff00ff'), 'set', OPTYPE_const, 3, OPTYPE_RegMemDisp, REG_IY, 4, 2, 0),
(('fdcb00e6', 'ffff00ff'), 'set', OPTYPE_const, 4, OPTYPE_RegMemDisp, REG_IY, 4, 2, 0),
(('fdcb00ee', 'ffff00ff'), 'set', OPTYPE_const, 5, OPTYPE_RegMemDisp, REG_IY, 4, 2, 0),
(('fdcb00f6', 'ffff00ff'), 'set', OPTYPE_const, 6, OPTYPE_RegMemDisp, REG_IY, 4, 2, 0),
(('fdcb00fe', 'ffff00ff'), 'set', OPTYPE_const, 7, OPTYPE_RegMemDisp, REG_IY, 4, 2, 0),
(('fde1', 'ffff'), 'pop', OPTYPE_Reg, REG_IY, None, None, 2, 0, 0),
(('fde3', 'ffff'), 'ex', OPTYPE_RegMem, REG_SP, OPTYPE_Reg, REG_IY, 2, 0, 0),
(('fde5', 'ffff'), 'push', OPTYPE_Reg, REG_IY, None, None, 2, 0, 0),
(('fde9', 'ffff'), 'jp', OPTYPE_RegMem, REG_IY, None, None, 2, 0, 0),
(('fdf9', 'ffff'), 'ld', OPTYPE_Reg, REG_SP, OPTYPE_Reg, REG_IY, 2, 0, 0),
(('fe00', 'ff00'), 'cp', OPTYPE_imm8, None, None, None, 2, 1, 0),
(('ff', 'ff'), 'rst', OPTYPE_const, 56, None, None, 1, 0, 0),
]
from envi.bits import binbytes as bb
nbits = '00000000'
nnbits = '0000000000000000'
newtab = (
# 8bit ld variants...
(bb('01000000'), bb('11000000'), 'ld', OPTYPE_Reg, (2, 3), OPTYPE_Reg, (5, 3)),
(bb('00000110'), bb('11000111'), 'ld', OPTYPE_Reg, (2, 3), OPTYPE_Imm, (8, 8)),
(bb('01000110'), bb('11000111'), 'ld', OPTYPE_Reg, (2, 3), OPTYPE_OpReg, REG_HL),
(bb('110111010100011000000000'), bb('111111111100011100000000'), 'ld', OPTYPE_Reg, (10, 3), OPTYPE_RegMemDisp, (REG_IX, 16, 8)),
(bb('111111010100011000000000'), bb('111111111100011100000000'), 'ld', OPTYPE_Reg, (10, 3), OPTYPE_RegMemDisp, (REG_IY, 16, 8)),
(bb('01110000'), bb('11111000'), 'ld', OPTYPE_RegMem, (REG_HL, None, None), OPTYPE_Reg, (5, 3)),
(bb('110111010111000000000000'), bb('111111111111100000000000'), 'ld', OPTYPE_RegMemDisp, (REG_IX, 16, 8), OPTYPE_Reg, (13, 3)),
(bb('111111010111000000000000'), bb('111111111111100000000000'), 'ld', OPTYPE_RegMemDisp, (REG_IY, 16, 8), OPTYPE_Reg, (13, 3)),
(bb('0011011000000000'), bb('1111111100000000'), 'ld', OPTYPE_RegMem, (REG_HL, None, None), OPTYPE_Imm, (8, 8)),
(bb('11011101001101100000000000000000'), bb('11111111111111110000000000000000'), 'ld', OPTYPE_RegMemDisp, (REG_IX, 16, 8), OPTYPE_Imm, (24, 8)),
(bb('11111101001101100000000000000000'), bb('11111111111111110000000000000000'), 'ld', OPTYPE_RegMemDisp, (REG_IY, 16, 8), OPTYPE_Imm, (24, 8)),
(bb('00001010'), bb('11111111'), 'ld', OPTYPE_OpReg, REG_A, OPTYPE_RegMem, (REG_BC, None, None)),
(bb('00011010'), bb('11111111'), 'ld', OPTYPE_OpReg, REG_A, OPTYPE_RegMem, (REG_DE, None, None)),
(bb('001110100000000000000000'), bb('111111110000000000000000'), 'ld', OPTYPE_OpReg, REG_A, OPTYPE_ImmMem, (8, 16)),
(bb('00000010'), bb('11111111'), 'ld', OPTYPE_RegMem, (REG_BC, None, None), OPTYPE_OpReg, REG_A),
(bb('00010010'), bb('11111111'), 'ld', OPTYPE_RegMem, (REG_DE, None, None), OPTYPE_OpReg, REG_A),
(bb('001100100000000000000000'), bb('111111110000000000000000'), 'ld', OPTYPE_ImmMem, (8, 16), OPTYPE_OpReg, REG_A),
(bb('1110110101010111'), bb('1111111111111111'), 'ld', OPTYPE_OpReg, REG_A, OPTYPE_OpReg, REG_I),
(bb('1110110101011111'), bb('1111111111111111'), 'ld', OPTYPE_OpReg, REG_A, OPTYPE_OpReg, REG_R),
(bb('1110110101000111'), bb('1111111111111111'), 'ld', OPTYPE_OpReg, REG_I, OPTYPE_OpReg, REG_A),
(bb('111011010100f111'), bb('1111111111111111'), 'ld', OPTYPE_OpReg, REG_R, OPTYPE_OpReg, REG_A),
# 16 bit ld variants
(bb('000000010000000000000000'), bb('110011110000000000000000'), 'ld', OPTYPE_RegPair, (2, 2), OPTYPE_Imm, (8, 16)),
(bb('11011101001000010000000000000000'), bb('11111111111111110000000000000000'), 'ld', OPTYPE_OpReg, REG_IX, OPTYPE_Imm, (16, 16)),
(bb('11111101001000010000000000000000'), bb('11111111111111110000000000000000'), 'ld', OPTYPE_OpReg, REG_IY, OPTYPE_Imm, (16, 16)),
(bb('001010100000000000000000'), bb('111111110000000000000000'), 'ld', OPTYPE_OpReg, REG_HL, OPTYPE_ImmMem, (8,16)),
(bb('11101101010010110000000000000000'), bb('11111111110011110000000000000000'), 'ld', OPTYPE_RegPair, (10, 2), OPTYPE_ImmMem, (16, 16)),
(bb('11011101001010100000000000000000'), bb('11111111111111110000000000000000'), 'ld', OPTYPE_OpReg, REG_IX, OPTYPE_ImmMem, (16, 16)),
(bb('11111101001010100000000000000000'), bb('11111111111111110000000000000000'), 'ld', OPTYPE_OpReg, REG_IY, OPTYPE_ImmMem, (16, 16)),
(bb('001000100000000000000000'), bb('111111110000000000000000'), 'ld', OPTYPE_ImmMem, (8, 16), OPTYPE_OpReg, REG_HL),
)
| {
"pile_set_name": "Github"
} |
/* eslint-disable @typescript-eslint/explicit-module-boundary-types */
import { CommandOperation, CommandOperationOptions } from './command';
import { EvalOperation } from './eval';
import { Code, Document } from '../bson';
import type { Callback } from '../utils';
import type { Server } from '../sdam/server';
import type { Collection } from '../collection';
export type GroupOptions = CommandOperationOptions;
/** @internal */
export class GroupOperation extends CommandOperation<GroupOptions, Document> {
collectionName: string;
keys: any;
condition: Document;
initial: any;
reduceFunction: Code;
finalize: Code;
constructor(
collection: Collection,
keys: any,
condition: Document,
initial: Document,
reduce: any,
finalize: Code,
options?: GroupOptions
) {
super(collection, options);
this.collectionName = collection.collectionName;
this.keys = keys;
this.condition = condition;
this.initial = initial;
this.finalize = finalize;
this.reduceFunction = reduce && reduce._bsontype === 'Code' ? reduce : new Code(reduce);
}
execute(server: Server, callback: Callback<Document>): void {
const cmd: Document = {
group: {
ns: this.collectionName,
$reduce: this.reduceFunction,
cond: this.condition,
initial: this.initial,
out: 'inline'
}
};
// if finalize is defined
if (this.finalize != null) {
cmd.group.finalize = this.finalize;
}
// Set up group selector
if ('function' === typeof this.keys || (this.keys && this.keys._bsontype === 'Code')) {
cmd.group.$keyf =
this.keys && this.keys._bsontype === 'Code' ? this.keys : new Code(this.keys);
} else {
const hash: { [key: string]: 1 } = {};
this.keys.forEach((key: string) => {
hash[key] = 1;
});
cmd.group.key = hash;
}
// Execute command
super.executeCommand(server, cmd, (err, result) => {
if (err) return callback(err);
callback(undefined, result.retval);
});
}
}
const groupFunction =
'function () {\nvar c = db[ns].find(condition);\nvar map = new Map();\nvar reduce_function = reduce;\n\nwhile (c.hasNext()) {\nvar obj = c.next();\nvar key = {};\n\nfor (var i = 0, len = keys.length; i < len; ++i) {\nvar k = keys[i];\nkey[k] = obj[k];\n}\n\nvar aggObj = map.get(key);\n\nif (aggObj == null) {\nvar newObj = Object.extend({}, key);\naggObj = Object.extend(newObj, initial);\nmap.put(key, aggObj);\n}\n\nreduce_function(obj, aggObj);\n}\n\nreturn { "result": map.values() };\n}';
export class EvalGroupOperation extends EvalOperation {
constructor(
collection: Collection,
keys: string[],
condition: Document,
initial: Document,
reduce: any,
finalize: Code,
options?: GroupOptions
) {
// Create execution scope
const scope = reduce != null && reduce._bsontype === 'Code' ? reduce.scope : {};
scope.ns = collection.collectionName;
scope.keys = keys;
scope.condition = condition;
scope.initial = initial;
// Pass in the function text to execute within mongodb.
const groupfn = groupFunction.replace(/ reduce;/, reduce.toString() + ';');
super(collection, new Code(groupfn, scope), undefined, options);
}
}
| {
"pile_set_name": "Github"
} |
package edu.tum.cup2.generator.states;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedList;
import edu.tum.cup2.generator.GrammarInfo;
import edu.tum.cup2.generator.items.LR0Item;
import edu.tum.cup2.grammar.NonTerminal;
import edu.tum.cup2.grammar.Production;
import edu.tum.cup2.grammar.Symbol;
/**
* LR(0) state, consisting of a list of LR(0) items.
*
* @author Andreas Wenger
*/
public final class LR0State
extends LRState<LR0Item>
{
//cache
private final int hashCode;
/**
* Creates a new {@link LR0State} with the given items.
*/
public LR0State(Collection<LR0Item> items)
{
super(items);
//compute hashcode
int sum = 0;
for (LR0Item item : items)
{
sum += item.hashCode();
}
this.hashCode = sum;
}
public LR0State(LR0Item... items)
{
this(Arrays.asList(items));
}
/**
* Returns the closure of this {@link LR0State} as another
* {@link LR0State}.
*/
@Override public LR0State closure(GrammarInfo grammarInfo)
{
return new LR0State(closure(items, grammarInfo));
}
/**
* Returns the closure of the given {@link LR0Item}s as another
* set of {@link LR0Item}s.
* For a description of this algorithm, see Appel's book, page 60,
* or ASU, page 271.
*/
private HashSet<LR0Item> closure(Collection<LR0Item> items, GrammarInfo grammarInfo)
{
//the closure contains all items of the source...
HashSet<LR0Item> ret = new HashSet<LR0Item>();
ret.addAll(items);
//... and the following ones (for any item "A → α.Xβ" and any "X → γ" add "X → .γ")
LinkedList<LR0Item> queue = new LinkedList<LR0Item>();
queue.addAll(items);
while (!queue.isEmpty())
{
LR0Item it = queue.removeFirst();
Symbol nextSymbol = it.getNextSymbol();
if (nextSymbol instanceof NonTerminal)
{
for (Production p : grammarInfo.getProductionsFrom((NonTerminal) nextSymbol))
{
LR0Item newitem = new LR0Item(p, 0);
if (!ret.contains(newitem))
{
ret.add(newitem);
queue.addLast(newitem);
}
}
}
}
return ret;
}
/**
* Moves the position of the items one step further when
* the given symbol follows and returns them as a new state
* (only the kernel, without closure).
* For a description of this algorithm, see Appel's book, page 60.
*/
@Override public LR0State goTo(Symbol symbol)
{
HashSet<LR0Item> ret = new HashSet<LR0Item>();
//find all items where the given symbol follows and add them shifted
for (LR0Item item : items)
{
if (item.getNextSymbol() == symbol)
{
ret.add(item.shift());
}
}
return new LR0State(ret);
}
@Override public boolean equals(Object obj)
{
if (obj instanceof LR0State)
{
LR0State s = (LR0State) obj;
if (items.size() != s.items.size())
return false;
for (LR0Item item : items)
{
if (!s.items.contains(item))
return false;
}
return true;
}
return false;
}
@Override public int hashCode()
{
return hashCode;
}
}
| {
"pile_set_name": "Github"
} |
namespace TrafficManager.UI.Textures {
using UnityEngine;
using static TextureResources;
/// <summary>
/// Textures for UI controlling the traffic lights
/// </summary>
public static class TrafficLightTextures {
public static readonly Texture2D RedLight;
public static readonly Texture2D RedLightForwardLeft;
public static readonly Texture2D RedLightForwardRight;
public static readonly Texture2D RedLightLeft;
public static readonly Texture2D RedLightRight;
public static readonly Texture2D RedLightStraight;
public static readonly Texture2D PedestrianRedLight;
public static readonly Texture2D YellowLight;
public static readonly Texture2D YellowLightForwardLeft;
public static readonly Texture2D YellowLightForwardRight;
public static readonly Texture2D YellowLightLeft;
public static readonly Texture2D YellowLightRight;
public static readonly Texture2D YellowLightStraight;
public static readonly Texture2D YellowRedLight;
public static readonly Texture2D GreenLight;
public static readonly Texture2D GreenLightForwardLeft;
public static readonly Texture2D GreenLightForwardRight;
public static readonly Texture2D GreenLightLeft;
public static readonly Texture2D GreenLightRight;
public static readonly Texture2D GreenLightStraight;
public static readonly Texture2D PedestrianGreenLight;
//--------------------------
// Timed TL Editor
//--------------------------
public static readonly Texture2D LightMode;
public static readonly Texture2D LightCounter;
public static readonly Texture2D ClockPlay;
public static readonly Texture2D ClockPause;
public static readonly Texture2D ClockTest;
public static readonly Texture2D PedestrianModeAutomatic;
public static readonly Texture2D PedestrianModeManual;
//--------------------------
// Toggle TL Tool
//--------------------------
public static readonly Texture2D TrafficLightEnabled;
public static readonly Texture2D TrafficLightEnabledTimed;
public static readonly Texture2D TrafficLightDisabled;
static TrafficLightTextures() {
// simple
RedLight = LoadDllResource("TrafficLights.light_1_1.png", 103, 243);
YellowRedLight = LoadDllResource("TrafficLights.light_1_2.png", 103, 243);
GreenLight = LoadDllResource("TrafficLights.light_1_3.png", 103, 243);
// forward
RedLightStraight = LoadDllResource("TrafficLights.light_2_1.png", 103, 243);
YellowLightStraight = LoadDllResource("TrafficLights.light_2_2.png", 103, 243);
GreenLightStraight = LoadDllResource("TrafficLights.light_2_3.png", 103, 243);
// right
RedLightRight = LoadDllResource("TrafficLights.light_3_1.png", 103, 243);
YellowLightRight = LoadDllResource("TrafficLights.light_3_2.png", 103, 243);
GreenLightRight = LoadDllResource("TrafficLights.light_3_3.png", 103, 243);
// left
RedLightLeft = LoadDllResource("TrafficLights.light_4_1.png", 103, 243);
YellowLightLeft = LoadDllResource("TrafficLights.light_4_2.png", 103, 243);
GreenLightLeft = LoadDllResource("TrafficLights.light_4_3.png", 103, 243);
// forwardright
RedLightForwardRight = LoadDllResource("TrafficLights.light_5_1.png", 103, 243);
YellowLightForwardRight = LoadDllResource("TrafficLights.light_5_2.png", 103, 243);
GreenLightForwardRight = LoadDllResource("TrafficLights.light_5_3.png", 103, 243);
// forwardleft
RedLightForwardLeft = LoadDllResource("TrafficLights.light_6_1.png", 103, 243);
YellowLightForwardLeft = LoadDllResource("TrafficLights.light_6_2.png", 103, 243);
GreenLightForwardLeft = LoadDllResource("TrafficLights.light_6_3.png", 103, 243);
// yellow
YellowLight = LoadDllResource("TrafficLights.light_yellow.png", 103, 243);
// pedestrian
PedestrianRedLight = LoadDllResource("TrafficLights.pedestrian_light_1.png", 73, 123);
PedestrianGreenLight = LoadDllResource("TrafficLights.pedestrian_light_2.png", 73, 123);
//--------------------------
// Timed TL Editor
//--------------------------
// light mode
LightMode = LoadDllResource(
Translation.GetTranslatedFileName("TrafficLights.light_mode.png"),
103,
95);
LightCounter = LoadDllResource(
Translation.GetTranslatedFileName("TrafficLights.light_counter.png"),
103,
95);
// pedestrian mode
PedestrianModeAutomatic = LoadDllResource(
"TrafficLights.pedestrian_mode_1.png",
73,
70);
PedestrianModeManual = LoadDllResource("TrafficLights.pedestrian_mode_2.png", 73, 73);
// timer
ClockPlay = LoadDllResource("TrafficLights.clock_play.png", 512, 512);
ClockPause = LoadDllResource("TrafficLights.clock_pause.png", 512, 512);
ClockTest = LoadDllResource("TrafficLights.clock_test.png", 512, 512);
//--------------------------
// Toggle TL Tool
//--------------------------
TrafficLightEnabled = LoadDllResource(
"TrafficLights.IconJunctionTrafficLights.png",
64,
64);
TrafficLightEnabledTimed = LoadDllResource(
"TrafficLights.IconJunctionTimedTL.png",
64,
64);
TrafficLightDisabled = LoadDllResource(
"TrafficLights.IconJunctionNoTrafficLights.png",
64,
64);
}
}
} | {
"pile_set_name": "Github"
} |
[shark-graph](../../../index.md) / [shark](../../index.md) / [HeapObject](../index.md) / [HeapClass](index.md) / [superclass](./superclass.md)
# superclass
`val superclass: `[`HeapObject.HeapClass`](index.md)`?`
The [HeapClass](index.md) representing the superclass of this [HeapClass](index.md). If this [HeapClass](index.md)
represents either the [Object](https://docs.oracle.com/javase/6/docs/api/java/lang/Object.html) class or a primitive type, then
null is returned. If this [HeapClass](index.md) represents an array class then the
[HeapClass](index.md) object representing the [Object](https://docs.oracle.com/javase/6/docs/api/java/lang/Object.html) class is returned.
| {
"pile_set_name": "Github"
} |
The FreeType Project LICENSE
----------------------------
2006-Jan-27
Copyright 1996-2002, 2006 by
David Turner, Robert Wilhelm, and Werner Lemberg
Introduction
============
The FreeType Project is distributed in several archive packages;
some of them may contain, in addition to the FreeType font engine,
various tools and contributions which rely on, or relate to, the
FreeType Project.
This license applies to all files found in such packages, and
which do not fall under their own explicit license. The license
affects thus the FreeType font engine, the test programs,
documentation and makefiles, at the very least.
This license was inspired by the BSD, Artistic, and IJG
(Independent JPEG Group) licenses, which all encourage inclusion
and use of free software in commercial and freeware products
alike. As a consequence, its main points are that:
o We don't promise that this software works. However, we will be
interested in any kind of bug reports. (`as is' distribution)
o You can use this software for whatever you want, in parts or
full form, without having to pay us. (`royalty-free' usage)
o You may not pretend that you wrote this software. If you use
it, or only parts of it, in a program, you must acknowledge
somewhere in your documentation that you have used the
FreeType code. (`credits')
We specifically permit and encourage the inclusion of this
software, with or without modifications, in commercial products.
We disclaim all warranties covering The FreeType Project and
assume no liability related to The FreeType Project.
Finally, many people asked us for a preferred form for a
credit/disclaimer to use in compliance with this license. We thus
encourage you to use the following text:
"""
Portions of this software are copyright © <year> The FreeType
Project (www.freetype.org). All rights reserved.
"""
Please replace <year> with the value from the FreeType version you
actually use.
Legal Terms
===========
0. Definitions
--------------
Throughout this license, the terms `package', `FreeType Project',
and `FreeType archive' refer to the set of files originally
distributed by the authors (David Turner, Robert Wilhelm, and
Werner Lemberg) as the `FreeType Project', be they named as alpha,
beta or final release.
`You' refers to the licensee, or person using the project, where
`using' is a generic term including compiling the project's source
code as well as linking it to form a `program' or `executable'.
This program is referred to as `a program using the FreeType
engine'.
This license applies to all files distributed in the original
FreeType Project, including all source code, binaries and
documentation, unless otherwise stated in the file in its
original, unmodified form as distributed in the original archive.
If you are unsure whether or not a particular file is covered by
this license, you must contact us to verify this.
The FreeType Project is copyright (C) 1996-2000 by David Turner,
Robert Wilhelm, and Werner Lemberg. All rights reserved except as
specified below.
1. No Warranty
--------------
THE FREETYPE PROJECT IS PROVIDED `AS IS' WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. IN NO EVENT WILL ANY OF THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY DAMAGES CAUSED BY THE USE OR THE INABILITY TO
USE, OF THE FREETYPE PROJECT.
2. Redistribution
-----------------
This license grants a worldwide, royalty-free, perpetual and
irrevocable right and license to use, execute, perform, compile,
display, copy, create derivative works of, distribute and
sublicense the FreeType Project (in both source and object code
forms) and derivative works thereof for any purpose; and to
authorize others to exercise some or all of the rights granted
herein, subject to the following conditions:
o Redistribution of source code must retain this license file
(`FTL.TXT') unaltered; any additions, deletions or changes to
the original files must be clearly indicated in accompanying
documentation. The copyright notices of the unaltered,
original files must be preserved in all copies of source
files.
o Redistribution in binary form must provide a disclaimer that
states that the software is based in part of the work of the
FreeType Team, in the distribution documentation. We also
encourage you to put an URL to the FreeType web page in your
documentation, though this isn't mandatory.
These conditions apply to any software derived from or based on
the FreeType Project, not just the unmodified files. If you use
our work, you must acknowledge us. However, no fee need be paid
to us.
3. Advertising
--------------
Neither the FreeType authors and contributors nor you shall use
the name of the other for commercial, advertising, or promotional
purposes without specific prior written permission.
We suggest, but do not require, that you use one or more of the
following phrases to refer to this software in your documentation
or advertising materials: `FreeType Project', `FreeType Engine',
`FreeType library', or `FreeType Distribution'.
As you have not signed this license, you are not required to
accept it. However, as the FreeType Project is copyrighted
material, only this license, or another one contracted with the
authors, grants you the right to use, distribute, and modify it.
Therefore, by using, distributing, or modifying the FreeType
Project, you indicate that you understand and accept all the terms
of this license.
4. Contacts
-----------
There are two mailing lists related to FreeType:
o [email protected]
Discusses general use and applications of FreeType, as well as
future and wanted additions to the library and distribution.
If you are looking for support, start in this list if you
haven't found anything to help you in the documentation.
o [email protected]
Discusses bugs, as well as engine internals, design issues,
specific licenses, porting, etc.
Our home page can be found at
http://www.freetype.org
--- end of FTL.TXT ---
| {
"pile_set_name": "Github"
} |
fileFormatVersion: 2
guid: e424621259b45714a94ec1c278a1c50f
folderAsset: yes
timeCreated: 1504205928
licenseType: Free
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root> | {
"pile_set_name": "Github"
} |
/*
* 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.vision.v1p2beta1.model;
/**
* If an image was produced from a file (e.g. a PDF), this message gives information about the
* source of that image.
*
* <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 Vision 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 GoogleCloudVisionV1p5beta1ImageAnnotationContext extends com.google.api.client.json.GenericJson {
/**
* If the file was a PDF or TIFF, this field gives the page number within the file used to produce
* the image.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Integer pageNumber;
/**
* The URI of the file used to produce the image.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String uri;
/**
* If the file was a PDF or TIFF, this field gives the page number within the file used to produce
* the image.
* @return value or {@code null} for none
*/
public java.lang.Integer getPageNumber() {
return pageNumber;
}
/**
* If the file was a PDF or TIFF, this field gives the page number within the file used to produce
* the image.
* @param pageNumber pageNumber or {@code null} for none
*/
public GoogleCloudVisionV1p5beta1ImageAnnotationContext setPageNumber(java.lang.Integer pageNumber) {
this.pageNumber = pageNumber;
return this;
}
/**
* The URI of the file used to produce the image.
* @return value or {@code null} for none
*/
public java.lang.String getUri() {
return uri;
}
/**
* The URI of the file used to produce the image.
* @param uri uri or {@code null} for none
*/
public GoogleCloudVisionV1p5beta1ImageAnnotationContext setUri(java.lang.String uri) {
this.uri = uri;
return this;
}
@Override
public GoogleCloudVisionV1p5beta1ImageAnnotationContext set(String fieldName, Object value) {
return (GoogleCloudVisionV1p5beta1ImageAnnotationContext) super.set(fieldName, value);
}
@Override
public GoogleCloudVisionV1p5beta1ImageAnnotationContext clone() {
return (GoogleCloudVisionV1p5beta1ImageAnnotationContext) super.clone();
}
}
| {
"pile_set_name": "Github"
} |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import optparse
import mechanize
import urllib
import re
import urlparse
from _winreg import *
def val2addr(val):
addr = ''
for ch in val:
addr += '%02x ' % ord(ch)
addr = addr.strip(' ').replace(' ', ':')[0:17]
return addr
def wiglePrint(username, password, netid):
browser = mechanize.Browser()
browser.open('http://wigle.net')
reqData = urllib.urlencode({'credential_0': username,
'credential_1': password})
browser.open('https://wigle.net/gps/gps/main/login', reqData)
params = {}
params['netid'] = netid
reqParams = urllib.urlencode(params)
respURL = 'http://wigle.net/gps/gps/main/confirmquery/'
resp = browser.open(respURL, reqParams).read()
mapLat = 'N/A'
mapLon = 'N/A'
rLat = re.findall(r'maplat=.*\&', resp)
if rLat:
mapLat = rLat[0].split('&')[0].split('=')[1]
rLon = re.findall(r'maplon=.*\&', resp)
if rLon:
mapLon = rLon[0].split
print '[-] Lat: ' + mapLat + ', Lon: ' + mapLon
def printNets(username, password):
net = "SOFTWARE\Microsoft\Windows NT\CurrentVersion"+\
"\NetworkList\Signatures\Unmanaged"
key = OpenKey(HKEY_LOCAL_MACHINE, net)
print '\n[*] Networks You have Joined.'
for i in range(100):
try:
guid = EnumKey(key, i)
netKey = OpenKey(key, str(guid))
(n, addr, t) = EnumValue(netKey, 5)
(n, name, t) = EnumValue(netKey, 4)
macAddr = val2addr(addr)
netName = str(name)
print '[+] ' + netName + ' ' + macAddr
wiglePrint(username, password, macAddr)
CloseKey(netKey)
except:
break
def main():
parser = optparse.OptionParser('usage %prog '+\
'-u <wigle username> -p <wigle password>')
parser.add_option('-u', dest='username', type='string',
help='specify wigle password')
parser.add_option('-p', dest='password', type='string',
help='specify wigle username')
(options, args) = parser.parse_args()
username = options.username
password = options.password
if username == None or password == None:
print parser.usage
exit(0)
else:
printNets(username, password)
if __name__ == '__main__':
main()
| {
"pile_set_name": "Github"
} |
# -*- coding: utf-8 -*-
# This file is part of wger Workout Manager.
#
# wger Workout Manager is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# wger Workout Manager is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.
# Standard Library
import datetime
import logging
from decimal import Decimal
# Django
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from django.core import mail
from django.core.cache import cache
from django.core.exceptions import ValidationError
from django.core.validators import (
MaxValueValidator,
MinValueValidator
)
from django.db import models
from django.template.loader import render_to_string
from django.urls import reverse
from django.utils import (
timezone,
translation
)
from django.utils.text import slugify
from django.utils.translation import ugettext_lazy as _
# wger
from wger.core.models import Language
from wger.utils.cache import cache_mapper
from wger.utils.constants import TWOPLACES
from wger.utils.fields import Html5TimeField
from wger.utils.models import (
AbstractLicenseModel,
AbstractSubmissionModel
)
from wger.utils.units import AbstractWeight
from wger.weight.models import WeightEntry
MEALITEM_WEIGHT_GRAM = '1'
MEALITEM_WEIGHT_UNIT = '2'
ENERGY_FACTOR = {'protein': {'kg': 4,
'lb': 113},
'carbohydrates': {'kg': 4,
'lb': 113},
'fat': {'kg': 9,
'lb': 225}}
"""
Simple approximation of energy (kcal) provided per gram or ounce
"""
logger = logging.getLogger(__name__)
class NutritionPlan(models.Model):
"""
A nutrition plan
"""
# Metaclass to set some other properties
class Meta:
# Order by creation_date, descending (oldest first)
ordering = ["-creation_date", ]
user = models.ForeignKey(User,
verbose_name=_('User'),
editable=False,
on_delete=models.CASCADE)
language = models.ForeignKey(Language,
verbose_name=_('Language'),
editable=False,
on_delete=models.CASCADE)
creation_date = models.DateField(_('Creation date'), auto_now_add=True)
description = models.CharField(max_length=(80),
blank=True,
verbose_name=_('Description'),
help_text=_('A description of the goal of the plan, e.g. '
'"Gain mass" or "Prepare for summer"'))
has_goal_calories = models.BooleanField(verbose_name=_('Use daily calories'),
default=False,
help_text=_("Tick the box if you want to mark this "
"plan as having a goal amount of calories. "
"You can use the calculator or enter the "
"value yourself."))
"""A flag indicating whether the plan has a goal amount of calories"""
def __str__(self):
"""
Return a more human-readable representation
"""
if self.description:
return "{0}".format(self.description)
else:
return "{0}".format(_("Nutrition plan"))
def get_absolute_url(self):
"""
Returns the canonical URL to view this object
"""
return reverse('nutrition:plan:view', kwargs={'id': self.id})
def get_nutritional_values(self):
"""
Sums the nutritional info of all items in the plan
"""
nutritional_representation = cache.get(cache_mapper.get_nutrition_cache_by_key(self.pk))
if not nutritional_representation:
use_metric = self.user.userprofile.use_metric
unit = 'kg' if use_metric else 'lb'
result = {'total': {'energy': 0,
'protein': 0,
'carbohydrates': 0,
'carbohydrates_sugar': 0,
'fat': 0,
'fat_saturated': 0,
'fibres': 0,
'sodium': 0},
'percent': {'protein': 0,
'carbohydrates': 0,
'fat': 0},
'per_kg': {'protein': 0,
'carbohydrates': 0,
'fat': 0},
}
# Energy
for meal in self.meal_set.select_related():
values = meal.get_nutritional_values(use_metric=use_metric)
for key in result['total'].keys():
result['total'][key] += values[key]
energy = result['total']['energy']
# In percent
if energy:
for key in result['percent'].keys():
result['percent'][key] = \
result['total'][key] * ENERGY_FACTOR[key][unit] / energy * 100
# Per body weight
weight_entry = self.get_closest_weight_entry()
if weight_entry:
for key in result['per_kg'].keys():
result['per_kg'][key] = result['total'][key] / weight_entry.weight
# Only 2 decimal places, anything else doesn't make sense
for key in result.keys():
for i in result[key]:
result[key][i] = Decimal(result[key][i]).quantize(TWOPLACES)
nutritional_representation = result
cache.set(cache_mapper.get_nutrition_cache_by_key(self.pk), nutritional_representation)
return nutritional_representation
def get_closest_weight_entry(self):
"""
Returns the closest weight entry for the nutrition plan.
Returns None if there are no entries.
"""
target = self.creation_date
closest_entry_gte = WeightEntry.objects.filter(user=self.user) \
.filter(date__gte=target).order_by('date').first()
closest_entry_lte = WeightEntry.objects.filter(user=self.user) \
.filter(date__lte=target).order_by('-date').first()
if closest_entry_gte is None or closest_entry_lte is None:
return closest_entry_gte or closest_entry_lte
if abs(closest_entry_gte.date - target) < abs(closest_entry_lte.date - target):
return closest_entry_gte
else:
return closest_entry_lte
def get_owner_object(self):
"""
Returns the object that has owner information
"""
return self
def get_calories_approximation(self):
"""
Calculates the deviation from the goal calories and the actual
amount of the current plan
"""
goal_calories = self.user.userprofile.calories
actual_calories = self.get_nutritional_values()['total']['energy']
# Within 3%
if (actual_calories < goal_calories * 1.03) and (actual_calories > goal_calories * 0.97):
return 1
# within 7%
elif (actual_calories < goal_calories * 1.07) and (actual_calories > goal_calories * 0.93):
return 2
# within 10%
elif (actual_calories < goal_calories * 1.10) and (actual_calories > goal_calories * 0.9):
return 3
# even more
else:
return 4
def get_log_overview(self):
"""
Returns an overview for all logs available for this plan
"""
result = []
for date in self.logitem_set.datetimes('datetime', 'day', order='DESC'):
# TODO: in python 3.5 this can be simplified as z = {**x, **y}
tmp = self.get_log_summary(date=date).copy()
tmp.update({'date': date.date()})
result.append(tmp)
return result
def get_log_entries(self, date=None):
"""
Convenience function that returns the log entries for a given date
"""
if not date:
date = datetime.date.today()
return self.logitem_set.filter(datetime__date=date).select_related()
def get_log_summary(self, date=None):
"""
Sums the nutritional info of the items logged for the given date
"""
use_metric = self.user.userprofile.use_metric
result = {'energy': 0,
'protein': 0,
'carbohydrates': 0,
'carbohydrates_sugar': 0,
'fat': 0,
'fat_saturated': 0,
'fibres': 0,
'sodium': 0}
# Perform the sums
for item in self.get_log_entries(date):
values = item.get_nutritional_values(use_metric=use_metric)
for key in result.keys():
result[key] += values[key]
return result
class Ingredient(AbstractSubmissionModel, AbstractLicenseModel, models.Model):
"""
An ingredient, with some approximate nutrition values
"""
ENERGY_APPROXIMATION = 15
"""
How much the calculated energy from protein, etc. can deviate from the
energy amount given (in percent).
"""
# Metaclass to set some other properties
class Meta:
ordering = ["name", ]
language = models.ForeignKey(Language,
verbose_name=_('Language'),
editable=False,
on_delete=models.CASCADE)
creation_date = models.DateField(_('Date'), auto_now_add=True)
update_date = models.DateField(_('Date'),
auto_now=True,
blank=True,
editable=False)
name = models.CharField(max_length=200,
verbose_name=_('Name'), )
energy = models.IntegerField(verbose_name=_('Energy'),
help_text=_('In kcal per 100g'))
protein = models.DecimalField(decimal_places=3,
max_digits=6,
verbose_name=_('Protein'),
help_text=_('In g per 100g of product'),
validators=[MinValueValidator(0),
MaxValueValidator(100)])
carbohydrates = models.DecimalField(decimal_places=3,
max_digits=6,
verbose_name=_('Carbohydrates'),
help_text=_('In g per 100g of product'),
validators=[MinValueValidator(0),
MaxValueValidator(100)])
carbohydrates_sugar = models.DecimalField(decimal_places=3,
max_digits=6,
blank=True,
null=True,
verbose_name=_('Sugar content in carbohydrates'),
help_text=_('In g per 100g of product'),
validators=[MinValueValidator(0),
MaxValueValidator(100)])
fat = models.DecimalField(decimal_places=3,
max_digits=6,
verbose_name=_('Fat'),
help_text=_('In g per 100g of product'),
validators=[MinValueValidator(0),
MaxValueValidator(100)])
fat_saturated = models.DecimalField(decimal_places=3,
max_digits=6,
blank=True,
null=True,
verbose_name=_('Saturated fat content in fats'),
help_text=_('In g per 100g of product'),
validators=[MinValueValidator(0),
MaxValueValidator(100)])
fibres = models.DecimalField(decimal_places=3,
max_digits=6,
blank=True,
null=True,
verbose_name=_('Fibres'),
help_text=_('In g per 100g of product'),
validators=[MinValueValidator(0),
MaxValueValidator(100)])
sodium = models.DecimalField(decimal_places=3,
max_digits=6,
blank=True,
null=True,
verbose_name=_('Sodium'),
help_text=_('In g per 100g of product'),
validators=[MinValueValidator(0),
MaxValueValidator(100)])
#
# Django methods
#
def get_absolute_url(self):
"""
Returns the canonical URL to view this object
"""
return reverse('nutrition:ingredient:view',
kwargs={'id': self.id, 'slug': slugify(self.name)})
def clean(self):
"""
Do a very broad sanity check on the nutritional values according to
the following rules:
- 1g of protein: 4kcal
- 1g of carbohydrates: 4kcal
- 1g of fat: 9kcal
The sum is then compared to the given total energy, with ENERGY_APPROXIMATION
percent tolerance.
"""
# Note: calculations in 100 grams, to save us the '/100' everywhere
energy_protein = 0
if self.protein:
energy_protein = self.protein * ENERGY_FACTOR['protein']['kg']
energy_carbohydrates = 0
if self.carbohydrates:
energy_carbohydrates = self.carbohydrates * ENERGY_FACTOR['carbohydrates']['kg']
energy_fat = 0
if self.fat:
# TODO: for some reason, during the tests the fat value is not
# converted to decimal (django 1.9)
energy_fat = Decimal(self.fat * ENERGY_FACTOR['fat']['kg'])
energy_calculated = energy_protein + energy_carbohydrates + energy_fat
# Compare the values, but be generous
if self.energy:
energy_upper = self.energy * (1 + (self.ENERGY_APPROXIMATION / Decimal(100.0)))
energy_lower = self.energy * (1 - (self.ENERGY_APPROXIMATION / Decimal(100.0)))
if not ((energy_upper > energy_calculated) and (energy_calculated > energy_lower)):
raise ValidationError(_('Total energy is not the approximate sum of the energy '
'provided by protein, carbohydrates and fat.'))
def save(self, *args, **kwargs):
"""
Reset the cache
"""
super(Ingredient, self).save(*args, **kwargs)
cache.delete(cache_mapper.get_ingredient_key(self.id))
def __str__(self):
"""
Return a more human-readable representation
"""
return self.name
def __eq__(self, other):
"""
Compare ingredients based on their values, not like django on their PKs
"""
logger.debug('Overwritten behaviour: comparing ingredients on values, not PK.')
equal = True
if isinstance(other, self.__class__):
for i in self._meta.fields:
if (hasattr(self, i.name)
and hasattr(other, i.name)
and (getattr(self, i.name, None) != getattr(other, i.name, None))):
equal = False
else:
equal = False
return equal
def __hash__(self):
"""
Define a hash function
This is rather unnecessary, but it seems that newer versions of django
have a problem when the __eq__ function is implemented, but not the
__hash__ one. Returning hash(pk) is also django's default.
:return: hash(pk)
"""
return hash(self.pk)
#
# Own methods
#
def compare_with_database(self):
"""
Compares the current ingredient with the version saved in the database.
If the current object has no PK, returns false
"""
if not self.pk:
return False
ingredient = Ingredient.objects.get(pk=self.pk)
if self != ingredient:
return False
else:
return True
def send_email(self, request):
"""
Sends an email after being successfully added to the database (for user
submitted ingredients only)
"""
try:
user = User.objects.get(username=self.license_author)
except User.DoesNotExist:
return
if self.license_author and user.email:
translation.activate(user.userprofile.notification_language.short_name)
url = request.build_absolute_uri(self.get_absolute_url())
subject = _('Ingredient was successfully added to the general database')
context = {
'ingredient': self.name,
'url': url,
'site': Site.objects.get_current().domain
}
message = render_to_string('ingredient/email_new.tpl', context)
mail.send_mail(subject,
message,
settings.WGER_SETTINGS['EMAIL_FROM'],
[user.email],
fail_silently=True)
def set_author(self, request):
if request.user.has_perm('nutrition.add_ingredient'):
self.status = Ingredient.STATUS_ACCEPTED
if not self.license_author:
self.license_author = request.get_host().split(':')[0]
else:
if not self.license_author:
self.license_author = request.user.username
# Send email to administrator
subject = _('New user submitted ingredient')
message = _("""The user {0} submitted a new ingredient "{1}".""".format(
request.user.username, self.name))
mail.mail_admins(subject,
message,
fail_silently=True)
def get_owner_object(self):
"""
Ingredient has no owner information
"""
return False
class WeightUnit(models.Model):
"""
A more human usable weight unit (spoon, table, slice...)
"""
language = models.ForeignKey(Language,
verbose_name=_('Language'),
editable=False,
on_delete=models.CASCADE)
name = models.CharField(max_length=200,
verbose_name=_('Name'), )
# Metaclass to set some other properties
class Meta:
ordering = ["name", ]
def __str__(self):
"""
Return a more human-readable representation
"""
return self.name
def get_owner_object(self):
"""
Weight unit has no owner information
"""
return None
class IngredientWeightUnit(models.Model):
"""
A specific human usable weight unit for an ingredient
"""
ingredient = models.ForeignKey(Ingredient,
verbose_name=_('Ingredient'),
editable=False,
on_delete=models.CASCADE)
unit = models.ForeignKey(WeightUnit, verbose_name=_('Weight unit'), on_delete=models.CASCADE)
gram = models.IntegerField(verbose_name=_('Amount in grams'))
amount = models.DecimalField(decimal_places=2,
max_digits=5,
default=1,
verbose_name=_('Amount'),
help_text=_('Unit amount, e.g. "1 Cup" or "1/2 spoon"'))
def get_owner_object(self):
"""
Weight unit has no owner information
"""
return None
def __str__(self):
"""
Return a more human-readable representation
"""
return "{0}{1} ({2}g)".format(self.amount if self.amount > 1 else '',
self.unit.name,
self.gram)
class Meal(models.Model):
"""
A meal
"""
# Metaclass to set some other properties
class Meta:
ordering = ["time", ]
plan = models.ForeignKey(NutritionPlan,
verbose_name=_('Nutrition plan'),
editable=False,
on_delete=models.CASCADE)
order = models.IntegerField(verbose_name=_('Order'),
blank=True,
editable=False)
time = Html5TimeField(null=True,
blank=True,
verbose_name=_('Time (approx)'))
def __str__(self):
"""
Return a more human-readable representation
"""
return "{0} Meal".format(self.order)
def get_owner_object(self):
"""
Returns the object that has owner information
"""
return self.plan
def get_nutritional_values(self, use_metric=True):
"""
Sums the nutrional info of all items in the meal
:param use_metric Flag that controls the units used
"""
nutritional_info = {'energy': 0,
'protein': 0,
'carbohydrates': 0,
'carbohydrates_sugar': 0,
'fat': 0,
'fat_saturated': 0,
'fibres': 0,
'sodium': 0}
# Get the calculated values from the meal item and add them
for item in self.mealitem_set.select_related():
values = item.get_nutritional_values(use_metric=use_metric)
for key in nutritional_info.keys():
nutritional_info[key] += values[key]
# Only 2 decimal places, anything else doesn't make sense
for i in nutritional_info:
nutritional_info[i] = Decimal(nutritional_info[i]).quantize(TWOPLACES)
return nutritional_info
class BaseMealItem(object):
"""
Base class for an item (component) of a meal or log
This just provides some common helper functions
"""
def get_unit_type(self):
"""
Returns the type of unit used:
- a value in grams
- a 'human' unit like 'a cup' or 'a slice'
"""
if self.weight_unit:
return MEALITEM_WEIGHT_UNIT
else:
return MEALITEM_WEIGHT_GRAM
def get_nutritional_values(self, use_metric=True):
"""
Sums the nutritional info for the ingredient in the MealItem
:param use_metric Flag that controls the units used
"""
nutritional_info = {'energy': 0,
'protein': 0,
'carbohydrates': 0,
'carbohydrates_sugar': 0,
'fat': 0,
'fat_saturated': 0,
'fibres': 0,
'sodium': 0}
# Calculate the base weight of the item
if self.get_unit_type() == MEALITEM_WEIGHT_GRAM:
item_weight = self.amount
else:
item_weight = (self.amount
* self.weight_unit.amount
* self.weight_unit.gram)
nutritional_info['energy'] += self.ingredient.energy * item_weight / 100
nutritional_info['protein'] += self.ingredient.protein * item_weight / 100
nutritional_info['carbohydrates'] += self.ingredient.carbohydrates * item_weight / 100
if self.ingredient.carbohydrates_sugar:
nutritional_info['carbohydrates_sugar'] += \
self.ingredient.carbohydrates_sugar * item_weight / 100
nutritional_info['fat'] += self.ingredient.fat * item_weight / 100
if self.ingredient.fat_saturated:
nutritional_info['fat_saturated'] += self.ingredient.fat_saturated * item_weight / 100
if self.ingredient.fibres:
nutritional_info['fibres'] += self.ingredient.fibres * item_weight / 100
if self.ingredient.sodium:
nutritional_info['sodium'] += self.ingredient.sodium * item_weight / 100
# If necessary, convert weight units
if not use_metric:
for key, value in nutritional_info.items():
# Energy is not a weight!
if key == 'energy':
continue
# Everything else, to ounces
nutritional_info[key] = AbstractWeight(value, 'g').oz
# Only 2 decimal places, anything else doesn't make sense
for i in nutritional_info:
nutritional_info[i] = Decimal(nutritional_info[i]).quantize(TWOPLACES)
return nutritional_info
class MealItem(BaseMealItem, models.Model):
"""
An item (component) of a meal
"""
meal = models.ForeignKey(Meal,
verbose_name=_('Nutrition plan'),
editable=False,
on_delete=models.CASCADE)
ingredient = models.ForeignKey(Ingredient,
verbose_name=_('Ingredient'),
on_delete=models.CASCADE)
weight_unit = models.ForeignKey(IngredientWeightUnit,
verbose_name=_('Weight unit'),
null=True,
blank=True,
on_delete=models.CASCADE)
order = models.IntegerField(verbose_name=_('Order'),
blank=True,
editable=False)
amount = models.DecimalField(decimal_places=2,
max_digits=6,
verbose_name=_('Amount'),
validators=[MinValueValidator(1),
MaxValueValidator(1000)])
def __str__(self):
"""
Return a more human-readable representation
"""
return "{0}g ingredient {1}".format(self.amount, self.ingredient_id)
def get_owner_object(self):
"""
Returns the object that has owner information
"""
return self.meal.plan
class LogItem(BaseMealItem, models.Model):
"""
An item (component) of a log
"""
# Metaclass to set some other properties
class Meta:
ordering = ["datetime", ]
plan = models.ForeignKey(NutritionPlan,
verbose_name=_('Nutrition plan'),
editable=False,
on_delete=models.CASCADE)
"""
The plan this log belongs to
"""
datetime = models.DateTimeField(default=timezone.now)
"""
Time and date when the log was added
"""
comment = models.TextField(verbose_name=_('Comment'),
blank=True,
null=True)
"""
Comment field, for additional information
"""
ingredient = models.ForeignKey(Ingredient,
verbose_name=_('Ingredient'),
on_delete=models.CASCADE)
"""
Ingredient
"""
weight_unit = models.ForeignKey(IngredientWeightUnit,
verbose_name=_('Weight unit'),
null=True,
blank=True,
on_delete=models.CASCADE)
"""
Weight unit used (grams, slices, etc.)
"""
amount = models.DecimalField(decimal_places=2,
max_digits=6,
verbose_name=_('Amount'),
validators=[MinValueValidator(1),
MaxValueValidator(1000)])
"""
The amount of units
"""
def __str__(self):
"""
Return a more human-readable representation
"""
return "Diary entry for {}, plan {}".format(self.datetime, self.plan.pk)
def get_owner_object(self):
"""
Returns the object that has owner information
"""
return self.plan
| {
"pile_set_name": "Github"
} |
require 'rspec'
$LOAD_PATH.unshift(File.join(__dir__, '..', 'lib'))
$LOAD_PATH.unshift(File.join(__dir__, '..'))
Dir['spec/support/**/*.rb'].each { |f| require f }
require 'fakeredis'
require "fakeredis/rspec"
RSpec.configure do |config|
# Enable memory adapter
config.before(:each) { FakeRedis.enable }
config.backtrace_exclusion_patterns = []
end
def fakeredis?
FakeRedis.enabled?
end
| {
"pile_set_name": "Github"
} |
module mylib [extern_c] {
header "mylib.h"
link "mylib"
export *
}
| {
"pile_set_name": "Github"
} |
all:
vcs +v2k async_fifo_in_144b_out_72b.v async_fifo_in_72b_out_144b.v fallthrough_small_fifo.v fifo_ddr2_blk_rdwr_64b_2_72b.v fifo_ddr2_blk_rdwr_72b_2_64b.v small_async_fifo.v ddr2_blk_rdwr.v dram_ctrl.v tail_cache.v tail_cache_arb.v head_cache.v head_cache_arb.v dram_output_queues.v
clean:
rm -rf csrc simv *~
| {
"pile_set_name": "Github"
} |
// Generated using SwiftGen, by O.Halligon — https://github.com/AliSoftware/SwiftGen
{% if images %}
#if os(iOS) || os(tvOS) || os(watchOS)
import UIKit.UIImage
typealias Image = UIImage
#elseif os(OSX)
import AppKit.NSImage
typealias Image = NSImage
#endif
// swiftlint:disable file_length
// swiftlint:disable type_body_length
enum {{enumName}}: String {
{% for image in images %}
case {{image|swiftIdentifier}} = "{{image}}"
{% endfor %}
var image: Image {
return Image(asset: self)
}
}
// swiftlint:enable type_body_length
extension Image {
convenience init!(asset: {{enumName}}) {
self.init(named: asset.rawValue)
}
}
{% else %}
// No image found
{% endif %}
| {
"pile_set_name": "Github"
} |
package gocsv
import (
"reflect"
"strings"
"sync"
)
// --------------------------------------------------------------------------
// Reflection helpers
type structInfo struct {
Fields []fieldInfo
}
// fieldInfo is a struct field that should be mapped to a CSV column, or vice-versa
// Each IndexChain element before the last is the index of an the embedded struct field
// that defines Key as a tag
type fieldInfo struct {
keys []string
omitEmpty bool
IndexChain []int
}
func (f fieldInfo) getFirstKey() string {
return f.keys[0]
}
func (f fieldInfo) matchesKey(key string) bool {
for _, k := range f.keys {
if key == k || strings.TrimSpace(key) == k {
return true
}
}
return false
}
var structMap = make(map[reflect.Type]*structInfo)
var structMapMutex sync.RWMutex
func getStructInfo(rType reflect.Type) *structInfo {
structMapMutex.RLock()
stInfo, ok := structMap[rType]
structMapMutex.RUnlock()
if ok {
return stInfo
}
fieldsList := getFieldInfos(rType, []int{})
stInfo = &structInfo{fieldsList}
return stInfo
}
func getFieldInfos(rType reflect.Type, parentIndexChain []int) []fieldInfo {
fieldsCount := rType.NumField()
fieldsList := make([]fieldInfo, 0, fieldsCount)
for i := 0; i < fieldsCount; i++ {
field := rType.Field(i)
if field.PkgPath != "" {
continue
}
indexChain := append(parentIndexChain, i)
// if the field is a struct, create a fieldInfo for each of its fields
if field.Type.Kind() == reflect.Struct {
fieldsList = append(fieldsList, getFieldInfos(field.Type, indexChain)...)
}
// if the field is an embedded struct, ignore the csv tag
if field.Anonymous {
continue
}
fieldInfo := fieldInfo{IndexChain: indexChain}
fieldTag := field.Tag.Get("csv")
fieldTags := strings.Split(fieldTag, TagSeparator)
filteredTags := []string{}
for _, fieldTagEntry := range fieldTags {
if fieldTagEntry != "omitempty" {
filteredTags = append(filteredTags, fieldTagEntry)
} else {
fieldInfo.omitEmpty = true
}
}
if len(filteredTags) == 1 && filteredTags[0] == "-" {
continue
} else if len(filteredTags) > 0 && filteredTags[0] != "" {
fieldInfo.keys = filteredTags
} else {
fieldInfo.keys = []string{field.Name}
}
fieldsList = append(fieldsList, fieldInfo)
}
return fieldsList
}
func getConcreteContainerInnerType(in reflect.Type) (inInnerWasPointer bool, inInnerType reflect.Type) {
inInnerType = in.Elem()
inInnerWasPointer = false
if inInnerType.Kind() == reflect.Ptr {
inInnerWasPointer = true
inInnerType = inInnerType.Elem()
}
return inInnerWasPointer, inInnerType
}
func getConcreteReflectValueAndType(in interface{}) (reflect.Value, reflect.Type) {
value := reflect.ValueOf(in)
if value.Kind() == reflect.Ptr {
value = value.Elem()
}
return value, value.Type()
}
| {
"pile_set_name": "Github"
} |
---
title: API Reference
language_tabs:
- http
toc_footers:
- <a href='http://github.com/tripit/slate'>Documentation Powered by Slate</a>
includes:
- overview
- sessions
- users
- microposts
- followers
- followings
- feed
search: true
---
# Introduction
Welcome to rails tutorial API.
The implementation of the API can be found [here](https://github.com/vasilakisfil/rails5_api_tutorial). Using this API an Ember application is also built, found [here](https://github.com/vasilakisfil/ember_on_rails5).
The following documents the V1 API.
| {
"pile_set_name": "Github"
} |
client
dev tun
proto udp
remote 139.28.218.43 1194
resolv-retry infinite
remote-random
nobind
tun-mtu 1500
tun-mtu-extra 32
mssfix 1450
persist-key
persist-tun
ping 15
ping-restart 0
ping-timer-rem
reneg-sec 0
remote-cert-tls server
auth-user-pass ../Own_VPN_Config/nordvpnauth.txt
verb 3
pull
fast-io
cipher AES-256-CBC
auth SHA512
<ca>
-----BEGIN CERTIFICATE-----
MIIFCjCCAvKgAwIBAgIBATANBgkqhkiG9w0BAQ0FADA5MQswCQYDVQQGEwJQQTEQ
MA4GA1UEChMHTm9yZFZQTjEYMBYGA1UEAxMPTm9yZFZQTiBSb290IENBMB4XDTE2
MDEwMTAwMDAwMFoXDTM1MTIzMTIzNTk1OVowOTELMAkGA1UEBhMCUEExEDAOBgNV
BAoTB05vcmRWUE4xGDAWBgNVBAMTD05vcmRWUE4gUm9vdCBDQTCCAiIwDQYJKoZI
hvcNAQEBBQADggIPADCCAgoCggIBAMkr/BYhyo0F2upsIMXwC6QvkZps3NN2/eQF
kfQIS1gql0aejsKsEnmY0Kaon8uZCTXPsRH1gQNgg5D2gixdd1mJUvV3dE3y9FJr
XMoDkXdCGBodvKJyU6lcfEVF6/UxHcbBguZK9UtRHS9eJYm3rpL/5huQMCppX7kU
eQ8dpCwd3iKITqwd1ZudDqsWaU0vqzC2H55IyaZ/5/TnCk31Q1UP6BksbbuRcwOV
skEDsm6YoWDnn/IIzGOYnFJRzQH5jTz3j1QBvRIuQuBuvUkfhx1FEwhwZigrcxXu
MP+QgM54kezgziJUaZcOM2zF3lvrwMvXDMfNeIoJABv9ljw969xQ8czQCU5lMVmA
37ltv5Ec9U5hZuwk/9QO1Z+d/r6Jx0mlurS8gnCAKJgwa3kyZw6e4FZ8mYL4vpRR
hPdvRTWCMJkeB4yBHyhxUmTRgJHm6YR3D6hcFAc9cQcTEl/I60tMdz33G6m0O42s
Qt/+AR3YCY/RusWVBJB/qNS94EtNtj8iaebCQW1jHAhvGmFILVR9lzD0EzWKHkvy
WEjmUVRgCDd6Ne3eFRNS73gdv/C3l5boYySeu4exkEYVxVRn8DhCxs0MnkMHWFK6
MyzXCCn+JnWFDYPfDKHvpff/kLDobtPBf+Lbch5wQy9quY27xaj0XwLyjOltpiST
LWae/Q4vAgMBAAGjHTAbMAwGA1UdEwQFMAMBAf8wCwYDVR0PBAQDAgEGMA0GCSqG
SIb3DQEBDQUAA4ICAQC9fUL2sZPxIN2mD32VeNySTgZlCEdVmlq471o/bDMP4B8g
nQesFRtXY2ZCjs50Jm73B2LViL9qlREmI6vE5IC8IsRBJSV4ce1WYxyXro5rmVg/
k6a10rlsbK/eg//GHoJxDdXDOokLUSnxt7gk3QKpX6eCdh67p0PuWm/7WUJQxH2S
DxsT9vB/iZriTIEe/ILoOQF0Aqp7AgNCcLcLAmbxXQkXYCCSB35Vp06u+eTWjG0/
pyS5V14stGtw+fA0DJp5ZJV4eqJ5LqxMlYvEZ/qKTEdoCeaXv2QEmN6dVqjDoTAo
k0t5u4YRXzEVCfXAC3ocplNdtCA72wjFJcSbfif4BSC8bDACTXtnPC7nD0VndZLp
+RiNLeiENhk0oTC+UVdSc+n2nJOzkCK0vYu0Ads4JGIB7g8IB3z2t9ICmsWrgnhd
NdcOe15BincrGA8avQ1cWXsfIKEjbrnEuEk9b5jel6NfHtPKoHc9mDpRdNPISeVa
wDBM1mJChneHt59Nh8Gah74+TM1jBsw4fhJPvoc7Atcg740JErb904mZfkIEmojC
VPhBHVQ9LHBAdM8qFI2kRK0IynOmAZhexlP/aT/kpEsEPyaZQlnBn3An1CRz8h0S
PApL8PytggYKeQmRhl499+6jLxcZ2IegLfqq41dzIjwHwTMplg+1pKIOVojpWA==
-----END CERTIFICATE-----
</ca>
key-direction 1
<tls-auth>
#
# 2048 bit OpenVPN static key
#
-----BEGIN OpenVPN Static key V1-----
e685bdaf659a25a200e2b9e39e51ff03
0fc72cf1ce07232bd8b2be5e6c670143
f51e937e670eee09d4f2ea5a6e4e6996
5db852c275351b86fc4ca892d78ae002
d6f70d029bd79c4d1c26cf14e9588033
cf639f8a74809f29f72b9d58f9b8f5fe
fc7938eade40e9fed6cb92184abb2cc1
0eb1a296df243b251df0643d53724cdb
5a92a1d6cb817804c4a9319b57d53be5
80815bcfcb2df55018cc83fc43bc7ff8
2d51f9b88364776ee9d12fc85cc7ea5b
9741c4f598c485316db066d52db4540e
212e1518a9bd4828219e24b20d88f598
a196c9de96012090e333519ae18d3509
9427e7b372d348d352dc4c85e18cd4b9
3f8a56ddb2e64eb67adfc9b337157ff4
-----END OpenVPN Static key V1-----
</tls-auth>
| {
"pile_set_name": "Github"
} |
define( [
"../var/support"
], function( support ) {
"use strict";
support.focusin = "onfocusin" in window;
return support;
} );
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2005 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.drools.core.event;
import java.util.EventObject;
import org.drools.core.spi.AgendaGroup;
public class AgendaGroupEvent extends EventObject {
private static final long serialVersionUID = 510l;
public AgendaGroupEvent(final AgendaGroup agendaGroup) {
super( agendaGroup );
}
public AgendaGroup getAgendaGroup() {
return (AgendaGroup) getSource();
}
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2020 IBM Corporation
*
* 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.
*/
import { Registrar, MultiModalResponse } from '@kui-shell/core'
import reactContent from '../view/Sidecat'
const printCatInTopNavSidecar: MultiModalResponse = {
metadata: { name: '🐱' },
kind: 'Top',
modes: [
{
mode: 'Markdown Tab',
content:
'### Hello!\n #### **Kui** is a platform for enhancing the terminal experience with visualizations.\n\n ',
contentType: 'text/markdown'
},
{
mode: 'React Tab',
react: reactContent()
}
]
}
export default (commandTree: Registrar) => {
commandTree.listen('/hello/sidecat', () => printCatInTopNavSidecar)
}
| {
"pile_set_name": "Github"
} |
// Copyright (c) 2014-2019 K Team. All Rights Reserved.
DEF: null -> null
module TEST
rule A:Exp => A:Exp requires _andBool_(#token("#Bool", "true")(),, isExp(A:Exp))
syntax Exp ::=
endmodule
| {
"pile_set_name": "Github"
} |
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.gs.collections.api.list.MutableList;
import com.gs.collections.impl.list.mutable.FastList;
import com.gs.collections.impl.map.mutable.UnifiedMap;
import com.gs.collections.impl.set.mutable.UnifiedSet;
import java.util.*;
/**
* Create collection example
*
*
* Created by vedenin on 17.10.15.
*/
public class GuavaCreateCollection {
public static void main(String[] args) {
System.out.println("start");
createArrayList();
System.out.println();
createHashSet();
System.out.println();
createHashMap();
System.out.println("end");
}
// Create ArrayList using Gs, Guava and JDK
private static void createArrayList() {
System.out.println("createArrayList start");
// Create empty list
List<String> emptyGuava = Lists.newArrayList(); // using guava
List<String> emptyJDK = new ArrayList<>(); // using JDK
MutableList<String> emptyGS = FastList.newList(); // using gs
// Create list with 100 element
List < String > exactly100 = Lists.newArrayListWithCapacity(100); // using guava
List<String> exactly100JDK = new ArrayList<>(100); // using JDK
MutableList<String> empty100GS = FastList.newList(100); // using gs
// Create list with about 100 element
List<String> approx100 = Lists.newArrayListWithExpectedSize(100); // using guava
List<String> approx100JDK = new ArrayList<>(115); // using JDK
MutableList<String> approx100GS = FastList.newList(115); // using gs
// Create list with some elements
List<String> withElements = Lists.newArrayList("alpha", "beta", "gamma"); // using guava
List<String> withElementsJDK = Arrays.asList("alpha", "beta", "gamma"); // using JDK
MutableList<String> withElementsGS = FastList.newListWith("alpha", "beta", "gamma"); // using gs
System.out.println(withElements);
System.out.println(withElementsJDK);
System.out.println(withElementsGS);
// Create list from any Iterable interface (any collection)
Collection<String> collection = new HashSet<>(3);
collection.add("1");
collection.add("2");
collection.add("3");
List<String> fromIterable = Lists.newArrayList(collection); // using guava
List<String> fromIterableJDK = new ArrayList<>(collection); // using JDK
MutableList<String> fromIterableGS = FastList.newList(collection); // using gs
System.out.println(fromIterable);
System.out.println(fromIterableJDK);
System.out.println(fromIterableGS);
/* Attention: JDK create list only from Collection, but guava and gs can create list from Iterable and Collection */
// Create list from any Iterator
Iterator<String> iterator = collection.iterator();
List<String> fromIterator = Lists.newArrayList(iterator); // using guava
System.out.println(fromIterator);
// Create list from any array
String[] array = {"4", "5", "6"};
List<String> fromArray = Lists.newArrayList(array); // using guava
List<String> fromArrayJDK = Arrays.asList(array); // using JDK
MutableList<String> fromArrayGS = FastList.newListWith(array); // using gs
System.out.println(fromArray);
System.out.println(fromArrayJDK);
System.out.println(fromArrayGS);
// Create list using fabric
MutableList<String> fromFabricGS = FastList.newWithNValues(10, () -> String.valueOf(Math.random())); // using gs
System.out.println(fromFabricGS);
System.out.println("createArrayList end");
}
// Create HashSet using Guava,Gs and JDK
private static void createHashSet() {
System.out.println("createHashSet start");
// Create empty set
Set<String> emptyGuava = Sets.newHashSet(); // using guava
Set<String> emptyJDK = new HashSet<>(); // using JDK
Set<String> emptyGS = UnifiedSet.newSet(); // using gs
// Create set with 100 element
Set<String> approx100 = Sets.newHashSetWithExpectedSize(100); // using guava
Set<String> approx100JDK = new HashSet<>(130); // using JDK
Set<String> approx100GS = UnifiedSet.newSet(130); // using gs
// Create set from some elements
Set<String> withElements = Sets.newHashSet("alpha", "beta", "gamma"); // using guava
Set<String> withElementsJDK = new HashSet<>(Arrays.asList("alpha", "beta", "gamma")); // using JDK
Set<String> withElementsGS = UnifiedSet.newSetWith("alpha", "beta", "gamma"); // using gs
System.out.println(withElements);
System.out.println(withElementsJDK);
System.out.println(withElementsGS);
// Create set from any Iterable interface (any collection)
Collection<String> collection = new ArrayList<>(3);
collection.add("1");
collection.add("2");
collection.add("3");
Set<String> fromIterable = Sets.newHashSet(collection); // using guava
Set<String> fromIterableJDK = new HashSet<>(collection); // using JDK
Set<String> fromIterableGS = UnifiedSet.newSet(collection); // using gs
System.out.println(fromIterable);
System.out.println(fromIterableJDK);
System.out.println(fromIterableGS);
/* Attention: JDK create set only from Collection, but guava and gs can create set from Iterable and Collection */
// Create set from any Iterator
Iterator<String> iterator = collection.iterator();
Set<String> fromIterator = Sets.newHashSet(iterator); // using guava
System.out.println(fromIterator);
// Create set from any array
String[] array = {"4", "5", "6"};
Set<String> fromArray = Sets.newHashSet(array); // using guava
Set<String> fromArrayJDK = new HashSet<>(Arrays.asList(array)); // using JDK
Set<String> fromArrayGS = UnifiedSet.newSetWith(array); // using gs
System.out.println(fromArray);
System.out.println(fromArrayJDK);
System.out.println(fromArrayGS);
System.out.println("createHashSet end");
}
// Create HashMap using Guava,Gs and JDK
private static void createHashMap() {
System.out.println("createHashMap start");
// Create empty map
Map<String, String> emptyGuava = Maps.newHashMap(); // using guava
Map<String, String> emptyJDK = new HashMap<>(); // using JDK
Map<String, String> emptyGS = UnifiedMap.newMap(); // using gs
// Create map with about 100 element
Map<String, String> approx100 = Maps.newHashMapWithExpectedSize(100); // using guava
Map<String, String> approx100JDK = new HashMap<>(130); // using JDK
Map<String, String> approx100GS = UnifiedMap.newMap(130); // using gs
// Create map from another map
Map<String, String> map = new HashMap<>(3);
map.put("k1","v1");
map.put("k2","v2");
Map<String, String> withMap = Maps.newHashMap(map); // using guava
Map<String, String> withMapJDK = new HashMap<>(map); // using JDK
Map<String, String> withMapGS = UnifiedMap.newMap(map); // using gs
System.out.println(withMap);
System.out.println(withMapJDK);
System.out.println(withMapGS);
// Create map from keys
Map<String, String> withKeys = UnifiedMap.newWithKeysValues("1", "a", "2", "b");
System.out.println(withKeys);
System.out.println("createHashMap end");
}
}
| {
"pile_set_name": "Github"
} |
/*
* Namespace: DTS (DataTables Scroller)
*/
div.DTS tbody th,
div.DTS tbody td {
white-space: nowrap;
}
div.DTS tbody tr.even {
background-color: white;
}
div.DTS div.DTS_Loading {
position: absolute;
top: 50%;
left: 50%;
width: 200px;
height: 20px;
margin-top: -20px;
margin-left: -100px;
z-index: 1;
border: 1px solid #999;
padding: 20px 0;
text-align: center;
background-color: white;
background-color: rgba(255, 255, 255, 0.5);
}
div.DTS div.dataTables_scrollHead,
div.DTS div.dataTables_scrollFoot {
background-color: white;
}
div.DTS div.dataTables_scrollBody {
z-index: 2;
}
div.DTS div.dataTables_scroll {
background: url('../images/loading-background.png') repeat 0 0;
}
| {
"pile_set_name": "Github"
} |
#pragma once
#include "mersenne64.h"
#include "mersenne32.h"
#include <util/system/defaults.h>
#include <util/stream/input.h>
#include <util/memory/tempbuf.h>
namespace NPrivate {
template <class T>
struct TMersenneTraits;
template <>
struct TMersenneTraits<ui64> {
typedef TMersenne64 TRealization;
enum {
Seed = ULL(19650218)
};
};
template <>
struct TMersenneTraits<ui32> {
typedef TMersenne32 TRealization;
enum {
Seed = 19650218UL
};
};
TTempBuf ReadRandData(TInputStream* pool, size_t len);
}
template <class T>
class TMersenne {
public:
inline TMersenne(T seed = ::NPrivate::TMersenneTraits<T>::Seed) throw ()
: R_(seed)
{
}
inline TMersenne(TInputStream* pool)
: R_((const T*)NPrivate::ReadRandData(pool, 128 * sizeof(T)).Data(), 128)
{
}
inline TMersenne(const T keys[], size_t len) throw ()
: R_(keys, len)
{
}
inline T GenRand() throw () {
return R_.GenRand();
}
inline T RandMax() throw () {
return Max<T>();
}
/* generates a random number on [0, 1]-real-interval */
inline double GenRandReal1() throw () {
return R_.GenRandReal1();
}
/* generates a random number on [0, 1)-real-interval */
inline double GenRandReal2() throw () {
return R_.GenRandReal2();
}
/* generates a random number on (0, 1)-real-interval */
inline double GenRandReal3() throw () {
return R_.GenRandReal3();
}
/* generates a random number on [0, 1) with 53-bit resolution */
inline double GenRandReal4() throw () {
return R_.GenRandReal4();
}
private:
typename ::NPrivate::TMersenneTraits<T>::TRealization R_;
};
| {
"pile_set_name": "Github"
} |
{
"type": "root",
"children": [
{
"type": "paragraph",
"children": [
{
"type": "text",
"value": "GitHub, thus RedCarpet, has a bug where “nested” fenced code blocks,\neven with shorter fences, can exit their actual “parent” block.",
"position": {
"start": {
"line": 1,
"column": 1,
"offset": 0
},
"end": {
"line": 2,
"column": 64,
"offset": 132
},
"indent": [
1
]
}
}
],
"position": {
"start": {
"line": 1,
"column": 1,
"offset": 0
},
"end": {
"line": 2,
"column": 64,
"offset": 132
},
"indent": [
1
]
}
},
{
"type": "paragraph",
"children": [
{
"type": "text",
"value": "Note that this bug does not occur on indented code-blocks.",
"position": {
"start": {
"line": 4,
"column": 1,
"offset": 134
},
"end": {
"line": 4,
"column": 59,
"offset": 192
},
"indent": []
}
}
],
"position": {
"start": {
"line": 4,
"column": 1,
"offset": 134
},
"end": {
"line": 4,
"column": 59,
"offset": 192
},
"indent": []
}
},
{
"type": "paragraph",
"children": [
{
"type": "inlineCode",
"value": "foo\n```bar\nbaz\n```",
"position": {
"start": {
"line": 6,
"column": 1,
"offset": 194
},
"end": {
"line": 10,
"column": 5,
"offset": 221
},
"indent": [
1,
1,
1,
1
]
}
}
],
"position": {
"start": {
"line": 6,
"column": 1,
"offset": 194
},
"end": {
"line": 10,
"column": 5,
"offset": 221
},
"indent": [
1,
1,
1,
1
]
}
},
{
"type": "paragraph",
"children": [
{
"type": "text",
"value": "Even with a different fence marker:",
"position": {
"start": {
"line": 12,
"column": 1,
"offset": 223
},
"end": {
"line": 12,
"column": 36,
"offset": 258
},
"indent": []
}
}
],
"position": {
"start": {
"line": 12,
"column": 1,
"offset": 223
},
"end": {
"line": 12,
"column": 36,
"offset": 258
},
"indent": []
}
},
{
"type": "paragraph",
"children": [
{
"type": "inlineCode",
"value": "foo\n~~~bar\nbaz\n~~~",
"position": {
"start": {
"line": 14,
"column": 1,
"offset": 260
},
"end": {
"line": 18,
"column": 5,
"offset": 287
},
"indent": [
1,
1,
1,
1
]
}
}
],
"position": {
"start": {
"line": 14,
"column": 1,
"offset": 260
},
"end": {
"line": 18,
"column": 5,
"offset": 287
},
"indent": [
1,
1,
1,
1
]
}
},
{
"type": "paragraph",
"children": [
{
"type": "text",
"value": "And reversed:",
"position": {
"start": {
"line": 20,
"column": 1,
"offset": 289
},
"end": {
"line": 20,
"column": 14,
"offset": 302
},
"indent": []
}
}
],
"position": {
"start": {
"line": 20,
"column": 1,
"offset": 289
},
"end": {
"line": 20,
"column": 14,
"offset": 302
},
"indent": []
}
},
{
"type": "paragraph",
"children": [
{
"type": "text",
"value": "~~~~foo\n~~~bar\nbaz\n~~~\n~~~~",
"position": {
"start": {
"line": 22,
"column": 1,
"offset": 304
},
"end": {
"line": 26,
"column": 5,
"offset": 331
},
"indent": [
1,
1,
1,
1
]
}
}
],
"position": {
"start": {
"line": 22,
"column": 1,
"offset": 304
},
"end": {
"line": 26,
"column": 5,
"offset": 331
},
"indent": [
1,
1,
1,
1
]
}
},
{
"type": "paragraph",
"children": [
{
"type": "text",
"value": "~~~~foo\n",
"position": {
"start": {
"line": 28,
"column": 1,
"offset": 333
},
"end": {
"line": 29,
"column": 1,
"offset": 341
},
"indent": [
1
]
}
},
{
"type": "inlineCode",
"value": "bar\nbaz",
"position": {
"start": {
"line": 29,
"column": 1,
"offset": 341
},
"end": {
"line": 31,
"column": 4,
"offset": 355
},
"indent": [
1,
1
]
}
},
{
"type": "text",
"value": "\n~~~~",
"position": {
"start": {
"line": 31,
"column": 4,
"offset": 355
},
"end": {
"line": 32,
"column": 5,
"offset": 360
},
"indent": [
1
]
}
}
],
"position": {
"start": {
"line": 28,
"column": 1,
"offset": 333
},
"end": {
"line": 32,
"column": 5,
"offset": 360
},
"indent": [
1,
1,
1,
1
]
}
}
],
"position": {
"start": {
"line": 1,
"column": 1,
"offset": 0
},
"end": {
"line": 33,
"column": 1,
"offset": 361
}
}
}
| {
"pile_set_name": "Github"
} |
import { Theme } from '../../index';
import './color.css';
import './root.css';
export const theme: Theme = {
color: 'yandex-default',
root: 'default',
};
| {
"pile_set_name": "Github"
} |
------------------------------------------------------------------------------
-- --
-- GNAT2WHY COMPONENTS --
-- --
-- F L O W _ V I S I B I L I T Y --
-- --
-- B o d y --
-- --
-- Copyright (C) 2018-2020, Altran UK Limited --
-- --
-- gnat2why is free software; you can redistribute it and/or modify it --
-- under terms of the GNU General Public License as published by the Free --
-- Software Foundation; either version 3, or (at your option) any later --
-- version. gnat2why is distributed in the hope that it will be useful, --
-- but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHAN- --
-- TABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public --
-- License for more details. You should have received a copy of the GNU --
-- General Public License distributed with gnat2why; see file COPYING3. --
-- If not, go to http://www.gnu.org/licenses for a complete copy of the --
-- license. --
-- --
------------------------------------------------------------------------------
with Ada.Containers.Hashed_Maps;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
with Ada.Text_IO;
with Common_Containers; use Common_Containers;
with Einfo; use Einfo;
with Flow_Refinement; use Flow_Refinement;
with Graphs;
with Nlists; use Nlists;
with Rtsfind; use Rtsfind;
with Sem_Aux; use Sem_Aux;
with Sem_Ch12; use Sem_Ch12;
with Sem_Util; use Sem_Util;
with SPARK_Util; use SPARK_Util;
with Sinfo; use Sinfo;
with Stand; use Stand;
package body Flow_Visibility is
----------------------------------------------------------------------------
-- Types
----------------------------------------------------------------------------
package Hierarchy_Info_Maps is new
Ada.Containers.Hashed_Maps (Key_Type => Entity_Id,
Element_Type => Hierarchy_Info_T,
Hash => Node_Hash,
Equivalent_Keys => "=",
"=" => "=");
type Edge_Kind is (Rule_Own,
Rule_Instance,
Rule_Up_Spec,
Rule_Down_Spec,
Rule_Up_Priv,
Rule_Up_Body);
function Hash (S : Flow_Scope) return Ada.Containers.Hash_Type;
package Scope_Graphs is new
Graphs (Vertex_Key => Flow_Scope,
Edge_Colours => Edge_Kind,
Null_Key => Null_Flow_Scope,
Key_Hash => Hash,
Test_Key => "=");
----------------------------------------------------------------------------
-- Local variables
----------------------------------------------------------------------------
function Standard_Scope return Flow_Scope is
(Ent => Standard_Standard, Part => Visible_Part);
-- ??? this should be a constant, but at the time of elaboration the
-- Standard_Standard is not yet defined.
Hierarchy_Info : Hierarchy_Info_Maps.Map;
Scope_Graph : Scope_Graphs.Graph := Scope_Graphs.Create;
Components : Scope_Graphs.Strongly_Connected_Components;
-- Pre-computed strongly connected components of the visibility graph for
-- quickly answering visibility queries.
----------------------------------------------------------------------------
-- Subprogram declarations
----------------------------------------------------------------------------
function Sanitize (S : Flow_Scope) return Flow_Scope is
(if Present (S) then S else Standard_Scope);
-- Convert between Null_Flow_Scope (which is used in the Flow_Refinement
-- package) to Standard_Scope (which is used here).
function Make_Info (N : Node_Id) return Hierarchy_Info_T;
function Is_Child (Info : Hierarchy_Info_T) return Boolean;
function Is_Nested (Info : Hierarchy_Info_T) return Boolean;
function Is_Instance (Info : Hierarchy_Info_T) return Boolean;
function Is_Instance_Child (Info : Hierarchy_Info_T) return Boolean;
-- Utility routines for the hierarchy data
procedure Print (G : Scope_Graphs.Graph);
-- Pretty-print visibility graph
procedure Print_Path (From, To : Flow_Scope);
pragma Unreferenced (Print_Path);
-- To be used from the debugger
generic
with procedure Process (N : Node_Id);
procedure Traverse_Compilation_Unit (Unit_Node : Node_Id);
-- Call Process on all declarations within compilation unit CU. Unlike the
-- standard frontend traversal, this one traverses into stubs; ??? it is
-- now similar to the generated globals traversal.
----------------------------------------------------------------------------
-- Subprogram bodies
----------------------------------------------------------------------------
-------------------------
-- Connect_Flow_Scopes --
-------------------------
procedure Connect_Flow_Scopes is
procedure Connect (E : Entity_Id; Info : Hierarchy_Info_T);
-------------
-- Connect --
-------------
procedure Connect (E : Entity_Id; Info : Hierarchy_Info_T) is
Spec_V : constant Scope_Graphs.Vertex_Id :=
Scope_Graph.Get_Vertex ((Ent => E, Part => Visible_Part));
Priv_V : constant Scope_Graphs.Vertex_Id :=
(if Info.Is_Package
then Scope_Graph.Get_Vertex ((Ent => E, Part => Private_Part))
else Scope_Graphs.Null_Vertex);
Body_V : constant Scope_Graphs.Vertex_Id :=
Scope_Graph.Get_Vertex ((Ent => E, Part => Body_Part));
-- Vertices for the visible (aka. "spec"), private and body parts
Rule : Edge_Kind;
-- Rule that causes an edge to be added; maintaining it as a global
-- variable is not elegant, but results in a cleaner code.
use type Scope_Graphs.Vertex_Id;
procedure Connect (Source, Target : Scope_Graphs.Vertex_Id)
with Pre => Source /= Scope_Graphs.Null_Vertex
and
Target /= Scope_Graphs.Null_Vertex
and
Source /= Target;
-- Add edge from Source to Target
-------------
-- Connect --
-------------
procedure Connect (Source, Target : Scope_Graphs.Vertex_Id) is
begin
pragma Assert (not Scope_Graph.Edge_Exists (Source, Target));
Scope_Graph.Add_Edge (Source, Target, Rule);
end Connect;
-- Start of processing for Connect
begin
----------------------------------------------------------------------
-- Create edges
----------------------------------------------------------------------
Rule := Rule_Own;
-- This rule is the "my own scope" rule, and is the most obvious form
-- of visibility.
if Info.Is_Package then
Connect (Body_V, Priv_V);
Connect (Priv_V, Spec_V);
else
Connect (Body_V, Spec_V);
end if;
----------------------------------------------------------------------
Rule := Rule_Instance;
-- This is the "generic" rule. It deals with the special upwards
-- visibility of generic instances. Instead of following the
-- normal rules for this we link all our parts to the template's
-- corresponding parts, since the template's position in the graph
-- determines our visibility, not the location of instantiation.
if Is_Instance (Info) then
if Is_Instance_Child (Info) then
Connect
(Spec_V,
Scope_Graph.Get_Vertex ((Ent => Info.Instance_Parent,
Part => Visible_Part)));
if Info.Is_Package then
Connect
(Priv_V,
Scope_Graph.Get_Vertex ((Ent => Info.Instance_Parent,
Part => Private_Part)));
end if;
else
Connect
(Spec_V,
Scope_Graph.Get_Vertex ((Ent => Info.Template,
Part => Visible_Part)));
-- Generic units acquire visibility from where they are
-- instantiated, so they can "see" subprograms used to
-- instantiate them (when instantiated, a formal subprogram
-- becomes a renaming). Same for formal packages.
--
-- ??? do something similar when Is_Instance_Child is True
Connect
(Spec_V,
Scope_Graph.Get_Vertex
(if Is_Nested (Info)
then Info.Container
else (Ent => Info.Parent,
Part => (if Info.Is_Private
then Private_Part
else Visible_Part))));
-- ??? The code for the target scope is repeated in rules
-- Rule_Up_Spec and Rule_Down_Spec; this should be refactored.
-- Visibility of the template's private part only matters if
-- the template itself is a child unit, but it is safe to
-- connect it in any case (and detecting which generic is a
-- child unit would require extra info in phase 2).
if Info.Is_Package then
Connect
(Priv_V,
Scope_Graph.Get_Vertex ((Ent => Info.Template,
Part => Private_Part)));
end if;
Connect
(Body_V,
Scope_Graph.Get_Vertex ((Ent => Info.Template,
Part => Body_Part)));
-- For generic subprograms instantiated in the wrapper packages
-- we need the visibility from the instantiated subprogram body
-- to the wrapper package body, as otherwise the
-- Subprogram_Refinement_Is_Visible says that the instantiated
-- generic subprogram body can't see its own refinement.
--
-- ??? wrapper packages were ignored in the design document,
-- probably this should be revisited.
--
-- ??? we need something similar for generic child subprograms
-- of generic parents (i.e. the Is_Instance_Child branch above)
if not Info.Is_Package then
Connect
(Body_V,
Scope_Graph.Get_Vertex (Body_Scope (Info.Container)));
end if;
end if;
end if;
----------------------------------------------------------------------
Rule := Rule_Up_Spec;
-- This rule deals with upwards visibility, i.e. adding a link to
-- the nearest "enclosing" scope. Generics are dealt with separately,
-- ??? except for generic child instantiations (they have visibility
-- of their parent's instantiation).
if not Is_Instance (Info) then
Connect
(Spec_V,
Scope_Graph.Get_Vertex
(if Is_Nested (Info)
then Info.Container
else (Ent => Info.Parent,
Part => (if Info.Is_Private
then Private_Part
else Visible_Part))));
end if;
----------------------------------------------------------------------
-- As mentioned before, instances break the chain so they need
-- special treatment, and the remaining three rules just add the
-- appropriate links. Note that although the last three are mutually
-- exclusive, any of them might be an instance.
----------------------------------------------------------------------
Rule := Rule_Down_Spec;
-- This rule deals with downwards visibility, i.e. contributing to
-- the visibility of the surrounding context. It is exactly the
-- inverse of Rule_Up_Spec, except there is no special treatment for
-- instances (since a scope does have visibility of the spec of
-- something instantiated inside it).
Connect
(Scope_Graph.Get_Vertex (if Is_Nested (Info)
then Info.Container
else (Ent => Info.Parent,
Part => (if Info.Is_Private
then Private_Part
else Visible_Part))),
Spec_V);
----------------------------------------------------------------------
Rule := Rule_Up_Priv;
-- This rule deals with upwards visibility for the private part of a
-- child package or subprogram. It doesn't apply to instances.
if Is_Child (Info)
and then not Is_Instance (Info)
then
Connect
((if Info.Is_Package
then Priv_V
else Body_V),
Scope_Graph.Get_Vertex ((Ent => Info.Parent,
Part => Private_Part)));
end if;
----------------------------------------------------------------------
Rule := Rule_Up_Body;
-- Finally, this rule deals with the upwards visibility for the body
-- of a nested package. A nested scope will have visibility of its
-- enclosing scope's body, since it is impossible to complete the
-- body anywhere else. Again, it doesn't apply to instances.
if Is_Nested (Info)
and then not Is_Instance (Info)
then
Connect
(Body_V,
Scope_Graph.Get_Vertex ((Ent => Info.Container.Ent,
Part => Body_Part)));
end if;
end Connect;
-- Start of processing for Connect_Flow_Scopes
begin
for C in Hierarchy_Info.Iterate loop
declare
E : Entity_Id renames Hierarchy_Info_Maps.Key (C);
Info : Hierarchy_Info_T renames Hierarchy_Info (C);
begin
Connect (E, Info);
end;
end loop;
-- Release memory to the provers
-- ??? Hierarchy_Info.Clear;
-- At this point we could compute a transitive closure, but that can
-- take huge amount of memory. This is because typically the visibility
-- graph has many vertices and all of them are connected to all the
-- enclosing scopes (up to Standard); however, the visibility paths
-- are short and can be quickly discovered.
-- In phase 1 we print the graph (if requested), but keep the hirarchy
-- info for writing it to the ALI file; in phase 2 we clear the info,
-- as it is no longer needed (while the graph is still needed for failed
-- check explanations).
if Gnat2Why_Args.Global_Gen_Mode then
if Gnat2Why_Args.Flow_Advanced_Debug then
Print (Scope_Graph);
end if;
else
Hierarchy_Info.Clear;
Hierarchy_Info.Reserve_Capacity (0);
end if;
Components := Scope_Graph.SCC;
-- Sanity check: all vertices should be now connected to Standard
declare
Standard : constant Scope_Graphs.Vertex_Id :=
Scope_Graph.Get_Vertex ((Ent => Standard_Standard,
Part => Visible_Part))
with Ghost;
use Scope_Graphs;
begin
pragma Assert
(for all V of Scope_Graph.Get_Collection (All_Vertices) =>
(if V /= Standard
then Scope_Graph.Edge_Exists (Components, V, Standard)));
end;
end Connect_Flow_Scopes;
----------
-- Hash --
----------
function Hash (S : Flow_Scope) return Ada.Containers.Hash_Type is
use type Ada.Containers.Hash_Type;
begin
-- Adding S.Part'Pos, which ranges from 0 to 3, should keep hash values
-- unique, because S.Ent values of different scopes are not that close
-- to each other.
return Node_Hash (S.Ent) + Declarative_Part'Pos (S.Part);
end Hash;
--------------
-- Is_Child --
--------------
function Is_Child (Info : Hierarchy_Info_T) return Boolean is
(Present (Info.Parent));
-----------------
-- Is_Instance --
-----------------
function Is_Instance (Info : Hierarchy_Info_T) return Boolean is
(Present (Info.Template));
-----------------------
-- Is_Instance_Child --
-----------------------
function Is_Instance_Child (Info : Hierarchy_Info_T) return Boolean is
(Present (Info.Instance_Parent));
---------------
-- Is_Nested --
---------------
function Is_Nested (Info : Hierarchy_Info_T) return Boolean is
(Present (Info.Container));
----------------
-- Is_Visible --
----------------
function Is_Visible
(Looking_From : Flow_Scope;
Looking_At : Flow_Scope)
return Boolean
is
begin
-- The visibility graph is not reflexive; we must explicitly check for
-- visibility between the same scopes.
return Looking_From = Looking_At
or else Scope_Graph.Edge_Exists
(Components,
Sanitize (Looking_From),
Sanitize (Looking_At));
end Is_Visible;
---------------
-- Make_Info --
---------------
function Make_Info (N : Node_Id) return Hierarchy_Info_T is
Def_E : constant Entity_Id := Defining_Entity (N);
E : constant Entity_Id :=
(if Nkind (N) = N_Private_Type_Declaration
then DIC_Procedure (Def_E)
elsif Nkind (N) = N_Full_Type_Declaration
then Invariant_Procedure (Def_E)
else Def_E);
Is_Package : Boolean;
Is_Private : Boolean;
Parent : Entity_Id;
Instance_Parent : Entity_Id;
Template : Entity_Id;
Container : Flow_Scope;
begin
-- Special Text_IO packages behave as nested within the Ada.Text_IO
-- (that is what Ada RM A.10.1 mandates), but in GNAT they are defined
-- as private generic children of Ada.Text_IO. We special-case them
-- according to what the Ada RM says.
if Ekind (E) in E_Package | E_Generic_Package then
Is_Package := True;
if Is_Child_Unit (E) then
if Is_Text_IO_Special_Package (E) then
Is_Private := False;
Parent := Empty;
else
Is_Private :=
Nkind (Atree.Parent (N)) = N_Compilation_Unit
and then
Private_Present (Atree.Parent (N));
Parent := Scope (E);
end if;
elsif Get_Flow_Scope (N) = Null_Flow_Scope then
Is_Private := False;
Parent := Standard_Standard;
else
Is_Private := False;
Parent := Empty;
end if;
else
pragma Assert (Ekind (E) in Entry_Kind
| E_Function
| E_Procedure
| E_Protected_Type
| E_Task_Type
| Generic_Subprogram_Kind);
Is_Package := False;
Is_Private :=
Is_Compilation_Unit (E)
and then
Private_Present (Enclosing_Comp_Unit_Node (E));
if Is_Compilation_Unit (E) then
if Ekind (E) in E_Function | E_Procedure
and then Is_Generic_Instance (E)
then
Parent := Empty;
else
Parent := Scope (E);
end if;
else
Parent := Empty;
end if;
end if;
if Is_Generic_Instance (E)
and then not Is_Wrapper_Package (E)
then
Template := Generic_Parent (Specification (N));
-- Deal with instances of child instances; this is based on frontend
-- Install_Parent_Private_Declarations.
if Is_Child_Unit (Template)
and then Is_Generic_Unit (Scope (Template))
then
declare
Child_Inst : constant Entity_Id :=
(if Ekind (E) = E_Package
then E
else Defining_Entity (Atree.Parent (Subprogram_Spec (E))));
-- If the child instance is a package, we can directly pass it
-- to Get_Unit_Instantiation_Node; when it is a subprogram, we
-- must get its wrapper package. Typically it is just the Scope
-- of E, except for instance-as-compilation-unit, where we need
-- to retrieve the wrapper package syntactically.
pragma Assert
(Ekind (E) = E_Package
or else
(Ekind (E) in E_Function | E_Procedure
and then Is_Wrapper_Package (Child_Inst)));
Inst_Node : constant Node_Id :=
Get_Unit_Instantiation_Node (Child_Inst);
begin
pragma Assert (Nkind (Inst_Node) in N_Generic_Instantiation);
-- The original frontend routine expects formal packages too,
-- but in the backend we only instantiations, because formal
-- packages have been expanded to renamings of instances.
pragma Assert (Nkind (Name (Inst_Node)) = N_Expanded_Name);
-- When analysing the generic parent body, frontend expects the
-- child to be named either as "P.C" (N_Expanded_Name) or "C"
-- (N_Identifier); when analysing its instance in the backend
-- we only see N_Expanded_Name.
Instance_Parent := Entity (Prefix (Name (Inst_Node)));
pragma Assert (Ekind (Instance_Parent) = E_Package);
if Present (Renamed_Entity (Instance_Parent)) then
Instance_Parent := Renamed_Entity (Instance_Parent);
pragma Assert (Ekind (Instance_Parent) = E_Package);
end if;
end;
else
Instance_Parent := Empty;
end if;
else
Template := Empty;
Instance_Parent := Empty;
end if;
if Is_Child_Unit (E)
and then Is_Package_Or_Generic_Package (E)
and then Is_Text_IO_Special_Package (E)
then
Container := (Ent => Scope (E), Part => Visible_Part);
else
Container := Get_Flow_Scope (N);
end if;
-------------------------------------------------------------------------
-- Invariant
--
-- This is intentonally a sequance of pragmas and not a Boolean-value
-- function, because with pragmas if one of the conditions fails, it
-- is easier to know which one.
-------------------------------------------------------------------------
pragma Assert (Present (Container) or else Present (Parent));
-- Everything is nested or else has a parent
pragma Assert (not (Is_Private and Present (Container)));
-- Being "private" can only apply to non-nested packages
pragma Assert (if Present (Template) then Is_Generic_Unit (Template));
-- Template, if present, is a generic unit
pragma Assert (if Present (Parent)
then Ekind (Parent) in E_Package | E_Generic_Package);
-- Parent, if present, must be a package or a generic package
-------------------------------------------------------------------------
return (Is_Package => Is_Package,
Is_Private => Is_Private,
Parent => Parent,
Instance_Parent => Instance_Parent,
Template => Template,
Container => Container);
end Make_Info;
-----------
-- Print --
-----------
procedure Print (G : Scope_Graphs.Graph)
is
use Scope_Graphs;
Show_Empty_Subprogram_Bodies : constant Boolean := False;
-- A debug flag fow showing/hiding subprograms with bo bodies (e.g. when
-- the body is in another compilation unit, especially in a predefined
-- one, like System; or when the subprogram is abstract). Those bodies
-- make the graph harder to read.
-- ??? perhaps we should not create vertices for those bodies in the
-- first place.
function NDI (G : Graph; V : Vertex_Id) return Node_Display_Info;
-- Pretty-printing for vertices in the dot output
function EDI
(G : Graph;
A : Vertex_Id;
B : Vertex_Id;
Marked : Boolean;
Colour : Edge_Kind) return Edge_Display_Info;
-- Pretty-printing for edges in the dot output
---------
-- NDI --
---------
function NDI (G : Graph; V : Vertex_Id) return Node_Display_Info
is
S : constant Flow_Scope := G.Get_Key (V);
Label : constant String :=
Full_Source_Name (S.Ent) &
(case S.Part is
when Visible_Part => " (Spec)",
when Private_Part => " (Priv)",
when Body_Part => " (Body)",
when Null_Part => raise Program_Error);
Show : Boolean;
begin
if S.Part = Body_Part
and then Ekind (S.Ent) in E_Function | E_Procedure
and then No (Subprogram_Body_Entity (S.Ent))
then
pragma Assert (G.In_Neighbour_Count (V) = 0);
Show := Show_Empty_Subprogram_Bodies;
else
Show := True;
end if;
return (Show => Show,
Shape => Shape_None,
Colour =>
To_Unbounded_String
(if S = Standard_Scope then "blue"
elsif Is_Generic_Unit (S.Ent) then "red"
else ""),
Fill_Colour => Null_Unbounded_String,
Label => To_Unbounded_String (Label));
end NDI;
---------
-- EDI --
---------
function EDI
(G : Graph;
A : Vertex_Id;
B : Vertex_Id;
Marked : Boolean;
Colour : Edge_Kind) return Edge_Display_Info
is
pragma Unreferenced (B, Marked, Colour);
S : constant Flow_Scope := G.Get_Key (A);
Show : Boolean;
begin
if Ekind (S.Ent) in E_Function | E_Procedure
and then S.Part = Body_Part
and then No (Subprogram_Body_Entity (S.Ent))
then
pragma Assert (G.In_Neighbour_Count (A) = 0);
Show := Show_Empty_Subprogram_Bodies;
else
Show := True;
end if;
return
(Show => Show,
Shape => Edge_Normal,
Colour => Null_Unbounded_String,
Label => Null_Unbounded_String);
-- ??? Label should reflect the Colour argument, but the current
-- names of the rules are too long and produce unreadable graphs.
end EDI;
Filename : constant String :=
Unique_Name (Unique_Main_Unit_Entity) & "_visibility";
-- Start of processing for Print
begin
G.Write_Pdf_File
(Filename => Filename,
Node_Info => NDI'Access,
Edge_Info => EDI'Access);
end Print;
----------------
-- Print_Path --
----------------
procedure Print_Path (From, To : Flow_Scope) is
Source : constant Scope_Graphs.Vertex_Id :=
Scope_Graph.Get_Vertex (Sanitize (From));
Target : constant Scope_Graphs.Vertex_Id :=
Scope_Graph.Get_Vertex (Sanitize (To));
procedure Is_Target
(V : Scope_Graphs.Vertex_Id;
Instruction : out Scope_Graphs.Traversal_Instruction);
procedure Print_Vertex (V : Scope_Graphs.Vertex_Id);
---------------
-- Is_Target --
---------------
procedure Is_Target
(V : Scope_Graphs.Vertex_Id;
Instruction : out Scope_Graphs.Traversal_Instruction)
is
use type Scope_Graphs.Vertex_Id;
begin
Instruction :=
(if V = Target
then Scope_Graphs.Found_Destination
else Scope_Graphs.Continue);
end Is_Target;
------------------
-- Print_Vertex --
------------------
procedure Print_Vertex (V : Scope_Graphs.Vertex_Id) is
S : constant Flow_Scope := Scope_Graph.Get_Key (V);
begin
-- Print_Flow_Scope (S);
-- ??? the above code produces no output in gdb; use Ada.Text_IO
if Present (S.Ent) then
Ada.Text_IO.Put_Line
(Full_Source_Name (S.Ent) &
" | " &
(case Declarative_Part'(S.Part) is
when Visible_Part => "spec",
when Private_Part => "priv",
when Body_Part => "body"));
else
Ada.Text_IO.Put_Line ("standard");
end if;
end Print_Vertex;
-- Start of processing for Print_Path
begin
Scope_Graphs.Shortest_Path
(G => Scope_Graph,
Start => Source,
Allow_Trivial => True,
Search => Is_Target'Access,
Step => Print_Vertex'Access);
end Print_Path;
--------------------------
-- Register_Flow_Scopes --
--------------------------
procedure Register_Flow_Scopes (Unit_Node : Node_Id) is
procedure Process_Scope_Declaration (N : Node_Id)
with Pre => Nkind (N) in N_Entry_Declaration
| N_Generic_Declaration
| N_Package_Declaration
| N_Protected_Type_Declaration
| N_Subprogram_Declaration
| N_Subprogram_Body_Stub
| N_Task_Type_Declaration
| N_Abstract_Subprogram_Declaration
or else (Nkind (N) = N_Subprogram_Body
and then Acts_As_Spec (N))
or else (Nkind (N) = N_Private_Type_Declaration
and then Has_Own_DIC (Defining_Entity (N)))
or else (Nkind (N) = N_Full_Type_Declaration
and then Has_Own_Invariants (Defining_Entity (N)));
-------------------------------
-- Process_Scope_Declaration --
-------------------------------
procedure Process_Scope_Declaration (N : Node_Id) is
Def_E : constant Entity_Id := Defining_Entity (N);
E : constant Entity_Id :=
(if Nkind (N) = N_Private_Type_Declaration
then DIC_Procedure (Def_E)
elsif Nkind (N) = N_Full_Type_Declaration
then Invariant_Procedure (Def_E)
else Def_E);
Info : constant Hierarchy_Info_T := Make_Info (N);
Spec_V, Priv_V, Body_V : Scope_Graphs.Vertex_Id;
-- Vertices for the visible (aka. "spec"), private and body parts
begin
if Is_Eliminated (E) then
-- ??? when returning early we don't need the Info constant
return;
end if;
-- ??? we don't need this info (except for debug?)
Hierarchy_Info.Insert (E, Info);
----------------------------------------------------------------------
-- Create vertices
----------------------------------------------------------------------
Scope_Graph.Add_Vertex ((Ent => E, Part => Visible_Part), Spec_V);
if Info.Is_Package then
Scope_Graph.Add_Vertex ((Ent => E, Part => Private_Part), Priv_V);
end if;
Scope_Graph.Add_Vertex ((Ent => E, Part => Body_Part), Body_V);
end Process_Scope_Declaration;
procedure Traverse is
new Traverse_Compilation_Unit (Process_Scope_Declaration);
-- Start of processing for Build_Graph
begin
if Unit_Node = Standard_Package_Node then
-- The Standard package is special: create vertices for its
-- visible and private parts and connect them. This package declares
-- no subprograms or abstract states, so we don't need a vertex for
-- its body part.
--
-- This is based on the Ada RM 10.1.1(1): "Each library unit (except
-- Standard) has a parent unit, which is a library package or generic
-- library package."
Scope_Graph.Add_Vertex
((Ent => Standard_Standard, Part => Visible_Part));
Scope_Graph.Add_Vertex
((Ent => Standard_Standard, Part => Private_Part));
Scope_Graph.Add_Edge
((Ent => Standard_Standard, Part => Private_Part),
(Ent => Standard_Standard, Part => Visible_Part),
Rule_Own);
else
Traverse (Unit_Node);
end if;
end Register_Flow_Scopes;
-------------------------------
-- Traverse_Compilation_Unit --
-------------------------------
procedure Traverse_Compilation_Unit (Unit_Node : Node_Id)
is
procedure Traverse_Declaration_Or_Statement (N : Node_Id);
procedure Traverse_Declarations_And_HSS (N : Node_Id);
procedure Traverse_Declarations_Or_Statements (L : List_Id);
procedure Traverse_Handled_Statement_Sequence (N : Node_Id);
procedure Traverse_Package_Body (N : Node_Id);
procedure Traverse_Visible_And_Private_Parts (N : Node_Id);
procedure Traverse_Protected_Body (N : Node_Id);
procedure Traverse_Subprogram_Body (N : Node_Id);
procedure Traverse_Task_Body (N : Node_Id);
-- Traverse corresponding construct, calling Process on all declarations
---------------------------------------
-- Traverse_Declaration_Or_Statement --
---------------------------------------
procedure Traverse_Declaration_Or_Statement (N : Node_Id) is
begin
-- Call Process on all interesting declarations and traverse
case Nkind (N) is
when N_Package_Declaration =>
Process (N);
Traverse_Visible_And_Private_Parts (Specification (N));
when N_Generic_Package_Declaration =>
Process (N);
when N_Package_Body =>
if Ekind (Unique_Defining_Entity (N)) /= E_Generic_Package then
Traverse_Package_Body (N);
end if;
when N_Package_Body_Stub =>
if Ekind (Unique_Defining_Entity (N)) /= E_Generic_Package then
Traverse_Package_Body (Get_Body_From_Stub (N));
end if;
when N_Entry_Declaration
| N_Generic_Subprogram_Declaration
| N_Subprogram_Declaration
| N_Abstract_Subprogram_Declaration
=>
-- ??? abstract subprograms have no bodies
Process (N);
when N_Subprogram_Body =>
if Acts_As_Spec (N) then
Process (N);
end if;
if not Is_Generic_Subprogram (Unique_Defining_Entity (N)) then
Traverse_Subprogram_Body (N);
end if;
when N_Entry_Body =>
Traverse_Subprogram_Body (N);
when N_Subprogram_Body_Stub =>
if Is_Subprogram_Stub_Without_Prior_Declaration (N) then
Process (N);
end if;
if not Is_Generic_Subprogram (Unique_Defining_Entity (N)) then
Traverse_Subprogram_Body (Get_Body_From_Stub (N));
end if;
when N_Protected_Body =>
Traverse_Protected_Body (N);
when N_Protected_Body_Stub =>
Traverse_Protected_Body (Get_Body_From_Stub (N));
when N_Protected_Type_Declaration =>
Process (N);
Traverse_Visible_And_Private_Parts (Protected_Definition (N));
when N_Task_Type_Declaration =>
Process (N);
-- Task type definition is optional (unlike protected type
-- definition, which is mandatory).
declare
Task_Def : constant Node_Id := Task_Definition (N);
begin
if Present (Task_Def) then
Traverse_Visible_And_Private_Parts (Task_Def);
end if;
end;
when N_Task_Body =>
Traverse_Task_Body (N);
when N_Task_Body_Stub =>
Traverse_Task_Body (Get_Body_From_Stub (N));
when N_Block_Statement =>
Traverse_Declarations_And_HSS (N);
when N_If_Statement =>
-- Traverse the statements in the THEN part
Traverse_Declarations_Or_Statements (Then_Statements (N));
-- Loop through ELSIF parts if present
if Present (Elsif_Parts (N)) then
declare
Elif : Node_Id := First (Elsif_Parts (N));
begin
while Present (Elif) loop
Traverse_Declarations_Or_Statements
(Then_Statements (Elif));
Next (Elif);
end loop;
end;
end if;
-- Finally traverse the ELSE statements if present
Traverse_Declarations_Or_Statements (Else_Statements (N));
when N_Case_Statement =>
-- Process case branches
declare
Alt : Node_Id := First (Alternatives (N));
begin
loop
Traverse_Declarations_Or_Statements (Statements (Alt));
Next (Alt);
exit when No (Alt);
end loop;
end;
when N_Extended_Return_Statement =>
Traverse_Handled_Statement_Sequence
(Handled_Statement_Sequence (N));
when N_Loop_Statement =>
Traverse_Declarations_Or_Statements (Statements (N));
when N_Private_Type_Declaration =>
-- Both private and full view declarations might be represented
-- by N_Private_Type_Declaration; the former comes from source,
-- the latter comes from rewriting.
if Comes_From_Source (N) then
declare
T : constant Entity_Id := Defining_Entity (N);
begin
if Has_Own_DIC (T)
and then Present (DIC_Procedure (T))
then
Process (N);
end if;
end;
end if;
when N_Full_Type_Declaration =>
declare
T : constant Entity_Id := Defining_Entity (N);
begin
-- For Type_Invariant'Class there will be no invariant
-- procedure; we ignore it, because this aspect is not
-- supported in SPARK anyway.
if Comes_From_Source (N)
and then Has_Own_Invariants (T)
and then Present (Invariant_Procedure (T))
then
Process (N);
end if;
end;
when others =>
null;
end case;
end Traverse_Declaration_Or_Statement;
-----------------------------------
-- Traverse_Declarations_And_HSS --
-----------------------------------
procedure Traverse_Declarations_And_HSS (N : Node_Id) is
begin
Traverse_Declarations_Or_Statements (Declarations (N));
Traverse_Handled_Statement_Sequence (Handled_Statement_Sequence (N));
end Traverse_Declarations_And_HSS;
-----------------------------------------
-- Traverse_Declarations_Or_Statements --
-----------------------------------------
procedure Traverse_Declarations_Or_Statements (L : List_Id) is
N : Node_Id := First (L);
begin
-- Loop through statements or declarations
while Present (N) loop
Traverse_Declaration_Or_Statement (N);
Next (N);
end loop;
end Traverse_Declarations_Or_Statements;
-----------------------------------------
-- Traverse_Handled_Statement_Sequence --
-----------------------------------------
procedure Traverse_Handled_Statement_Sequence (N : Node_Id) is
Handler : Node_Id;
begin
if Present (N) then
Traverse_Declarations_Or_Statements (Statements (N));
if Present (Exception_Handlers (N)) then
Handler := First (Exception_Handlers (N));
while Present (Handler) loop
Traverse_Declarations_Or_Statements (Statements (Handler));
Next (Handler);
end loop;
end if;
end if;
end Traverse_Handled_Statement_Sequence;
---------------------------
-- Traverse_Package_Body --
---------------------------
procedure Traverse_Package_Body (N : Node_Id) is
begin
Traverse_Declarations_Or_Statements (Declarations (N));
Traverse_Handled_Statement_Sequence (Handled_Statement_Sequence (N));
end Traverse_Package_Body;
-----------------------------
-- Traverse_Protected_Body --
-----------------------------
procedure Traverse_Protected_Body (N : Node_Id) is
begin
Traverse_Declarations_Or_Statements (Declarations (N));
end Traverse_Protected_Body;
------------------------------
-- Traverse_Subprogram_Body --
------------------------------
procedure Traverse_Subprogram_Body (N : Node_Id) renames
Traverse_Declarations_And_HSS;
------------------------
-- Traverse_Task_Body --
------------------------
procedure Traverse_Task_Body (N : Node_Id) renames
Traverse_Declarations_And_HSS;
----------------------------------------
-- Traverse_Visible_And_Private_Parts --
----------------------------------------
procedure Traverse_Visible_And_Private_Parts (N : Node_Id) is
begin
Traverse_Declarations_Or_Statements (Visible_Declarations (N));
Traverse_Declarations_Or_Statements (Private_Declarations (N));
end Traverse_Visible_And_Private_Parts;
-- Start of processing for Traverse_Compilation_Unit
begin
Traverse_Declaration_Or_Statement (Unit_Node);
end Traverse_Compilation_Unit;
-------------------------
-- Iterate_Flow_Scopes --
-------------------------
procedure Iterate_Flow_Scopes is
begin
for C in Hierarchy_Info.Iterate loop
Process (Hierarchy_Info_Maps.Key (C), Hierarchy_Info (C));
end loop;
-- Release data that is no longer needed
Hierarchy_Info.Clear;
Hierarchy_Info.Reserve_Capacity (0);
end Iterate_Flow_Scopes;
end Flow_Visibility;
| {
"pile_set_name": "Github"
} |
--TEST--
GH-455: expectOutputString not working in strict mode
--FILE--
<?php
$_SERVER['argv'][1] = '--no-configuration';
$_SERVER['argv'][2] = '--disallow-test-output';
$_SERVER['argv'][3] = 'Issue445Test';
$_SERVER['argv'][4] = __DIR__ . '/445/Issue445Test.php';
require __DIR__ . '/../../bootstrap.php';
PHPUnit_TextUI_Command::main();
?>
--EXPECTF--
PHPUnit %s by Sebastian Bergmann and contributors.
..F 3 / 3 (100%)
Time: %s, Memory: %s
There was 1 failure:
1) Issue445Test::testNotMatchingOutput
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
-'foo'
+'bar'
FAILURES!
Tests: 3, Assertions: 3, Failures: 1.
| {
"pile_set_name": "Github"
} |
<!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 (1.8.0_40) on Fri Nov 09 11:56:14 PST 2018 -->
<title>Values.Parser (kafka 2.1.0 API)</title>
<meta name="date" content="2018-11-09">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Values.Parser (kafka 2.1.0 API)";
}
}
catch(err) {
}
//-->
var methods = {"i0":10,"i1":10,"i2":10,"i3":10,"i4":10,"i5":10,"i6":10,"i7":10,"i8":10,"i9":10,"i10":10};
var tabs = {65535:["t0","All Methods"],2:["t2","Instance Methods"],8:["t4","Concrete Methods"]};
var altColor = "altColor";
var rowColor = "rowColor";
var tableTab = "tableTab";
var activeTableTab = "activeTableTab";
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<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 class="navBarCell1Rev">Class</li>
<li><a href="package-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><a href="../../../../../org/apache/kafka/connect/data/Values.html" title="class in org.apache.kafka.connect.data"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../../../org/apache/kafka/connect/data/Values.SchemaDetector.html" title="class in org.apache.kafka.connect.data"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/apache/kafka/connect/data/Values.Parser.html" target="_top">Frames</a></li>
<li><a href="Values.Parser.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>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor.summary">Constr</a> | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor.detail">Constr</a> | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">org.apache.kafka.connect.data</div>
<h2 title="Class Values.Parser" class="title">Class Values.Parser</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>org.apache.kafka.connect.data.Values.Parser</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>Enclosing class:</dt>
<dd><a href="../../../../../org/apache/kafka/connect/data/Values.html" title="class in org.apache.kafka.connect.data">Values</a></dd>
</dl>
<hr>
<br>
<pre>protected static class <span class="typeNameLabel">Values.Parser</span>
extends java.lang.Object</pre>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor.summary">
<!-- -->
</a>
<h3>Constructor Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../../../../org/apache/kafka/connect/data/Values.Parser.html#Parser-java.lang.String-">Parser</a></span>(java.lang.String original)</code> </td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method.summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd"> </span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd"> </span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">Concrete Methods</a></span><span class="tabEnd"> </span></span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr id="i0" class="altColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../org/apache/kafka/connect/data/Values.Parser.html#canConsume-java.lang.String-">canConsume</a></span>(java.lang.String expected)</code> </td>
</tr>
<tr id="i1" class="rowColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../org/apache/kafka/connect/data/Values.Parser.html#canConsume-java.lang.String-boolean-">canConsume</a></span>(java.lang.String expected,
boolean ignoreLeadingAndTrailingWhitespace)</code> </td>
</tr>
<tr id="i2" class="altColor">
<td class="colFirst"><code>protected boolean</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../org/apache/kafka/connect/data/Values.Parser.html#canConsumeNextToken--">canConsumeNextToken</a></span>()</code> </td>
</tr>
<tr id="i3" class="rowColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../org/apache/kafka/connect/data/Values.Parser.html#hasNext--">hasNext</a></span>()</code> </td>
</tr>
<tr id="i4" class="altColor">
<td class="colFirst"><code>protected boolean</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../org/apache/kafka/connect/data/Values.Parser.html#isNext-java.lang.String-boolean-">isNext</a></span>(java.lang.String expected,
boolean ignoreLeadingAndTrailingWhitespace)</code> </td>
</tr>
<tr id="i5" class="rowColor">
<td class="colFirst"><code>int</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../org/apache/kafka/connect/data/Values.Parser.html#mark--">mark</a></span>()</code> </td>
</tr>
<tr id="i6" class="altColor">
<td class="colFirst"><code>java.lang.String</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../org/apache/kafka/connect/data/Values.Parser.html#next--">next</a></span>()</code> </td>
</tr>
<tr id="i7" class="rowColor">
<td class="colFirst"><code>java.lang.String</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../org/apache/kafka/connect/data/Values.Parser.html#original--">original</a></span>()</code> </td>
</tr>
<tr id="i8" class="altColor">
<td class="colFirst"><code>int</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../org/apache/kafka/connect/data/Values.Parser.html#position--">position</a></span>()</code> </td>
</tr>
<tr id="i9" class="rowColor">
<td class="colFirst"><code>java.lang.String</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../org/apache/kafka/connect/data/Values.Parser.html#previous--">previous</a></span>()</code> </td>
</tr>
<tr id="i10" class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../org/apache/kafka/connect/data/Values.Parser.html#rewindTo-int-">rewindTo</a></span>(int position)</code> </td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods.inherited.from.class.java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor.detail">
<!-- -->
</a>
<h3>Constructor Detail</h3>
<a name="Parser-java.lang.String-">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>Parser</h4>
<pre>public Parser(java.lang.String original)</pre>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method.detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="position--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>position</h4>
<pre>public int position()</pre>
</li>
</ul>
<a name="mark--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>mark</h4>
<pre>public int mark()</pre>
</li>
</ul>
<a name="rewindTo-int-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>rewindTo</h4>
<pre>public void rewindTo(int position)</pre>
</li>
</ul>
<a name="original--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>original</h4>
<pre>public java.lang.String original()</pre>
</li>
</ul>
<a name="hasNext--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>hasNext</h4>
<pre>public boolean hasNext()</pre>
</li>
</ul>
<a name="canConsumeNextToken--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>canConsumeNextToken</h4>
<pre>protected boolean canConsumeNextToken()</pre>
</li>
</ul>
<a name="next--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>next</h4>
<pre>public java.lang.String next()</pre>
</li>
</ul>
<a name="previous--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>previous</h4>
<pre>public java.lang.String previous()</pre>
</li>
</ul>
<a name="canConsume-java.lang.String-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>canConsume</h4>
<pre>public boolean canConsume(java.lang.String expected)</pre>
</li>
</ul>
<a name="canConsume-java.lang.String-boolean-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>canConsume</h4>
<pre>public boolean canConsume(java.lang.String expected,
boolean ignoreLeadingAndTrailingWhitespace)</pre>
</li>
</ul>
<a name="isNext-java.lang.String-boolean-">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>isNext</h4>
<pre>protected boolean isNext(java.lang.String expected,
boolean ignoreLeadingAndTrailingWhitespace)</pre>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<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 class="navBarCell1Rev">Class</li>
<li><a href="package-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><a href="../../../../../org/apache/kafka/connect/data/Values.html" title="class in org.apache.kafka.connect.data"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../../../org/apache/kafka/connect/data/Values.SchemaDetector.html" title="class in org.apache.kafka.connect.data"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/apache/kafka/connect/data/Values.Parser.html" target="_top">Frames</a></li>
<li><a href="Values.Parser.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>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor.summary">Constr</a> | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor.detail">Constr</a> | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| {
"pile_set_name": "Github"
} |
source 'https://rubygems.org'
gem 'graphql_java_gen', path: '../libs/graphql_java_gen/' | {
"pile_set_name": "Github"
} |
/*
* Broadcom specific AMBA
* ChipCommon core driver
*
* Copyright 2005, Broadcom Corporation
* Copyright 2006, 2007, Michael Buesch <[email protected]>
* Copyright 2012, Hauke Mehrtens <[email protected]>
*
* Licensed under the GNU/GPL. See COPYING for details.
*/
#include "bcma_private.h"
#include <linux/bcm47xx_wdt.h>
#include <linux/export.h>
#include <linux/platform_device.h>
#include <linux/bcma/bcma.h>
static inline u32 bcma_cc_write32_masked(struct bcma_drv_cc *cc, u16 offset,
u32 mask, u32 value)
{
value &= mask;
value |= bcma_cc_read32(cc, offset) & ~mask;
bcma_cc_write32(cc, offset, value);
return value;
}
u32 bcma_chipco_get_alp_clock(struct bcma_drv_cc *cc)
{
if (cc->capabilities & BCMA_CC_CAP_PMU)
return bcma_pmu_get_alp_clock(cc);
return 20000000;
}
EXPORT_SYMBOL_GPL(bcma_chipco_get_alp_clock);
static bool bcma_core_cc_has_pmu_watchdog(struct bcma_drv_cc *cc)
{
struct bcma_bus *bus = cc->core->bus;
if (cc->capabilities & BCMA_CC_CAP_PMU) {
if (bus->chipinfo.id == BCMA_CHIP_ID_BCM53573) {
WARN(bus->chipinfo.rev <= 1, "No watchdog available\n");
/* 53573B0 and 53573B1 have bugged PMU watchdog. It can
* be enabled but timer can't be bumped. Use CC one
* instead.
*/
return false;
}
return true;
} else {
return false;
}
}
static u32 bcma_chipco_watchdog_get_max_timer(struct bcma_drv_cc *cc)
{
struct bcma_bus *bus = cc->core->bus;
u32 nb;
if (bcma_core_cc_has_pmu_watchdog(cc)) {
if (bus->chipinfo.id == BCMA_CHIP_ID_BCM4706)
nb = 32;
else if (cc->core->id.rev < 26)
nb = 16;
else
nb = (cc->core->id.rev >= 37) ? 32 : 24;
} else {
nb = 28;
}
if (nb == 32)
return 0xffffffff;
else
return (1 << nb) - 1;
}
static u32 bcma_chipco_watchdog_timer_set_wdt(struct bcm47xx_wdt *wdt,
u32 ticks)
{
struct bcma_drv_cc *cc = bcm47xx_wdt_get_drvdata(wdt);
return bcma_chipco_watchdog_timer_set(cc, ticks);
}
static u32 bcma_chipco_watchdog_timer_set_ms_wdt(struct bcm47xx_wdt *wdt,
u32 ms)
{
struct bcma_drv_cc *cc = bcm47xx_wdt_get_drvdata(wdt);
u32 ticks;
ticks = bcma_chipco_watchdog_timer_set(cc, cc->ticks_per_ms * ms);
return ticks / cc->ticks_per_ms;
}
static int bcma_chipco_watchdog_ticks_per_ms(struct bcma_drv_cc *cc)
{
struct bcma_bus *bus = cc->core->bus;
if (cc->capabilities & BCMA_CC_CAP_PMU) {
if (bus->chipinfo.id == BCMA_CHIP_ID_BCM4706)
/* 4706 CC and PMU watchdogs are clocked at 1/4 of ALP
* clock
*/
return bcma_chipco_get_alp_clock(cc) / 4000;
else
/* based on 32KHz ILP clock */
return 32;
} else {
return bcma_chipco_get_alp_clock(cc) / 1000;
}
}
int bcma_chipco_watchdog_register(struct bcma_drv_cc *cc)
{
struct bcma_bus *bus = cc->core->bus;
struct bcm47xx_wdt wdt = {};
struct platform_device *pdev;
if (bus->chipinfo.id == BCMA_CHIP_ID_BCM53573 &&
bus->chipinfo.rev <= 1) {
pr_debug("No watchdog on 53573A0 / 53573A1\n");
return 0;
}
wdt.driver_data = cc;
wdt.timer_set = bcma_chipco_watchdog_timer_set_wdt;
wdt.timer_set_ms = bcma_chipco_watchdog_timer_set_ms_wdt;
wdt.max_timer_ms =
bcma_chipco_watchdog_get_max_timer(cc) / cc->ticks_per_ms;
pdev = platform_device_register_data(NULL, "bcm47xx-wdt",
bus->num, &wdt,
sizeof(wdt));
if (IS_ERR(pdev))
return PTR_ERR(pdev);
cc->watchdog = pdev;
return 0;
}
static void bcma_core_chipcommon_flash_detect(struct bcma_drv_cc *cc)
{
struct bcma_bus *bus = cc->core->bus;
switch (cc->capabilities & BCMA_CC_CAP_FLASHT) {
case BCMA_CC_FLASHT_STSER:
case BCMA_CC_FLASHT_ATSER:
bcma_debug(bus, "Found serial flash\n");
bcma_sflash_init(cc);
break;
case BCMA_CC_FLASHT_PARA:
bcma_debug(bus, "Found parallel flash\n");
bcma_pflash_init(cc);
break;
default:
bcma_err(bus, "Flash type not supported\n");
}
if (cc->core->id.rev == 38 ||
bus->chipinfo.id == BCMA_CHIP_ID_BCM4706) {
if (cc->capabilities & BCMA_CC_CAP_NFLASH) {
bcma_debug(bus, "Found NAND flash\n");
bcma_nflash_init(cc);
}
}
}
void bcma_core_chipcommon_early_init(struct bcma_drv_cc *cc)
{
struct bcma_bus *bus = cc->core->bus;
if (cc->early_setup_done)
return;
spin_lock_init(&cc->gpio_lock);
if (cc->core->id.rev >= 11)
cc->status = bcma_cc_read32(cc, BCMA_CC_CHIPSTAT);
cc->capabilities = bcma_cc_read32(cc, BCMA_CC_CAP);
if (cc->core->id.rev >= 35)
cc->capabilities_ext = bcma_cc_read32(cc, BCMA_CC_CAP_EXT);
if (cc->capabilities & BCMA_CC_CAP_PMU)
bcma_pmu_early_init(cc);
if (bus->hosttype == BCMA_HOSTTYPE_SOC)
bcma_core_chipcommon_flash_detect(cc);
cc->early_setup_done = true;
}
void bcma_core_chipcommon_init(struct bcma_drv_cc *cc)
{
u32 leddc_on = 10;
u32 leddc_off = 90;
if (cc->setup_done)
return;
bcma_core_chipcommon_early_init(cc);
if (cc->core->id.rev >= 20) {
u32 pullup = 0, pulldown = 0;
if (cc->core->bus->chipinfo.id == BCMA_CHIP_ID_BCM43142) {
pullup = 0x402e0;
pulldown = 0x20500;
}
bcma_cc_write32(cc, BCMA_CC_GPIOPULLUP, pullup);
bcma_cc_write32(cc, BCMA_CC_GPIOPULLDOWN, pulldown);
}
if (cc->capabilities & BCMA_CC_CAP_PMU)
bcma_pmu_init(cc);
if (cc->capabilities & BCMA_CC_CAP_PCTL)
bcma_err(cc->core->bus, "Power control not implemented!\n");
if (cc->core->id.rev >= 16) {
if (cc->core->bus->sprom.leddc_on_time &&
cc->core->bus->sprom.leddc_off_time) {
leddc_on = cc->core->bus->sprom.leddc_on_time;
leddc_off = cc->core->bus->sprom.leddc_off_time;
}
bcma_cc_write32(cc, BCMA_CC_GPIOTIMER,
((leddc_on << BCMA_CC_GPIOTIMER_ONTIME_SHIFT) |
(leddc_off << BCMA_CC_GPIOTIMER_OFFTIME_SHIFT)));
}
cc->ticks_per_ms = bcma_chipco_watchdog_ticks_per_ms(cc);
cc->setup_done = true;
}
/* Set chip watchdog reset timer to fire in 'ticks' backplane cycles */
u32 bcma_chipco_watchdog_timer_set(struct bcma_drv_cc *cc, u32 ticks)
{
u32 maxt;
maxt = bcma_chipco_watchdog_get_max_timer(cc);
if (bcma_core_cc_has_pmu_watchdog(cc)) {
if (ticks == 1)
ticks = 2;
else if (ticks > maxt)
ticks = maxt;
bcma_pmu_write32(cc, BCMA_CC_PMU_WATCHDOG, ticks);
} else {
struct bcma_bus *bus = cc->core->bus;
if (bus->chipinfo.id != BCMA_CHIP_ID_BCM4707 &&
bus->chipinfo.id != BCMA_CHIP_ID_BCM47094 &&
bus->chipinfo.id != BCMA_CHIP_ID_BCM53018)
bcma_core_set_clockmode(cc->core,
ticks ? BCMA_CLKMODE_FAST : BCMA_CLKMODE_DYNAMIC);
if (ticks > maxt)
ticks = maxt;
/* instant NMI */
bcma_cc_write32(cc, BCMA_CC_WATCHDOG, ticks);
}
return ticks;
}
void bcma_chipco_irq_mask(struct bcma_drv_cc *cc, u32 mask, u32 value)
{
bcma_cc_write32_masked(cc, BCMA_CC_IRQMASK, mask, value);
}
u32 bcma_chipco_irq_status(struct bcma_drv_cc *cc, u32 mask)
{
return bcma_cc_read32(cc, BCMA_CC_IRQSTAT) & mask;
}
u32 bcma_chipco_gpio_in(struct bcma_drv_cc *cc, u32 mask)
{
return bcma_cc_read32(cc, BCMA_CC_GPIOIN) & mask;
}
u32 bcma_chipco_gpio_out(struct bcma_drv_cc *cc, u32 mask, u32 value)
{
unsigned long flags;
u32 res;
spin_lock_irqsave(&cc->gpio_lock, flags);
res = bcma_cc_write32_masked(cc, BCMA_CC_GPIOOUT, mask, value);
spin_unlock_irqrestore(&cc->gpio_lock, flags);
return res;
}
EXPORT_SYMBOL_GPL(bcma_chipco_gpio_out);
u32 bcma_chipco_gpio_outen(struct bcma_drv_cc *cc, u32 mask, u32 value)
{
unsigned long flags;
u32 res;
spin_lock_irqsave(&cc->gpio_lock, flags);
res = bcma_cc_write32_masked(cc, BCMA_CC_GPIOOUTEN, mask, value);
spin_unlock_irqrestore(&cc->gpio_lock, flags);
return res;
}
EXPORT_SYMBOL_GPL(bcma_chipco_gpio_outen);
/*
* If the bit is set to 0, chipcommon controlls this GPIO,
* if the bit is set to 1, it is used by some part of the chip and not our code.
*/
u32 bcma_chipco_gpio_control(struct bcma_drv_cc *cc, u32 mask, u32 value)
{
unsigned long flags;
u32 res;
spin_lock_irqsave(&cc->gpio_lock, flags);
res = bcma_cc_write32_masked(cc, BCMA_CC_GPIOCTL, mask, value);
spin_unlock_irqrestore(&cc->gpio_lock, flags);
return res;
}
EXPORT_SYMBOL_GPL(bcma_chipco_gpio_control);
u32 bcma_chipco_gpio_intmask(struct bcma_drv_cc *cc, u32 mask, u32 value)
{
unsigned long flags;
u32 res;
spin_lock_irqsave(&cc->gpio_lock, flags);
res = bcma_cc_write32_masked(cc, BCMA_CC_GPIOIRQ, mask, value);
spin_unlock_irqrestore(&cc->gpio_lock, flags);
return res;
}
u32 bcma_chipco_gpio_polarity(struct bcma_drv_cc *cc, u32 mask, u32 value)
{
unsigned long flags;
u32 res;
spin_lock_irqsave(&cc->gpio_lock, flags);
res = bcma_cc_write32_masked(cc, BCMA_CC_GPIOPOL, mask, value);
spin_unlock_irqrestore(&cc->gpio_lock, flags);
return res;
}
u32 bcma_chipco_gpio_pullup(struct bcma_drv_cc *cc, u32 mask, u32 value)
{
unsigned long flags;
u32 res;
if (cc->core->id.rev < 20)
return 0;
spin_lock_irqsave(&cc->gpio_lock, flags);
res = bcma_cc_write32_masked(cc, BCMA_CC_GPIOPULLUP, mask, value);
spin_unlock_irqrestore(&cc->gpio_lock, flags);
return res;
}
u32 bcma_chipco_gpio_pulldown(struct bcma_drv_cc *cc, u32 mask, u32 value)
{
unsigned long flags;
u32 res;
if (cc->core->id.rev < 20)
return 0;
spin_lock_irqsave(&cc->gpio_lock, flags);
res = bcma_cc_write32_masked(cc, BCMA_CC_GPIOPULLDOWN, mask, value);
spin_unlock_irqrestore(&cc->gpio_lock, flags);
return res;
}
#ifdef CONFIG_BCMA_DRIVER_MIPS
void bcma_chipco_serial_init(struct bcma_drv_cc *cc)
{
unsigned int irq;
u32 baud_base;
u32 i;
unsigned int ccrev = cc->core->id.rev;
struct bcma_serial_port *ports = cc->serial_ports;
if (ccrev >= 11 && ccrev != 15) {
baud_base = bcma_chipco_get_alp_clock(cc);
if (ccrev >= 21) {
/* Turn off UART clock before switching clocksource. */
bcma_cc_write32(cc, BCMA_CC_CORECTL,
bcma_cc_read32(cc, BCMA_CC_CORECTL)
& ~BCMA_CC_CORECTL_UARTCLKEN);
}
/* Set the override bit so we don't divide it */
bcma_cc_write32(cc, BCMA_CC_CORECTL,
bcma_cc_read32(cc, BCMA_CC_CORECTL)
| BCMA_CC_CORECTL_UARTCLK0);
if (ccrev >= 21) {
/* Re-enable the UART clock. */
bcma_cc_write32(cc, BCMA_CC_CORECTL,
bcma_cc_read32(cc, BCMA_CC_CORECTL)
| BCMA_CC_CORECTL_UARTCLKEN);
}
} else {
bcma_err(cc->core->bus, "serial not supported on this device ccrev: 0x%x\n",
ccrev);
return;
}
irq = bcma_core_irq(cc->core, 0);
/* Determine the registers of the UARTs */
cc->nr_serial_ports = (cc->capabilities & BCMA_CC_CAP_NRUART);
for (i = 0; i < cc->nr_serial_ports; i++) {
ports[i].regs = cc->core->io_addr + BCMA_CC_UART0_DATA +
(i * 256);
ports[i].irq = irq;
ports[i].baud_base = baud_base;
ports[i].reg_shift = 0;
}
}
#endif /* CONFIG_BCMA_DRIVER_MIPS */
| {
"pile_set_name": "Github"
} |
// @(#)root/net:$Id$
// Author: Fons Rademakers 19/12/96
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#ifndef ROOT_TMessage
#define ROOT_TMessage
//////////////////////////////////////////////////////////////////////////
// //
// TMessage //
// //
// Message buffer class used for serializing objects and sending them //
// over the network. //
// //
//////////////////////////////////////////////////////////////////////////
#include "Compression.h"
#include "TBufferFile.h"
#include "MessageTypes.h"
#include "TBits.h"
class TList;
class TVirtualStreamerInfo;
class TMessage : public TBufferFile {
friend class TAuthenticate;
friend class TSocket;
friend class TUDPSocket;
friend class TPSocket;
friend class TXSocket;
private:
TList *fInfos{nullptr}; // List of TStreamerInfo used in WriteObject
TBits fBitsPIDs; // Array of bits to mark the TProcessIDs uids written to the message
UInt_t fWhat{0}; // Message type
TClass *fClass{nullptr}; // If message is kMESS_OBJECT pointer to object's class
Int_t fCompress{0}; // Compression level and algorithm
char *fBufComp{nullptr}; // Compressed buffer
char *fBufCompCur{nullptr}; // Current position in compressed buffer
char *fCompPos{nullptr}; // Position of fBufCur when message was compressed
Bool_t fEvolution{kFALSE}; // True if support for schema evolution required
static Bool_t fgEvolution; //True if global support for schema evolution required
// TMessage objects cannot be copied or assigned
TMessage(const TMessage &); // not implemented
void operator=(const TMessage &); // not implemented
// used by friend TSocket
Bool_t TestBitNumber(UInt_t bitnumber) const { return fBitsPIDs.TestBitNumber(bitnumber); }
protected:
TMessage(void *buf, Int_t bufsize); // only called by T(P)Socket::Recv()
void SetLength() const; // only called by T(P)Socket::Send()
public:
TMessage(UInt_t what = kMESS_ANY, Int_t bufsiz = TBuffer::kInitialSize);
virtual ~TMessage();
void ForceWriteInfo(TVirtualStreamerInfo *info, Bool_t force) override;
void Forward();
TClass *GetClass() const { return fClass;}
void TagStreamerInfo(TVirtualStreamerInfo* info) override;
void Reset() override;
void Reset(UInt_t what) { SetWhat(what); Reset(); }
UInt_t What() const { return fWhat; }
void SetWhat(UInt_t what);
void EnableSchemaEvolution(Bool_t enable = kTRUE) { fEvolution = enable; }
Bool_t UsesSchemaEvolution() const { return fEvolution; }
TList *GetStreamerInfos() const { return fInfos; }
Int_t GetCompressionAlgorithm() const;
Int_t GetCompressionLevel() const;
Int_t GetCompressionSettings() const;
void SetCompressionAlgorithm(Int_t algorithm = ROOT::RCompressionSetting::EAlgorithm::kUseGlobal);
void SetCompressionLevel(Int_t level = ROOT::RCompressionSetting::ELevel::kUseMin);
void SetCompressionSettings(Int_t settings = ROOT::RCompressionSetting::EDefaults::kUseCompiledDefault);
Int_t Compress();
Int_t Uncompress();
char *CompBuffer() const { return fBufComp; }
Int_t CompLength() const { return (Int_t)(fBufCompCur - fBufComp); }
UShort_t WriteProcessID(TProcessID *pid) override;
static void EnableSchemaEvolutionForAll(Bool_t enable = kTRUE);
static Bool_t UsesSchemaEvolutionForAll();
ClassDefOverride(TMessage,0) // Message buffer class
};
//______________________________________________________________________________
inline Int_t TMessage::GetCompressionAlgorithm() const
{
return (fCompress < 0) ? -1 : fCompress / 100;
}
//______________________________________________________________________________
inline Int_t TMessage::GetCompressionLevel() const
{
return (fCompress < 0) ? -1 : fCompress % 100;
}
//______________________________________________________________________________
inline Int_t TMessage::GetCompressionSettings() const
{
return (fCompress < 0) ? -1 : fCompress;
}
#endif
| {
"pile_set_name": "Github"
} |
package dpf.sp.gpinf.indexer.parsers.lnk;
public class LNKLinkLocation {
private String volumeLabel, localPath, commonPath, driveSerial;
private String localPathUnicode, commonPathUnicode, volumeLabelUnicode;
private String netShare, netDevName;
private String netShareUnicode, netDevNameUnicode;
private int flagsLocation, flagsNetwork, netProviderType, driveType;
public String getDriveSerial() {
return driveSerial;
}
public void setDriveSerial(String driveSerial) {
if (driveSerial != null)
this.driveSerial = "0x" + driveSerial; //$NON-NLS-1$
else
this.driveSerial = null;
}
public int getDriveType() {
return driveType;
}
public void setDriveType(int driveType) {
this.driveType = driveType;
}
public String getVolumeLabel() {
return volumeLabel;
}
public void setVolumeLabel(String volumeLabel) {
this.volumeLabel = volumeLabel;
}
public String getLocalPath() {
return localPath;
}
public void setLocalPath(String localPath) {
this.localPath = localPath;
}
public String getCommonPath() {
return commonPath;
}
public void setCommonPath(String commonPath) {
this.commonPath = commonPath;
}
public String getNetShare() {
return netShare;
}
public void setNetShare(String netShare) {
this.netShare = netShare;
}
public String getNetDevName() {
return netDevName;
}
public void setNetDevName(String netDevName) {
this.netDevName = netDevName;
}
public int getNetProviderType() {
return netProviderType;
}
public void setNetProviderType(int netProviderType) {
this.netProviderType = netProviderType;
}
public int getFlagsLocation() {
return flagsLocation;
}
public void setFlagsLocation(int flagsLocation) {
this.flagsLocation = flagsLocation;
}
public int getFlagsNetwork() {
return flagsNetwork;
}
public void setFlagsNetwork(int flagsNetwork) {
this.flagsNetwork = flagsNetwork;
}
public String getLocalPathUnicode() {
return localPathUnicode;
}
public void setLocalPathUnicode(String localPathUnicode) {
this.localPathUnicode = localPathUnicode;
}
public String getCommonPathUnicode() {
return commonPathUnicode;
}
public void setCommonPathUnicode(String commonPathUnicode) {
this.commonPathUnicode = commonPathUnicode;
}
public String getNetShareUnicode() {
return netShareUnicode;
}
public void setNetShareUnicode(String netShareUnicode) {
this.netShareUnicode = netShareUnicode;
}
public String getNetDevNameUnicode() {
return netDevNameUnicode;
}
public void setNetDevNameUnicode(String netDevNameUnicode) {
this.netDevNameUnicode = netDevNameUnicode;
}
public String getVolumeLabelUnicode() {
return volumeLabelUnicode;
}
public void setVolumeLabelUnicode(String volumeLabelUnicode) {
this.volumeLabelUnicode = volumeLabelUnicode;
}
public String getDriveTypeStr() {
switch (driveType) {
case 1:
return "DRIVE_NO_ROOT_DIR"; //$NON-NLS-1$
case 2:
return "DRIVE_REMOVABLE"; //$NON-NLS-1$
case 3:
return "DRIVE_FIXED"; //$NON-NLS-1$
case 4:
return "DRIVE_REMOTE"; //$NON-NLS-1$
case 5:
return "DRIVE_CDROM"; //$NON-NLS-1$
case 6:
return "DRIVE_RAMDISK"; //$NON-NLS-1$
default:
return "DRIVE_UNKNOWN"; //$NON-NLS-1$
}
}
}
| {
"pile_set_name": "Github"
} |
/**
*
* WARNING! This file was autogenerated by:
* _ _ _ _ __ __
* | | | | | | |\ \ / /
* | | | | |_| | \ V /
* | | | | _ | / \
* | |_| | | | |/ /^\ \
* \___/\_| |_/\/ \/
*
* This file was autogenerated by UnrealHxGenerator using UHT definitions.
* It only includes UPROPERTYs and UFUNCTIONs. Do not modify it!
* In order to add more definitions, create or edit a type with the same name/package, but with an `_Extra` suffix
**/
package unreal.editor;
/**
WARNING: This type was not defined as DLL export on its declaration. Because of that, some of its methods are inaccessible
**/
@:umodule("UnrealEd")
@:glueCppIncludes("ThumbnailRendering/FontThumbnailRenderer.h")
@:noClass @:uextern @:uclass extern class UFontThumbnailRenderer extends unreal.editor.UTextureThumbnailRenderer {
}
| {
"pile_set_name": "Github"
} |
<?php
/**
* Kunena Component
* @package Kunena.Framework
*
* @copyright Copyright (C) 2008 - 2020 Kunena Team. All rights reserved.
* @license https://www.gnu.org/copyleft/gpl.html GNU/GPL
* @link https://www.kunena.org
**/
defined('_JEXEC') or die();
use Joomla\CMS\Factory;
use Joomla\CMS\Language\Text;
use Joomla\CMS\Uri\Uri;
use Joomla\CMS\Log\Log;
use Joomla\CMS\Router\Route;
jimport('joomla.application.component.helper');
/**
* Class KunenaController
* @since Kunena
*/
class KunenaController extends \Joomla\CMS\MVC\Controller\BaseController
{
/**
* @var \Joomla\CMS\Application\CMSApplication|null
* @since Kunena
*/
public $app = null;
/**
* @var KunenaUser|null
* @since Kunena
*/
public $me = null;
/**
* @var KunenaConfig|null
* @since Kunena
*/
public $config = null;
/**
* @param array $config config
*
* @since Kunena
* @throws Exception
*/
public function __construct($config = array())
{
parent::__construct($config);
$this->profiler = KunenaProfiler::instance('Kunena');
$this->app = Factory::getApplication();
$this->config = KunenaFactory::getConfig();
$this->me = KunenaUserHelper::getMyself();
// Save user profile if it didn't exist.
if ($this->me->userid && !$this->me->exists())
{
$this->me->save();
}
if (empty($this->input))
{
$this->input = $this->app->input;
}
}
/**
* Method to get the appropriate controller.
*
* @param string $prefix prefix
* @param mixed $config config
*
* @return KunenaController
* @since Kunena
* @throws Exception
*/
public static function getInstance($prefix = 'Kunena', $config = array())
{
static $instance = null;
if (!$prefix)
{
$prefix = 'Kunena';
}
if (!empty($instance) && !isset($instance->home))
{
return $instance;
}
$input = Factory::getApplication()->input;
$app = Factory::getApplication();
$command = $input->get('task', 'display');
// Check for a controller.task command.
if (strpos($command, '.') !== false)
{
// Explode the controller.task command.
list($view, $task) = explode('.', $command);
// Reset the task without the controller context.
$input->set('task', $task);
}
else
{
// Base controller.
$view = strtolower(Factory::getApplication()->input->getWord('view', $app->isClient('administrator') ? 'cpanel' : 'home'));
}
$path = JPATH_COMPONENT . "/controllers/{$view}.php";
// If the controller file path exists, include it ... else die with a 500 error.
if (is_file($path))
{
require_once $path;
}
else
{
throw new Exception(Text::sprintf('COM_KUNENA_INVALID_CONTROLLER', ucfirst($view)), 404);
}
// Set the name for the controller and instantiate it.
if ($app->isClient('administrator'))
{
$class = $prefix . 'AdminController' . ucfirst($view);
KunenaFactory::loadLanguage('com_kunena.controllers', 'admin');
KunenaFactory::loadLanguage('com_kunena.models', 'admin');
KunenaFactory::loadLanguage('com_kunena.sys', 'admin');
KunenaFactory::loadLanguage('com_kunena', 'site');
}
else
{
$class = $prefix . 'Controller' . ucfirst($view);
KunenaFactory::loadLanguage('com_kunena.controllers');
KunenaFactory::loadLanguage('com_kunena.models');
KunenaFactory::loadLanguage('com_kunena.sys', 'admin');
}
if (class_exists($class))
{
$instance = new $class;
}
else
{
throw new Exception(Text::sprintf('COM_KUNENA_INVALID_CONTROLLER_CLASS', $class), 404);
}
return $instance;
}
/**
* Calls a task and creates HTML or JSON response from it.
*
* If response is in HTML, we just redirect and enqueue message if there's an exception.
* NOTE: legacy display task is a special case and reverts to original Joomla behavior.
*
* If response is in JSON, we return JSON response, which follows \Joomla\CMS\Response\JsonResponse with some extra
* data:
*
* Default: {code, location=null, success, message, messages, data={step, location, html}}
* Redirect: {code, location=[string], success, message, messages=null, data}
* Exception: {code, location=[null|string], success=false, message, messages, data={exceptions=[{code,
* message}...]}}
*
* code = [int]: Usually HTTP status code, but can also error code from the exception (informal only).
* location = [null|string]: If set, JavaScript should always redirect to another page.
* success = [bool]: Determines whether the request (or action) was successful. Can be false without being an
* error.
* message = [string|null]: The main response message.
* messages = [array|null]: Array of enqueue'd messages.
* data = [mixed]: The response data.
*
* @param string $task Task to be run.
*
* @return void
* @since Kunena
* @throws Exception
* @throws null
*/
public function execute($task)
{
if (!$task)
{
$task = 'display';
}
$app = Factory::getApplication();
$this->format = $this->input->getWord('format', 'html');
try
{
// TODO: This would be great, but we would need to store POST before doing it in here...
/*
if ($task != 'display')
{
// Make sure that Kunena is online before running any tasks (doesn't affect admins).
if (!KunenaForum::enabled(true))
{
throw new KunenaExceptionAuthorise(Text::_('COM_KUNENA_FORUM_IS_OFFLINE'), 503);
}
// If forum is for registered users only, prevent guests from accessing tasks.
if ($this->config->regonly && !$this->me->exists())
{
throw new KunenaExceptionAuthorise(Text::_('COM_KUNENA_LOGIN_NOTIFICATION'), 403);
}
}
*/
// Execute the task.
$content = static::executeTask($task);
}
catch (Exception $e)
{
$content = $e;
}
// Legacy view support.
if ($task == 'display')
{
if ($content instanceof Exception)
{
throw $content;
}
return;
}
// Create HTML redirect.
if ($this->format == 'html')
{
if ($content instanceof Exception)
{
$app->enqueueMessage($content->getMessage(), 'error');
if (!$this->redirect)
{
// On exceptions always return back to the referrer page.
$this->setRedirect(KunenaRoute::getReferrer());
}
}
// The following code gets only called for successful tasks.
if (!$this->redirect)
{
// If controller didn't set a new redirect, try if request has return url in it.
$return = base64_decode($app->input->getBase64('return'));
// Only allow internal urls to be used.
if ($return && Uri::isInternal($return))
{
$redirect = Route::_($return, false);
}
// Otherwise return back to the referrer.
else
{
$redirect = KunenaRoute::getReferrer();
}
$this->setRedirect($redirect);
}
return;
}
// Otherwise tell the browser that our response is in JSON.
header('Content-type: application/json', true);
// Create JSON response and set the redirect.
$response = new KunenaResponseJson($content, null, false, !empty($this->redirect));
$response->location = $this->redirect;
// In case of an error we want to set HTTP error code.
if ($content instanceof Exception)
{
// We want to wrap the exception to be able to display correct HTTP status code.
$exception = new KunenaExceptionAuthorise($content->getMessage(), $content->getCode(), $content);
header('HTTP/1.1 ' . $exception->getResponseStatus(), true);
}
echo json_encode($response);
// It's much faster and safer to exit now than let Joomla to send the response.
Factory::getApplication()->close();
}
/**
* Execute task (slightly modified from Joomla).
*
* @param string $task task
*
* @return mixed
* @since Kunena
* @throws Exception
*
*/
protected function executeTask($task)
{
$dot = strpos($task, '.');
$this->task = $dot ? substr($task, $dot + 1) : $task;
$task = strtolower($this->task);
if (isset($this->taskMap[$this->task]))
{
$doTask = $this->taskMap[$this->task];
}
elseif (isset($this->taskMap['__default']))
{
$doTask = $this->taskMap['__default'];
}
else
{
throw new Exception(Text::sprintf('JLIB_APPLICATION_ERROR_TASK_NOT_FOUND', $task), 404);
}
// Record the actual task being fired
$this->doTask = $doTask;
return $this->$doTask();
}
/**
* Method to display a view.
*
* @param boolean $cachable If true, the view output will be cached
* @param array|bool $urlparams An array of safe url parameters and their variable types, for valid values see
* {@link \Joomla\CMS\Filter\InputFilter::clean()}.
*
* @return \Joomla\CMS\MVC\Controller\BaseController A \Joomla\CMS\MVC\Controller\BaseController object to
* support chaining.
* @since Kunena
* @throws Exception
* @throws null
*/
public function display($cachable = false, $urlparams = false)
{
KUNENA_PROFILER ? $this->profiler->mark('beforeDisplay') : null;
KUNENA_PROFILER ? KunenaProfiler::instance()->start('function ' . __CLASS__ . '::' . __FUNCTION__ . '()') : null;
// Get the document object.
$document = Factory::getDocument();
// Set the default view name and format from the Request.
$vName = Factory::getApplication()->input->getWord('view', $this->app->isClient('administrator') ? 'cpanel' : 'home');
$lName = Factory::getApplication()->input->getWord('layout', 'default');
$vFormat = $document->getType();
if ($this->app->isClient('administrator'))
{
// Load admin language files
KunenaFactory::loadLanguage('com_kunena.install', 'admin');
KunenaFactory::loadLanguage('com_kunena.views', 'admin');
// Load last to get deprecated language files to work
KunenaFactory::loadLanguage('com_kunena', 'admin');
// Version warning, disable J4 for now.
require_once KPATH_ADMIN . '/install/version.php';
$version = new KunenaVersion;
$version_warning = $version->getVersionWarning();
if (!empty($version_warning))
{
$this->app->enqueueMessage($version_warning, 'notice');
}
}
else
{
// Load site language files
KunenaFactory::loadLanguage('com_kunena.views');
KunenaFactory::loadLanguage('com_kunena.templates');
// Load last to get deprecated language files to work
KunenaFactory::loadLanguage('com_kunena');
$menu = $this->app->getMenu();
$active = $menu->getActive();
// Check if menu item was correctly routed
$routed = $menu->getItem(KunenaRoute::getItemID());
if ($vFormat == 'html' && !empty($routed->id) && (empty($active->id) || $active->id != $routed->id))
{
// Routing has been changed, redirect
// FIXME: check possible redirect loops!
$route = KunenaRoute::_(null, false);
$activeId = !empty($active->id) ? $active->id : 0;
Log::add("Redirect from " . Uri::getInstance()->toString(array('path', 'query')) . " ({$activeId}) to {$route} ($routed->id)", Log::DEBUG, 'kunena');
$this->app->redirect($route);
}
// Joomla 2.5+ multi-language support
/*
// FIXME:
if (isset($active->language) && $active->language != '*') {
$language = Factory::getDocument()->getLanguage();
if (strtolower($active->language) != strtolower($language)) {
$route = KunenaRoute::_(null, false);
Log::add("Language redirect from ".Uri::getInstance()->toString(array('path', 'query'))." to {$route}", Log::DEBUG, 'kunena');
$this->redirect ($route);
}
}
*/
}
$view = $this->getView($vName, $vFormat);
if ($view)
{
if ($this->app->isClient('site') && $vFormat == 'html')
{
$common = $this->getView('common', $vFormat);
$model = $this->getModel('common');
$common->setModel($model, true);
$view->ktemplate = $common->ktemplate = KunenaFactory::getTemplate();
$view->common = $common;
}
// Set the view layout.
$view->setLayout($lName);
// Get the appropriate model for the view.
$model = $this->getModel($vName);
// Push the model into the view (as default).
$view->setModel($model, true);
// Push document object into the view.
$view->document = $document;
// Render the view.
if ($vFormat == 'html')
{
\Joomla\CMS\Plugin\PluginHelper::importPlugin('kunena');
Factory::getApplication()->triggerEvent('onKunenaDisplay', array('start', $view));
$view->displayAll();
Factory::getApplication()->triggerEvent('onKunenaDisplay', array('end', $view));
}
else
{
$view->displayLayout();
}
}
KUNENA_PROFILER ? KunenaProfiler::instance()->stop('function ' . __CLASS__ . '::' . __FUNCTION__ . '()') : null;
return $this;
}
/**
* Escapes a value for output in a view script.
*
* @param string $var The output to escape.
*
* @return string The escaped value.
* @since Kunena
*/
public function escape($var)
{
return htmlspecialchars($var, ENT_COMPAT, 'UTF-8');
}
/**
* @return string
* @since Kunena
*/
public function getRedirect()
{
return $this->redirect;
}
/**
* @return string
* @since Kunena
*/
public function getMessage()
{
return $this->message;
}
/**
* @return string
* @since Kunena
*/
public function getMessageType()
{
return $this->messageType;
}
/**
* Redirect back to the referrer page.
*
* If there's no referrer or it's external, Kunena will return to the default page.
* Also redirects back to tasks are prevented.
*
* @param string $default default
* @param string $anchor anchor
*
* @return void
* @since Kunena
* @throws null
* @throws Exception
*/
protected function setRedirectBack($default = null, $anchor = null)
{
$this->setRedirect(KunenaRoute::getReferrer($default, $anchor));
}
}
| {
"pile_set_name": "Github"
} |
---
title: "there"
layout: cask
---
{{ content }}
| {
"pile_set_name": "Github"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.