identifier
stringlengths
42
383
collection
stringclasses
1 value
open_type
stringclasses
1 value
license
stringlengths
0
1.81k
date
float64
1.99k
2.02k
title
stringlengths
0
100
creator
stringlengths
1
39
language
stringclasses
157 values
language_type
stringclasses
2 values
word_count
int64
1
20k
token_count
int64
4
1.32M
text
stringlengths
5
1.53M
__index_level_0__
int64
0
57.5k
https://github.com/hauner/openapi-spring-generator/blob/master/docs/modules/ROOT/pages/mapping/index.adoc
Github Open Source
Open Source
Apache-2.0
2,022
openapi-spring-generator
hauner
AsciiDoc
Code
186
246
= Type mapping Type mapping is an important feature of the processor and helps it to create the expected code. Using type mapping we can tell the processor to map types (schemas) from an openapi.yaml description to a specific existing java type instead of generating a model class from the source OpenAPI type. This can be a type created by us or a type from a framework. For example to map paging parameters and result to the Spring types `Page<>` & `Pageable`. It can also be used to map the OpenAPI `array` type to a different java collection type if the default does not fulfill our needs. Type mapping is very flexible. It is possible to define the mapping globally, globally for a specific response or parameter or limited to a specific endpoint or even http method fo an endpoint. Type mapping also supports generic parameters to the target type. One level. That means you can provide generic types for the direct target type but not for nested types of the target. Type mapping works best with named schemas (i.e. schemas `$ref` erenced by their name).
37,280
https://github.com/lsferreira42/lpt-switch/blob/master/lib/parapin/parapin_java/example/src/OpenAndCloseTest.java
Github Open Source
Open Source
BSD-3-Clause
2,020
lpt-switch
lsferreira42
Java
Code
61
140
import net.sf.parapin.ParallelPort; /** * Opens the parallel port then close it immediately then exits. */ public final class OpenAndCloseTest { public static final String COPYRIGHT = "© 2007 Neil Stockbridge"; public static final String LICENSE = "LGPL"; public static final String REVISION = "$Revision: 1.2 $"; public static void main( String[] args ) { ParallelPort port = ParallelPort.open(); port.close(); } }
4,694
https://github.com/SmallBlackBeans/WeatherForecast/blob/master/WeatherForecast/WeatherForecast/Classes/City/Controllers/CitysViewController.m
Github Open Source
Open Source
MIT
2,015
WeatherForecast
SmallBlackBeans
Objective-C
Code
646
2,827
// // CitysViewController.m // 天气 // // 海内存知己,我叫叶良辰 // // Created by 韩小醋 on 15-10-21. // Copyright (c) 2015年 hanxiaocu. All rights reserved. // //代表当前section是否是展开 #define kIsExpand @"isExpand" //当前section对应的数组 #define kCityArray @"cityArray" #import "CitysViewController.h" #import "CityModel.h" @interface CitysViewController ()<UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate> { NSMutableArray *_cityArray; UITableView *_tableView; UISearchBar *_searchBar; } @end @implementation CitysViewController - (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor = COLOR_WHITECOLOR; self.navigationItem.title =@"添加城市"; [self parserData]; [self createUI]; } #pragma mark - 解析数据 - (void)parserData{ NSArray *citysArray = [NSMutableArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"citys" ofType:@"plist"]]; _cityArray = [NSMutableArray arrayWithCapacity:0]; for (NSArray *citys in citysArray) { NSMutableArray *array = [NSMutableArray arrayWithCapacity:0]; for (NSDictionary *city in citys) { CityModel *model = [[CityModel alloc] init]; [model setValuesForKeysWithDictionary:city]; [array addObject:model]; } /** * 将每组数据封装成字典,实现关闭和打开分组的效果,默认为关闭状态 */ NSMutableDictionary *dict = [@{kCityArray : array ,kIsExpand : @(NO)} mutableCopy]; [_cityArray addObject:dict]; } // NSLog(@"cityArray -- %@",_cityArray); } #pragma mark - 创建界面 - (void)createUI{ [self createTableView]; [self createSearchBar]; } #pragma mark 创建tableView - (void)createTableView{ _tableView = [[UITableView alloc] initWithFrame:SCREEN_BOUNDS style:UITableViewStylePlain]; _tableView.delegate = self; _tableView.dataSource = self; [self.view addSubview:_tableView]; } #pragma mark 创建searchBar - (void)createSearchBar { _searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 44)]; _searchBar.placeholder = @"输入城市名"; _searchBar.delegate = self; _tableView.tableHeaderView = _searchBar; } #pragma mark - UITableViewDataSource,UITableViewDelegate #pragma mark 组数 - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return _cityArray.count; } #pragma mark 每组行数 - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { NSMutableDictionary *dict = _cityArray[section]; if ([dict[kIsExpand] boolValue]) { return [dict[kCityArray] count]; } else return 0; } #pragma mark UITableViewCell static NSString *cellId = @"cityCell"; - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId]; if (!cell) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId]; } NSArray *sectionArray = _cityArray[indexPath.section][kCityArray]; // NSLog(@"%@",[sectionArray[indexPath.row] name]); cell.textLabel.text = [sectionArray[indexPath.row] name]; cell.backgroundColor = [UIColor clearColor]; return cell; } #pragma mark cell的高度 - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { return 30; } #pragma mark cell点击事件 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { NSMutableArray *cityArray = [NSMutableArray arrayWithContentsOfFile:kChosenCitysPath]; if (cityArray == nil) { cityArray = [NSMutableArray arrayWithCapacity:0]; } CityModel *model = _cityArray[indexPath.section][kCityArray][indexPath.row]; NSDictionary *city = @{@"name" : model.name , @"parentname": model.parentname, @"code" : model.code}; BOOL isExists = NO; for (NSDictionary *dict in cityArray) { if ([dict[@"code"] isEqualToString:city[@"code"]]) { isExists = YES; break; } } // 如果该城市没有添加过,则添加 if (!isExists) { [cityArray addObject:city]; BOOL ret = [cityArray writeToFile:kChosenCitysPath atomically:YES]; NSLog(@"ret -- %d",ret); } [self.navigationController popViewControllerAnimated:YES]; } #pragma mark headerView的高度 - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section { return 40; } #pragma mark headerView - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section { UIView *view = [[UIView alloc] init]; NSArray *sectionArray = _cityArray[section][kCityArray]; NSString *title = [NSString stringWithFormat:@"%@ %d个市区", [sectionArray[0] parentname],(int)sectionArray.count]; NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:title]; NSRange range = [title rangeOfString:@" "]; // 省份名称黑色20号,省份下城市个数暗灰色14号 [attributeString addAttributes:@{NSFontAttributeName : FONT(20),NSForegroundColorAttributeName : [UIColor blueColor]} range:NSMakeRange(0, range.location)]; [attributeString addAttributes:@{NSFontAttributeName : FONT(14),NSForegroundColorAttributeName : COLOR_LIGHTGRAYCOLOR} range:NSMakeRange(range.location + range.length, title.length - range.location - 1)]; UIButton *btn = [XCView createButtonWithFrame:CGRectMake(10, 0, SCREEN_WIDTH, 39) title:title target:self action:@selector(changeExpandSection:) backgroundColor:COLOR_WHITECOLOR]; [btn setAttributedTitle:attributeString forState:UIControlStateNormal]; [btn setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft]; btn.tag = section; [view addSubview:btn]; // 分割线 UIView *line = [[UIView alloc] initWithFrame:CGRectMake(10, 39, SCREEN_WIDTH - 10, 1)]; line.backgroundColor = COLOR_LIGHTGRAYCOLOR; [view addSubview:line]; return view; } //改变展开的section - (void)changeExpandSection:(UIButton *)btn { NSInteger section = btn.tag; NSMutableDictionary *dict = _cityArray[section]; BOOL isExpand = [dict[kIsExpand] boolValue]; [dict setValue:@(!isExpand) forKey:kIsExpand]; NSIndexSet *indexSet = [NSIndexSet indexSetWithIndex:section]; [_tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic]; } #pragma mark - UISearchBarDelegate #pragma mark 开始输入搜索内容 - (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar { [searchBar becomeFirstResponder]; [searchBar setShowsCancelButton:YES]; } - (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar { [searchBar setShowsCancelButton:NO]; [searchBar resignFirstResponder]; [searchBar setText:@""]; [self parserData]; [_tableView reloadData]; } - (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar { [searchBar resignFirstResponder]; } - (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar { [searchBar resignFirstResponder]; if (searchBar.text.length == 0) { [self parserData]; [_tableView reloadData]; } else { //显示加载视图 [XCView showHUDWithText:@"正在搜索..." toView:self.view]; // 从网络加载数据 [[AFHTTPRequestOperationManager manager] GET:kSearchCity parameters:@{@"p0" : searchBar.text} success:^(AFHTTPRequestOperation *operation, id responseObject) { // 隐藏加载视图 [XCView hideHUDFromView:self.view]; NSDictionary *city = [responseObject[@"reply"] lastObject]; CityModel *model = [[CityModel alloc] init]; [model setValuesForKeysWithDictionary:city]; NSLog(@"city -- %@",model); model.parentname = [model.parentname componentsSeparatedByString:@" "][1]; [_cityArray removeAllObjects]; [_cityArray addObject:[@{kCityArray : [NSArray arrayWithObjects:model, nil] , kIsExpand : @(YES) } mutableCopy]]; [_tableView reloadData]; } failure:^(AFHTTPRequestOperation * operation, NSError *error) { // 隐藏加载视图 [XCView hideHUDFromView:self.view]; NSLog(@"error -- %@",error.localizedDescription); }]; } } @end
18,388
https://github.com/intuita-inc/tldraw/blob/master/packages/tldraw/src/state/shapes/DrawUtil/drawHelpers.ts
Github Open Source
Open Source
MIT
2,022
tldraw
intuita-inc
TypeScript
Code
231
684
import { Utils } from '@tldraw/core' import { getStrokeOutlinePoints, getStrokePoints, StrokeOptions } from 'perfect-freehand' import type { DrawShape } from '~types' import { getShapeStyle } from '../shared/shape-styles' const simulatePressureSettings: StrokeOptions = { easing: (t) => Math.sin((t * Math.PI) / 2), simulatePressure: true, } const realPressureSettings: StrokeOptions = { easing: (t) => t * t, simulatePressure: false, } export function getFreehandOptions(shape: DrawShape) { const styles = getShapeStyle(shape.style) const options: StrokeOptions = { size: 1 + styles.strokeWidth * 1.5, thinning: 0.65, streamline: 0.65, smoothing: 0.65, ...(shape.points[1][2] === 0.5 ? simulatePressureSettings : realPressureSettings), last: shape.isComplete, } return options } export function getFillPath(shape: DrawShape) { if (shape.points.length < 2) return '' return Utils.getSvgPathFromStroke( getStrokePoints(shape.points, getFreehandOptions(shape)).map((pt) => pt.point) ) } export function getDrawStrokePoints(shape: DrawShape, options: StrokeOptions) { return getStrokePoints(shape.points, options) } /** * Get path data for a stroke with the DashStyle.Draw dash style. */ export function getDrawStrokePathTDSnapshot(shape: DrawShape) { if (shape.points.length < 2) return '' const options = getFreehandOptions(shape) const strokePoints = getDrawStrokePoints(shape, options) const stroke = getStrokeOutlinePoints(strokePoints, options) const path = Utils.getSvgPathFromStroke(stroke) return path } /** * Get SVG path data for a shape that has a DashStyle other than DashStyles.Draw. */ export function getSolidStrokePathTDSnapshot(shape: DrawShape) { const { points } = shape if (points.length < 2) return 'M 0 0 L 0 0' const options = getFreehandOptions(shape) const strokePoints = getDrawStrokePoints(shape, options).map((pt) => pt.point.slice(0, 2)) const path = Utils.getSvgPathFromStroke(strokePoints, false) return path }
10,372
https://github.com/qussarah/declare/blob/master/compiler/testData/codegen/box/strings/rawStrings.kt
Github Open Source
Open Source
Apache-2.0
2,022
declare
qussarah
Kotlin
Code
27
47
fun box() : String { val s = """ foo \n bar """ if (s != " foo \\n bar ") return "Fail: '$s'" return "OK" }
29,306
https://github.com/inthiyazbasha9876/obs_v2/blob/master/zuul-auth-ojas-parent/ojas-obs-employeecontactinfo/src/test/java/com/ojas/obs/controller/EmployeeContactInfoControllerTest.java
Github Open Source
Open Source
MIT
2,020
obs_v2
inthiyazbasha9876
Java
Code
1,056
5,285
package com.ojas.obs.controller; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.lang.reflect.Field; import java.sql.SQLException; import java.sql.Timestamp; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.Spy; import org.springframework.dao.DuplicateKeyException; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import com.ojas.obs.facade.EmployeeContactFacade; import com.ojas.obs.facadeimpl.EmployeeContactFacadeImpl; import com.ojas.obs.model.EmployeeContactInfo; import com.ojas.obs.requests.EmployeeContactInfoRequest; import com.ojas.obs.response.EmployeeContactInfoResponse; import com.ojas.obs.response.ErrorResponse; public class EmployeeContactInfoControllerTest { @InjectMocks private EmployeeContactInfoController employeeContactInfoController; @Mock EmployeeContactFacade employeeStatusFacade; @Spy ErrorResponse errorResponse = new ErrorResponse(); @Spy ResponseEntity<Object> responseEntity = new ResponseEntity<Object>(errorResponse, HttpStatus.UNPROCESSABLE_ENTITY); @Spy ResponseEntity<Object> successEntity = new ResponseEntity<Object>(HttpStatus.OK); @Spy EmployeeContactInfoRequest employeeContactInfoRequest = new EmployeeContactInfoRequest(); @Spy EmployeeContactInfoResponse employeeContactInfoResponse = new EmployeeContactInfoResponse(); @Spy List<EmployeeContactInfo> employeeContactInfolist = new ArrayList<>(); @Before public void beforeTest() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { employeeContactInfoController = new EmployeeContactInfoController(); employeeStatusFacade = mock(EmployeeContactFacadeImpl.class); // MockitoAnnotations.initMocks(This.class); setCollaborator(employeeContactInfoController, "empFacade", employeeStatusFacade); } private void setCollaborator(Object object, String name, Object service) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { Field field; field = object.getClass().getDeclaredField(name); field.setAccessible(true); field.set(object, service); } public List<EmployeeContactInfo> getEmployeeContactInfo() { List<EmployeeContactInfo> list = new ArrayList<>(); EmployeeContactInfo employeeContactInfo = new EmployeeContactInfo(); Timestamp timestamp = new Timestamp(new java.util.Date().getTime()); employeeContactInfo.setId(1); employeeContactInfo.setAlternateMobileNo("9876543210"); employeeContactInfo.setCurrentAddressLine1("Raidurgam"); employeeContactInfo.setCurrentAddressLine2("Police Line-2"); employeeContactInfo.setCurrentCity("Hyderbad"); employeeContactInfo.setCurrentState("AP"); employeeContactInfo.setCurrentPin(500001); employeeContactInfo.setPermanentAddressLine1("Hyderbad"); employeeContactInfo.setEmpId("19201"); employeeContactInfo.setCreatedBy("SaiKrishna"); employeeContactInfo.setUpdatedBy("Krishna"); employeeContactInfo.setCreatedDate(timestamp); employeeContactInfo.setUpdatedDate(timestamp); employeeContactInfo.setFlag(true); list.add(employeeContactInfo); return list; } public List<EmployeeContactInfo> getEmployeeContactInfo1() { List<EmployeeContactInfo> list = new ArrayList<>(); EmployeeContactInfo employeeContactInfo = new EmployeeContactInfo(); Timestamp timestamp = new Timestamp(new java.util.Date().getTime()); employeeContactInfo.setId(null); employeeContactInfo.setAlternateMobileNo("9876543210"); employeeContactInfo.setCurrentAddressLine1("Raidurgam"); employeeContactInfo.setCurrentAddressLine2("Police Line-2"); employeeContactInfo.setCurrentCity("Hyderbad"); employeeContactInfo.setCurrentState("TS"); employeeContactInfo.setCurrentPin(500001); employeeContactInfo.setPermanentAddressLine1("Hyderbad"); employeeContactInfo.setEmpId("19201"); employeeContactInfo.setCreatedBy("SaiKrishna"); employeeContactInfo.setUpdatedBy("Krishna"); employeeContactInfo.setCreatedDate(timestamp); employeeContactInfo.setUpdatedDate(timestamp); employeeContactInfo.setFlag(true); list.add(employeeContactInfo); return list; } // public List<EmployeeContactInfo> emptyEmployeeContactInfo() { // List<EmployeeContactInfo> list = new ArrayList<>(); // // EmployeeContactInfo employeeContactInfo = new EmployeeContactInfo(); // EmployeeContactInfo employeeContactInfo1 = new EmployeeContactInfo(); // // list.add(employeeContactInfo); // list.add(employeeContactInfo1); // return list; // } // -------Request null test Set------ @Test public void reqNullTestSet() throws Exception { EmployeeContactInfoRequest empContactInfoRequest = null; HttpServletRequest request = null; HttpServletResponse response = null; Mockito.lenient().when(employeeStatusFacade.setEmployeeContactInfo(empContactInfoRequest)) .thenReturn(successEntity); ResponseEntity<Object> setEmployeeContactInfo = employeeContactInfoController .setEmployeeContactInfo(empContactInfoRequest, request, response); HttpStatus statusCode = setEmployeeContactInfo.getStatusCode(); assertEquals(HttpStatus.UNPROCESSABLE_ENTITY, statusCode); } // -------Get null test ------ @Test public void reqNullTestGet() throws Exception { EmployeeContactInfoRequest empContactInfoRequest = null; HttpServletRequest request = null; HttpServletResponse response = null; Mockito.lenient().when(employeeStatusFacade.getEmployeeContactInfo(empContactInfoRequest)) .thenReturn(successEntity); ResponseEntity<Object> setEmployeeContactInfo = employeeContactInfoController .getEmployeeContactInfo(empContactInfoRequest, request, response); HttpStatus statusCode = setEmployeeContactInfo.getStatusCode(); assertEquals(HttpStatus.UNPROCESSABLE_ENTITY, statusCode); } // -----null Tx Test------ @Test public void nullTxTest() throws Exception { EmployeeContactInfoRequest empContactInfoRequest = new EmployeeContactInfoRequest(); empContactInfoRequest.setEmpInfo(this.getEmployeeContactInfo()); empContactInfoRequest.setTransactionType(""); HttpServletRequest request = null; HttpServletResponse response = null; Mockito.lenient().when(employeeStatusFacade.setEmployeeContactInfo(empContactInfoRequest)) .thenReturn(successEntity); ResponseEntity<Object> setEmployeeContactInfo = employeeContactInfoController .setEmployeeContactInfo(empContactInfoRequest, request, response); HttpStatus statusCode = setEmployeeContactInfo.getStatusCode(); assertEquals(HttpStatus.UNPROCESSABLE_ENTITY, statusCode); } /* * @Test public void testSetEmployeeContactInfoInvalidEmail() { * EmployeeContactInfoRequest empContactInfoRequest = new * EmployeeContactInfoRequest(); * empContactInfoRequest.setEmpInfo(this.getEmployeeContactInfo()); * * empContactInfoRequest.setTransactionType("save"); HttpServletRequest request * = null; HttpServletResponse response = null; ResponseEntity<Object> * setEmployeeContactInfo = employeeContactInfoController * .setEmployeeContactInfo(empContactInfoRequest, request, response); HttpStatus * statusCode = setEmployeeContactInfo.getStatusCode(); * * assertEquals(HttpStatus.UNPROCESSABLE_ENTITY, statusCode); } * * @Test public void testSetEmployeeContactInfoEmptyEmail() { * EmployeeContactInfoRequest empContactInfoRequest = new * EmployeeContactInfoRequest(); * empContactInfoRequest.setEmpInfo(this.getEmployeeContactInfo()); * * empContactInfoRequest.setTransactionType("save"); HttpServletRequest request * = null; HttpServletResponse response = null; ResponseEntity<Object> * setEmployeeContactInfo = employeeContactInfoController * .setEmployeeContactInfo(empContactInfoRequest, request, response); HttpStatus * statusCode = setEmployeeContactInfo.getStatusCode(); * System.out.println(statusCode); * * assertEquals(HttpStatus.UNPROCESSABLE_ENTITY, statusCode); } */ @Test public void testSetEmployeeContactInfoUpdateId() { EmployeeContactInfoRequest empContactInfoRequest = new EmployeeContactInfoRequest(); empContactInfoRequest.setEmpInfo(this.getEmployeeContactInfo()); empContactInfoRequest.getEmpInfo().get(0).setId(null); empContactInfoRequest.setTransactionType("update"); HttpServletRequest request = null; HttpServletResponse response = null; ResponseEntity<Object> setEmployeeContactInfo = employeeContactInfoController .setEmployeeContactInfo(empContactInfoRequest, request, response); HttpStatus statusCode = setEmployeeContactInfo.getStatusCode(); System.out.println(statusCode); assertEquals(HttpStatus.UNPROCESSABLE_ENTITY, statusCode); } @Test public void testSetEmployeeContactInfoDeleteId() { EmployeeContactInfoRequest empContactInfoRequest = new EmployeeContactInfoRequest(); empContactInfoRequest.setEmpInfo(this.getEmployeeContactInfo()); empContactInfoRequest.getEmpInfo().get(0).setId(null); empContactInfoRequest.setTransactionType("delete"); HttpServletRequest request = null; HttpServletResponse response = null; ResponseEntity<Object> setEmployeeContactInfo = employeeContactInfoController .setEmployeeContactInfo(empContactInfoRequest, request, response); HttpStatus statusCode = setEmployeeContactInfo.getStatusCode(); System.out.println(statusCode); assertEquals(HttpStatus.UNPROCESSABLE_ENTITY, statusCode); } @Test public void testSetEmployeeContactInfoNullTransactionType() { EmployeeContactInfoRequest empContactInfoRequest = new EmployeeContactInfoRequest(); empContactInfoRequest.setEmpInfo(this.getEmployeeContactInfo()); // empContactInfoRequest.setTransactionType("save"); HttpServletRequest request = null; HttpServletResponse response = null; ResponseEntity<Object> setEmployeeContactInfo = employeeContactInfoController .setEmployeeContactInfo(empContactInfoRequest, request, response); HttpStatus statusCode = setEmployeeContactInfo.getStatusCode(); System.out.println(statusCode); assertEquals(HttpStatus.UNPROCESSABLE_ENTITY, statusCode); } /* * @Test public void testSetEmployeeContactInfoSave() { * EmployeeContactInfoRequest empContactInfoRequest = new * EmployeeContactInfoRequest(); * empContactInfoRequest.setEmpInfo(getEmployeeContactInfo()); * * empContactInfoRequest.setTransactionType("save"); HttpServletRequest request * = null; HttpServletResponse response = null; ResponseEntity<Object> * setEmployeeContactInfo = employeeContactInfoController * .setEmployeeContactInfo(empContactInfoRequest, request, response); HttpStatus * statusCode = setEmployeeContactInfo.getStatusCode(); * * assertEquals(HttpStatus.OK, statusCode); } */ @Test public void setEmployeeContactInfoTestUpdate() throws Exception { EmployeeContactInfoRequest empContactInfoRequest = new EmployeeContactInfoRequest(); empContactInfoRequest.setEmpInfo(this.getEmployeeContactInfo1()); HttpServletRequest request = null; HttpServletResponse response = null; empContactInfoRequest.setTransactionType("update"); // when(employeeStatusFacade.setEmployeeContactInfo(empContactInfoRequest)).thenThrow(new // RuntimeException()); ResponseEntity<Object> setEmployeeContactInfo = employeeContactInfoController .setEmployeeContactInfo(empContactInfoRequest, request, response); HttpStatus statusCode = setEmployeeContactInfo.getStatusCode(); assertEquals(HttpStatus.UNPROCESSABLE_ENTITY, statusCode); } @Test public void setEmployeeContactInfoTestDelete() throws Exception { EmployeeContactInfoRequest empContactInfoRequest = new EmployeeContactInfoRequest(); empContactInfoRequest.setEmpInfo(this.getEmployeeContactInfo1()); HttpServletRequest request = null; HttpServletResponse response = null; empContactInfoRequest.setTransactionType("delete"); // when(employeeStatusFacade.setEmployeeContactInfo(empContactInfoRequest)).thenThrow(new // RuntimeException()); ResponseEntity<Object> setEmployeeContactInfo = employeeContactInfoController .setEmployeeContactInfo(empContactInfoRequest, request, response); HttpStatus statusCode = setEmployeeContactInfo.getStatusCode(); assertEquals(HttpStatus.UNPROCESSABLE_ENTITY, statusCode); } @Test public void getEmployeeContactInfoTestNotEqualGetAll() throws Exception { EmployeeContactInfoRequest empContactInfoRequest = new EmployeeContactInfoRequest(); empContactInfoRequest.setEmpInfo(this.getEmployeeContactInfo()); HttpServletRequest request = null; HttpServletResponse response = null; empContactInfoRequest.setTransactionType("getegdg"); when(employeeStatusFacade.getEmployeeContactInfo(empContactInfoRequest)).thenReturn(successEntity); ResponseEntity<Object> setEmployeeContactInfo = employeeContactInfoController .getEmployeeContactInfo(empContactInfoRequest, request, response); HttpStatus statusCode = setEmployeeContactInfo.getStatusCode(); assertEquals(HttpStatus.OK, statusCode); } @Test public void getEmployeeContactInfoTestGetAll() throws Exception { EmployeeContactInfoRequest empContactInfoRequest = new EmployeeContactInfoRequest(); empContactInfoRequest.setEmpInfo(this.getEmployeeContactInfo()); HttpServletRequest request = null; HttpServletResponse response = null; empContactInfoRequest.setTransactionType("getAll"); when(employeeStatusFacade.getEmployeeContactInfo(empContactInfoRequest)).thenReturn(successEntity); ResponseEntity<Object> setEmployeeContactInfo = employeeContactInfoController .getEmployeeContactInfo(empContactInfoRequest, request, response); HttpStatus statusCode = setEmployeeContactInfo.getStatusCode(); assertEquals(HttpStatus.OK, statusCode); } // -----------set DuplicateException test case--------------- @Test public void setDuplicateExceptionTest() throws Exception { EmployeeContactInfoRequest empContactInfoRequest = new EmployeeContactInfoRequest(); empContactInfoRequest.setEmpInfo(this.getEmployeeContactInfo()); empContactInfoRequest.setTransactionType("save"); HttpServletRequest request = null; HttpServletResponse response = null; when(employeeStatusFacade.setEmployeeContactInfo(empContactInfoRequest)) .thenThrow(new DuplicateKeyException("")); ResponseEntity<Object> setEmployeeContactInfo = employeeContactInfoController .setEmployeeContactInfo(empContactInfoRequest, request, response); HttpStatus statusCode = setEmployeeContactInfo.getStatusCode(); System.out.println(statusCode); assertEquals(HttpStatus.CONFLICT, statusCode); } // -----------Set SQLException test case--------------- @Test public void setSQLExceptionTest() throws Exception { EmployeeContactInfoRequest empContactInfoRequest = new EmployeeContactInfoRequest(); empContactInfoRequest.setEmpInfo(this.getEmployeeContactInfo()); empContactInfoRequest.setTransactionType("save"); HttpServletRequest request = null; HttpServletResponse response = null; when(employeeStatusFacade.setEmployeeContactInfo(empContactInfoRequest)).thenThrow(SQLException.class); ResponseEntity<Object> setEmployeeContactInfo = employeeContactInfoController .setEmployeeContactInfo(empContactInfoRequest, request, response); HttpStatus statusCode = setEmployeeContactInfo.getStatusCode(); assertEquals(HttpStatus.CONFLICT, statusCode); } // -----------set Exception test case--------------- @Test public void setExceptionTest() throws Exception { EmployeeContactInfoRequest empContactInfoRequest = new EmployeeContactInfoRequest(); empContactInfoRequest.setEmpInfo(this.getEmployeeContactInfo()); HttpServletRequest request = null; HttpServletResponse response = null; empContactInfoRequest.setTransactionType("save"); when(employeeStatusFacade.setEmployeeContactInfo(empContactInfoRequest)).thenThrow(new RuntimeException()); ResponseEntity<Object> setEmployeeContactInfo = employeeContactInfoController .setEmployeeContactInfo(empContactInfoRequest, request, response); HttpStatus statusCode = setEmployeeContactInfo.getStatusCode(); assertEquals(HttpStatus.CONFLICT, statusCode); } // -----------get DuplicateException test case--------------- @Test public void getDuplicateExceptionTest() throws Exception { EmployeeContactInfoRequest empContactInfoRequest = new EmployeeContactInfoRequest(); empContactInfoRequest.setEmpInfo(this.getEmployeeContactInfo()); empContactInfoRequest.setTransactionType("getAll"); HttpServletRequest request = null; HttpServletResponse response = null; when(employeeStatusFacade.getEmployeeContactInfo(empContactInfoRequest)) .thenThrow(new DuplicateKeyException("")); ResponseEntity<Object> getEmployeeContactInfo = employeeContactInfoController .getEmployeeContactInfo(empContactInfoRequest, request, response); HttpStatus statusCode = getEmployeeContactInfo.getStatusCode(); System.out.println(statusCode); assertEquals(HttpStatus.CONFLICT, statusCode); } // -----------get SQL Exception test case--------------- @Test public void getSqlExceptionTest() throws Exception { EmployeeContactInfoRequest empContactInfoRequest = new EmployeeContactInfoRequest(); empContactInfoRequest.setEmpInfo(this.getEmployeeContactInfo()); empContactInfoRequest.setTransactionType("getAll"); HttpServletRequest request = null; HttpServletResponse response = null; when(employeeStatusFacade.getEmployeeContactInfo(empContactInfoRequest)) .thenThrow(SQLException.class); ResponseEntity<Object> getEmployeeContactInfo = employeeContactInfoController .getEmployeeContactInfo(empContactInfoRequest, request, response); HttpStatus statusCode = getEmployeeContactInfo.getStatusCode(); System.out.println(statusCode); assertEquals(HttpStatus.CONFLICT, statusCode); } // -----------get Exception test case--------------- @Test public void getExceptionTest() throws Exception { EmployeeContactInfoRequest empContactInfoRequest = new EmployeeContactInfoRequest(); empContactInfoRequest.setEmpInfo(this.getEmployeeContactInfo()); empContactInfoRequest.setTransactionType("getAll"); HttpServletRequest request = null; HttpServletResponse response = null; when(employeeStatusFacade.getEmployeeContactInfo(empContactInfoRequest)) .thenThrow(new RuntimeException()); ResponseEntity<Object> getEmployeeContactInfo = employeeContactInfoController .getEmployeeContactInfo(empContactInfoRequest, request, response); HttpStatus statusCode = getEmployeeContactInfo.getStatusCode(); System.out.println(statusCode); assertEquals(HttpStatus.CONFLICT, statusCode); } }
40,394
https://github.com/jkennedyvz/DeepFaceLive/blob/master/xlib/avecl/_internal/op/matmul.py
Github Open Source
Open Source
MIT
2,022
DeepFaceLive
jkennedyvz
Python
Code
618
1,819
import numpy as np from ..AShape import AShape from ..backend import Kernel from ..HArgs import HArgs from ..SCacheton import SCacheton from ..Tensor import Tensor def matmul(a_t : Tensor, b_t : Tensor, output_t: Tensor=None, is_add_to_output=False) -> Tensor: """ matmul operator in row-major format A(...,M,K) x B(...,K,N) = (...,M,N) arguments output_t compute result to this Tensor. Tensor may be with different shape, but should match total size. gradfn will not be set. is_add_to_output add result to output_t if output_t is set. """ return matmulc(b_t, a_t, output_t=output_t, is_add_to_output=is_add_to_output) def matmulc(a_t : Tensor, b_t : Tensor, output_t : Tensor = None, is_add_to_output=False) -> Tensor: """ matmul operator in col-major format A(...,K,M) x B(...,N,K) = (...,N,M) arguments output_t compute result to this Tensor. Tensor may be with different shape, but should match total size. gradfn will not be set. is_add_to_output add result to output_t if output_t is set. """ device = HArgs.check_get_same_device([a_t, b_t]) op = SCacheton.get(_MatmulOp, a_t.shape, a_t.dtype, b_t.shape, b_t.dtype, False if output_t is None else is_add_to_output) if output_t is None: output_t = Tensor (op.o_shape, op.o_dtype, device=device ) elif output_t.shape.size != op.o_shape.size: raise ValueError(f'output_t must have size {op.o_shape.size}') device.run_kernel(op.forward_krn, output_t.get_buffer(), a_t.get_buffer(), b_t.get_buffer(), ) return output_t class _MatmulOp: def __init__(self, a_shape, a_dtype, b_shape, b_dtype, is_add_to_output): a_dtype = np.dtype(a_dtype).type b_dtype = np.dtype(b_dtype).type if a_dtype != np.float32 or b_dtype != np.float32: raise ValueError('matmul works only with float32 tensors.') if a_shape.ndim != b_shape.ndim: raise ValueError(f'ndims are not equal. {a_shape.ndim} != {b_shape.ndim}') ndim = a_shape.ndim if ndim < 2: raise ValueError('Tensors ndim must be at least 2.') K, M = a_shape[-2], a_shape[-1] N, B_COLS = b_shape[-2], b_shape[-1] if K != B_COLS: raise ValueError('A_ROWS != B_COLS') BATCH = a_shape[0:-2].size B_BATCH = b_shape[0:-2].size if BATCH != B_BATCH: raise ValueError(f'BATCH size {BATCH} != {B_BATCH} in shapes {a_shape} {b_shape}') if ndim == 2: self.o_shape = AShape( (N, M) ) else: self.o_shape = AShape( a_shape[:-2]+(N, M) ) self.o_dtype = np.float32 self.M = M self.N = N self.K = K # Determining optimal tile widths for MW in [8,4,2,1]: if M % MW == 0: break for KW in [8,4,2,1]: if N % KW == 0 and K % KW == 0: break NW = KW self.forward_krn = Kernel(global_shape=(M//MW, N//NW, BATCH), kernel_text=f""" #define K {K} #define N {N} #define MW {MW} // M tile Width #define NW {NW} // N tile Width -- NW & KW should be the same ! #define KW {KW} // K tile Width #define MT {M//MW} // MT is max for 'mt' (M tile count) #define KT {K//KW} // KT is max for 'kt' (K tile count) #define floatMW { f'float{MW}' if MW != 1 else 'float'} #define floatKW { f'float{KW}' if KW != 1 else 'float'} __kernel void GeMM(__global floatMW* O, const __global floatMW* restrict A, const __global floatKW* restrict B) {{ size_t mt = get_global_id(0); //global M-tile id size_t nc = get_global_id(1); //global N-tile id size_t batch = get_global_id(2); float AT[KW][MW]; // sub tiles float BT[NW][KW]; float CT[NW][MW]; #pragma unroll for (uint i=0; i<NW*MW; ++i) // zero CT tile ((float*) CT)[i] = 0.0; for (uint kt=0; kt<KT; ++kt) // iterate over K-dim tiles {{ #pragma unroll for (uint k=0; k<KW; ++k) // every k-element inside K-dim tile *( (floatMW*) AT[k] ) = A[batch*K*MT + (kt*KW + k)*MT + mt]; // store M-Width floats #pragma unroll for (uint n=0; n<NW; ++n) // every n-element inside N-dim tile *( (floatKW*) BT[n] ) = B[batch*N*KT + (nc*NW + n)*KT + kt]; // store K-Width floats #pragma unroll for (uint k=0; k<KW; ++k) #pragma unroll for (uint n=0; n<NW; ++n) // sub tiles multiplication #pragma unroll for (uint m=0; m<MW; ++m) CT[n][m] += AT[k][m] * BT[n][k]; }} #pragma unroll for (uint n=0; n<NW; ++n) O[ batch*N*MT + (nc*NW + n)*MT + mt] {'+=' if is_add_to_output else '='} *( (floatMW*) CT[n]); }}""")
40,660
https://github.com/ardikabs/ContainerSSH/blob/master/cmd/license-report/main.go
Github Open Source
Open Source
MIT
2,020
ContainerSSH
ardikabs
Go
Code
281
950
package main import ( "bytes" "fmt" "io/ioutil" "log" "os" "os/exec" "path" "regexp" "strings" ) func main() { cmd := exec.Command("golicense", os.Args[1], os.Args[2]) var stdOutBuf bytes.Buffer cmd.Stdout = &stdOutBuf cmd.Stderr = os.Stderr cmd.Env = nil err := cmd.Run() if err != nil { log.Fatalf("failed to run golicense (%v)", err) } data := stdOutBuf.String() lines := strings.Split(data, "\n") noticeFiles := map[string]string{} licenses := map[string]string{} re := regexp.MustCompile(`\s+`) cmd = exec.Command("go", "mod", "vendor") err = cmd.Run() if err != nil { log.Fatalf("%v", err) } extractLicenses(lines, re, licenses, noticeFiles) noticeContents := renderNotice(licenses, noticeFiles) err = ioutil.WriteFile(os.Args[3], noticeContents, 0644) if err != nil { log.Fatalf("%v", err) } err = os.RemoveAll("vendor") if err != nil { log.Fatalf("%v", err) } } func extractLicenses(lines []string, re *regexp.Regexp, licenses map[string]string, noticeFiles map[string]string) { for _, line := range lines { if line == "" { continue } parts := re.Split(line, -1) if len(parts) < 2 { continue } repo := strings.TrimSpace(parts[0]) licenses[repo] = strings.TrimSpace(parts[1]) noticeFile := path.Join("vendor", repo, "NOTICE") noticeFileMarkdown := path.Join("vendor", repo, "NOTICE.md") if _, err := os.Stat(noticeFile); err == nil { noticeFiles[repo] = noticeFile } else if _, err := os.Stat(noticeFileMarkdown); err == nil { noticeFiles[repo] = noticeFileMarkdown } } } func renderNotice(licenses map[string]string, noticeFiles map[string]string) []byte { var finalNotice bytes.Buffer finalNotice.Write([]byte("# Third party licenses\n\n")) finalNotice.Write([]byte("This project contains third party packages under the following licenses:\n\n")) for packageName, license := range licenses { finalNotice.Write([]byte(fmt.Sprintf("## [%s](https://%s)\n\n", packageName, packageName))) finalNotice.Write([]byte(fmt.Sprintf("**License:** %s\n\n", license))) if noticeFile, ok := noticeFiles[packageName]; ok { noticeData, err := ioutil.ReadFile(noticeFile) if err != nil { log.Fatalf("failed to read notice file %s (%v)", noticeFile, err) } trimmedNotice := strings.TrimSpace(string(noticeData)) if trimmedNotice != "" { finalNotice.Write([]byte(fmt.Sprintf("%s\n\n", "> "+strings.ReplaceAll(trimmedNotice, "\n", "\n> ")))) } } } noticeContents := finalNotice.Bytes() return noticeContents }
48,346
https://github.com/aantakli/AJAN-editor/blob/master/app/components/editor/rdf-interaction-header.js
Github Open Source
Open Source
MIT
2,023
AJAN-editor
aantakli
JavaScript
Code
825
2,417
/* * Created on Tue Nov 10 2020 * * The MIT License (MIT) * Copyright (c) 2020 André Antakli, Alex Grethen (German Research Center for Artificial Intelligence, DFKI). * * 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. */ import {computed, observer} from "@ember/object"; import { sendAskQuery, sendSelectQuery, sendQuery } from "ajan-editor/helpers/RDFServices/ajax/query-rdf4j"; import Component from "@ember/component"; import { graphDatasetBeautify, csvDatasetBeautify } from "ajan-editor/helpers/RDFServices/RDF-utility/dataset-format"; import Sparql from "npm:sparqljs"; import stringToStream from "npm:string-to-stream"; import rdf from "npm:rdf-ext"; import N3Parser from "npm:rdf-parser-n3"; let defaultRepositoryString = "defaultRepository"; let currentRepositoryString = "defaultRepository"; let ajax = null; // ajax export default Component.extend({ ajax: Ember.inject.service(), vocabularyManager: Ember.inject.service("data-manager/vocabulary-manager"), defaultRepository: computed("defaultRepository", function () { const urlParams = new URLSearchParams(window.location.search); let repo = urlParams.get('repo'); if (this.get("repositories").filter(item => item.uri == repo).length) { return repo; } else { return localStorage.currentStore + "agents"; } }), showQueryResults: true, prefixes: [], currentRepository: computed("defaultRepository", function () { return this.get(defaultRepositoryString); }), modeChanged: observer("mode", function() { handleQuery("", this); }), didInsertElement() { let dataPromise = this.vocabularyManager.getAllDataPromise(); let that = this; ajax = that.get("ajax"); dataPromise.then(data => { data = data.map(ele => { return { label: ele.prefix, iri: ele.uri }; }); that.set("prefixes", data); that.set("parentView.prefixes", data); this.send("repoSelected", this.get(defaultRepositoryString)); let editor = ace.edit("ace-editor"); editor.getSession().on("change", function(changes, session) { editorContentUpdate(changes, session, that); }); }); }, actions: { repoSelected(repo) { this.set(currentRepositoryString, repo); this.set("parentView.currentRepository", this.get(currentRepositoryString)); console.log(this.parentView.currentRepository); let query = getWhereGraphQuery( ace .edit("ace-editor") .getValue() .toString() ); handleQuery(query, this); } } }); function editorContentUpdate(changes, session, that) { // TODO: handle delete update (e.g. when replacing a string) let query = session.getValue().toString(); // query = getWhereGraphQuery(query); handleQuery(query, that); } function handleQuery(query, that) { that.set("malformedQuery", false); try { let query = ace .edit("ace-editor") .getValue() .toString(); switch (that.get("mode")) { case "all": query = getAllQuery(); setGraphDataRDF(query, that); break; case "where": query = getWhereGraphQuery(query); setGraphDataRDF(query, that); break; case "query": resolveQuery(query, that); break; case "none": default: that.set("tableData", undefined); return; } // let promise = sendQuery(that.get(currentRepositoryString), query); // promise.then(data => { // let dataset = datasetBeautify(data); // that.set("tableData", dataset); // }); } catch (e) { console.warn("Could not handle query", query, e); that.set("malformedQuery", true); that.set("tableData", undefined); } } function getAllQuery() { return "CONSTRUCT WHERE {?s ?p ?o}"; } function getWhereGraphQuery(query) { let prefixes = getPrefixes(query); let base = getBasicForm(); let whereClause = getWhereClause(query); if (!whereClause) return; let newQuery = prefixes + base + whereClause; return newQuery; } function getPrefixes(query) { let index = query.toUpperCase().indexOf("ASK"); if (index < 0) index = query.toUpperCase().indexOf("CONSTRUCT"); if (index < 0) index = query.toUpperCase().indexOf("DESCRIBE"); if (index < 0) index = query.toUpperCase().indexOf("SELECT"); if (index < 0) index = query.toUpperCase().indexOf("DELETE"); if (index < 0) index = query.toUpperCase().indexOf("INSERT"); return index > -1 ? query.slice(0, index) : ""; } function getBasicForm() { return ` CONSTRUCT `; } function getWhereClause(query) { // let index = query.toUpperCase().indexOf("WHERE"); let index = query.toUpperCase().indexOf("WHERE"); return index > -1 ? query.slice(index) : undefined; } function resolveQuery(query, that) { console.log("resolveQuery", ...arguments) let parser = new Sparql.Parser(); let parsedQuery = parser.parse(query); console.log("Resolving query of type", parsedQuery) switch (parsedQuery.queryType) { case "DESCRIBE": case "CONSTRUCT": setGraphDataRDF(query, that); break; case "ASK": setDataBool(query, that); break; case "SELECT": setTableData(query, that); break; default: console.warn("Could not read query type ", parsedQuery.queryType); } } function setGraphDataRDF(query, that) { that.set("dataFormat", "RDF"); let promise = sendQuery(ajax, that.get(currentRepositoryString), query, "application/trig"); promise.then(data => { that.set("data", data); const parser = new N3Parser(); const quadStream = parser.import(stringToStream(data)); let dataset = rdf.dataset().import(quadStream); let beautiful = graphDatasetBeautify(dataset, that.prefixes); beautiful.then(dataTable => { that.set("tableData", dataTable) }); }); } function setTableData(query, that) { that.set("dataFormat", "TABLE"); let promise = sendSelectQuery(ajax, that.get(currentRepositoryString), query); promise.then(data => { var lines = data.split('\r'); for (let i = 0; i < lines.length; i++) { lines[i] = lines[i].replace(/\s/, '') } var csv = []; var headers = lines[0].split(","); for (var i = 1; i < lines.length; i++) { var obj = {}; var currentline = lines[i].split(","); for (var j = 0; j < headers.length; j++) { obj[headers[j].toString()] = currentline[j]; } csv.push(obj); } let dataset = csvDatasetBeautify(csv, that.prefixes); that.set("tableData", dataset); }); } function setDataBool(query, that) { that.set("dataFormat", "BOOL"); let promise = sendAskQuery(ajax, that.get(currentRepositoryString), query); promise.then(data => { that.set("tableData", undefined); data = !(!data || data == "false"); that.set("data", data); }); }
46,454
https://github.com/lotterfriends/ngx-webrtc/blob/master/apps/demo-video-chat-client/src/app/components/video-chat/video-chat.component.ts
Github Open Source
Open Source
MIT
2,022
ngx-webrtc
lotterfriends
TypeScript
Code
925
3,827
import { AfterViewInit, Component, ComponentRef, ElementRef, HostListener, Input, OnInit, ViewChild, ViewContainerRef } from '@angular/core'; import { UntilDestroy, untilDestroyed } from '@ngneat/until-destroy'; import { ConferenceGridHolderComponent } from '@ngx-webrtc/demo-ui-components'; import { MessageType, User } from '@ngx-webrtc/demo-video-chat-models'; import { CallService, DeviceService, IceServer, PeerConnectionClient, PeerConnectionClientSignalMessage, StreamService, StreamType } from 'ngx-webrtc'; import { distinctUntilChanged, filter, first, map } from 'rxjs/operators'; import { MessagesService } from '../../services/messages.service'; import { SocketService } from '../../services/socket.service'; import { UiService, ViewMode } from '../../services/ui.service'; import { UserStorageService } from '../../services/user-storage.service'; import { RemotePeerComponent } from './remote-peer/remote-peer.component'; /** * This is an example implementation of an video chat */ @UntilDestroy() @Component({ selector: 'ngx-webrtc-video-chat', templateUrl: './video-chat.component.html', styleUrls: ['./video-chat.component.css'] }) export class VideoChatComponent implements OnInit, AfterViewInit { private debug = true; public pclients: {user: User, connection: PeerConnectionClient, component: ComponentRef<RemotePeerComponent>}[] = []; public viewMode = UiService.DEFAULTS.VIEW_MODE; private localStream: MediaStream | null = null; public localVideoEnabled = false; private isInitiator = false; private self: string | null = null; private users: User[] = []; private identifier: (keyof User) = this.callService.getUserIdentifier(); private servers: IceServer[] = []; @Input() room!: string; @ViewChild('localStreamNode', { static: false }) localStreamNode!: ElementRef; @ViewChild('remotePeerHolder', { read: ViewContainerRef }) remotePeerHolder!: ViewContainerRef; @ViewChild('holder', { static: false }) public holder!: ConferenceGridHolderComponent; @HostListener('window:resize') public onWinResize(): void { this.resize(); } @HostListener('window:beforeunload') onClose(): void { this.stopCall(); } constructor( private userStorageService: UserStorageService, private socketService: SocketService, private messageService: MessagesService, private streamService: StreamService, private callService: CallService, private uiService: UiService, private deviceService: DeviceService ) {} ngAfterViewInit(): void { this.uiService.isChatVisible$.pipe(untilDestroyed(this)).subscribe(this.resize.bind(this)); this.uiService.isUserlistVisible$.pipe(untilDestroyed(this)).subscribe(this.resize.bind(this)); } ngOnInit(): void { this.log('init'); this.self = this.userStorageService.getCurrentUsername(); this.socketService.onUserLeftRoom().pipe( untilDestroyed(this), distinctUntilChanged() ).subscribe(this.onUserLeft.bind(this)); // signaling in this.socketService.getPrivateMessages().pipe( untilDestroyed(this), filter(m => m.type === MessageType.Signal) ).subscribe(message => { for (const client of this.pclients) { if (client.user.name === message.author) { client.connection.receiveSignalingMessage(message.message); } } }); // send stream events to peers this.streamService.localAudioStreamStatusChanged.pipe( untilDestroyed(this), ).subscribe(localAudioEnabled => { this.pclients.forEach(e => { localAudioEnabled ? e.connection.audioUnmuted() : e.connection.audioMuted(); }); }); this.streamService.localVideoStreamStatusChanged.pipe( untilDestroyed(this), ).subscribe(localVideoEnabled => { this.localVideoEnabled = localVideoEnabled; this.pclients.forEach(e => { localVideoEnabled ? e.connection.videoUnmuted() : e.connection.videoMuted(); }); }); // change audio output this.streamService.audioOutput$.pipe( untilDestroyed(this), filter(e => e !== null) ).subscribe(deviceId => { this.pclients.forEach(async client => { await client.component?.instance?.audioStreamNode?.nativeElement?.setSinkId(deviceId); }); }); this.streamService.replaceTrack$.pipe( untilDestroyed(this), filter(e => e !== null) ).subscribe((track) => { this.log('replaceTrack', track); if (track) { this.pclients.forEach(async client => { client.connection.replaceTrack(track); }); } else { this.log('WARNING: track is null'); } }); // send call events to peers this.callService.startShareScreen.pipe( untilDestroyed(this), ).subscribe(() => { this.pclients.forEach(e => { e.connection.startShareScreen(); }); }); this.callService.stopShareScreen.pipe( untilDestroyed(this), ).subscribe(() => { this.pclients.forEach(e => { e.connection.stopShareScreen(); }); }); } public startCall(servers: IceServer[]): void { this.log('startCall'); this.servers = servers; this.getMediaAndStart(); } private getMediaAndStart(): void { const preferredVideoInputDevice = this.deviceService.preferredVideoInputDevice$.getValue(); const preferredAudioInputDevice = this.deviceService.preferredAudioInputDevice$.getValue(); const preferredAudioInputDeviceVolume = this.deviceService.preferredAudioInputDeviceVolume$.getValue(); let audioConstraint: boolean | { deviceId?: string, volume?: number } = true; if (preferredAudioInputDevice || preferredAudioInputDeviceVolume !== null) { if (preferredAudioInputDevice && preferredAudioInputDeviceVolume !== null) { audioConstraint = { deviceId: preferredAudioInputDevice, volume: preferredAudioInputDeviceVolume } } else if (preferredAudioInputDevice) { audioConstraint = { deviceId: preferredAudioInputDevice } } else if (preferredAudioInputDeviceVolume) { audioConstraint = { volume: preferredAudioInputDeviceVolume } } } this.streamService.tryGetUserMedia({ video: preferredVideoInputDevice ? { deviceId: preferredVideoInputDevice } : true, audio: audioConstraint }).then(this.onLocalStream.bind(this), this.onNoStream.bind(this)); } private onLocalStream(stream: MediaStream): void { this.localVideoEnabled = true; this.localStream = stream; this.streamService.setLocalStream(stream); this.streamService.setStreamInNode(this.localStreamNode.nativeElement, stream, true, true); this.log('joinedRoom'); this.socketService.onUsersJoinedRoom().pipe( untilDestroyed(this), distinctUntilChanged() ).subscribe(this.onUserJoined.bind(this)); this.socketService.joinedRoom(); this.callService.start(); } private onNoStream(): void { this.socketService.onUsersJoinedRoom().pipe( untilDestroyed(this), distinctUntilChanged() ).subscribe(this.onUserJoined.bind(this)); this.socketService.joinedRoom(); this.callService.start(); } private filterConnectedUsers(user: User): boolean { return user[this.identifier] !== this.self && !this.pclients.map(e => e.user[this.identifier]).includes(user[this.identifier]); } private async onUserJoined(users: User[]): Promise<void> { if (this.users === users) { return; } this.users = users; this.log('onUserJoined', users); if (users.length > 1) { if (users.length > 2 && this.pclients.length) { this.isInitiator = true; } for (const [i, user] of users.filter(this.filterConnectedUsers.bind(this)).entries()) { this.log('new user', user); const component = this.remotePeerHolder.createComponent(RemotePeerComponent); const connection = await this.addPeer(user, component); this.pclients.push({ component, user, connection }); this.callService.addUser(user, connection, component); component.instance.setUser(user); this.resize(); } } else { this.isInitiator = true; } } private async onUserLeft(user: User): Promise<void> { this.log('onUserLeft', user); if (user.name !== this.self) { this.callService.removeUser(user); const entry = this.pclients.find(e => e.user[this.identifier] === user[this.identifier]); if (entry?.component?.instance?.audioStreamNode) { this.streamService.stopStreamInNode(entry.component.instance.audioStreamNode); } if (entry?.component?.instance?.videoStreamNode) { this.streamService.stopStreamInNode(entry.component.instance.videoStreamNode); } if (entry?.connection) { entry.connection.close(); } if (entry?.component) { entry.component.destroy(); } this.pclients = this.pclients.filter(e => e.user[this.identifier] !== user[this.identifier]); // everyone else left, now I'm the initiator if (!this.pclients.length) { this.isInitiator = true; } this.resize(); } } private async addPeer(user: User, component: ComponentRef<RemotePeerComponent>): Promise<PeerConnectionClient> { this.log('addPeer', user, component); const cert = await this.callService.createCertifcate(); const pclient = await this.callService.createPeerClient({ peerConnectionConfig: { iceServers: this.servers, certificates: [cert], } }); // add media if (this.localStream) { pclient.addStream(this.localStream); } // signaling out pclient.signalingMessage.subscribe(m => { // this.log(m); this.socketService.sendSignalMessage(m, user.name); }); pclient.remoteStreamAdded.pipe( untilDestroyed(this), ).subscribe(stream => { this.log('remoteStreamAdded', user); if (stream.kind === StreamType.Audio) { this.streamService.setStreamInNode(component.instance.audioStreamNode.nativeElement, stream.track, false); this.callService.userHasMic(user); } if (stream.kind === StreamType.Video) { this.streamService.setStreamInNode(component.instance.videoStreamNode.nativeElement, stream.track); this.callService.userHasCam(user); } }); if (this.localStream) { pclient.negotiationNeededTriggered.pipe( untilDestroyed(this) ).subscribe(() => { this.startPeerConnection(pclient, user); }); } else { this.startPeerConnection(pclient, user); } pclient.muteMyAudio.pipe(untilDestroyed(this)).subscribe(() => { this.streamService.muteLocalAudioStream(); }); pclient.muteMyVideo.pipe(untilDestroyed(this)).subscribe(() => { this.streamService.muteLocalVideoStream(); }); pclient.userMuteAudio.pipe(untilDestroyed(this)).subscribe(() => { this.callService.userAudioMuted(user); }); pclient.userUnmuteAudio.pipe(untilDestroyed(this)).subscribe(() => { this.callService.userAudioUnmuted(user); }); pclient.userUnmuteVideo.pipe(untilDestroyed(this)).subscribe(() => { this.callService.userVideoUnmuted(user); }); pclient.userMuteVideo.pipe(untilDestroyed(this)).subscribe(() => { this.callService.userVideoMuted(user); }); // pclient.remoteHangUp.pipe(first()).subscribe(() => { // this.streamService.stopStream(component.instance.audioStreamNode); // this.streamService.stopStream(component.instance.videoStreamNode); // pclient.close(); // }); return pclient; } private startPeerConnection(pclient: PeerConnectionClient, user: User): void { if (this.isInitiator) { pclient.startAsCaller(); this.log('start as caller', user); } else { this.messageService.getPrivateMessages(this.room, MessageType.Signal, user.name, this.callService.getSince()).pipe( first(), map(m => m.messages.map(e => JSON.parse(e.message) as PeerConnectionClientSignalMessage)) ).subscribe(messages => { this.log('start as callee', user, messages); pclient.startAsCallee(messages); }); } } public stopCall(): void { this.callService.users$.next([]); this.streamService.stopStreamInNode(this.localStreamNode); this.streamService.setLocalStream(null); if (this.pclients && this.pclients.length) { this.pclients.forEach(client => { client.connection.close(); }); } this.remotePeerHolder.clear(); this.pclients = []; this.callService.updateSince(); this.callService.stop(); } private resize(): void { setTimeout(() => { if (this.viewMode === ViewMode.Grid) { this.holder.resizeGrid(); } else { this.holder.removeSize(); } }); } // eslint-disable-next-line @typescript-eslint/no-explicit-any private log(...args: any[]): void { if (this.debug) { console.log(...args); } } }
50,581
https://github.com/johnwatsonncr/s3pypi/blob/master/cdk/bin/cdk.ts
Github Open Source
Open Source
MIT
2,019
s3pypi
johnwatsonncr
JavaScript
Code
22
82
#!/usr/bin/env node import 'source-map-support/register'; import cdk = require('@aws-cdk/core'); import { PyPiS3Stack } from '../lib/cdk-stack'; const app = new cdk.App(); new PyPiS3Stack(app, 'PyPiS3Stack2');
3,126
https://github.com/antpost/antpost-client/blob/master/node_modules/@progress/kendo-angular-upload/dist/npm/file-list-item.d.ts
Github Open Source
Open Source
MIT
null
antpost-client
antpost
TypeScript
Code
74
206
import { ElementRef } from '@angular/core'; import { FileInfo } from './file-info'; import { NavigationService } from './navigation.service'; /** * @hidden */ export declare class FileListItemDirective { private navigationService; files: Array<FileInfo>; index: number; fileClass: boolean; focused: boolean; element: ElementRef; constructor(el: ElementRef, navigationService: NavigationService); focus(): void; readonly uidAttribute: string; readonly tabIndex: string; readonly kFileError: boolean; readonly kFileInvalid: boolean; readonly kFileProgress: boolean; readonly kFileSuccess: boolean; readonly kStateFocused: boolean; onFocus(): void; onBlur(): void; onClick(event: any): void; }
44,377
https://github.com/problem-frames/openpf/blob/master/workspace/event/src-gen/uk/ac/open/event/eventcalculus/util/EventcalculusAdapterFactory.java
Github Open Source
Open Source
BSD-3-Clause
2,019
openpf
problem-frames
Java
Code
3,424
8,289
/** */ package uk.ac.open.event.eventcalculus.util; import org.eclipse.emf.common.notify.Adapter; import org.eclipse.emf.common.notify.Notifier; import org.eclipse.emf.common.notify.impl.AdapterFactoryImpl; import org.eclipse.emf.ecore.EObject; import uk.ac.open.event.eventcalculus.*; /** * <!-- begin-user-doc --> * The <b>Adapter Factory</b> for the model. * It provides an adapter <code>createXXX</code> method for each class of the model. * <!-- end-user-doc --> * @see uk.ac.open.event.eventcalculus.EventcalculusPackage * @generated */ public class EventcalculusAdapterFactory extends AdapterFactoryImpl { /** * The cached model package. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected static EventcalculusPackage modelPackage; /** * Creates an instance of the adapter factory. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EventcalculusAdapterFactory() { if (modelPackage == null) { modelPackage = EventcalculusPackage.eINSTANCE; } } /** * Returns whether this factory is applicable for the type of the object. * <!-- begin-user-doc --> * This implementation returns <code>true</code> if the object is either the model's package or is an instance object of the model. * <!-- end-user-doc --> * @return whether this factory is applicable for the type of the object. * @generated */ @Override public boolean isFactoryForType(Object object) { if (object == modelPackage) { return true; } if (object instanceof EObject) { return ((EObject)object).eClass().getEPackage() == modelPackage; } return false; } /** * The switch that delegates to the <code>createXXX</code> methods. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected EventcalculusSwitch<Adapter> modelSwitch = new EventcalculusSwitch<Adapter>() { @Override public Adapter caseModel(Model object) { return createModelAdapter(); } @Override public Adapter caseImport(Import object) { return createImportAdapter(); } @Override public Adapter caseAnnotation(Annotation object) { return createAnnotationAdapter(); } @Override public Adapter caseDeclaration(Declaration object) { return createDeclarationAdapter(); } @Override public Adapter caseDefines(Defines object) { return createDefinesAdapter(); } @Override public Adapter caseDefSort(DefSort object) { return createDefSortAdapter(); } @Override public Adapter caseDefRange(DefRange object) { return createDefRangeAdapter(); } @Override public Adapter caseDefOption(DefOption object) { return createDefOptionAdapter(); } @Override public Adapter caseDefCompletion(DefCompletion object) { return createDefCompletionAdapter(); } @Override public Adapter caseDefNonInertia(DefNonInertia object) { return createDefNonInertiaAdapter(); } @Override public Adapter caseDefXor(DefXor object) { return createDefXorAdapter(); } @Override public Adapter caseDefMutex(DefMutex object) { return createDefMutexAdapter(); } @Override public Adapter caseStatement(Statement object) { return createStatementAdapter(); } @Override public Adapter caseLabeledExpression(LabeledExpression object) { return createLabeledExpressionAdapter(); } @Override public Adapter caseSortDefinition(SortDefinition object) { return createSortDefinitionAdapter(); } @Override public Adapter caseDefinition(Definition object) { return createDefinitionAdapter(); } @Override public Adapter caseExpression(Expression object) { return createExpressionAdapter(); } @Override public Adapter caseQualifier(Qualifier object) { return createQualifierAdapter(); } @Override public Adapter caseParameters(Parameters object) { return createParametersAdapter(); } @Override public Adapter caseTerminalExpression(TerminalExpression object) { return createTerminalExpressionAdapter(); } @Override public Adapter caseAssignPlus(AssignPlus object) { return createAssignPlusAdapter(); } @Override public Adapter caseAssignMin(AssignMin object) { return createAssignMinAdapter(); } @Override public Adapter caseOr(Or object) { return createOrAdapter(); } @Override public Adapter caseAnd(And object) { return createAndAdapter(); } @Override public Adapter caseRelNotEq(RelNotEq object) { return createRelNotEqAdapter(); } @Override public Adapter caseRelEqEq(RelEqEq object) { return createRelEqEqAdapter(); } @Override public Adapter caseRelLtEq(RelLtEq object) { return createRelLtEqAdapter(); } @Override public Adapter caseRelGtEq(RelGtEq object) { return createRelGtEqAdapter(); } @Override public Adapter caseRelEq(RelEq object) { return createRelEqAdapter(); } @Override public Adapter caseRelLt(RelLt object) { return createRelLtAdapter(); } @Override public Adapter caseRelGt(RelGt object) { return createRelGtAdapter(); } @Override public Adapter casePlus(Plus object) { return createPlusAdapter(); } @Override public Adapter caseMinus(Minus object) { return createMinusAdapter(); } @Override public Adapter caseMulti(Multi object) { return createMultiAdapter(); } @Override public Adapter caseDiv(Div object) { return createDivAdapter(); } @Override public Adapter casePow(Pow object) { return createPowAdapter(); } @Override public Adapter caseFunctionRef(FunctionRef object) { return createFunctionRefAdapter(); } @Override public Adapter caseIntLiteral(IntLiteral object) { return createIntLiteralAdapter(); } @Override public Adapter caseStringLiteral(StringLiteral object) { return createStringLiteralAdapter(); } @Override public Adapter caseBooleanLiteral(BooleanLiteral object) { return createBooleanLiteralAdapter(); } @Override public Adapter defaultCase(EObject object) { return createEObjectAdapter(); } }; /** * Creates an adapter for the <code>target</code>. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param target the object to adapt. * @return the adapter for the <code>target</code>. * @generated */ @Override public Adapter createAdapter(Notifier target) { return modelSwitch.doSwitch((EObject)target); } /** * Creates a new adapter for an object of class '{@link uk.ac.open.event.eventcalculus.Model <em>Model</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see uk.ac.open.event.eventcalculus.Model * @generated */ public Adapter createModelAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link uk.ac.open.event.eventcalculus.Import <em>Import</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see uk.ac.open.event.eventcalculus.Import * @generated */ public Adapter createImportAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link uk.ac.open.event.eventcalculus.Annotation <em>Annotation</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see uk.ac.open.event.eventcalculus.Annotation * @generated */ public Adapter createAnnotationAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link uk.ac.open.event.eventcalculus.Declaration <em>Declaration</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see uk.ac.open.event.eventcalculus.Declaration * @generated */ public Adapter createDeclarationAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link uk.ac.open.event.eventcalculus.Defines <em>Defines</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see uk.ac.open.event.eventcalculus.Defines * @generated */ public Adapter createDefinesAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link uk.ac.open.event.eventcalculus.DefSort <em>Def Sort</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see uk.ac.open.event.eventcalculus.DefSort * @generated */ public Adapter createDefSortAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link uk.ac.open.event.eventcalculus.DefRange <em>Def Range</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see uk.ac.open.event.eventcalculus.DefRange * @generated */ public Adapter createDefRangeAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link uk.ac.open.event.eventcalculus.DefOption <em>Def Option</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see uk.ac.open.event.eventcalculus.DefOption * @generated */ public Adapter createDefOptionAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link uk.ac.open.event.eventcalculus.DefCompletion <em>Def Completion</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see uk.ac.open.event.eventcalculus.DefCompletion * @generated */ public Adapter createDefCompletionAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link uk.ac.open.event.eventcalculus.DefNonInertia <em>Def Non Inertia</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see uk.ac.open.event.eventcalculus.DefNonInertia * @generated */ public Adapter createDefNonInertiaAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link uk.ac.open.event.eventcalculus.DefXor <em>Def Xor</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see uk.ac.open.event.eventcalculus.DefXor * @generated */ public Adapter createDefXorAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link uk.ac.open.event.eventcalculus.DefMutex <em>Def Mutex</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see uk.ac.open.event.eventcalculus.DefMutex * @generated */ public Adapter createDefMutexAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link uk.ac.open.event.eventcalculus.Statement <em>Statement</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see uk.ac.open.event.eventcalculus.Statement * @generated */ public Adapter createStatementAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link uk.ac.open.event.eventcalculus.LabeledExpression <em>Labeled Expression</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see uk.ac.open.event.eventcalculus.LabeledExpression * @generated */ public Adapter createLabeledExpressionAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link uk.ac.open.event.eventcalculus.SortDefinition <em>Sort Definition</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see uk.ac.open.event.eventcalculus.SortDefinition * @generated */ public Adapter createSortDefinitionAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link uk.ac.open.event.eventcalculus.Definition <em>Definition</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see uk.ac.open.event.eventcalculus.Definition * @generated */ public Adapter createDefinitionAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link uk.ac.open.event.eventcalculus.Expression <em>Expression</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see uk.ac.open.event.eventcalculus.Expression * @generated */ public Adapter createExpressionAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link uk.ac.open.event.eventcalculus.Qualifier <em>Qualifier</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see uk.ac.open.event.eventcalculus.Qualifier * @generated */ public Adapter createQualifierAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link uk.ac.open.event.eventcalculus.Parameters <em>Parameters</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see uk.ac.open.event.eventcalculus.Parameters * @generated */ public Adapter createParametersAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link uk.ac.open.event.eventcalculus.TerminalExpression <em>Terminal Expression</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see uk.ac.open.event.eventcalculus.TerminalExpression * @generated */ public Adapter createTerminalExpressionAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link uk.ac.open.event.eventcalculus.AssignPlus <em>Assign Plus</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see uk.ac.open.event.eventcalculus.AssignPlus * @generated */ public Adapter createAssignPlusAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link uk.ac.open.event.eventcalculus.AssignMin <em>Assign Min</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see uk.ac.open.event.eventcalculus.AssignMin * @generated */ public Adapter createAssignMinAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link uk.ac.open.event.eventcalculus.Or <em>Or</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see uk.ac.open.event.eventcalculus.Or * @generated */ public Adapter createOrAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link uk.ac.open.event.eventcalculus.And <em>And</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see uk.ac.open.event.eventcalculus.And * @generated */ public Adapter createAndAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link uk.ac.open.event.eventcalculus.RelNotEq <em>Rel Not Eq</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see uk.ac.open.event.eventcalculus.RelNotEq * @generated */ public Adapter createRelNotEqAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link uk.ac.open.event.eventcalculus.RelEqEq <em>Rel Eq Eq</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see uk.ac.open.event.eventcalculus.RelEqEq * @generated */ public Adapter createRelEqEqAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link uk.ac.open.event.eventcalculus.RelLtEq <em>Rel Lt Eq</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see uk.ac.open.event.eventcalculus.RelLtEq * @generated */ public Adapter createRelLtEqAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link uk.ac.open.event.eventcalculus.RelGtEq <em>Rel Gt Eq</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see uk.ac.open.event.eventcalculus.RelGtEq * @generated */ public Adapter createRelGtEqAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link uk.ac.open.event.eventcalculus.RelEq <em>Rel Eq</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see uk.ac.open.event.eventcalculus.RelEq * @generated */ public Adapter createRelEqAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link uk.ac.open.event.eventcalculus.RelLt <em>Rel Lt</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see uk.ac.open.event.eventcalculus.RelLt * @generated */ public Adapter createRelLtAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link uk.ac.open.event.eventcalculus.RelGt <em>Rel Gt</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see uk.ac.open.event.eventcalculus.RelGt * @generated */ public Adapter createRelGtAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link uk.ac.open.event.eventcalculus.Plus <em>Plus</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see uk.ac.open.event.eventcalculus.Plus * @generated */ public Adapter createPlusAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link uk.ac.open.event.eventcalculus.Minus <em>Minus</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see uk.ac.open.event.eventcalculus.Minus * @generated */ public Adapter createMinusAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link uk.ac.open.event.eventcalculus.Multi <em>Multi</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see uk.ac.open.event.eventcalculus.Multi * @generated */ public Adapter createMultiAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link uk.ac.open.event.eventcalculus.Div <em>Div</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see uk.ac.open.event.eventcalculus.Div * @generated */ public Adapter createDivAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link uk.ac.open.event.eventcalculus.Pow <em>Pow</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see uk.ac.open.event.eventcalculus.Pow * @generated */ public Adapter createPowAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link uk.ac.open.event.eventcalculus.FunctionRef <em>Function Ref</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see uk.ac.open.event.eventcalculus.FunctionRef * @generated */ public Adapter createFunctionRefAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link uk.ac.open.event.eventcalculus.IntLiteral <em>Int Literal</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see uk.ac.open.event.eventcalculus.IntLiteral * @generated */ public Adapter createIntLiteralAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link uk.ac.open.event.eventcalculus.StringLiteral <em>String Literal</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see uk.ac.open.event.eventcalculus.StringLiteral * @generated */ public Adapter createStringLiteralAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link uk.ac.open.event.eventcalculus.BooleanLiteral <em>Boolean Literal</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see uk.ac.open.event.eventcalculus.BooleanLiteral * @generated */ public Adapter createBooleanLiteralAdapter() { return null; } /** * Creates a new adapter for the default case. * <!-- begin-user-doc --> * This default implementation returns null. * <!-- end-user-doc --> * @return the new adapter. * @generated */ public Adapter createEObjectAdapter() { return null; } } //EventcalculusAdapterFactory
11,198
https://github.com/Kethsar/twitter_image_links/blob/master/twitter_open_profile_from_image.user.js
Github Open Source
Open Source
MIT
2,021
twitter_image_links
Kethsar
JavaScript
Code
176
571
// ==UserScript== // @name Twitter-Profile-From-Image-Link // @description Middle-Click image to open the user's twitter profile in a new tab if the username is set as the link hash // @author Kethsar // @version 1.0 // @match https://pbs.twimg.com/media/* // @grant GM_openInTab // @grant GM.openInTab // @updateURL https://raw.githubusercontent.com/Kethsar/twitter_image_links/master/twitter_open_profile_from_image.user.js // @downloadURL https://raw.githubusercontent.com/Kethsar/twitter_image_links/master/twitter_open_profile_from_image.user.js // ==/UserScript== (function() { 'use strict'; /* * This script is a companion to the twitter and tweetdeck scripts * that add allow you to copy image links with the user name * https://github.com/Kethsar/twitter_image_links */ const MIDDLE_CLICK = 1; var openTab = null; function init() { if (GM_openInTab) { openTab = GM_openInTab; } else if (typeof(GM) != "undefined" && GM.openInTab) { openTab = GM.openInTab; } else { console.log("Tab opening function not found"); return; } registerHandler(); } function registerHandler() { if (window.location.hash != "") { let uname = window.location.hash.replace(/^#@/, ""); if (uname) { let img = document.getElementsByTagName("img")[0]; img.addEventListener("mouseup", function(e){ // For whatever reason, middle-clicking doesn't fire the event. Left click it is then if (e.button == MIDDLE_CLICK) { openTab("https://twitter.com/" + uname); } }); } } } init(); })();
34,454
https://github.com/SnelStartSoftware/B2B.client.v2.net/blob/master/SnelStart.B2B.V2.Client/Operations/Artikelen/IArtikelenOperations.cs
Github Open Source
Open Source
MIT
2,020
B2B.client.v2.net
SnelStartSoftware
C#
Code
31
124
using System; using System.Threading; using System.Threading.Tasks; namespace SnelStart.B2B.V2.Client.Operations { public interface IArtikelenOperations : ICrudOperations<ArtikelModel>, IGetAllOperations<ArtikelModel>, IQueryOperations<ArtikelModel> { Task<Response<ArtikelModel>> GetByIdAsync(Guid id, string queryString); Task<Response<ArtikelModel>> GetByIdAsync(Guid id, string queryString, CancellationToken cancellationToken); } }
20,322
https://github.com/TotalCross/skia/blob/master/tests/sksl/shared/Assignment.glsl
Github Open Source
Open Source
BSD-3-Clause
null
skia
TotalCross
GLSL
Code
74
285
out vec4 sk_FragColor; uniform vec4 colorGreen; vec4 main() { ivec4 i4; i4 = ivec4(1, 2, 3, 4); vec4 x; x.w = 0.0; x.yx = vec2(0.0); int ai[1]; ai[0] = 0; ivec4 ai4[1]; ai4[0] = ivec4(1, 2, 3, 4); mat3 ah2x4[1]; ah2x4[0] = mat3(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0); vec4 af4[1]; af4[0].x = 0.0; af4[0].ywxz = vec4(1.0); ai[0] += ai4[0].x; af4[0] *= ah2x4[0][0].x; i4.y *= 0; x.y *= 0.0; return colorGreen; }
23,920
https://github.com/GimoXagros/morebobs/blob/master/morebobs_shiny_0.16.1/morebobs_shiny_0.16.1/data-final-fixes.lua
Github Open Source
Open Source
MIT
2,020
morebobs
GimoXagros
Lua
Code
3
21
-- moreshinybobs require('prototypes/moreshinybobs')
24,321
https://github.com/voelkerb/iHouse/blob/master/iHouseRemote/iHouseRemote/Device.m
Github Open Source
Open Source
MIT
2,017
iHouse
voelkerb
Objective-C
Code
248
753
// // Device.m // iHouseRemote // // Created by Benjamin Völker on 05/01/2017. // Copyright © 2017 Benjamin Völker. All rights reserved. // #import "Device.h" @implementation Device @synthesize image, name, type, info; /* * Init function */ - (id)init { if((self = [super init])) { image = [UIImage imageNamed:@"devices_256"]; name = [[NSString alloc] initWithFormat:@"New Device"]; type = light; info = [[NSMutableDictionary alloc] init]; } return self; } - (void)encodeWithCoder:(NSCoder *)encoder { //Encode properties, other class variables, etc [encoder encodeObject:self.image forKey:@"image"]; [encoder encodeObject:self.name forKey:@"name"]; [encoder encodeInteger:self.type forKey:@"type"]; [encoder encodeObject:self.info forKey:@"info"]; } - (id)initWithCoder:(NSCoder *)decoder { if((self = [super init])) { //decode properties, other class vars self.image = [decoder decodeObjectForKey:@"image"]; self.name = [decoder decodeObjectForKey:@"name"]; self.type = [decoder decodeIntegerForKey:@"type"]; self.info = [decoder decodeObjectForKey:@"info"]; } return self; } /* * Return string with readable name for the given device type */ - (NSString*)deviceTypeToString { return [self DeviceTypeToString:self.type]; } - (NSString*)DeviceTypeToString:(DeviceType) theType{ NSString *result = nil; switch(theType) { case light: result = @"Light"; break; case switchableSocket: result = @"Socket"; break; case meter: result = @"Meter"; break; case sensor: result = @"Sensor"; break; case heating: result = @"Heating"; break; case hoover: result = @"Hoover"; break; case display: result = @"Display"; break; case speaker: result = @"Speaker"; break; case microphone: result = @"Microphone"; break; case iPadDisplay: result = @"Touch Display"; break; case coffee: result = @"Coffee Machine"; break; case ir: result = @"Infrared Remote"; break; case differentDeviceCount: result = @"Total number of different devices"; break; default: [NSException raise:NSGenericException format:@"Unexpected MODE."]; } return result; } @end
28,923
https://github.com/Vestmark/vestmark-gradle/blob/master/subprojects/docs/src/samples/play/custom-distribution/scripts/runPlayBinaryAsUser.sh
Github Open Source
Open Source
Apache-2.0
2,022
vestmark-gradle
Vestmark
Shell
Code
25
92
#!/bin/bash RUNASUSER=$1 if test "${RUNASUSER}" = "" then echo "Usage: `basename $0` <username>" exit 1 fi SCRIPTDIR=`dirname $0` SCRIPTDIR=`cd ${SCRIPTDIR}; pwd` sudo -u ${RUNASUSER} ${SCRIPTDIR}/playBinary
9,523
https://github.com/fredgrott/base_statewidget/blob/master/lib/app/common/logging/types.dart
Github Open Source
Open Source
BSD-3-Clause
null
base_statewidget
fredgrott
Dart
Code
41
104
// Copyright(c) 2021 Fredrick Allan Grott. All rights reserved. // Use of this source code is governed by a BSD-style license. import 'package:logging/logging.dart'; abstract class LoggerType { Logger get logger; } extension LoggerSpawner on LoggerType{ Logger newLogger(String name) => Logger('${logger.fullName}.$name'); }
25,341
https://github.com/omerwwazap/Java-Projects/blob/master/Java_Simple_Code/L12_Inheritance_demo/AnimalMain.java
Github Open Source
Open Source
MIT
2,020
Java-Projects
omerwwazap
Java
Code
300
961
package labguide12.q1; import java.util.Scanner; public class AnimalMain { /** * @param args the command line arguments */ public static void main(String[] args) { Duck duck; Zebra zebra; int age, id, stripeCount; String gender, beakColor; double weight; Scanner input = new Scanner(System.in); String animalType; do { System.out.println("Which animal do you want to add?(Write Stop to Stop)"); System.out.println("(Duck - Zebra)"); animalType = input.next(); //input.skip("\n"); if (!animalType.equalsIgnoreCase("stop")) { if (animalType.equalsIgnoreCase("duck")) { System.out.println("\n***Enter the Info of Duck*** "); System.out.print("Enter ID: "); id = input.nextInt(); System.out.print("Enter age: "); age = input.nextInt(); System.out.print("Enter the gender of duck:(Female/Male)"); gender = input.next(); input.skip("\n"); System.out.print("Enter the weight: "); weight = input.nextDouble(); System.out.print("Enter beak color: "); beakColor = input.next(); duck = new Duck(beakColor, id, age, gender, weight); AnimalList.addAnimal(duck); } else if (animalType.equalsIgnoreCase("zebra")) { System.out.println("\n***Enter the Info of Zebra*** "); System.out.print("Enter ID: "); id = input.nextInt(); System.out.print("Enter age: "); age = input.nextInt(); System.out.print("Enter the gender of zebra:(Female/Male)"); gender = input.next(); System.out.print("Enter the weight: "); weight = input.nextDouble(); System.out.print("Enter stripe count: "); stripeCount = input.nextInt(); zebra = new Zebra(stripeCount, id, age, gender, weight); AnimalList.addAnimal(zebra); } } } while (!animalType.equalsIgnoreCase("stop")); //Display all animals for (int j = 0; j < AnimalList.getAllAnimals().size(); j++) { System.out.println(AnimalList.getAllAnimals().get(j).toString()); } //remove System.out.println("\n\nEnter the ID of the animal to REMOVE......."); System.out.print("Remove by ID: "); id = input.nextInt(); if (AnimalList.removeAnimal(id)) { System.out.println("The object that matches the criteria were successfully removed from the list."); } else { System.out.println("Error: No such object was in the list."); } //search System.out.println("\n\nEnter the ID of the objects to SEARCH......."); System.out.print("Search by ID: "); id = input.nextInt(); if (AnimalList.searchAnimal(id) == null) { System.out.println("There is no such ID in the list..!"); } else { AnimalList.searchAnimal(id).getClass(); System.out.println("The ID number: " + id + " has been found in the list."); } //Display all animals for (int j = 0; j < AnimalList.getAllAnimals().size(); j++) { System.out.println(AnimalList.getAllAnimals().get(j).toString()); } } }
16,008
https://github.com/dizhaung/SkaETL/blob/master/process-importer-impl/src/main/java/io/skalogs/skaetl/service/GenericValidator.java
Github Open Source
Open Source
Apache-2.0
2,018
SkaETL
dizhaung
Java
Code
334
1,517
package io.skalogs.skaetl.service; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.util.ISO8601DateFormat; import io.prometheus.client.Counter; import io.skalogs.skaetl.domain.*; import io.skalogs.skaetl.service.validate.*; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang.StringUtils; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import java.io.IOException; import java.text.ParseException; import java.util.ArrayList; import java.util.Date; import java.util.List; import static io.skalogs.skaetl.service.UtilsValidateData.createValidateData; import static java.util.stream.Collectors.toList; @Component @Slf4j public class GenericValidator { private static final Counter nbMandatoryImporter = Counter.build() .name("skaetl_nb_mandatory_importer") .labelNames("type") .help("nb message not json.") .register(); private final ISO8601DateFormat dateFormat = new ISO8601DateFormat(); private final ObjectMapper objectMapper = new ObjectMapper(); private List<ValidatorProcess> listValidator = new ArrayList<>(); @PostConstruct public void init() { listValidator.add(new BlackListValidator(TypeValidation.BLACK_LIST_FIELD)); listValidator.add(new MandatoryFieldValidator(TypeValidation.MANDATORY_FIELD)); listValidator.add(new MaxFieldValidator(TypeValidation.MAX_FIELD)); listValidator.add(new MaxMessageSizeValidator(TypeValidation.MAX_MESSAGE_SIZE)); listValidator.add(new FieldExistValidator(TypeValidation.FIELD_EXIST)); } public JsonNode createJsonObject(String value) { try { return objectMapper.readTree(value); } catch (IOException e) { nbMandatoryImporter.labels("jsonFormat").inc(); return null; } } public ValidateData mandatoryImporter(String value, ObjectNode jsonValue) { //JSON if (jsonValue == null) { nbMandatoryImporter.labels("jsonFormat").inc(); return createValidateData(false, StatusCode.invalid_json, TypeValidation.FORMAT_JSON, value); } //PROJECT String project = jsonValue.path("project").asText(); if (StringUtils.isBlank(project)) { nbMandatoryImporter.labels("project").inc(); return createValidateData(false, StatusCode.missing_mandatory_field_project, TypeValidation.MANDATORY_FIELD, value, "missing project"); } //TYPE String type = jsonValue.path("type").asText(); if (StringUtils.isBlank(type)) { nbMandatoryImporter.labels("type").inc(); return createValidateData(false, StatusCode.missing_mandatory_field_type, TypeValidation.MANDATORY_FIELD, value, "missing type"); } //TIMESTAMP String timestampAnnotedAsString = jsonValue.path("@timestamp").asText(); String timestampAsString = jsonValue.path("timestamp").asText(); if (StringUtils.isBlank(timestampAsString) && StringUtils.isBlank(timestampAnnotedAsString)) { return createValidateData(project, type, false, StatusCode.missing_timestamp, TypeValidation.MANDATORY_FIELD, value); } Date timestamp; try { if (StringUtils.isBlank(timestampAsString)) { timestamp = dateFormat.parse(timestampAnnotedAsString); jsonValue.set("timestamp", jsonValue.path("@timestamp")); } else { timestamp = dateFormat.parse(timestampAsString); } } catch (ParseException e) { return createValidateData(jsonValue, project, type, false, StatusCode.invalid_format_timestamp, TypeValidation.MANDATORY_FIELD, value); } return createValidateData(jsonValue, timestamp, project, type, true, value); } public ValidateData process(String value, ProcessConsumer processConsumer) { ObjectNode jsonValue = (ObjectNode) createJsonObject(value); ValidateData validateMandatory = mandatoryImporter(value, jsonValue); if (!validateMandatory.success) { return createValidateData(false, validateMandatory.statusCode, validateMandatory.errorList, TypeValidation.MANDATORY_FIELD, value); } List<ValidateData> result = treat(value, jsonValue, processConsumer); List<ValidateData> listNotSuccess = result.stream().filter(e -> !e.success).collect(toList()); if (!listNotSuccess.isEmpty()) { return createValidateData(false, validateMandatory.statusCode, listNotSuccess.stream().map(e -> e.getStatusCode()).collect(toList()), TypeValidation.MANDATORY_FIELD, value); } return ValidateData.builder() .success(true) .jsonValue(jsonValue) .type(validateMandatory.type) .project(validateMandatory.project) .timestamp(validateMandatory.timestamp) .value(value).build(); } public List<ValidateData> treat(String value, JsonNode jsonValue, ProcessConsumer processConsumer) { List<ValidateData> result = new ArrayList<>(); if (processConsumer.getProcessValidation() != null && !processConsumer.getProcessValidation().isEmpty()) { for (ProcessValidation pv : processConsumer.getProcessValidation()) { listValidator.stream() .filter(e -> e.type(pv.getTypeValidation())) .forEach(e -> result.add(e.process(pv, jsonValue, value))); } } return result; } }
16,085
https://github.com/GCrispino/aprenda-go-com-testes/blob/master/criando-uma-aplicacao/linha-de-comando/v1/tape_test.go
Github Open Source
Open Source
MIT
2,021
aprenda-go-com-testes
GCrispino
Go
Code
47
181
package poquer import ( "io/ioutil" "testing" ) func TestTape_Write(t *testing.T) { arquivo, clean := criarArquivoTemporario(t, "12345") defer clean() tape := &tape{arquivo} tape.Write([]byte("abc")) arquivo.Seek(0, 0) newFileContents, _ := ioutil.ReadAll(arquivo) obtido := string(newFileContents) esperado := "abc" if obtido != esperado { t.Errorf("recebi '%s' esperava '%s'", obtido, esperado) } }
41,269
https://github.com/alexnogueirasilva/alanti/blob/master/index.php
Github Open Source
Open Source
MIT
null
alanti
alexnogueirasilva
PHP
Code
75
290
<?php use App\App; use App\Lib\Erro; session_start(); /* if (!isset($_SESSION['usuarioID'])) { //Verifica se há seções session_destroy(); //Destroi a seção por segurança header("Location: SOMVC/login.php"); exit; //Redireciona o visitante para login } */ error_reporting(E_ALL & ~E_NOTICE); require_once("vendor/autoload.php"); try { $app = new App(); $app->run(); }catch (\Exception $e){ $oError = new Erro($e); $oError->render(); } $registro = $_SESSION['registro']; $limite = $_SESSION['limite']; if($registro){ $segundos = time()- $registro; } if($segundos>$limite){ session_destroy(); //header("Location: ../index.php"); } else{ $_SESSION['registro'] = time(); } $andre = date('Y-m-d-H:i:s');
15,710
https://github.com/visheshc14/Evangelion/blob/master/views/channels/new.ejs
Github Open Source
Open Source
MIT
2,021
Evangelion
visheshc14
EJS
Code
102
763
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>New Channel</title> <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <link rel="stylesheet" href="../styles/index.css"> </head> <body> <div class="container"> <div class="row"> <div class="col-md-6 offset-md-3"> <div class="card mt-5"> <div class="card-header"> <h4>Create a new channel</h4> </div> <form action="/channels" method="post"> <div class="card-body"> <label for="">Channel Name</label> <input type="text" class="form-control" name="name" placeholder="Enter a name for your channel."> <br> <input type="radio" name="type" value="public" checked> <label for="">Public</label> <input type="radio" name="type" value="private"> <label for="">Private</label> </div> <div class="card-footer"> <input type="submit" value="Create Channel" class="btn btn-primary btn-block"> </div> </form> </div> </div> </div> </div> </body> </html>
18,026
https://github.com/sdlirjc/algorithm/blob/master/js/csv-read-display/node_modules/@vaadin/common-frontend/ConnectionState.js
Github Open Source
Open Source
Apache-2.0
2,023
algorithm
sdlirjc
JavaScript
Code
433
1,135
var _a; export var ConnectionState; (function (ConnectionState) { /** * Application is connected to server: last transaction over the wire (XHR / * heartbeat / endpoint call) was successful. */ ConnectionState["CONNECTED"] = "connected"; /** * Application is connected and Flow is loading application state from the * server, or Fusion is waiting for an endpoint call to return. */ ConnectionState["LOADING"] = "loading"; /** * Application has been temporarily disconnected from the server because the * last transaction over the wire (XHR / heartbeat / endpoint call) resulted * in a network error, or the browser has received the 'online' event and needs * to verify reconnection with the server. Flow is attempting to reconnect * a configurable number of times before giving up. */ ConnectionState["RECONNECTING"] = "reconnecting"; /** * Application has been permanently disconnected due to browser receiving the * 'offline' event, or the server not being reached after a number of reconnect * attempts. */ ConnectionState["CONNECTION_LOST"] = "connection-lost"; })(ConnectionState || (ConnectionState = {})); export class ConnectionStateStore { constructor(initialState) { this.stateChangeListeners = new Set(); this.loadingCount = 0; this.connectionState = initialState; this.serviceWorkerMessageListener = this.serviceWorkerMessageListener.bind(this); if (navigator.serviceWorker) { // Query service worker if the most recent fetch was served from cache // Add message listener for handling response navigator.serviceWorker.addEventListener('message', this.serviceWorkerMessageListener); // Send JSON-RPC request to Vaadin service worker navigator.serviceWorker.ready.then((registration) => { var _a; (_a = registration === null || registration === void 0 ? void 0 : registration.active) === null || _a === void 0 ? void 0 : _a.postMessage({ method: 'Vaadin.ServiceWorker.isConnectionLost', id: 'Vaadin.ServiceWorker.isConnectionLost', }); }); } } addStateChangeListener(listener) { this.stateChangeListeners.add(listener); } removeStateChangeListener(listener) { this.stateChangeListeners.delete(listener); } loadingStarted() { this.state = ConnectionState.LOADING; this.loadingCount += 1; } loadingFinished() { this.decreaseLoadingCount(ConnectionState.CONNECTED); } loadingFailed() { this.decreaseLoadingCount(ConnectionState.CONNECTION_LOST); } decreaseLoadingCount(finalState) { if (this.loadingCount > 0) { this.loadingCount -= 1; if (this.loadingCount === 0) { this.state = finalState; } } } get state() { return this.connectionState; } set state(newState) { if (newState !== this.connectionState) { const prevState = this.connectionState; this.connectionState = newState; this.loadingCount = 0; for (const listener of this.stateChangeListeners) { listener(prevState, this.connectionState); } } } get online() { return this.connectionState === ConnectionState.CONNECTED || this.connectionState === ConnectionState.LOADING; } get offline() { return !this.online; } serviceWorkerMessageListener(event) { // Handle JSON-RPC response from service worker if (typeof event.data === 'object' && event.data.id === 'Vaadin.ServiceWorker.isConnectionLost') { if (event.data.result === true) { this.state = ConnectionState.CONNECTION_LOST; } // Cleanup: remove event listener upon receiving response navigator.serviceWorker.removeEventListener('message', this.serviceWorkerMessageListener); } } } const $wnd = window; if (!((_a = $wnd.Vaadin) === null || _a === void 0 ? void 0 : _a.connectionState)) { $wnd.Vaadin = $wnd.Vaadin || {}; $wnd.Vaadin.connectionState = new ConnectionStateStore(navigator.onLine ? ConnectionState.CONNECTED : ConnectionState.CONNECTION_LOST); } //# sourceMappingURL=ConnectionState.js.map
25,006
https://github.com/crazyants/forum/blob/master/Forum3/Interfaces/Services/IImageStore.cs
Github Open Source
Open Source
Unlicense
2,018
forum
crazyants
C#
Code
18
67
using System.Threading.Tasks; namespace Forum3.Interfaces.Services { using ServiceModels = Forum3.Models.ServiceModels; public interface IImageStore { Task<string> StoreImage(ServiceModels.ImageStoreOptions options); } }
2,946
https://github.com/SuperCuber/dotfiles/blob/master/nvim/lua/supercuber/plugins/telescope.lua
Github Open Source
Open Source
WTFPL
2,022
dotfiles
SuperCuber
Lua
Code
86
412
local util = require("supercuber.util") util.nnoremap(",e", "<cmd>Telescope find_files<cr>") util.nnoremap(",/", "<cmd>Telescope live_grep<cr>") util.nnoremap(",*", "<cmd>Telescope grep_string<cr>") util.nnoremap(",b", "<cmd>Telescope buffers<cr>") util.nnoremap(",cd", "<cmd>call v:lua.cd_picker()<cr>") local actions = require("telescope.actions") require("telescope").setup({ defaults = { mappings = { i = { ["<esc>"] = actions.close } } } }) _G.cd_picker = function() require("telescope.pickers").new({}, { prompt_title = "Change Directory", finder = require("telescope.finders").new_oneshot_job({"fd", "-a", "--type", "d"}, {cwd = "{{#if vim_root_dir}}{{vim_root_dir}}{{else}}~{{/if}}"}), previewer = nil, sorter = require("telescope.config").values.file_sorter(opts), attach_mappings = function(prompt_bufnr, map) local function change_directory() actions.close(prompt_bufnr) vim.api.nvim_command("cd " .. require("telescope.actions.state").get_selected_entry()[1]) end map("i", "<cr>", change_directory) return true end }):find() end
20,272
https://github.com/fuszenecker/Promptuarium/blob/master/tests/StabilityTests.cs
Github Open Source
Open Source
MIT
null
Promptuarium
fuszenecker
C#
Code
242
737
using System; using System.IO; using System.Threading.Tasks; using Microsoft.VisualStudio.TestTools.UnitTesting; using Promptuarium; namespace PromptuariumTests { [TestClass] public class StabilityTests { private readonly Random random = new ((int)DateTime.Now.Ticks); [TestMethod] public async Task Stability() { const int maxTests = 10000; const int minChildren = 0; const int maxChildren = 10; const double probability = 0.75; await CreateAndVerifyTrees(maxTests, minChildren, maxChildren, probability, @".\stability.p").ConfigureAwait(false); } [TestMethod] public async Task BigTrees() { const int maxTests = 10; const int minChildren = 0; const int maxChildren = 20; const double probability = 0.95; await CreateAndVerifyTrees(maxTests, minChildren, maxChildren, probability, @".\big_trees.p").ConfigureAwait(false); } private Element GenerateTree(int minimumChildren, int maximumChildren, double probability) { var root = new Element(); GenerateTree(root, minimumChildren, maximumChildren, probability); return root; } private void GenerateTree(Element node, int minimumChildren, int maximumChildren, double probability, int level = 0) { if (random.NextDouble() < probability) { int numChildren = random.Next(maximumChildren - minimumChildren) + minimumChildren; for (int x = 0; x < numChildren; x++) { var nodeGuid = Guid.NewGuid(); var child = new Element() { MetaData = Data.FromAsciiString(nodeGuid.ToString("N")), Data = Data.FromUtf8String(string.Format("LEVEL: {0}, NODE: {1}", level, nodeGuid)) }; GenerateTree(child, minimumChildren, maximumChildren, probability * probability, level++); node.Add(child); } } } private async Task CreateAndVerifyTrees(int maxTests, int minChildren, int maxChildren, double probability, string fileName) { for (int x = 0; x < maxTests; x++) { Element originalTree = GenerateTree(minChildren, maxChildren, probability); string originalTreeString = originalTree.TreeToString(); await originalTree.SaveAsync(fileName).ConfigureAwait(false); Statistics stats = originalTree.GetStatistics(); Assert.IsTrue(new FileInfo(fileName).Length > 0); Element currentTree = await Element.LoadAsync(fileName).ConfigureAwait(false); string currentTreeString = currentTree.TreeToString(); Assert.AreEqual(originalTreeString, currentTreeString); } } } }
3,270
https://github.com/Nov11/statsd-client/blob/master/src/main/java/io/github/nov11/MetricSender.java
Github Open Source
Open Source
MIT
null
statsd-client
Nov11
Java
Code
12
35
package io.github.nov11; public interface MetricSender { void send(String msg); void shutdown(); }
49,664
https://github.com/baretata/JavaScript-Fundamentals/blob/master/08.Strings/04.ChangeTextCase/ChangeTextCase.js
Github Open Source
Open Source
MIT
null
JavaScript-Fundamentals
baretata
JavaScript
Code
255
740
/* Problem 4: You are given a text. Write a function that changes the text in all regions: <upcase>text</upcase> to uppercase. <lowcase>text</lowcase> to lowercase <mixcase>text</mixcase> to mix casing(random) We are <mixcase>living</mixcase> in a <upcase>yellow submarine</upcase>. We <mixcase>don't</mixcase> have <lowcase>anything</lowcase> else. The expected result: We are LiVinG in a YELLOW SUBMARINE. We dOn'T have anything else. Regions can be nested. */ function getReplacedTextRegions(text) { text = String(text); var answer = "", cases = [], currLetter, j, i; function mixCase(letter) { var upper = Math.random() < 0.5; if (upper) { return letter.toUpperCase(); } else { return letter.toLowerCase(); } } function lowCase(letter) { return letter.toLowerCase(); } function upCase(letter) { return letter.toUpperCase(); } for (i = 0; i < text.length; i+=1) { if (text[i] == '<') { i++; if (text[i] == "/") { cases.pop(); while (text[i] != '>') { i++; } } else if (text[i] == 'm') { cases.push(mixCase); while (text[i] != '>') { i++; } } else if (text[i] == 'u') { cases.push(upCase); while (text[i] != '>') { i++; } } else if (text[i] == 'l') { cases.push(lowCase); while (text[i] != '>') { i++; } } else { alert(i + "Something wrong at this index mr Developer"); } } else { if (cases.length == 0) { answer += text[i]; } else { currLetter = text[i]; for (j = cases.length - 1; j >= 0; j-=1) { currLetter = cases[j](currLetter); } answer += currLetter; } } } return answer; } var text = "We are <mixcase>living</mixcase> in a <upcase>yellow submarine</upcase>. We <mixcase>don't</mixcase> have <lowcase>anything</lowcase> else.", changed = getReplacedTextRegions(text); console.log(changed);
37,070
https://github.com/PaloAltoNetworks/a3s/blob/master/ui/login/src/jwt-dialog.tsx
Github Open Source
Open Source
Apache-2.0
2,022
a3s
PaloAltoNetworks
TypeScript
Code
288
1,029
import { Alert, AlertTitle, Button, Dialog, DialogActions, DialogContent, DialogContentText, Divider, Stack, Typography, useMediaQuery, } from "@mui/material" import { useEffect, useState } from "react" import { useVerifyJwt } from "./use-verify-jwt" import { formatDuration, intervalToDuration } from "date-fns" export const JwtDialog = ({ payload, token, onClose, }: { payload: Record<string, any> token: string onClose(): void }) => { const fullScreen = useMediaQuery("(max-width: 600px)") const [isValid, setIsValid] = useState<boolean>() const [error, setError] = useState<string>() const [currentTimeInMs, setCurrentTimeInMs] = useState<number>(Date.now()) useEffect(() => { const intervalTimer = setInterval(() => { setCurrentTimeInMs(Date.now()) }, 1000) return () => { clearInterval(intervalTimer) } }, []) const expInMs = payload.exp * 1000 const isExpired = expInMs < currentTimeInMs const lifetime = isExpired ? "" : formatDuration( intervalToDuration({ start: currentTimeInMs, end: expInMs, }) ) const verifyJwt = useVerifyJwt() useEffect(() => { if (!isExpired) { verifyJwt({ token }) .then(isValid => { setIsValid(isValid) if (!isValid) { throw Error(`Signature doesn't match`) } }) .catch(err => { setIsValid(false) if (err instanceof Error) { setError(err.message) } }) } else { setIsValid(false) setError("Token has expired") } }, [token, isExpired]) return ( <Dialog open fullScreen={fullScreen}> {/* <DialogTitle>Decoded JWT</DialogTitle> */} <DialogContent sx={{ mt: 1 }}> {isValid === undefined ? null : isValid ? ( <Alert variant="outlined" severity="success"> <AlertTitle>Signature Verified</AlertTitle> Issuer: {payload.iss} </Alert> ) : ( <Alert variant="outlined" severity="error"> <AlertTitle>Signature Verification Failed</AlertTitle> {error} </Alert> )} <Typography variant="h6" mt={3} mb={1}> Claims </Typography> <Stack direction="column" spacing={0.5} divider={<Divider />} py={1} px={2} borderRadius={1} overflow="auto" bgcolor="action.hover" > {payload.identity.map((claim: string) => ( <Typography key={claim}>{claim}</Typography> ))} </Stack> <Typography variant="h6" mt={3} mb={1}> Audiences </Typography> <Stack direction="column" spacing={0.5} divider={<Divider />} py={1} px={2} borderRadius={1} overflow="auto" bgcolor="action.hover" > {payload.aud.map((audience: string) => ( <Typography key={audience}>{audience}</Typography> ))} </Stack> {!isExpired && ( <DialogContentText mt={3}> Token will expire in {lifetime}. </DialogContentText> )} </DialogContent> <DialogActions> <Button onClick={onClose} variant="contained"> Close </Button> </DialogActions> </Dialog> ) }
48,108
https://github.com/MatjazKavcic/chartjs-plugin-datalabels/blob/master/test/specs/module.spec.js
Github Open Source
Open Source
MIT
null
chartjs-plugin-datalabels
MatjazKavcic
JavaScript
Code
63
216
import Chart from 'chart.js'; describe('module', function() { it ('should be globally exported in ChartDataLabels', function() { expect(typeof window.ChartDataLabels).toBe('object'); }); it ('should be referenced with id "datalabels"', function() { expect(window.ChartDataLabels.id).toBe('datalabels'); }); // TODO Change this expectation at version 1: 'should NOT be registered' // https://github.com/chartjs/chartjs-plugin-datalabels/issues/42 it ('should be globally registered', function() { var plugins = Chart.plugins.getAll().filter((p) => p.id === 'datalabels'); expect(plugins[0]).toBe(window.ChartDataLabels); expect(plugins.length).toBe(1); }); });
17,664
https://github.com/miggymail/DapperDemo/blob/master/ConsoleUI/Program.cs
Github Open Source
Open Source
Apache-2.0
null
DapperDemo
miggymail
C#
Code
1,110
4,302
using Dapper; using DataAccessLayer.Models; using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Reflection; namespace ConsoleUI { class Program { static void Main() { MapMultipleObjects(); //MapMultipleObjectsWithParameters(); //MultipleSets(); //MultipleSetsWithParameters("Banner", "7898", "10"); //OutputParamers("Carol", "Danvers", "ACCT006"); //WithTransaction("Natasha", "Romanoff", "ACCT007"); //InsertCollectionOfData(); Console.ReadLine(); } static void MapMultipleObjects() { using IDbConnection cnn = new SqlConnection(ConfigurationManager.ConnectionStrings["DapperDemoDb"].ConnectionString); string sql = @"SELECT C.Id, C.FirstName, C.LastName, C.AccountNumber, P1.*, P2.*, A1.*, A2.* FROM dbo.[Customer] C LEFT OUTER JOIN dbo.[Phone] P1 ON C.MobileNo = P1.Id LEFT OUTER JOIN dbo.[Phone] P2 ON C.WorkNo = P2.Id LEFT OUTER JOIN dbo.[Address] A1 ON C.HomeAddress = A1.Id LEFT OUTER JOIN dbo.[Address] A2 ON C.WorkAddress = A2.Id;"; var customers = cnn.Query<CustomerModel, PhoneModel, PhoneModel, AddressModel, AddressModel, CustomerModel>(sql, (customer, phone1, phone2, address1, address2) => { customer.MobileNo = phone1; customer.WorkNo = phone2; customer.HomeAddress = address1; customer.WorkAddress = address2; return customer; }, splitOn: "Id,Id"); foreach (var c in customers) { Console.WriteLine($"{c.FirstName} {c.LastName} - Account #{c.AccountNumber} "); Console.WriteLine($"\tHome Address: {c.HomeAddress.Street} {c.HomeAddress.City}, {c.HomeAddress.State} {c.HomeAddress.ZipCode} Mobile No: {c.MobileNo.PhoneNumber}"); Console.WriteLine($"\tWork Address: {c.WorkAddress.Street} {c.WorkAddress.City}, {c.WorkAddress.State} {c.WorkAddress.ZipCode} Work No: {c.WorkNo.PhoneNumber}"); } } static void MapMultipleObjectsWithParameters() { using IDbConnection cnn = new SqlConnection(ConfigurationManager.ConnectionStrings["DapperDemoDb"].ConnectionString); var ln = new { LastName = "Stark" }; string sql = @"SELECT C.Id, C.FirstName, C.LastName, C.AccountNumber, P1.*, P2.*, A1.*, A2.* FROM dbo.[Customer] C LEFT OUTER JOIN dbo.[Phone] P1 ON C.MobileNo = P1.Id LEFT OUTER JOIN dbo.[Phone] P2 ON C.WorkNo = P2.Id LEFT OUTER JOIN dbo.[Address] A1 ON C.HomeAddress = A1.Id LEFT OUTER JOIN dbo.[Address] A2 ON C.WorkAddress = A2.Id WHERE C.LastName = @LastName;"; var customers = cnn.Query<CustomerModel, PhoneModel, PhoneModel, AddressModel, AddressModel, CustomerModel>(sql, (customer, phone1, phone2, address1, address2) => { customer.MobileNo = phone1; customer.WorkNo = phone2; customer.HomeAddress = address1; customer.WorkAddress = address2; return customer; }, param: ln, splitOn: "Id,Id"); foreach (var c in customers) { Console.WriteLine($"{c.FirstName} {c.LastName} - Account #{c.AccountNumber} "); Console.WriteLine($"\tHome Address: {c.HomeAddress.Street} {c.HomeAddress.City}, {c.HomeAddress.State} {c.HomeAddress.ZipCode} Mobile No: {c.MobileNo.PhoneNumber}"); Console.WriteLine($"\tWork Address: {c.WorkAddress.Street} {c.WorkAddress.City}, {c.WorkAddress.State} {c.WorkAddress.ZipCode} Work No: {c.WorkNo.PhoneNumber}"); } } static void MultipleSets() { using IDbConnection cnn = new SqlConnection(ConfigurationManager.ConnectionStrings["DapperDemoDb"].ConnectionString); string sql = @"SELECT C.Id, C.FirstName, C.LastName, C.AccountNumber FROM dbo.[Customer] C; SELECT P.* FROM dbo.[Phone] P; SELECT A.* FROM dbo.[Address] A;"; List<CustomerModel> customers = null; List<PhoneModel> phones = null; List<AddressModel> addresses = null; using (var qry = cnn.QueryMultiple(sql)) { customers = qry.Read<CustomerModel>().ToList(); phones = qry.Read<PhoneModel>().ToList(); addresses = qry.Read<AddressModel>().ToList(); } Console.WriteLine("Customers List"); foreach (var c in customers) { Console.WriteLine($"# {c.Id}. {c.FirstName} {c.LastName} - Account #{c.AccountNumber} "); } Console.WriteLine("\nPhone List"); foreach (var p in phones) { Console.WriteLine($"# {p.Id}. Phone Number : {p.PhoneNumber}"); } Console.WriteLine("\nAddress List"); foreach (var a in addresses) { Console.WriteLine($"# {a.Id}. Address: {a.Street} {a.City}, {a.State} {a.ZipCode}"); } } static void MultipleSetsWithParameters(string lastname, string phoneending, string streetwithnumber) { using IDbConnection cnn = new SqlConnection(ConfigurationManager.ConnectionStrings["DapperDemoDb"].ConnectionString); string sql = @"SELECT C.Id, C.FirstName, C.LastName, C.AccountNumber FROM dbo.[Customer] C WHERE C.LastName = @LastName; SELECT P.* FROM dbo.[Phone] P WHERE P.PhoneNumber LIKE '%' + @PhoneEnding; SELECT A.* FROM dbo.[Address] A WHERE A.Street LIKE '%' + @StreetWithNumber + '%';"; var @params = new { LastName = lastname, PhoneEnding = phoneending, StreetWithNumber = streetwithnumber }; List<CustomerModel> customers = null; List<PhoneModel> phones = null; List<AddressModel> addresses = null; using (var qry = cnn.QueryMultiple(sql, @params)) { customers = qry.Read<CustomerModel>().ToList(); phones = qry.Read<PhoneModel>().ToList(); addresses = qry.Read<AddressModel>().ToList(); } Console.WriteLine("Customers List"); foreach (var c in customers) { Console.WriteLine($"# {c.Id}. {c.FirstName} {c.LastName} - Account #{c.AccountNumber} "); } Console.WriteLine("\nPhone List"); foreach (var p in phones) { Console.WriteLine($"# {p.Id}. Phone Number : {p.PhoneNumber}"); } Console.WriteLine("\nAddress List"); foreach (var a in addresses) { Console.WriteLine($"# {a.Id}. Address: {a.Street} {a.City}, {a.State} {a.ZipCode}"); } } static void OutputParamers(string firstname, string lastname, string accountnumber) { using IDbConnection cnn = new SqlConnection(ConfigurationManager.ConnectionStrings["DapperDemoDb"].ConnectionString); //Insert Phone Numbers string sql = @"INSERT INTO dbo.[Phone] ([PhoneNumber]) VALUES (@PhoneNumber); SELECT @Id = @@IDENTITY;"; var p = new DynamicParameters(); p.Add("@Id", 0, DbType.Int32, ParameterDirection.Output); p.Add("@PhoneNumber", "231-456-7891"); cnn.Execute(sql, p); int phoneId1 = p.Get<int>("@Id"); p = new DynamicParameters(); p.Add("@Id", 0, DbType.Int32, ParameterDirection.Output); p.Add("@PhoneNumber", "231-456-7892"); cnn.Execute(sql, p); int phoneId2 = p.Get<int>("@Id"); //Insert Addresses sql = @"INSERT INTO dbo.[Address] ([Street],[City],[State],[ZipCode]) VALUES (@Street, @City, @State, @ZipCode); SELECT @Id = @@IDENTITY;"; p = new DynamicParameters(); p.Add("@Id", 0, DbType.Int32, ParameterDirection.Output); p.Add("@Street", "11 Main Street"); p.Add("@City", "Los Angeles"); p.Add("@State", "California"); p.Add("@ZipCode", "90011"); cnn.Execute(sql, p); int addressId1 = p.Get<int>("@Id"); p = new DynamicParameters(); p.Add("@Id", 0, DbType.Int32, ParameterDirection.Output); p.Add("@Street", "12 Main Street"); p.Add("@City", "Los Angeles"); p.Add("@State", "California"); p.Add("@ZipCode", "90012"); cnn.Execute(sql, p); int addressId2 = p.Get<int>("@Id"); sql = @"INSERT INTO dbo.[Customer] (FirstName, LastName, AccountNumber, MobileNo, WorkNo, HomeAddress, WorkAddress) VALUES (@FirstName, @LastName, @AccountNumber, @MobileNo, @WorkNo, @HomeAddress, @WorkAddress); SELECT @Id = @@IDENTITY;"; p = new DynamicParameters(); p.Add("@Id", 0, DbType.Int32, ParameterDirection.Output); p.Add("@FirstName", firstname); p.Add("@LastName", lastname); p.Add("@AccountNumber", accountnumber); p.Add("@MobileNo", phoneId1); p.Add("@WorkNo", phoneId2); p.Add("@HomeAddress", addressId1); p.Add("@WorkAddress", addressId2); cnn.Execute(sql, p); int newId = p.Get<int>("@Id"); Console.WriteLine($"New Customer Id #{ newId }"); MapMultipleObjects(); } static void WithTransaction(string firstname, string lastname, string accountnumber) { using IDbConnection cnn = new SqlConnection(ConfigurationManager.ConnectionStrings["DapperDemoDb"].ConnectionString); string sql = @"INSERT INTO dbo.[Customer] (FirstName, LastName, AccountNumber, MobileNo, WorkNo, HomeAddress, WorkAddress) VALUES (@FirstName, @LastName, @AccountNumber, 0, 0, 0, 0);"; var p = new DynamicParameters(); p.Add("@FirstName", firstname); p.Add("@LastName", lastname); p.Add("@AccountNumber", accountnumber); cnn.Open(); using (var trans = cnn.BeginTransaction()) { try { int records = cnn.Execute(sql, p, transaction: trans); Console.WriteLine($"Records Updated: { records }"); cnn.Execute(@"UPDATE dbo.[Customer] SET Id = 1", transaction: trans); trans.Commit(); } catch (Exception ex) { trans.Rollback(); Console.WriteLine($"Transaction Rollback, Error : { ex.Message } \n"); } } MapMultipleObjects(); } static void InsertCollectionOfData() { using IDbConnection cnn = new SqlConnection(ConfigurationManager.ConnectionStrings["DapperDemoDb"].ConnectionString); var listofaddresses = GetAddresses(); var listofphonenumbers = GetPhoneNumbers(); var listofcustomers = GetCustomers(); cnn.Open(); var trx = cnn.BeginTransaction(); try { string sql = @"[dbo].[spAddressUDT_Insert]"; var addr = new { addresses = listofaddresses.AsTableValuedParameter("AddressUDT") }; int rowsAffected = cnn.Execute(sql, addr, commandType: CommandType.StoredProcedure, transaction: trx); Console.WriteLine($"Address rows affected: { rowsAffected }"); sql = @"[dbo].[spPhoneUDT_Insert]"; var phn = new { phonenumbers = listofphonenumbers.AsTableValuedParameter("PhoneUDT") }; rowsAffected = cnn.Execute(sql, phn, commandType: CommandType.StoredProcedure, transaction: trx); Console.WriteLine($"Phone Number rows affected: { rowsAffected }"); sql = @"[dbo].[spCustomerUDT_Insert]"; var cust = new { customers = listofcustomers.AsTableValuedParameter("CustomerUDT") }; rowsAffected = cnn.Execute(sql, cust, commandType: CommandType.StoredProcedure, transaction: trx); Console.WriteLine($"Customer rows affected: { rowsAffected }"); trx.Commit(); } catch (Exception ex) { trx.Rollback(); Console.WriteLine($"Error : { ex.Message }"); } MapMultipleObjects(); } public static DataTable GetCustomers() { var customers = new DataTable(); customers.Columns.Add("FirstName", typeof(string)); customers.Columns.Add("LastName", typeof(string)); customers.Columns.Add("AccountNumber", typeof(string)); customers.Columns.Add("MobileNo", typeof(int)); customers.Columns.Add("WorkNo", typeof(int)); customers.Columns.Add("HomeAddress", typeof(int)); customers.Columns.Add("WorkAddress", typeof(int)); customers.Rows.Add("Clint", "Barton", "ACCT008", 13, 14, 13, 14); customers.Rows.Add("James", "Rhodes", "ACCT009", 15, 16, 15, 16); customers.Rows.Add("Scott", "Lang", "ACCT010", 17, 18, 17, 18); return customers; } public static DataTable GetPhoneNumbers() { var phonenumbers = new DataTable(); phonenumbers.Columns.Add("PhoneNumber", typeof(string)); phonenumbers.Rows.Add("231-456-7893"); phonenumbers.Rows.Add("231-456-7894"); phonenumbers.Rows.Add("231-456-7895"); phonenumbers.Rows.Add("231-456-7896"); phonenumbers.Rows.Add("231-456-7897"); phonenumbers.Rows.Add("231-456-7898"); return phonenumbers; } public static DataTable GetAddresses() { var addresses = new DataTable(); addresses.Columns.Add("Street", typeof(string)); addresses.Columns.Add("City", typeof(string)); addresses.Columns.Add("State", typeof(string)); addresses.Columns.Add("ZipCode", typeof(string)); addresses.Rows.Add("13 Rodeo Drive", "Beverly Hills", "California", "90210"); addresses.Rows.Add("14 Rodeo Drive", "Beverly Hills", "California", "90210"); addresses.Rows.Add("15 Rodeo Drive", "Beverly Hills", "California", "90210"); addresses.Rows.Add("16 Rodeo Drive", "Beverly Hills", "California", "90210"); addresses.Rows.Add("17 Rodeo Drive", "Beverly Hills", "California", "90210"); addresses.Rows.Add("18 Rodeo Drive", "Beverly Hills", "California", "90210"); return addresses; } } }
46,243
https://github.com/YDK-Solutions/ydk/blob/master/sdk/cpp/core/tests/models/ydktest-sanity-typedefs@2018-01-30.yang
Github Open Source
Open Source
ECL-2.0, Apache-2.0
2,022
ydk
YDK-Solutions
YANG
Code
11,826
30,499
module ydktest-sanity-typedefs { yang-version 1; namespace "http://cisco.com/ns/yang/ydktest-sanity-typedefs"; prefix top; organization "Cisco Systems, Inc."; contact "Cisco Systems, Inc. Customer Service Postal: 170 West Tasman Drive San Jose, CA 95134 Tel: +1 800 553-NETS E-mail: ydk-admin@cisco.com"; description "This module contains 461 typedef statements copied from NXOS Device YANG Model The module created to test YDK with newer version of libyang library, which supports more than 255 typedef statements"; revision 2018-01-30 { description "Initial Revision. Generated by ygorelik"; } typedef address_Ipv4 { type string { } } typedef address_Ipv6 { type string { } } typedef address_Ip { type union { type address_Ipv4; type address_Ipv6; } } typedef address_Mac { type string { } } typedef mtx_array_ifindex { type string { } } typedef mtx_array_uint8 { type string { } } typedef mtx_array_uint16 { type string { } } typedef mtx_array_uint32 { type string { } } typedef mtx_array_uint64 { type string { } } typedef mtx_array_bit { type string { } } typedef mtx_array_community { type string { } } typedef aaa_AccountStatus { type enumeration { // Active enum active { value 0; } // Inactive enum inactive { value 1; } } default "active"; } typedef aaa_BannerMsg { type string; } typedef aaa_Boolean { type enumeration { // No enum no { value 0; } // Yes enum yes { value 1; } } default "yes"; } typedef aaa_Clear { type enumeration { // No enum no { value 0; } // Yes enum yes { value 1; } } default "no"; } typedef aaa_CmdType { type enumeration { // Config enum config { value 0; } // Exec enum exec { value 1; } } default "config"; } typedef aaa_Date { type string; } typedef aaa_Delimiter { type string; } typedef aaa_Email { type address_Email { } } typedef aaa_EncKey { type string { length "0..240"; } } typedef aaa_EncryptedArray { type mtx_array_uint8; } typedef aaa_ExternalUnixUID { type uint16 { range "16000..23999"; } } typedef aaa_HistoryDepth { type uint8 { range "0..15"; } default "5"; } typedef aaa_IdleTimer { type uint16 { range "0..1440"; } } typedef aaa_KeyEnc { type enumeration { // Clear Text enum 0 { value 0; } // Type-6 Encrypted enum 6 { value 6; } // Encrypted enum 7 { value 7; } } default "0"; } typedef aaa_KeyEncUserPass { type enumeration { // Unspecified enum unspecified { value 255; } // Clear Text enum clear { value 0; } // Encrypted enum Encrypt { value 5; } } } typedef aaa_LdapAttribute { type string { length "0..63"; } } // NXOS supports maximum limits in the type definitions typedef aaa_LdapDn { type string { length "0..127"; } } typedef aaa_LdapFilter { type string { length "0..63"; } } typedef aaa_LdapSSLStrictnessLevel { type enumeration { // Strict enum strict { value 0; } // Permissive enum permissive { value 1; } } default "strict"; } typedef aaa_LoggingLevel { type enumeration { // Emergency enum Emergency { value 0; } // Alert enum Alert { value 1; } // Critical enum Critical { value 2; } // Error enum Error { value 3; } // Warning enum Warning { value 4; } // Notifications enum Notif { value 5; } // Informational enum Inform { value 6; } // Debug enum Debug { value 7; } } default "Error"; } typedef aaa_MonitorServerType { type enumeration { // Disabled enum disabled { value 0; } // Enabled enum enabled { value 1; } } default "disabled"; } typedef aaa_MonitoringPasswordType { type string; } typedef aaa_MonitoringUserType { type string { } default "test"; } typedef aaa_NoRolePolicy { type enumeration { // No Login enum no-login { value 0; } // Assign Default Role enum assign-default-role { value 1; } } } typedef aaa_Order { type uint16 { range "0..16"; } } typedef aaa_Passwd { type string { length "1..127"; } } typedef aaa_Phone { type address_Phone; } typedef aaa_Port { type uint32 { range "1..65535"; } } typedef aaa_ProviderGroupDeadtime { type uint32 { range "0..1440"; } default "0"; } // Limited by NXOS maximum size for server group typedef aaa_ProviderGroupName { type string { length "0..127"; } } typedef aaa_ProviderGroupProtocol { type enumeration { // TACACS enum tacacs { value 0; } // RADIUS enum radius { value 1; } // LDAP enum ldap { value 2; } } } typedef aaa_ProviderGroupSnmpIndex { type uint32; } typedef aaa_ProviderSnmpIndex { type uint32; } typedef aaa_ProviderState { type enumeration { // Unknown enum unknown { value 0; } // Operable enum operable { value 1; } // Inoperable enum inoperable { value 2; } } default "unknown"; } typedef aaa_PwdChangeCount { type uint8 { range "0..10"; } } typedef aaa_PwdChangeInterval { type uint16 { range "1..745"; } } typedef aaa_PwdExpWarnTime { type uint8 { range "0..30"; } } typedef aaa_PwdHistory { type string; } typedef aaa_PwdLen { type uint32; } typedef aaa_PwdLifeTime { type uint16 { range "0..3650"; } } typedef aaa_PwdPolicy { type enumeration { // Enable enum enable { value 0; } // Disable enum disable { value 1; } } default "enable"; } typedef aaa_RadPort { type uint32 { range "0..65535"; } } typedef aaa_RadSrvUseType { type enumeration { // Authentication enum Auth { value 0; } // Authorization enum Author { value 1; } // Accounting enum Acc { value 2; } // All enum All { value 3; } } default "All"; } typedef aaa_Realm { type enumeration { // Local enum local { value 0; } // RADIUS enum radius { value 1; } // TACACS+ enum tacacs { value 2; } // LDAP enum ldap { value 3; } } default "local"; } typedef aaa_Retries { type uint32 { range "0..5"; } default "1"; } typedef aaa_RuleAccessType { type enumeration { // none enum none { value 0; } // Read enum read { value 1; } // Read Write enum read-write { value 2; } // Command enum command { value 3; } } } typedef aaa_RuleCmdStrType { type string { length "0..128"; } } typedef aaa_RuleEntityType { type string { length "0..512"; } } typedef aaa_RuleNumberType { type uint32 { range "1..256"; } } typedef aaa_RulePermissionType { type enumeration { // none enum none { value 0; } // Permit enum permit { value 1; } // Deny enum deny { value 2; } } } typedef aaa_RuleScopeType { type enumeration { // none enum none { value 0; } // Feature enum feature { value 2; } // Feature Group enum feature-group { value 3; } // OID enum oid { value 21; } } } typedef aaa_SshData { type string { length "0..16384"; } } typedef aaa_TimeMin { type uint32 { range "0..1440"; } default "0"; } typedef aaa_TimeSec { type uint32 { range "1..60"; } default "5"; } typedef aaa_UnixUID { type uint16 { range "99..15999"; } } typedef aaa_UserCertDataType { type string; } typedef aaa_UserRolePrivType { type enumeration { // No Privilege enum noDataPriv { value 0; } // Read Privilege enum readPriv { value 1; } // Write Privilege enum writePriv { value 2; } } default "noDataPriv"; } typedef aaa_authenticationProtocol { type enumeration { // PAP enum pap { value 0; } // CHAP enum chap { value 1; } // MS-CHAP enum mschap { value 2; } // MS-CHAPv2 enum mschapv2 { value 3; } // ASCII enum ascii { value 4; } } } // Bank type typedef ac_BankT { type enumeration { // Even enum even { value 1; } // Odd enum Odd { value 2; } } default "even"; } // Control typedef ac_Control { // bits- Using string type string; } // ECN typedef ac_Ecn { type uint8 { range "0..2"; } default "0"; } // Ether type typedef ac_EtherT { type uint16; } // Ip options typedef ac_IpOpt { // bits- Using string type string; } // MAC typedef ac_Mac { type address_Mac; } // Order typedef ac_Order { type uint16 { range "1..1024"; } } // Payload size typedef ac_PayloadSz { type uint8; } // Interface identifier typedef nw_IfId { type string; } // Port id typedef ac_PortId { type nw_IfId; } // Operational state of HW rules typedef ac_RuleOperSt { type enumeration { // Pending enum pending { value 1; } // Installed enum installed { value 2; } // Failed enum failed { value 3; } } default "pending"; } typedef acl_ACEStats { type uint8; default "0"; } // ACE action type typedef acl_ActionType { type enumeration { // Invalid enum invalid { value 0; } // Permit enum permit { value 1; } // Deny enum deny { value 2; } // Copy enum copy { value 3; } // Divert enum divert { value 4; } // Redirect enum redirect { value 5; } } default "invalid"; } // Capture Session typedef acl_CaptureSes { type uint16 { range "0..48"; } } // config State typedef acl_ConfigState { type uint8; default "0"; } // http option (http-method) value enum typedef acl_HttpOptionType { type enumeration { // get enum get { value 1; } // put enum put { value 2; } // head enum head { value 3; } // post enum post { value 4; } // delete enum delete { value 5; } // trace enum trace { value 6; } // connect enum connect { value 7; } // invalid enum invalid { value 0; } } } // Name of interface, e.g. "Eth1/2" typedef acl_IfName { type nw_IfId; } // MAC Protocol typedef acl_MACProtocol { // MAX Converted to int from 0x10000 type uint32 { range "0..65536"; } default "65536"; } // ACL name typedef acl_Name { type string { length "1..64"; } } // L4 port relationship operator typedef acl_Operator { type uint8; default "0"; } // Packet Length typedef acl_PktLen { type uint16 { range "19..9210"; } } // L4 port number typedef acl_PortNumber { type uint16; default "0"; } // ACL name typedef acl_RemarkStr { type string { length "1..100"; } } // ACE sequence number typedef acl_SequenceNumber { type uint32 { range "0..4294967295"; } } // TCP Flags Mask typedef acl_TcpFlagsMask { type uint8 { range "0..64"; } } // TCP option length typedef acl_TcpOptionLengthType { type uint32 { range "0..41"; } } // time-range name typedef acl_TimeRangeName { type string { length "0..64"; } } // UDF mask typedef acl_UdfMask { type uint16 { range "0..65535"; } } // UDF name typedef acl_UdfName { type string { length "1..16"; } } // UDF value typedef acl_UdfVal { type uint16 { range "0..65535"; } } // VLAN Acl action type typedef acl_VAclActionType { type enumeration { // invalid enum invalid { value 0; } // forward enum forward { value 1; } // drop enum drop { value 2; } // redirect enum redirect { value 3; } } default "invalid"; } // VLAN Acl action log enable/disable typedef acl_VAclLog { type uint8; default "0"; } // VLAN Acl match acl type // Refer to CLI_ACL_IP/CLI_ACL_IPV6/CLI_ACL_MAC for values typedef acl_VAclMatchType { type uint16; default "0"; } // Vlan List String for VLAN Acl Policy typedef acl_VlanListStr { type string { length "0..512"; } } // VLAN typedef acl_VlanType { type uint32 { range "0..4095"; } default "4095"; } // nve vni ID typedef acl_VniType { type uint32 { range "0..16777216"; } } // cos type typedef acl_cosType { type uint8 { range "0..8"; } default "8"; } // erspan DSCP typedef acl_erspanDscpType { type uint8 { range "0..64"; } default "64"; } // erspan gre protocol typedef acl_erspanGreType { type uint32 { range "0..65536"; } default "65536"; } // VLAN Acl policy operation apply/remove typedef acl_operation { type uint8; default "1"; } typedef action_AdminSt { type enumeration { // Unknown enum unknown { value 0; } // Start enum start { value 1; } // Stop enum stop { value 2; } // Suspend enum suspend { value 3; } } default "unknown"; } typedef action_Descr { type string; } // Frequency of the task typedef action_Freq { type string; } typedef action_OperSt { type enumeration { // Scheduled enum scheduled { value 0; } // Processing enum processing { value 1; } // Completed enum completed { value 2; } // Cancelled enum cancelled { value 3; } // Failed enum failed { value 4; } // Indeterminate enum indeterminate { value 5; } // Suspended enum suspended { value 6; } // Crash-Suspect enum crashsuspect { value 7; } } default "scheduled"; } // Task status qualifier typedef action_Qual { type string; } // Result history retention size: how many records // to keep per rule typedef action_RetentionSize { type uint16 { range "1..1024"; } default "100"; } // Resuilt history retention time: how long records are // to be kept per rule typedef action_RetentionTime { type string; } // Type of the task typedef action_Type { type enumeration { // Clear enum clear { value 1; } // Reset enum reset { value 2; } // Reload enum reload { value 3; } // Locate enum locate { value 4; } // Install enum install { value 5; } // Test enum test { value 6; } // Collect enum collect { value 7; } // Set Interface In-Service enum interface-in-service { value 8; } } default "clear"; } // Global access controls typedef actrl_AccControl { // bits- Using string type string; } // Rule direction typedef actrl_Direction { type enumeration { // Uni-directional enum uni-dir { value 1; } // Bi-directional enum bi-dir { value 2; } } default "uni-dir"; } // Entry priority, this is the priority for entry typedef actrl_EntryPrio { type uint8 { range "1..7"; } default "7"; } // Filter id // @@@ Keep this in sync with vzFltId. // @@@ Only way to moving FltId from 16 to 32 bits without dropping traffic // @@@ during upgrade, was to introduce vzFiltId (16 bits) typedef actrl_FltId { // MAX Converted to int from 0xffffffff type uint32 { range "1..4294967295"; } } // Log clear interval typedef actrl_LogClrIntvl { type uint16 { range "1000..2800"; } default "2800"; } // Operational state of Rule typedef actrl_OperSt { type enumeration { // enabled enum enabled { value 1; } // disabled enum disabled { value 2; } } default "disabled"; } // Reasons for rule being disabled. typedef actrl_OperStQual { // bits- Using string type string; } // PPF Node id typedef actrl_PpfNodeId { // MAX Converted to int from 0xffffffff type uint32 { range "1..4294967295"; } } // Array PPF Node id typedef actrl_PpfNodeIdArray { type mtx_array_uint32; } // Rule id typedef actrl_RuleId { // MAX Converted to int from 0xffffffff type uint32 { range "1..4294967295"; } } // Filter to Rule ID mapping array typedef actrl_RuleIdArray { type mtx_array_uint32; } // Rule ID array index typedef actrl_RuleIndex { type uint16 { range "1..1024"; } } // Rule priority, this is the priority for a set of rules typedef actrl_RulePrio { type uint8 { range "1..11"; } } // Rule type typedef actrl_RuleT { type enumeration { // Tenant enum tenant { value 1; } // Management enum mgmt { value 2; } // SNMP enum snmp { value 3; } // Flood enum bd_flood { value 4; } // Vrf enum vrf_default { value 5; } // Infra enum infra { value 6; } } default "tenant"; } // Scope id (24-bit) typedef actrl_ScopeId { // MAX Converted to int from 0xffffff type uint32 { range "1..16777215"; } default "1"; } // Security Label (12-bit) typedef actrl_SecLbl { // MAX Converted to int from 0xfff type uint16 { range "1..4095"; } } // Subject represents the entitiy to which the capability constraint gets applied typedef actrlcap_Subj { type enumeration { // Unknown enum unknown { value 0; } // Actrl Rules enum rule-namespace { value 1; } // Actrl Scopes enum scope-namespace { value 2; } } default "unknown"; } typedef address_Email { type string; } typedef address_HostNameOrDottedQuad { type string { length "1..256"; } } typedef address_Phone { type string; } // Adjacency Flags typedef adjacency_AdjFlags { // bits- Using string type string; } // Adjacency operational state typedef adjacency_AdjOperSt { type enumeration { // Unknown enum unspecified { value 0; } // Incomplete enum incomplete { value 1; } // Resolved enum normal { value 2; } } } // Database type typedef adjacency_DbT { type enumeration { // IP database enum ip { value 1; } // IPv6 database enum ipv6 { value 2; } } default "ip"; } typedef aggregate_AdminState { type enumeration { // Unknown enum unknown { value 0; } // Up enum up { value 1; } // Down enum down { value 2; } } default "down"; } // Address Family Type typedef aggregate_AfT { type enumeration { // Ipv4 unicast address family enum ipv4-ucast { value 0; } // Vpnv4 unicast address family enum vpnv4-ucast { value 1; } // Ipv6 unicast address family enum ipv6-ucast { value 2; } // Vpnv6 unicast address family enum vpnv6-ucast { value 3; } // L2-Evpn unicast address family enum l2-evpn { value 4; } } default "l2-evpn"; } typedef aggregate_BfdStatus { type enumeration { // Unknown enum unknown { value 0; } // Admin Down enum admin_down { value 1; } // Oper Down enum down { value 2; } // Intialization enum init { value 3; } // Up enum up { value 4; } } default "admin_down"; } typedef aggregate_BooleanFlag { type enumeration { // No enum no { value 0; } // Yes enum yes { value 1; } } default "no"; } // <type name="VxLanMCFlag" // base="scalar:Enum8" // > // <const name="unknown" value="0" label="Unknown"/> // <const name="yes" value="1" label="Yes"/> // <const name="no" value="2" label="No"/> // <default value="no"/> // </type> // <type name="IpVnidBindingFlag" // base="scalar:Enum8" // > // <const name="unknown" value="0" label="Unknown"/> // <const name="yes" value="1" label="Yes"/> // <const name="no" value="2" label="No"/> // <default value="no"/> // </type> // Bandwidth metric of the SVI in kilobits per second. typedef aggregate_Bw { type uint32 { range "1..400000000"; } default "10000000"; } typedef aggregate_ConfTmplStatus { type enumeration { // ConfigTmplInactive enum inactive { value 0; } // ConfigTmplOperational enum active { value 1; } // ConfigTmplFailed enum failed { value 2; } } default "inactive"; } typedef aggregate_ConfigMgmtStatus { type enumeration { // Unknown enum unknown { value 0; } // ConfigMgmtReady enum configMgmtReady { value 1; } // ConfigMgmtNotReady enum configMgmtNotReady { value 2; } // ConfigMgmtPurgeStart enum configMgmtPurgeStart { value 4; } } default "configMgmtNotReady"; } typedef aggregate_ConfigSourceType { type enumeration { // Unknown enum unknown { value 0; } // Cli enum cli { value 1; } // Controller enum controller { value 2; } } default "cli"; } typedef aggregate_ConfigStatus { type enumeration { // Unknown enum unknown { value 0; } // ConfigReady enum configReady { value 1; } // ConfigNotReady enum configNotReady { value 2; } // ConfigPurgeInProgress enum configPurgeInProgress { value 4; } } default "configNotReady"; } typedef aggregate_ControllerID { type uint32 { range "0..16"; } default "0"; } typedef aggregate_ControllerIdBitmap { type mtx_array_bit; } typedef aggregate_CpuType { type string; } typedef aggregate_CtrlrType { type enumeration { // Unknown enum unknown { value 0; } // L2Vxlan enum l2-vxlan { value 1; } // Vxlan enum vxlan { value 2; } } default "l2-vxlan"; } // Default Value computed from unicast typedef aggregate_EpType { // bits- Using string type string; default "unicast"; } typedef aggregate_GroupAddr { type string; } typedef aggregate_HostReachabilityMode { type enumeration { // Unknown enum unknown { value 0; } // FloodAndLearn enum floodAndLearn { value 1; } // Controller enum controller { value 2; } // Bgp enum bgp { value 3; } } default "floodAndLearn"; } typedef aggregate_IngressRepProtocolType { type enumeration { // Unknown enum unknown { value 0; } // Static enum static { value 1; } // Bgp enum bgp { value 2; } } default "unknown"; } typedef aggregate_IntfAssignMode { type enumeration { // Dedicated enum dedicated { value 0; } // Shared enum shared { value 1; } } } typedef aggregate_IntfType { type enumeration { // Unknown enum unknown { value 0; } // Port enum port { value 1; } // Port Channel enum port-channel { value 2; } // Tunnel enum tunnel { value 3; } // Loopback enum loopback { value 4; } // SVI enum svi { value 5; } } } typedef aggregate_MTU { type uint32 { range "1..9216"; } default "9216"; } // Mac type typedef aggregate_MacType { type enumeration { // Unknown enum unknown { value 0; } // Unicast enum unicast { value 1; } // Multicast enum multicast { value 2; } } default "unicast"; } // Minimum rx interval (in ms) typedef aggregate_MinRxIntvl { type uint16 { range "0..999"; } default "50"; } // Minimum tx interval (in ms) typedef aggregate_MinTxIntvl { type uint16 { range "0..999"; } default "50"; } typedef aggregate_ModuleType { type string; } typedef aggregate_OperState { type enumeration { // Unknown enum unknown { value 0; } // Up enum up { value 1; } // Down enum down { value 2; } } default "down"; } typedef aggregate_ReplicationModeType { type enumeration { // Unknown enum unknown { value 0; } // ReplicationServer enum replicationServer { value 1; } // IngressReplication enum ingressReplication { value 2; } // IpMulticast enum ipMulticast { value 3; } } default "unknown"; } typedef aggregate_ResourceStatus { type enumeration { // Unknown enum unknown { value 0; } // VlanCreated enum vlanCreated { value 1; } // VlanFailed enum vlanFailed { value 2; } // VnidCreated enum vnidCreated { value 3; } // VnidFailed enum vnidFailed { value 4; } // VlansCarved enum vlansCarved { value 5; } // VlansNotCarved enum vlansNotCarved { value 6; } // VnidCreationReceived enum vnidCreationReceived { value 7; } // MyTEPIPPublished enum myTEPIPPublished { value 101; } // ControllerIntfNotCarved enum controllerIntfNotCarved { value 201; } // ControllerIntfCarved enum controllerIntfCarved { value 202; } } default "unknown"; } // Route target policy type typedef aggregate_RttPType { type enumeration { // Import enum import { value 1; } // Export enum export { value 2; } } default "import"; } typedef aggregate_TunnelType { type enumeration { // Unknown enum unknown { value 0; } // VxLanOverIPV4 enum vxlanipv4 { value 1; } // VxLanOverIPV6 enum vxlanipv6 { value 2; } // NVGRE enum nvgre { value 3; } } } typedef aggregate_VpcKeepaliveStatus { type enumeration { // VpcOobUnknown enum VpcOobUnknown { value 0; } // VpcOobDisabled enum VpcOobDisabled { value 1; } // VpcOobPeerAlive enum VpcOobPeerAlive { value 2; } // VpcOobPeerNotAlive enum VpcOobPeerNotAlive { value 3; } // VpcOobPeerAliveDomainMismatch enum VpcOobPeerAliveDomainMismatch { value 4; } // VpcOobSuspended enum VpcOobSuspended { value 5; } // VpcOobNotOperational enum VpcOobNotOperational { value 6; } // VpcOobSuspendedVrf enum VpcOobSuspendedVrf { value 7; } // VpcOobMisconfig enum VpcOobMisconfig { value 8; } } default "VpcOobUnknown"; } typedef aggregate_VpcOperStatus { type enumeration { // down enum down { value 0; } // up enum up { value 1; } } default "down"; } typedef aggregate_VpcPeerLinkStatus { type enumeration { // VpcPeerNolink enum VpcPeerNolink { value 0; } // VpcPeerLinkDown enum VpcPeerLinkDown { value 1; } // VpcPeerOk enum VpcPeerOk { value 2; } // VpcPeerNotfound enum VpcPeerNotfound { value 3; } } default "VpcPeerNolink"; } // Fabric Forwarding Mode typedef aggregate_fabFwdMode { type enumeration { // Standard enum standard { value 0; } // Anycast Gateway enum anycastgw { value 1; } // ProxyGw enum proxygw { value 2; } } default "standard"; } // Database type typedef aib_DbT { type enumeration { // Adjacency Database enum adj { value 1; } } default "adj"; } // Owner type typedef aib_Owner { type string; } // Preference type typedef aib_Pref { // MAX Converted to int from 0xffff type uint16 { range "1..65535"; } default "1"; } // Update time stamp type typedef aib_UpdateTs { type string; } // Burst interval shift typedef analytics_BurstIntvlShift { type uint8 { range "0..255"; } default "0"; } // Mode typedef analytics_CModeT { type enumeration { // ACI mode enum aci { value 0; } // Standalone mode enum standalone { value 1; } } default "aci"; } // Collector buket identifier typedef analytics_CollBucketId { type uint8 { range "1..255"; } } // Collect Interval typedef analytics_CollIntvl { type uint32 { range "100..64000"; } default "100"; } // Collector version typedef analytics_CollVersion { type enumeration { // Version 5 enum v5 { value 1; } // Version 9 enum v9 { value 2; } // Cisco proprietary version 1 enum cisco-v1 { value 3; } } default "cisco-v1"; } // Collect params // Default Value computed from src-intf typedef analytics_CollectParams { // bits- Using string type string; default "src-intf"; } // Collector identifier typedef analytics_CollectorId { type uint32 { range "0..65535"; } } // Default filtering policy type typedef analytics_DefPolicyT { type enumeration { // Permit enum permit { value 0; } // Deny enum deny { value 1; } } default "permit"; } // Direction type typedef analytics_DirectionT { type enumeration { // Ingress enum in { value 1; } // Egress enum out { value 2; } // Both enum both { value 3; } } default "in"; } // IP filter type typedef analytics_FltType { type enumeration { // Ipv4 type enum ipv4 { value 1; } // Ipv6 type enum ipv6 { value 2; } // CE type enum ce { value 3; } } default "ipv4"; } // Forwarding instance target identifier typedef analytics_FwdInstTargetId { type uint32 { range "0..16777215"; } } // Hash value typedef analytics_HashT { type uint32 { range "0..4294967295"; } default "0"; } // Hash width type typedef analytics_HashWidthT { type uint16 { range "1..255"; } default "12"; } // IP packet identifier shift typedef analytics_IpPktIdShift { type uint8 { range "0..255"; } default "0"; } // Layer4 port typedef analytics_L4Port { type uint32 { range "1..65535"; } } // Match params // Default Value computed from src-ipv4 typedef analytics_MatchParams { // bits- Using string type string; default "src-ipv4"; } // Mode typedef analytics_ModeT { type enumeration { // Analytics mode enum analytics { value 0; } // Netflow mode enum netflow { value 1; } } default "netflow"; } // MTU typedef analytics_Mtu { type uint16 { range "576..9216"; } default "1500"; } // Operational state of Rule typedef analytics_OperSt { type enumeration { // enabled enum enabled { value 1; } // disabled enum disabled { value 2; } } default "disabled"; } // Reasons for rule being disabled. typedef analytics_OperStQual { // bits- Using string type string; } // Payload length identifier typedef analytics_PayloadLenIdT { type uint8 { range "0..10"; } } // Payload length typedef analytics_PayloadLenT { // MAX Converted to int from 0x3fff type uint32 { range "0..16383"; } default "0"; } // Receive window size identifier typedef analytics_RcvWindowSzIdT { type uint8 { range "0..4"; } } // Receive window size typedef analytics_RcvWindowSzT { type uint32 { range "0..65535"; } default "0"; } // Sample size typedef analytics_SampleSzT { type uint32 { range "1..65535"; } default "1"; } // Sampler mode typedef analytics_SamplerMode { type enumeration { // M out of N flows enum flow { value 1; } // M out of N pkts enum pkts { value 2; } } default "flow"; } // TCP options header length identifier typedef analytics_TCPOptHdrLenIdT { type uint8 { range "0..6"; } } // TCP options header length typedef analytics_TCPOptHdrLenT { type uint32 { range "0..15"; } default "0"; } // Sequence number guess threshold typedef analytics_ThresholdT { type uint32 { range "0..4294967295"; } default "0"; } // Create Count typedef analytics_createCount { type uint32 { range "0..16777215"; } default "0"; } // Hit Count typedef analytics_hitCount { type uint32 { range "0..16777215"; } default "0"; } // Num tcam entries type typedef analytics_numTcamEntT { type uint32 { range "1..65535"; } default "1024"; } // Num tcam entries per V4 type typedef analytics_numTcamEntV4T { type uint16 { range "1..256"; } default "1"; } // Num tcam entries per V6 type typedef analytics_numTcamEntV6T { type uint16 { range "1..256"; } default "4"; } // Adjacency Flags typedef arp_AdjFlags { // bits- Using string type string; } // Adjacency operational state typedef arp_AdjOperSt { type enumeration { // Unknown enum unspecified { value 0; } // Incomplete enum incomplete { value 1; } // Resolved enum normal { value 2; } } } typedef arp_AdjRouteDist { type uint32 { range "2..250"; } default "250"; } // ARP Cache Limit typedef arp_ArpCacheLimit { type uint32 { range "1..614400"; } default "174080"; } // ARP Cache Syslog Rate typedef arp_ArpCacheSyslogRate { type uint32 { range "1..1000"; } default "1"; } // Config Error typedef arp_ConfigErr { // bits- Using string type string; } // Config Error Inst MO typedef arp_ConfigErrInst { // bits- Using string type string; } // Database type typedef arp_DbT { type enumeration { // IP database enum ip { value 1; } // SupCache database enum supcache { value 2; } } default "ip"; } // Event History Size typedef arp_EventLogSize { type enumeration { // Disable enum disabled { value 0; } // Small enum small { value 1; } // Medium enum medium { value 2; } // Large enum large { value 3; } } default "small"; } // Event Log Type typedef arp_EventType { type enumeration { // CLI Events enum cli { value 0; } // Client Events enum client-events { value 1; } // Client Errors enum client-errors { value 2; } // Control Events enum control-events { value 3; } // Internal Events enum internal-events { value 4; } // Internal Errors enum internal-errors { value 5; } // High Availability Events enum high-availability { value 6; } // IP Sync Events enum ip-sync { value 7; } // ARP Local Cache Events enum local-cache-events { value 8; } // ARP Local Cache Errors enum local-cache-errors { value 9; } // Packet Messages Logs enum pkt-messages { value 10; } // SNMP Events enum snmp { value 11; } // ARP Suppression Events enum suppress-events { value 12; } // ARP Suppression Errors enum suppress-errors { value 13; } // Sync Event Logs enum sync { value 14; } // Controller MAC-IP route error logs enum arp-controller-errors { value 15; } // DME debug event enum arp-dme-event { value 16; } // Adjacency Control Logs enum adjacency-control { value 101; } // Adjacency Error Logs enum adjacency-errors { value 102; } // Adjacency IPC Logs enum adjacency-ipc-events { value 103; } // Adjacency Stats Logs enum adjacency-stats { value 104; } // Adjacency High Availability Logs enum adjacency-high-availability { value 105; } // Adjacency CLI Logs enum adjacency-cli { value 106; } // Adjacency SDB Logs enum adjacency-sdb { value 107; } // Adjacency SNMP Logs enum adjacency-snmp { value 108; } // Adjacency Net Broker Logs enum adjacency-netbroker { value 109; } // Adjacency DME event debugs enum am-dme-event { value 110; } // Adjacency event debugs enum am-event { value 111; } } } // Logging Level typedef arp_LoggingLevel { type enumeration { // Emergency enum emergency { value 0; } // Alert enum alert { value 1; } // Critical enum critical { value 2; } // Error enum error { value 3; } // Warning enum warning { value 4; } // Notification enum notification { value 5; } // Informational enum informational { value 6; } // Debug enum debug { value 7; } } default "error"; } // MAC Delete adjaceny refresh timeout typedef arp_MacDelTimeout { type uint16; } // Max packet count typedef arp_MaxPacket { type uint32 { range "0..32767"; } default "1000"; } // ARP off list timeout typedef arp_OffListTimeout { type uint16 { range "180..1800"; } default "180"; } // Opcode typedef arp_Opcode { type enumeration { // Unspecified enum unspecified { value 0; } // ARP request enum req { value 1; } // ARP reply enum reply { value 2; } } default "unspecified"; } // RARP Fabric Forwarding Rate Limit typedef arp_RarpForwadingRate { type uint16 { range "200..400"; } default "200"; } // Static Adjacency operational state typedef arp_StAdjOperSt { type enumeration { // Down enum down { value 0; } // Incomplete enum up { value 1; } // Unspecified enum unspecified { value 10; } } default "unspecified"; } // Static Adjacency operational state qualifier typedef arp_StAdjOperStQual { type enumeration { // Unspecified enum unspecified { value 0; } // Subnet mismatch enum subnet-mismatch { value 1; } // Invalid MAC enum invalid-mac { value 2; } // Invalid IP enum invalid-ip { value 3; } // Invalid VRF enum invalid-vrf { value 4; } // Own MAC enum own-mac { value 5; } // Interface down enum if-down { value 6; } // Up enum up { value 7; } // Invalid Interface enum invalid-if { value 8; } // Invalid CLI Data enum invalid-clidata { value 9; } // No Memory enum no-memory { value 10; } } default "unspecified"; } // Suppression Cache flag typedef arp_SupCacheFlag { // bits- Using string type string; } // Suppression ARP Mode typedef arp_SuppressArpMode { type enumeration { // Disabled enum disabled { value 0; } // L2SuppressARP enum l2suppressarp { value 1; } // L2L3SuppressARP enum l2l3suppressarp { value 2; } // Invalid enum invalid { value 3; } } } // ARP suppress timeout typedef arp_SuppressionTimeout { type uint16 { range "0..28800"; } default "0"; } // Syslog threshold typedef arp_SyslogCnt { type uint32 { range "0..65535"; } default "10000"; } // throttle timeout typedef arp_ThrottleTimeout { type uint16 { range "300..1800"; } default "300"; } // ARP timeout typedef arp_Timeout { type uint16 { range "60..28800"; } default "1500"; } // Default SVI autoState typedef bd_DefaultSVIAutoState { type enumeration { enum disable { value 0; } enum enable { value 1; } } default "enable"; } // Address family type typedef bfd_AfT { type enumeration { // IPv4 address family enum ipv4 { value 1; } // IPv6 address family enum ipv6 { value 2; } } default "ipv4"; } // Application private data typedef bfd_AppData { type mtx_array_uint8; } // Application session flags typedef bfd_AppFlags { // bits- Using string type string; } // Application ID typedef bfd_AppId { type uint32; } // Authentication hex key typedef bfd_AuthHexKey { type mtx_array_uint8; } // Authentication hex key size typedef bfd_AuthHexKeySize { type uint8 { range "0..40"; } } // Authentication key typedef bfd_AuthKey { type string { length "min..20"; } } // Authentication key id typedef bfd_AuthKeyId { type uint8 { range "1..255"; } } // Authentication Sequence Number typedef bfd_AuthSeqno { type uint32; } // Authentication type typedef bfd_AuthT { type enumeration { // No authentication enum none { value 0; } // Keyed SHA1 enum sha1 { value 4; } // Met Keyed SHA1 enum met-sha1 { value 5; } } default "none"; } // Current session index typedef bfd_CurSessIndex { type uint32; } // Detection multiplier typedef bfd_DetectMult { type uint8 { range "1..50"; } default "3"; } // Diag Code typedef bfd_DiagCode { type enumeration { // No Diagnostic enum none { value 0; } // Control Detection Time Expired enum detect-timeout { value 1; } // Echo Function Failed enum echo-fail { value 2; } // Neighbor Signaled Session Down enum nbr-signal-down { value 3; } // Forwarding Plane Reset enum fwd-plane-reset { value 4; } // Path Down enum path-down { value 5; } // Concatenated Path Down enum concat-path-down { value 6; } // Administratively Down enum admin-down { value 7; } // Reverse Concatenated Path Down enum rev-concat-path-down { value 8; } } } // Session discriminator typedef bfd_Discr { type uint32; } // echo rx interval (in ms) typedef bfd_EchoRxIntvl { type uint16 { range "0..999"; } default "0"; } typedef bfd_IfControl { // bits- Using string type string; } // Interface Detection multiplier typedef bfd_IfDetectMult { type uint8 { range "0..50"; } default "0"; } // Interface Minimum rx interval (in ms) typedef bfd_IfMinRxIntvl { type uint16 { range "0..999"; } default "0"; } // Interface Minimum tx interval (in ms) typedef bfd_IfMinTxIntvl { type uint16 { range "0..999"; } default "0"; } // Global flags typedef bfd_InstFlags { // bits- Using string type string; } // Minimum rx interval (in ms) typedef bfd_MinRxIntvl { type uint16 { range "50..999"; } default "50"; } // Minimum tx interval (in ms) typedef bfd_MinTxIntvl { type uint16 { range "50..999"; } default "50"; } // Oper State typedef bfd_OperSt { type enumeration { // AdminDown enum admin-down { value 0; } // Down enum down { value 1; } // Init enum init { value 2; } // Up enum up { value 3; } } } // Packet flags typedef bfd_PktFlags { // bits- Using string type string; } // Packet Interval (in ms) typedef bfd_PktInterval { type uint32; } // Application sap ID typedef bfd_SapId { type uint32; } // Slow interval (in ms) typedef bfd_SlowIntvl { type uint16 { range "1000..30000"; } default "2000"; } // BFD Start timeout // Default Value "0" Removed - out of range 60..3600 typedef bfd_StTm { type uint32 { range "60..3600"; } } // Startup interval (in second) typedef bfd_StartupIntvl { type uint16 { range "0..30"; } default "5"; } // BFD Cfg State typedef bfd_TrkMbrLnk { type enumeration { // Enabled enum enable { value 1; } // Disabled enum disable { value 0; } } default "disable"; } // Additional Paths capability in DomAf typedef bgp_AddlPathCapT { // bits- Using string type string; } // Administrative state typedef bgp_AdminSt { type enumeration { // Enabled enum enabled { value 1; } // Disabled enum disabled { value 2; } } default "disabled"; } // Advertisement Interval typedef bgp_AdvInterval { type uint16 { range "0..600"; } } // Advertise l2vpn evpn typedef bgp_AdvertL2vpnEvpn { type enumeration { // Enabled enum enabled { value 1; } // Disabled enum disabled { value 0; } } default "disabled"; } typedef bgp_AdvtMapCondition { type enumeration { // no options enum none { value 0; } // Exist Route Map enum exist { value 1; } // Non-Exist Route Map enum non-exist { value 2; } } default "none"; } // Address family type typedef bgp_AfT { type enumeration { // IPv4 unicast address family enum ipv4-ucast { value 1; } // IPv4 multicast address family enum ipv4-mcast { value 2; } // Vpnv4 unicast address family enum vpnv4-ucast { value 3; } // IPv6 unicast address family enum ipv6-ucast { value 5; } // IPv6 multicast address family enum ipv6-mcast { value 6; } // Vpnv6 unicast address family enum vpnv6-ucast { value 7; } // L2Vpn EVpn address family enum l2vpn-evpn { value 9; } // IPv4 labeled unicast address family enum ipv4-lucast { value 10; } // IPv6 labeled unicast address family enum ipv6-lucast { value 11; } // Link state address family enum lnkstate { value 12; } // IPv4 mvpn address family enum ipv4-mvpn { value 13; } // IPv6 mvpn address family enum ipv6-mvpn { value 14; } // L2Vpn vpls address family enum l2vpn-vpls { value 15; } // IPv4 mdt address family enum ipv4-mdt { value 16; } } default "ipv4-ucast"; } // Activate the affinity group typedef bgp_AffGrpActv { type uint16 { range "0..65535"; } } // AS path database size typedef bgp_AsPathDbSz { type uint32; } // AS segment type typedef bgp_AsSegT { type enumeration { // Sequence enum sequence { value 1; } // Set enum set { value 2; } } default "set"; } // AS Set typedef bgp_AsSet { type enumeration { // Enabled enum enabled { value 1; } // Disabled enum disabled { value 0; } } default "disabled"; } // Asn number typedef bgp_AsnNum { type string; } // Customizes AS_PATH attribute for routes received from eBGP neighbor typedef bgp_AsnPropagation { type enumeration { // no options enum none { value 0; } // no-prepend enum no-prepend { value 1; } // no-prepend+replace-as enum replace-as { value 2; } // noPrepend+replace-as+dual-as enum dual-as { value 3; } } default "none"; } // Attribute database size typedef bgp_AttribDbSz { type uint32; } // BestPath Timeout Limit typedef bgp_BestPathIntvl { type uint16 { range "1..3600"; } default "300"; } // BMP server state typedef bgp_BmpSt { type enumeration { // Enabled enum enabled { value 0; } // Disabled enum disabled { value 1; } } default "enabled"; } // Additional Paths capability in Neighbor Af typedef bgp_CapAddlPathCapT { // bits- Using string type string; } // Capability type typedef bgp_CapT { // bits- Using string type string; } // Cluster ID typedef bgp_ClusterId { type string; } // Connection Attempts typedef bgp_ConnAttempts { type uint32; default "0"; } // Connection info typedef bgp_ConnMode { // bits- Using string type string; } // BGP Distance typedef bgp_Distance { type uint16 { range "1..255"; } } // VRF Id typedef bgp_DomId { type uint32; } // Domain operational state typedef bgp_DomOperSt { type enumeration { // Unknown enum unknown { value 0; } // Up enum up { value 1; } // Down enum down { value 2; } } default "unknown"; } // Egress Peer Engineering EPE for neighbor status typedef bgp_EgressPeerEng { type enumeration { // Disabled enum none { value 0; } // Egress Peer Engineering Enabled enum enabled { value 1; } // Advertise Adjacency-SIDs for multi-hop neighbor paths enum enabled-adj-sid { value 2; } } default "none"; } // Event History Buffer Type typedef bgp_EhType { type enumeration { enum none { value 0; } // Cli buffer enum cli { value 1; } // Events buffer enum events { value 2; } // Periodic buffer enum periodic { value 3; } // Detailed buffer enum detail { value 4; } // Errors buffer enum errors { value 5; } // Objstore buffer enum objstore { value 6; } } default "none"; } // EVPN route-type typedef bgp_EvpnRtType { type enumeration { // Unspecified enum none { value 0; } // Ethernet Auto-Discovery route enum a-d { value 1; } // MAC/IP Advertisement route enum mac-ip { value 2; } // Inclusive Multicast Ethernet Tag route enum imet { value 3; } // Ethernet Segment route enum eth-seg { value 4; } // IP Prefix route enum ip-pfx { value 5; } } default "none"; } // Graceful restart controls // Default Value computed from complete typedef bgp_GrCtrl { // bits- Using string type string; default "complete"; } // Graceful restart interval typedef bgp_GrIntvl { type uint16 { range "1..3600"; } default "120"; } // Graceful stale interval typedef bgp_GrStaleIntvl { type uint16 { range "1..3600"; } default "300"; } // Hold Interval typedef bgp_HoldIntvl { type uint16 { range "3..3600"; } default "180"; } // IGP Preference typedef bgp_IgpPref { type uint8; } // IGP Route Type typedef bgp_IgpRtType { type uint8; } // Inherit template peer control bits. This contains common fields of peer and peer-session templates (please refer to // MOs PeerCont and SessionCont). typedef bgp_InheritContPeerCtrlType { // bits- Using string type string; } // Inherit template peer-policy control bits. (Please refer // to MO PolicyCont). typedef bgp_InheritContPeerPolicyCtrlType { // bits- Using string type string; } // Keepalive Interval typedef bgp_KaIntvl { type uint16 { range "0..3600"; } default "60"; } // Last error len typedef bgp_LastErrLen { type uint8; } // Last error value typedef bgp_LastErrVal { type uint32; } // NH iLast Resolved Timestamp typedef bgp_LastResolvTs { type string; default "0"; } // Label typedef bgp_Lbl { type uint32; default "0"; } // Link Attribute TLV flags for Link-state // Default Value computed from none typedef bgp_LnkLsAttrFlags { // bits- Using string type string; default "none"; } // Log Neighbor changes typedef bgp_LogNbrSt { type enumeration { // none enum none { value 0; } // Enable enum enable { value 1; } // Disable enum disable { value 2; } } default "none"; } // Link-State status typedef bgp_LsAdminSt { type enumeration { // Inactive enum inactive { value 0; } // Active enum active { value 1; } } default "inactive"; } // Link-State attribute entry type typedef bgp_LsAttrEntryType { type enumeration { // Unspecified enum none { value 0; } // Peer Node Segment Identifier enum peer-node-sid { value 1101; } // Peer Adjacency Segment Identifier enum peer-adj-sid { value 1102; } // Peer Set Segment Identifier enum peer-set-sid { value 1103; } } default "none"; } // Link-State NLRI Type typedef bgp_LsNlriType { type enumeration { // Unspecified enum none { value 0; } // Node NLRI enum node { value 1; } // Link NLRI enum link { value 2; } // IPv4 Topology Prefix NLRI enum ipv4-topo { value 3; } // IPv6 Topology Prefix NLRI enum ipv6-topo { value 4; } } default "none"; } // Link-State Protocol Identifier typedef bgp_LsProtoId { type enumeration { // Unspecified enum none { value 0; } // IS-IS Level 1 enum isis-l1 { value 1; } // IS-IS Level 2 enum isis-l2 { value 2; } // OSPFv2 enum ospf-v2 { value 3; } // Direct enum direct { value 4; } // Static configuration enum static { value 5; } // OSPFv3 enum ospf-v3 { value 6; } // Egress Peer Engineering enum epe { value 7; } } default "none"; } // Major notify error typedef bgp_MajNotifErr { type enumeration { // None enum none { value 0; } // Header Error enum hdr-err { value 1; } // Open Message Error enum open-msg-err { value 2; } // Update Message Error enum upd-msg-err { value 3; } // Holdtimer Expired enum hold-timer-exp { value 4; } // FSM Error enum fsm-err { value 5; } // Cease Error enum cease-err { value 6; } // Capability Message Error enum cap-msg-err { value 7; } // Process Restart Error enum process-restart-err { value 101; } // FD Read Error enum fd-read-err { value 102; } // FD Ioctl Error enum fd-ioctl-err { value 103; } // Peer Closed Session Error enum peer-close-sess-err { value 104; } // Peer Received Notification Error enum rcvd-notif-err { value 105; } // Received Duplicate Connection Request enum rcvd-dup-conn-req { value 106; } // Dynamic Capability no Buffer enum dyn-cap-no-buf { value 107; } } } // Maximum AS Limit typedef bgp_MaxAsLimit { type uint16 { range "0..512"; } } // Maximum Ecmp typedef bgp_MaxEcmp { type uint8 { range "1..64"; } default "1"; } // Maximum Peers typedef bgp_MaxPeerCnt { type uint32 { range "0..1000"; } } // Maximum Prefix typedef bgp_MaxPfx { type uint32; } // Action when the prefixes crosses the maximum limit typedef bgp_MaxPfxAct { type enumeration { // Log enum log { value 1; } // Shutdown enum shut { value 2; } // Restart enum restart { value 3; } } default "shut"; } // Duration before we restart the peer when the maximum // prefix limit is reached typedef bgp_MaxPfxDuration { // MAX Converted to int from 0xffff type uint16 { range "0..65535"; } } // Threshold at which warning is issued when number of prefixes // crosses the threshold, units in percentage typedef bgp_MaxPfxThresh { type uint8 { range "0..100"; } } // MED dampening interval typedef bgp_MedIntvl { type uint32 { range "0..4294967295"; } } // Memory consumed (in bytes) typedef bgp_MemConsumed { type uint32; } // Metric typedef bgp_Metric { type uint32; } // Minor notify error typedef bgp_MinNotifErr { type enumeration { // None enum none { value 0; } // Unspecified Msg Header Error enum unspecified-msg-hdr-err { value 1; } // Connection not Synchronized enum conn-not-synced { value 2; } // Bad Message Length enum bad-msg-len { value 3; } // Bad Message Type enum bad-msg-type { value 4; } // Unknown Message Header Error enum unknown-msg-hdr-err { value 5; } // Unspecified Open Error enum unspecified-open-err { value 6; } // Unsupported Version enum unsupp-version { value 7; } // Bad Peer AS enum bad-peer-as { value 8; } // Bad Peer Router ID enum bad-peer-rtrid { value 9; } // Unsupported Optional Parameter enum unsupp-opt-param { value 10; } // Authentication Error enum auth-err { value 11; } // Unacceptable Holdtime enum bad-holdtime { value 12; } // Unsupported Capability enum unsupp-cap { value 13; } // Unknown Open Header Error enum unknown-open-hdr-err { value 14; } // Unspecified Update Error enum unspecified-update-err { value 15; } // Malformed Attribute List enum malformed-attr-list { value 16; } // Unrecognized Wellknown Attr enum unrecognized-wellknown-attr { value 17; } // Missing Well-known Attribute enum missing-wellknown-attr { value 18; } // Attribute Flags Error enum attr-flags-err { value 19; } // Attribute Length Error enum attr-len-err { value 20; } // Invalid Origin Attribute enum invalid-origin-attr { value 21; } // Bgp AS Routing Loop Error enum as-loop-err { value 22; } // Invalid Next-hop Attribute enum invalid-nh-attr { value 23; } // Optional Attribute Error enum opt-attr-err { value 24; } // Invalid Network Field enum invalid-nw-field { value 25; } // Malformed AS Path enum bad-as-path { value 26; } // Unknown Update Header Error enum unknown-update-hdr-err { value 27; } // Unspecified Cease Error enum unspecified-cease-err { value 28; } // Maximum Prefix Count enum max-pfx-count-err { value 29; } // Administratively Shutdown enum admin-shut { value 30; } // Peer Deconfigured enum peer-decfg { value 31; } // Session Cleared enum session-cleared { value 32; } // Connection Rejected enum conn-rej { value 33; } // Other Configuration Change Error enum other-cfg-chg { value 34; } // Connection Collision Resolution enum conn-coll-resolution { value 35; } // Out of Resource enum out-of-rsrc { value 36; } // Dynamic Capability Configuration Change enum dyn-cap-cfg-chg { value 37; } // TTL Configuration Change enum ttl-cfg-chg { value 38; } // TTL Security Configuration Change enum ttl-security-cfg-chg { value 39; } // Passive Neighbor Configuration Change enum passive-neighbor-cfg-chg { value 40; } // Address-family Configuration Change enum af-cfg-chg { value 41; } // Route-reflector Configuration Change enum rr-cfg-chg { value 42; } // Router-id Configuration Change enum rtrid-cfg-chg { value 43; } // Confederation Id Change enum confed-id-chg { value 44; } // Confederation Membership Change enum confed-membership-change { value 45; } // Graceful-restart Configuration Change enum gr-cfg-chg { value 46; } // Soft-reconfiguration Change enum soft-recfg-chg { value 47; } // Update-source Interface Change enum updatesrc-if-chg { value 48; } // Local-as Change enum localas-chg { value 49; } // Unknown Cease Error enum unknown-cease-err { value 50; } // Unspecified Cappability Message Error enum unspecified-cap-msg-err { value 51; } // Unknown Sequence Number enum unknown-seq-num { value 52; } // Invalid Capability Length enum invalid-cap-len { value 53; } // Malformed Capability Value enum bad-cap-val { value 54; } // Unsupported Capability Code enum unsupp-cap-code { value 55; } // Unknown Capability Error enum unknown-cap-err { value 56; } } } // Mode typedef bgp_Mode { type enumeration { // Fabric enum fabric { value 1; } // External enum external { value 2; } } default "fabric"; } // MCAST-VPN NLRI route-type typedef bgp_MvpnRtType { type enumeration { // Unspecified enum none { value 0; } // Multicast Inter-AS PMSI Auto Discovery route enum interas-ipmsi-ad { value 1; } // Multicast Intra-AS PMSI Auto Discovery route enum intraas-ipmsi-ad { value 2; } // Multicast S-PMSI Auto Discovery route enum spmsi-ad { value 3; } // Multicast Leaf Auto Discovery route enum leaf-ad { value 4; } // Multicast Source-Active Auto Discovery route enum sa-ad { value 5; } // Shared C-Multicast route enum shared-c-mcast { value 6; } // Source C-Multicast route enum source-c-mcast { value 7; } } default "none"; } // NH Next Advertised Timestamp typedef bgp_NextAdvTs { type string; default "0"; } // Nexthop flags typedef bgp_NhFlags { // bits- Using string type string; } // Link Attribute TLV flags for Link-state // Default Value computed from none typedef bgp_NodeLsAttrFlags { // bits- Using string type string; default "none"; } // Number of paths typedef bgp_NumPaths { type uint32; } // Number of Peers typedef bgp_NumPeers { type uint32; } // Order (for AS path segments and AS path items) typedef bgp_Order { type uint16; } // Origin typedef bgp_Origin { type enumeration { // Learned Via IGP enum igp { value 1; } // Learned Via EGP enum egp { value 2; } // Learned by some other Means enum incomplete { value 3; } } default "igp"; } // Authentication status typedef bgp_PasswdSet { type enumeration { // Enabled enum enabled { value 1; } enum disabled { value 0; } } default "disabled"; } // Path flags typedef bgp_PathFlags { // bits- Using string type string; } // Path id typedef bgp_PathId { type uint32; } // Path status typedef bgp_PathSt { type enumeration { // Deleted enum deleted { value 0; } // Staled enum staled { value 1; } // Valid enum valid { value 2; } // InValid enum invalid { value 3; } // history enum history { value 4; } // suppressed enum suppressed { value 5; } // dampened enum dampened { value 6; } } } // Path type typedef bgp_PathT { type enumeration { // Internal enum internal { value 1; } // External enum external { value 2; } // Confederation enum confederation { value 3; } // Local enum local { value 4; } // Aggregate enum aggregate { value 5; } // Redistribute enum redistribute { value 6; } // Injected enum injected { value 7; } } default "internal"; } // Peer Address Family Control typedef bgp_PeerAfControl { // bits- Using string type string; } // Peer AF flags typedef bgp_PeerAfFlags { // bits- Using string type string; } // Peer Control typedef bgp_PeerControl { // bits- Using string type string; } // TODO: Change this to nw:Cnt64 Count of BGP Messages typedef bgp_PeerCount { type uint64; } // Peer Fabric Type typedef bgp_PeerFabType { type enumeration { // Fabric internal enum fabric-internal { value 0; } // Fabric external enum fabric-external { value 1; } // Fabric Border Leaf enum fabric-border-leaf { value 2; } } default "fabric-internal"; } // Peer flags typedef bgp_PeerFlags { // bits- Using string type string; } // Peer graceful restart state typedef bgp_PeerGrSt { type enumeration { // Not applicable enum na { value 1; } // Reset enum reset { value 2; } // Up enum up { value 3; } } default "na"; } // Peer Index typedef bgp_PeerIdx { type uint16; } // Peer operational state typedef bgp_PeerOperSt { type enumeration { // Unspecified enum unspecified { value 0; } // Illegal enum illegal { value 1; } // Shut enum shut { value 2; } // Idle enum idle { value 3; } // Connect enum connect { value 4; } // Active enum active { value 5; } // Open sent enum open-sent { value 6; } // Open confirm enum open-confirm { value 7; } // Established enum established { value 8; } // Closing enum closing { value 9; } // Error enum error { value 10; } // Unknown enum unknown { value 11; } } default "unspecified"; } // Peer Type typedef bgp_PeerType { type enumeration { // ibgp enum ibgp { value 1; } // ebgp enum ebgp { value 2; } } default "ibgp"; } // Pfx Flushed typedef bgp_PfxFlushed { type uint64; } // Prefix Attributes TLV flags for Link-state // Default Value computed from none typedef bgp_PfxLsAttrFlags { // bits- Using string type string; default "none"; } // TODO: Change this to nw:Cnt64 Counts for Prefix Peers typedef bgp_PfxPeerCounts { type uint64; } // Prefix Peer Timeout typedef bgp_PfxPeerTimeout { type uint16 { range "0..1200"; } } // Prefix Peer Wait typedef bgp_PfxPeerWaitTime { type uint16 { range "0..1200"; } } // TODO: Change this to nw:Cnt64 Pfx Saved typedef bgp_PfxSaved { type uint64; } // Pfx Sent typedef bgp_PfxSent { type uint64; } // Prefix-Sid attribute entry type typedef bgp_PfxSidAttrEntryType { type enumeration { // Unspecified enum none { value 0; } // Label Index enum label-index { value 1; } // IPv6-SID enum ipv6-sid { value 2; } // Originator SRGB enum origin-srgb { value 3; } } default "none"; } // PMSI Tunnel Type typedef bgp_PmsiTunType { type enumeration { // Unspecified enum none { value 0; } // Ingress Replication enum ingress-repl { value 1; } } default "none"; } // private-as Control typedef bgp_PrivateASControl { type enumeration { enum none { value 0; } // Remove private AS enum remove-exclusive { value 1; } // Remove all private AS enum remove-all { value 2; } // Replace private AS with local AS enum replace-as { value 3; } } default "none"; } // Reconnect Interval Value typedef bgp_ReConnectIntvl { type uint16 { range "1..60"; } default "60"; } // RNH Epoch typedef bgp_RnhEpoch { type uint8; } // Route control direction typedef bgp_RtCtrlDir { type enumeration { // Incoming enum in { value 1; } // Outgoing enum out { value 2; } } default "in"; } // Route control operational state typedef bgp_RtCtrlOperSt { type enumeration { // Unresolved enum unresolved { value 1; } // Resolved enum resolved { value 2; } } default "unresolved"; } // Route flags typedef bgp_RtFlags { // bits- Using string type string; } // Labeled address-family route flags typedef bgp_RtLblAfFlags { // bits- Using string type string; } // Route version typedef bgp_RtVer { type uint32; } // Route target policy type typedef bgp_RttPType { type enumeration { // Import enum import { value 1; } // Export enum export { value 2; } } default "import"; } // Segment Routing Global Block // Default Value "0" Removed - out of range 16..471804 typedef bgp_SRGBRange { type uint32 { range "16..471804"; } } // Peer shut state qualifier typedef bgp_ShutStQual { type enumeration { // Unspecified enum unspecified { value 0; } // Administratively down enum admin { value 1; } // No memory enum no-mem { value 2; } // Exceeded prefix limit enum exceeded-pfxlimit { value 3; } // Administratively up enum admin-up { value 4; } // No Affinity enum no-affinity { value 5; } } default "unspecified"; } // Event History Buffer Size typedef bgp_Size { type uint32 { range "0..4 | 8192..1048576"; } default "0"; } // FD to connect to the peer typedef bgp_SockFD { type uint32; } // Soft Reconfiguration typedef bgp_SoftReconfigBackup { type enumeration { enum none { value 0; } // Inbound Only enum inbound { value 1; } // Inbound Always enum inbound-always { value 2; } } } // BMP Server ID typedef bgp_SrvId { type uint8 { range "1..2"; } } // Peer Idle State Reason typedef bgp_StReason { type enumeration { enum none { value 0; } // NoMem enum no-mem { value 1; } } default "none"; } // Aggregate Address Summary-Only typedef bgp_SummaryOnly { type enumeration { // Enabled enum enabled { value 1; } // Disabled enum disabled { value 0; } } default "disabled"; } // Table state typedef bgp_TblSt { type enumeration { // Unknown enum unknown { value 0; } // Up enum up { value 1; } // Down enum down { value 2; } } } // Table version typedef bgp_TblVer { type uint32; } // eBGP Multihop TTL value typedef bgp_TtlVal { type uint16 { range "0..255"; } } // Unknown Attribute Length typedef bgp_UnknownAttrLen { // MAX Converted to int from 0xffffffff type uint32 { range "0..4294967295"; } } // Version typedef bgp_Ver { type enumeration { // BGP Version 4 enum v4 { value 4; } } default "v4"; } // VNID // Default Value "0" Removed - out of range 4096..16777215 typedef bgp_Vnid { // MAX Converted to int from 0xffffff type uint32 { range "4096..16777215"; } } // Dampen Igp Metric typedef bgp_igpMetric { type uint16 { range "0..3600"; } default "600"; } typedef cap_Constraint { type uint32; } typedef cap_Counter { type uint32; } typedef cap_Model { type string; } // Quantitative typedef cap_Quant { // MAX Converted to int from 0xFFFF type uint16 { range "0..65535"; } default "0"; } typedef cap_RaiseFaultState { type enumeration { enum nominal { value 0; } enum ruleHasLess { value 1; } enum ruleHasMore { value 2; } } default "nominal"; } typedef cap_RuleT { type enumeration { enum limit { value 1; } } default "limit"; } typedef cap_Scope { type enumeration { enum node { value 0; } enum policy-domain { value 1; } enum fabric { value 2; } } default "node"; } typedef cap_StorageHint { type uint8; } typedef cap_Vendor { type string; } typedef cap_Version { type string; } // Adjacency state qualifier typedef cdp_AdjStQual { // bits- Using string type string; } // Capability type typedef cdp_CapT { // bits- Using string type string; } // Neighbor device id typedef cdp_DevId { type string; } // Device identifier type typedef cdp_DevIdT { type enumeration { // MAC address enum mac { value 1; } // Serial number enum serialNum { value 2; } // System name enum sysName { value 3; } // System name and serial number enum sysNameAndSerialNum { value 4; } } default "sysNameAndSerialNum"; } // Neighbor device index typedef cdp_DevIndex { type uint32; } // Duplex typedef cdp_Duplex { type enumeration { // Unknown enum unknown { value 0; } // Half duplex enum half { value 1; } // Full duplex enum full { value 2; } } } // Hold interval // No Enums - transformed from scalar:Enum8 to scalar:UByte, YANG integer equivalent uint8 typedef cdp_HoldIntvl { type uint8 { range "10..255"; } default "180"; } // MTU typedef cdp_MTU { type uint32; } // Neighbor version typedef cdp_NbrVer { type string; } // Operational state typedef cdp_OperSt { type enumeration { // Up enum up { value 1; } // Down enum down { value 2; } } default "down"; } // Operational state qualifier typedef cdp_OperStQual { type enumeration { // Up enum up { value 1; } // Administratively down enum admin-down { value 2; } // Interface down enum if-down { value 3; } // Unsupported enum unsupported { value 4; } } default "unsupported"; } // Neighbor platform id typedef cdp_PlatId { type string; } // Neighbor port id typedef cdp_PortId { type string; } // System Location typedef cdp_SysLoc { type string; } // System name typedef cdp_SysName { type string; } // System OID Length typedef cdp_SysObjIdL { type uint8; } // System OID Value typedef cdp_SysObjIdV { type mtx_array_uint32; } // Transmission frequency // No Enums - transformed from scalar:Enum8 to scalar:UByte, YANG integer equivalent uint8 typedef cdp_TxFreq { type uint8 { range "5..254"; } default "60"; } // Version typedef cdp_Ver { type enumeration { // Version 1 enum v1 { value 1; } // Version 2 enum v2 { value 2; } } default "v2"; } // Vlan id typedef cdp_VlanId { type uint16; default "0"; } typedef comm_Port { type uint32 { range "1024..65000"; } } typedef comp_DelimitedString { type string; } typedef comp_HostState { type enumeration { // Maintenance Mode enum maintenance { value 0; } // Connected enum connected { value 1; } // Not Responding enum noresponse { value 2; } // Disconnected enum disconnected { value 3; } // Powered On enum poweredOn { value 4; } // Powered Off enum poweredOff { value 5; } // StandBy enum standBy { value 6; } // Suspended enum suspended { value 7; } // Unknown enum unknown { value 8; } } default "disconnected"; } typedef comp_NicInstType { type enumeration { // Unknown enum unknown { value 0; } // Baremetal Host enum phys { value 1; } // Virtual Machine enum virt { value 2; } // Hypervisor Host enum hv { value 3; } } default "unknown"; } typedef comp_NicState { type enumeration { // Down enum down { value 0; } // Up enum up { value 1; } } default "down"; } typedef comp_Vendor { type enumeration { enum VMware { value 1; } enum Microsoft { value 2; } } default "VMware"; } // Result of filter check typedef compat_FilterStatus { type enumeration { // failed enum failed { value 0; } // passed enum passed { value 1; } } default "failed"; } // Operation type typedef conftmpl_OperationType { type enumeration { // Create enum create { value 1; } // Delete enum delete { value 2; } } default "create"; } // Template type typedef conftmpl_TemplateType { type enumeration { // Unknown enum unknown { value 0; } // Vrf enum vrf { value 1; } // Vlan enum vlan { value 2; } // Intf enum intf { value 3; } } default "unknown"; } // Adj addr typedef coop_AdjAddr { type address_Ipv4; } // Adjacency flags typedef coop_AdjFlags { // bits- Using string type string; } // Adjacency operational state typedef coop_AdjOperSt { type enumeration { // Down enum down { value 1; } // Up enum up { value 2; } } default "down"; } // Adjacency operational state qualifier typedef coop_AdjOperStQual { type enumeration { // Unspecified enum unspecified { value 0; } // Route not reachable enum route-unreachable { value 1; } // TCP Connection Down enum tcp-down { value 2; } // Peer inactive enum peer-inactive { value 3; } // Peer congested enum peer-congested { value 4; } // Up enum up { value 5; } } default "unspecified"; } // Collisions load factor typedef coop_CollLdFactor { // MAX Converted to int from 0xffff type uint16 { range "1..65535"; } default "1"; } // Ctx flags typedef coop_CtxFlags { // bits- Using string type string; } // Dampen action typedef coop_DampAction { type enumeration { // Freeze enum freeze { value 1; } // Withdraw enum withdraw { value 2; } } default "freeze"; } // Half life typedef coop_DampHalfLife { // MAX Converted to int from 0xffff type uint16 { range "1..65535"; } default "10"; } // Dampen Penalty typedef coop_DampPenalty { // MAX Converted to int from 0xffff type uint16 { range "100..65535"; } default "1000"; } // Dampen reuse threshold typedef coop_DampReuseThresh { // MAX Converted to int from 0xffff type uint16 { range "100..65535"; } default "2500"; } // Dampen saturation threshold typedef coop_DampSatThresh { // MAX Converted to int from 0xffff type uint16 { range "100..65535"; } default "10000"; } // Dampen threshold typedef coop_DampThresh { // MAX Converted to int from 0xffff type uint16 { range "100..65535"; } default "4000"; } // Domain operational state typedef coop_DomOperSt { type enumeration { // Down enum down { value 0; } // Initializing enum init { value 1; } // Up enum up { value 2; } } default "down"; } // Domain operational state qualifier typedef coop_DomOperStQual { type enumeration { // Unspecified enum unspecified { value 0; } // Configuration not resolved enum config-unresolved { value 1; } // Time not synced enum time-not-synced { value 2; } // Infra domain down enum infra-dom-down { value 3; } // Council pending enum council-pending { value 4; } // Inconsistent configuration enum inconsistent-config { value 5; } // Admin down enum admin-down { value 6; } // Up enum up { value 7; } } default "unspecified"; } // Ep controls // Default Value computed from notify-citizen typedef coop_EpControl { // bits- Using string type string; default "notify-citizen"; } // Ep flags typedef coop_EpFlags { // bits- Using string type string; } // Graceful restart time (in seconds) typedef coop_GRTime { // MAX Converted to int from 0xffff type uint32 { range "1..65535"; } default "600"; } // Hello Interval (in seconds) typedef coop_HelloIntvl { // MAX Converted to int from 0xffff type uint16 { range "1..65535"; } default "60"; } // IGMP version typedef coop_IGMPVersion { type uint8 { range "1..3"; } default "2"; } // McastGrp flags typedef coop_McGrpFlags { // bits- Using string type string; } // Mrtr flags typedef coop_MrtrFlags { // bits- Using string type string; } // Peer controls typedef coop_PeerControl { // bits- Using string type string; } // Port id typedef coop_PortId { // MAX Converted to int from 0xffffffff type uint32 { range "0..4294967295"; } default "0"; } // Publisher id typedef coop_PubId { type address_Ipv4; } // Refresh interval (in seconds) typedef coop_RefreshIntvl { // MAX Converted to int from 0x2aaaaaaa type uint32 { range "1..715827882"; } default "3600"; } // Repository size typedef coop_RepSz { // MAX Converted to int from 0xffffffff type uint32 { range "1..4294967295"; } default "1000000"; } // Repository type typedef coop_RepT { type enumeration { // Endpoint reachability repository enum ep { value 1; } // Oracle repository enum oracle { value 2; } // Leaf repository enum leaf { value 3; } // Multicast group membership repository enum mgrpmbr { value 4; } // Multicast router repository enum mrouter { value 5; } // Service node repository enum svcnode { value 6; } // Anycast repository enum anycast { value 7; } // External router repository enum extrtr { value 8; } // VPC repository enum vpc { value 9; } // VTEP repository enum vtep { value 10; } // Context repository enum ctx { value 11; } } default "ep"; } // Role typedef coop_Role { type enumeration { // Citizen enum citizen { value 1; } // Oracle enum oracle { value 2; } } default "citizen"; } // Shard Interval typedef coop_ShardIntvl { // MAX Converted to int from 0xffffffff type uint32 { range "1..4294967295"; } } // Switch id typedef coop_SwId { type address_Ipv4; } // Synthetic flags typedef coop_SynthFlags { // bits- Using string type string; } // Synthetic Generator algorithm typedef coop_SynthGen { type enumeration { enum xxx { value 1; } } default "xxx"; } // Synthetic ip typedef coop_SynthIp { type address_Ipv4; } // Synthetic vrf typedef coop_SynthVrf { type uint32; } // Timestamp (NTP raw format) typedef coop_Timestamp { type string; } // VNID typedef coop_Vnid { // MAX Converted to int from 0xffffff type uint32 { range "1..16777215"; } default "1"; } // Specifies the HA mode in which this system is configured typedef top_Mode { type enumeration { enum unspecified { value 0; } enum stand-alone { value 1; } enum cluster { value 2; } } default "unspecified"; } grouping System-group { leaf id { type uint32; } // Specifies if this system is configured in standalone mode or HA pair // Type is an MO-Defined-Type leaf mode { description "System mode"; // Type is an MO-Defined-Type type top_Mode; } } container System { description "System"; uses System-group; } }
28,310
https://github.com/jackfoxy/aardvark.base/blob/master/src/Aardvark.Base/Math/Tensors/TensorMathExt_template.cs
Github Open Source
Open Source
Apache-2.0
2,022
aardvark.base
jackfoxy
C#
Code
1,769
4,677
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Aardvark.Base { public static class Vector { /// <summary> /// Vector constructor from a given array that does not require to write generic type /// </summary> public static Vector<T> Create<T>(T[] array) { return new Vector<T>(array); } } public static class Matrix { /// <summary> /// Matrix constructor from a given array that does not require to write generic type. /// </summary> public static Matrix<T> Create<T>(T[] array, int sx, int sy) { if (array.Length != sx * sy) throw new ArgumentException("Data array of matrix does not match given size"); return new Matrix<T>(array, sx, sy); } /// <summary> /// Matrix constructor from a given array that does not require to write generic type. /// </summary> public static Matrix<T> Create<T>(T[] array, long sx, long sy) { if (array.Length != sx * sy) throw new ArgumentException("Data array of matrix does not match given size"); return new Matrix<T>(array, sx, sy); } } public static class TensorMathExt { //# foreach (var isDouble in new[] { false, true }) { //# var ft = isDouble ? "double" : "float"; //# var tc = isDouble ? "d" : "f"; //# var zero = isDouble ? "0.0" : "0.0f"; #region Vector Extensions /// <summary> /// Calculates the dot product of two vectors: /// a dot b = Sum(a0*b0 + a1*b1 + ... aN*bN) /// </summary> public static __ft__ DotProduct(this Vector<__ft__> v0, Vector<__ft__> v1) { __ft__ result = __zero__; __ft__[] a0 = v0.Data, a1 = v1.Data; for (long i0 = v0.Origin, i1 = v1.Origin, e0 = i0 + v0.DSX, d0 = v0.D, d1 = v1.D; i0 != e0; i0 += d0, i1 += d1) result += a0[i0] * a1[i1]; return result; } /// <summary> /// Calculates the squared norm of a vector: /// ||a|| = Sum(a0*a0 + a1*a1 + ... aN*aN) /// </summary> public static __ft__ NormSquared(this Vector<__ft__> v) { __ft__ result = __zero__; __ft__[] a = v.Data; for (long i = v.Origin, e = i + v.DSX, d = v.D; i != e; i += d) result += a[i] * a[i]; return result; } public static __ft__ Dist1(this Vector<__ft__> v0, Vector<__ft__> v1) => v0.InnerProduct(v1, (x0, x1) => Fun.Abs(x1 - x0), __zero__, (s, p) => s + p); public static __ft__ Dist2Squared(this Vector<__ft__> v0, Vector<__ft__> v1) => v0.InnerProduct(v1, (x0, x1) => Fun.Square(x1 - x0), __zero__, (s, p) => s + p); public static __ft__ Dist2(this Vector<__ft__> v0, Vector<__ft__> v1) => Fun.Sqrt(v0.Dist2Squared(v1)); public static __ft__ DistMax(this Vector<__ft__> v0, Vector<__ft__> v1) => v0.InnerProduct(v1, (x0, x1) => Fun.Abs(x1 - x0), __zero__, Fun.Max); public static Vector<__ft__> Multiply(this Vector<__ft__> a, Vector<__ft__> b) { if (a.Dim != b.Dim) throw new InvalidOperationException("Cannot multiply vectors with different lengths!"); var result = new __ft__[a.Dim]; __ft__[] a0 = a.Data, a1 = b.Data; for (long i0 = a.Origin, ri = 0, i1 = b.Origin, e0 = i0 + a.DSX, d0 = a.D, d1 = b.D; i0 != e0; i0 += d0, i1 += d1, ri++) result[ri] = a0[i0] * a1[i1]; return Vector.Create(result); } /// <summary> /// Multiply vector a as column vector with vector b as row vector resulting a matrix [b.Dim x a.Dim] /// </summary> public static Matrix<__ft__> MultiplyTransposed(this Vector<__ft__> a, Vector<__ft__> b) { var result = new __ft__[b.Dim * a.Dim]; __ft__[] a0 = a.Data, a1 = b.Data; long f1 = b.Origin, e1 = f1 + b.DSX, d1 = b.D; for (long i0 = a.Origin, ri = 0, e0 = i0 + a.DSX, d0 = a.D; i0 != e0; i0 += d0) for (long i1 = f1; i1 != e1; i1 += d1, ri++) result[ri] = a0[i0] * a1[i1]; return Matrix.Create(result, b.Dim, a.Dim); } public static Vector<__ft__> Multiply(this Vector<__ft__> vec, __ft__ s) { var result = new __ft__[vec.Dim]; __ft__[] a0 = vec.Data; for (long i0 = vec.Origin, ri = 0, e0 = i0 + vec.DSX, d0 = vec.D; i0 != e0; i0 += d0, ri++) result[ri] = a0[i0] * s; return Vector.Create(result); } public static Vector<__ft__> Subtract(this Vector<__ft__> a, Vector<__ft__> b) { if (a.Dim != b.Dim) throw new InvalidOperationException(String.Format("Cannot subtract vectors with length {0} and {1}", a.Dim, b.Dim)); var result = new __ft__[a.Dim]; __ft__[] a0 = a.Data, a1 = b.Data; for (long i0 = a.Origin, ri = 0, i1 = b.Origin, e0 = i0 + a.DSX, d0 = a.D, d1 = b.D; i0 != e0; i0 += d0, i1 += d1, ri++) result[ri] = a0[i0] - a1[i1]; return Vector.Create(result); } public static Vector<__ft__> Subtract(this Vector<__ft__> a, __ft__ b) { var result = new __ft__[a.Dim]; __ft__[] a0 = a.Data; for (long i0 = a.Origin, ri = 0, e0 = i0 + a.DSX, d0 = a.D; i0 != e0; i0 += d0, ri++) result[ri] = a0[i0] - b; return Vector.Create(result); } public static Vector<__ft__> Add(this Vector<__ft__> a, Vector<__ft__> b) { if (a.Dim != b.Dim) throw new InvalidOperationException(String.Format("Cannot subtract vectors with length {0} and {1}", a.Dim, b.Dim)); var result = new __ft__[a.Dim]; __ft__[] a0 = a.Data, a1 = b.Data; for (long i0 = a.Origin, ri = 0, i1 = b.Origin, e0 = i0 + a.DSX, d0 = a.D, d1 = b.D; i0 != e0; i0 += d0, i1 += d1, ri++) result[ri] = a0[i0] + a1[i1]; return Vector.Create(result); } public static Vector<__ft__> Add(this Vector<__ft__> a, __ft__ b) { var result = new __ft__[a.Dim]; __ft__[] a0 = a.Data; for (long i0 = a.Origin, ri = 0, e0 = i0 + a.DSX, d0 = a.D; i0 != e0; i0 += d0, ri++) result[ri] = a0[i0] + b; return Vector.Create(result); } public static bool EqualTo(this Vector<__ft__> a, Vector<__ft__> b) { if (a.Dim != b.Dim) throw new InvalidOperationException("Cannot compare vectors with different lengths!"); bool eq = true; a.ForeachCoord(crd => eq &= a[crd] == b[crd]); return eq; } #endregion #region Matrix Extensions /// <summary> /// Multiply matrix with vector as column vector. /// Vector must have save length as columns of matrix. /// Returns a vector with size of matrix rows. /// </summary> public static Vector<__ft__> Multiply(this Matrix<__ft__> mat, Vector<__ft__> vec) { if (mat.Dim.X != vec.Dim) throw new InvalidOperationException(String.Format("Cannot multiply matrix {0} with vector of size {1}", mat.Dim, vec.Dim)); var result = new __ft__[mat.Dim.Y]; var data0 = mat.Data; var data1 = vec.Data; long my0 = mat.DY, d1 = vec.D; long mf1 = vec.FirstIndex; long ds0 = mat.DSX, d0 = mat.DX; for (long ri = 0, ye = mat.FirstIndex + mat.DSY, f0 = mat.FirstIndex, e0 = f0 + ds0; f0 != ye; f0 += my0, e0 += my0, ri++) { __ft__ dot = __zero__; for (long i0 = f0, i1 = mf1; i0 != e0; i0 += d0, i1 += d1) dot += data0[i0] * data1[i1]; result[ri] = dot; } return Vector.Create(result); } public static Matrix<__ft__> Multiply(this Matrix<__ft__> m0, Matrix<__ft__> m1) { if (m0.SX != m1.SY) throw new ArgumentException("m0.SX != m1.SY"); var result = new Matrix<__ft__>(m1.SX, m0.SY); var data = result.Data; var data0 = m0.Data; var data1 = m1.Data; long i = result.FirstIndex, yj = result.JY, my0 = m0.DY; long xs = result.DSX, mf1 = m1.FirstIndex, xj = result.JX, mx1 = m1.DX; long ds0 = m0.DSX, d0 = m0.DX, d1 = m1.DY; for (long ye = i + result.DSY, f0 = m0.FirstIndex, e0 = f0 + ds0; i != ye; i += yj, f0 += my0, e0 += my0) for (long xe = i + xs, f1 = mf1; i != xe; i += xj, f1 += mx1) { __ft__ dot = __zero__; for (long i0 = f0, i1 = f1; i0 != e0; i0 += d0, i1 += d1) dot += data0[i0] * data1[i1]; data[i] = dot; } return result; } public static Matrix<__ft__> Multiply(this Matrix<__ft__> mat, __ft__ a) { var result = new __ft__[mat.SX * mat.SY]; var data0 = mat.Data; long my0 = mat.DY; long mf0 = mat.FirstIndex; long ds0 = mat.DSX, d0 = mat.DX; for (long ri = 0, ye = mat.FirstIndex + mat.DSY, f0 = mat.FirstIndex, e0 = f0 + ds0; f0 != ye; f0 += my0, e0 += my0) { for (long i0 = f0; i0 != e0; i0 += d0, ri++) result[ri] = data0[i0] * a; } return Matrix.Create(result, mat.SX, mat.SY); } public static Matrix<__ft__> Subtract(this Matrix<__ft__> m0, Matrix<__ft__> m1) { if (m0.Dim != m1.Dim) throw new InvalidOperationException(String.Format("Cannot subtract matrix A={0} and matrix B={1}", m0.Dim, m1.Dim)); var result = new __ft__[m0.SX * m0.SY]; var data0 = m0.Data; var data1 = m1.Data; long mf0 = m0.FirstIndex, my0 = m0.DY, my1 = m1.DY; long ds0 = m0.DSX, d0 = m0.DX, d1 = m1.DX; for (long ye = mf0 + m0.DSY, f0 = mf0, f1 = m1.FirstIndex, ri = 0; f0 != ye; f0 += my0, f1 += my1) for (long xe = f0 + ds0, i0 = f0, i1 = f1; i0 != xe; i0 += d0, i1 += d1, ri++) result[ri] = data0[i0] - data1[i1]; return Matrix.Create(result, m0.SX, m0.SY); } public static Matrix<__ft__> Subtract(this Matrix<__ft__> mat, __ft__ a) { var result = new __ft__[mat.SX * mat.SY]; var data0 = mat.Data; long my0 = mat.DY; long mf0 = mat.FirstIndex; long ds0 = mat.DSX, d0 = mat.DX; for (long ri = 0, ye = mat.FirstIndex + mat.DSY, f0 = mat.FirstIndex, e0 = f0 + ds0; f0 != ye; f0 += my0, e0 += my0) { for (long i0 = f0; i0 != e0; i0 += d0, ri++) result[ri] = data0[i0] - a; } return Matrix.Create(result, mat.SX, mat.SY); } public static Matrix<__ft__> Add(this Matrix<__ft__> m0, Matrix<__ft__> m1) { if (m0.Dim != m1.Dim) throw new InvalidOperationException(String.Format("Cannot add matrix A={0} and matrix B={1}", m0.Dim, m1.Dim)); var result = new __ft__[m0.SX * m0.SY]; var data0 = m0.Data; var data1 = m1.Data; long mf0 = m0.FirstIndex, my0 = m0.DY, my1 = m1.DY; long ds0 = m0.DSX, d0 = m0.DX, d1 = m1.DX; for (long ye = mf0 + m0.DSY, f0 = mf0, f1 = m1.FirstIndex, ri = 0; f0 != ye; f0 += my0, f1 += my1) for (long xe = f0 + ds0, i0 = f0, i1 = f1; i0 != xe; i0 += d0, i1 += d1, ri++) result[ri] = data0[i0] + data1[i1]; return Matrix.Create(result, m0.SX, m0.SY); } public static Matrix<__ft__> Add(this Matrix<__ft__> mat, __ft__ a) { var result = new __ft__[mat.SX * mat.SY]; var data0 = mat.Data; long my0 = mat.DY; long mf0 = mat.FirstIndex; long ds0 = mat.DSX, d0 = mat.DX; for (long ri = 0, ye = mat.FirstIndex + mat.DSY, f0 = mat.FirstIndex, e0 = f0 + ds0; f0 != ye; f0 += my0, e0 += my0) { for (long i0 = f0; i0 != e0; i0 += d0, ri++) result[ri] = data0[i0] + a; } return Matrix.Create(result, mat.SX, mat.SY); } public static bool EqualTo(this Matrix<__ft__> a, Matrix<__ft__> b) { if (a.Dim != b.Dim) throw new InvalidOperationException(String.Format("Cannot compare matrix A={0} and matrix B={1}", a.Dim, b.Dim)); bool eq = true; a.ForeachCoord(crd => eq &= a[crd] == b[crd]); return eq; } #endregion //# } } }
35,474
https://github.com/chenrensong/T4/blob/master/src/Coding4Fun.VisualStudio.Telemetry/Coding4Fun.VisualStudio.RemoteSettings/IStableRemoteSettingsProvider.cs
Github Open Source
Open Source
MIT
null
T4
chenrensong
C#
Code
25
87
using System; namespace Coding4Fun.VisualStudio.RemoteSettings { internal interface IStableRemoteSettingsProvider : IRemoteSettingsProvider, ISettingsCollection, IDisposable { bool IsStable(string collectionPath); void MakeStable<T>(string collectionPath, string key, T value); } }
12,543
https://github.com/microsoft/BuildXL/blob/master/Public/Src/FrontEnd/TypeScript.Net/TypeScript.Net.UnitTests/Parsing/NumberLiterals.cs
Github Open Source
Open Source
MIT
2,023
BuildXL
microsoft
C#
Code
76
279
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using TypeScript.Net.Types; using TypeScript.Net.UnitTests.Utils; using Xunit; namespace TypeScript.Net.UnitTests.Parsing { public class NumberLiterals { [Theory] [InlineData("1", "1")] [InlineData(".1", ".1")] [InlineData("1.", "1")] // This is a special case, because 1. just parsed to 1 [InlineData("1.5", "1.5")] [InlineData("0x111111111111111111111111111", "21634570243895115118877068038417")] public void TestNumberLiterals(string s, string expectedLiteral) { string code = $"let x = {s};"; var node = ParsingHelper.ParseFirstStatementFrom<IVariableStatement>(code, roundTripTesting: false); var literal = node.DeclarationList.Declarations[0].Initializer.Cast<ILiteralExpression>(); Assert.Equal(expectedLiteral, literal.Text); } } }
10,375
https://github.com/wayshall/onetwo/blob/master/core/modules/poi/src/main/java/org/onetwo/ext/poi/excel/reader/ExtractorMapKey.java
Github Open Source
Open Source
Apache-2.0
2,021
onetwo
wayshall
Java
Code
9
41
package org.onetwo.ext.poi.excel.reader; public interface ExtractorMapKey { String getExtractorMapKey(); }
30,779
https://github.com/StephenMcConnel/BloomDesktop/blob/master/src/BloomExe/web/controllers/OrthographyConverter.cs
Github Open Source
Open Source
MIT
2,022
BloomDesktop
StephenMcConnel
C#
Code
774
1,881
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; namespace Bloom.web.controllers { public class OrthographyConverter { private Dictionary<string, string> mappings; private IOrderedEnumerable<int> keyLengthsThatHaveMappings; #region Construction and/or Initialization /// <summary> /// Constructor /// </summary> /// <param name="filename">The filename containing the conversion settings. It should be tab-delimited with 2 columns. The 1st column is a sequence of 1 or more characters in the source language. The 2nd column contains a sequence of characteres to map to in the target language.</param> public OrthographyConverter(string filename) { InitializeMappings(filename); } /// <summary> /// Constructor /// </summary> /// <param name="mappings">Construct the mapping from an existing dictionary (done by reference)</param> public OrthographyConverter(Dictionary<string, string> mappings) { InitializeMappings(mappings); } /// <summary> /// Initialize the mappings from a file /// </summary> /// <param name="filename">The filename containing the conversion settings. It should be tab-delimited with 2 columns. The 1st column is a sequence of 1 or more characters in the source language. The 2nd column contains a sequence of characteres to map to in the target language.</param> protected void InitializeMappings(string filename) { this.mappings = new Dictionary<string, string>(); string[] lines = File.ReadAllLines(filename); foreach (var line in lines) { // Allow empty lines and # comments. (See BL-7023) if (string.IsNullOrWhiteSpace(line) || line.TrimStart().StartsWith("#")) continue; // Allow any number of spaces or tabs to separate fields on a line. (See BL-7023) string[] fields = line.Split(new [] {'\t', ' '}, StringSplitOptions.RemoveEmptyEntries); if (fields.Length >= 2) { Debug.Assert(!mappings.ContainsKey(fields[0]), $"Invalid Orthography Conversion settings ({filename}). Duplicate key: \"{fields[0]}\"."); this.mappings[fields[0]] = fields[1]; // Nothing particularly good to do if a duplicate exists, so might as well overwrite it. } else { Debug.Assert(false, $"OrthographyConverter: Parsed line with invalid format (2+ fields expected): \"{line}\""); } } FinalizeInitialization(); } /// <summary> /// Initialize the mappings directly from a dictionary (by reference) /// </summary> protected void InitializeMappings(Dictionary<string, string> mappings) { this.mappings = mappings; FinalizeInitialization(); } /// <summary> /// Must be called at the end of any initialization of mappings /// </summary> protected void FinalizeInitialization() { // When we apply the mapping, it is really helpful for us to know // 1) What is the longest prefix? // 2) All the valid lengths of the prefixes // So we create this list to help us look up that info easily later this.keyLengthsThatHaveMappings = this.mappings.Keys.Select(x => x.Length) // the number of characters in the key (unmapped) side of the mapping .Where(x => x > 0) // Ensure no empty strings .Distinct() // Make distinct count .OrderByDescending(x => x); // Sorted it from biggest to smallest } #endregion /// <summary> /// Takes an unmapped string and applies this orthography conversion to it. /// </summary> public string ApplyMappings(string unmapped) { StringBuilder mapped = new StringBuilder(); if (String.IsNullOrEmpty(unmapped)) { return unmapped; } // Determine whether some prefix of this string matches any of the orthography conversion rules // We can just calculate all the prefixes that could possibly match a rule based on prefix length. // We want the longest matched rules to take precedence, so we start with the longest possible prefix and work our way down. // Once we have the prefix, we can just check if it exists in the mapping dictionary. // There's no need to enumerate all the other rules of the same length in the dictionary because for a single given length, only one rule could be able to match. int index = 0; while (index < unmapped.Length) { bool wasMatched = false; foreach (var possibleKeyLength in this.keyLengthsThatHaveMappings) { if (index + possibleKeyLength > unmapped.Length) { // Not enough chars left to construct this prefix. Continue on to the next prefix to check. continue; } string prefix = unmapped.Substring(index, possibleKeyLength); string replacement; if (this.mappings.TryGetValue(prefix, out replacement)) { mapped.Append(replacement); index += prefix.Length; wasMatched = true; break; } } if (!wasMatched) { // If nothing was matched, we can only safely advance 1. (Not by this.keyLengthsWithMappings.Max()) // For example, even if this index didn't have a trigram match, there could be a trigram match on the next index. // So can only advance by 1, not by 3. mapped.Append(unmapped[index]); ++index; } } return mapped.ToString(); } #region Filename Parsing // Given a filename, determines if it matches the expected format. If so, returns a tuple containing the source and target language codes. // If not, returns null instead. // Expected format: convert_[sourceLang](-[sourceScript])_to_[targetLang](-[targetScript]).txt public static Tuple<string, string> ParseSourceAndTargetFromFilename(string path) { string basename = Path.GetFileName(path); string[] fields = basename.Split('_'); if (fields.Length != 4) { return null; } else if (fields[0] != "convert" || fields[2] != "to") { return null; } else if (!basename.EndsWith(".txt")) { return null; } string source = fields[1]; string target = fields[3]; var extensionStartIndex = target.LastIndexOf('.'); target = target.Substring(0, extensionStartIndex); return Tuple.Create(source, target); } #endregion } }
44,330
https://github.com/mdznr/Genesis/blob/master/iOS/Genesis/Genesis/GNTableViewCell.h
Github Open Source
Open Source
ISC
2,012
Genesis
mdznr
Objective-C
Code
21
69
// // GNTableViewCell.h // Genesis // // Created by Matt on 5/22/12. // // #import <UIKit/UIKit.h> @interface GNTableViewCell : UITableViewCell @end
46,268
https://github.com/josephweinkam/embc-ess-mod/blob/master/responders/src/UI/embc-responder/src/app/feature-components/search/evacuee-search/evacuee-id-verify/evacuee-id-verify.component.ts
Github Open Source
Open Source
Apache-2.0
null
embc-ess-mod
josephweinkam
TypeScript
Code
161
618
import { Component, OnInit, Output, EventEmitter } from '@angular/core'; import { AbstractControl, FormBuilder, FormGroup, Validators } from '@angular/forms'; import { EvacueeSearchContextModel } from 'src/app/core/models/evacuee-search-context.model'; import { EvacueeSearchService } from '../evacuee-search.service'; @Component({ selector: 'app-evacuee-id-verify', templateUrl: './evacuee-id-verify.component.html', styleUrls: ['./evacuee-id-verify.component.scss'] }) export class EvacueeIdVerifyComponent implements OnInit { @Output() showIDPhotoComponent = new EventEmitter<boolean>(); idVerifyForm: FormGroup; evacueeSearchContextModel: EvacueeSearchContextModel; paperBased: boolean; tipsPanel1State = false; tipsPanel2State = false; constructor( private builder: FormBuilder, private evacueeSearchService: EvacueeSearchService ) {} /** * On component init, constructs the form */ ngOnInit(): void { this.constructIdVerifyForm(); this.paperBased = this.evacueeSearchService.paperBased; } /** * Returns form control */ get idVerifyFormControl(): { [key: string]: AbstractControl } { return this.idVerifyForm.controls; } /** * Builds the form */ constructIdVerifyForm(): void { this.idVerifyForm = this.builder.group({ photoId: [ this.evacueeSearchContextModel?.hasShownIdentification, [Validators.required] ] }); } /** * Saves the seach parameter into the model and Navigates to the evacuee-name-search component */ next(): void { // this.evacueeSearchService.setHasShownIdentification( // this.idVerifyForm.get('photoId').value // ); const idVerify = { hasShownIdentification: this.idVerifyForm.get('photoId').value }; this.evacueeSearchService.evacueeSearchContext = idVerify; this.showIDPhotoComponent.emit(false); } }
1,875
https://github.com/cisowscy-com-software/get-FTDNA-project-list/blob/master/bin/STEP_1_D_.js
Github Open Source
Open Source
BSD-3-Clause
null
get-FTDNA-project-list
cisowscy-com-software
JavaScript
Code
533
2,160
const SYS = require("./sys"); const curentDir = SYS.thisSolution(); REFACTORING(); STEP_2_INIT(); function REFACTORING() { const START = new Date(); const rawDATA = [SYS.step1B(curentDir), SYS.step1C(curentDir)]; SYS.step1D(curentDir, [{ V_Contacts: Array.from(V_contacts().values()) }, { V_Projects: Array.from(V_projects().values()) }, { E_ProjCont: E_projects_contacts() } ], 1); SYS.timeflow('step1D_refactoring_list_projects', curentDir, START); function V_contacts() { let emails = new Map(); rawDATA[1].forEach(e => { e.href2mail.forEach(m => { if ((m.mail.match(/@/g) || []).length == 1) { emails.set(m.mail, new Set()); } }); }); rawDATA[1].forEach(e => { e.href2mail.forEach(m => { if ((m.mail.match(/@/g) || []).length == 1) { emails.get(m.mail).add(m.name); } }); }); let rezult = new Map(); let i = 0; emails.forEach((n, e) => { rezult.set(e, { key: i, email: e.replace("mailto:", ""), name: [...n] }); i++; }); return rezult; } function V_projects() { let proj = new Map(); let typProj = new Map(); rawDATA[0].forEach(c => { typProj.set(c.idS0, c.type); }); rawDATA[1].map(e => { return { name: { text: e.name, goJoin: (e.href2join.charAt(e.href2join.length - 1) == '&' ? e.href2join.slice(0, -1) : e.href2join).slice(50), goInfo: e.href2info.slice(37, -12), goData: (e.href2data.length > 0) ? e.href2data[0].replace("?iframe=yresults", "").replace("?iframe=ycolorized", "").replace("?iframe=ymap", "").replace("?iframe=ysnp", "").replace("?iframe=mtresults", "").replace("?iframe=mtmap", "").slice(37) : null }, members: e.size, results: (function (s) { let o = {}; ["yresults", "ycolorized", "ymap", "ysnp", "mtresults", "mtmap"].forEach(q => { o[q] = s.has(q); }); return o; }(new Set(e.href2data.map(a => { return a.match(/(?<=iframe=)(.*)/gm)[0]; })))), type: typProj.get(e.idS0) }; }).forEach(p => { proj.set(p.name.goInfo, p); }); let rezult = new Map(); let i = 0; proj.forEach((v, k) => { v.key = i; rezult.set(k, v); i++; }); return rezult; } function E_projects_contacts() { let w = new Set(); rawDATA[1].forEach(e => { let keyProject, keyContact; keyProject = V_projects().get(e.href2info.slice(37, -12)).key; if (e.href2mail.length > 0) { e.href2mail.forEach(m => { if ((m.mail.match(/@/g) || []).length == 1) { keyContact = V_contacts().get(m.mail).key; w.add([keyProject, keyContact].join("_")); } }); } }); let rez = []; let ii = 0; w.forEach(e => { let kp = parseInt(e.split("_")[0]); let kc = parseInt(e.split("_")[1]); rez.push({ key: ii, key_V_project: kp, key_V_contact: kc }); ii++; }); return rez; } } function STEP_2_INIT() { const START = new Date(); const projects = SYS.projectsList(curentDir); let toGet = { map: [], str: [], snp: [], hvr: [] }; let iMap = 0, iHVR = 0, iSNP = 0, iSTR = 0; projects.forEach(p => { if (p.results.ymap) { toGet.map.push({ uri: 'https://www.familytreedna.com/ws/PublicmyMaps.aspx?axn=getdata&group=' + p.name.goData + '&dnaType=YDNA&subgroup=', dest: ['./.temp/' + curentDir + '/step3/' + p.key + '/forefather/map.json'], timeout: 30000, key: iMap, projKey: p.key, mapType: "forefather" }); iMap++; } if (p.results.mtmap) { toGet.map.push({ uri: 'https://www.familytreedna.com/ws/PublicmyMaps.aspx?axn=getdata&group=' + p.name.goData + '&dnaType=mtDNA&subgroup=', dest: ['./.temp/' + curentDir + '/step3/' + p.key + '/foremother/map.json'], timeout: 30000, key: iMap, projKey: p.key, mapType: "foremother" }); iMap++; } if (p.results.mtresults) { toGet.hvr.push({ uri: 'https://www.familytreedna.com/public/' + p.name.goData + '?iframe=yresults', dest: [ './.temp/' + curentDir + '/step2/' + p.key + '/foremother/rSRS.log', './.temp/' + curentDir + '/step2/' + p.key + '/foremother/rCRS.log' ], key: iHVR, projKey: p.key }); iHVR++; } if (p.results.ysnp) { toGet.snp.push({ uri: 'https://www.familytreedna.com/public/' + p.name.goData + '?iframe=yresults', dest: [ './.temp/' + curentDir + '/step2/' + p.key + '/forefather/SNP.log' ], key: iSNP, projKey: p.key }); iSNP++; } if (p.results.yresults) { toGet.str.push({ uri: 'https://www.familytreedna.com/public/' + p.name.goData + '?iframe=yresults', dest: [ './.temp/' + curentDir + '/step2/' + p.key + '/forefather/STR.log' ], key: iSTR, projKey: p.key }); iSTR++; } }); SYS.step2A(curentDir, toGet); SYS.timeflow('step2A_generating_list_tasks_to_download', curentDir, START); const START2 = new Date(); SYS.step2B(toGet, true); SYS.timeflow('step2B_generating_path_to_results_files', curentDir, START2); const START3 = new Date(); SYS.step2C(toGet.map.length); SYS.timeflow('step2C_generating_run_files4next_steps', curentDir, START3); }
48,987
https://github.com/fdobbie/plcrashreporter/blob/master/Scripts/build-xcframework.sh
Github Open Source
Open Source
Apache-2.0
null
plcrashreporter
fdobbie
Shell
Code
104
394
#!/bin/sh set -e # Build Mac Catalyst. # Print only target name and issues. Mimic Xcode output to make prettify tools happy. echo "=== BUILD TARGET ${PROJECT_NAME} iOS Framework OF PROJECT ${PROJECT_NAME} WITH CONFIGURATION ${CONFIGURATION} ===" # OBJROOT must be customized to avoid conflicts with the current process. xcodebuild -quiet \ SYMROOT="${SYMROOT}" OBJROOT="${BUILT_PRODUCTS_DIR}" PROJECT_TEMP_DIR="${PROJECT_TEMP_DIR}" \ ONLY_ACTIVE_ARCH=NO ARCHS="${ARCHS}" \ -project "${PROJECT_NAME}.xcodeproj" -configuration "${CONFIGURATION}" -scheme "${PROJECT_NAME} iOS Framework" \ -destination 'platform=macOS,variant=Mac Catalyst' # Remove the previous version of the xcframework. rm -rf "${BUILT_PRODUCTS_DIR}/${PRODUCT_NAME}.xcframework" # Build XCFramework. for SDK in iphoneos iphonesimulator appletvos appletvsimulator macOS maccatalyst; do FRAMEWORK_PATH="${BUILD_DIR}/${CONFIGURATION}-${SDK}/${PRODUCT_NAME}.framework" XC_FRAMEWORKS+=( -framework "${FRAMEWORK_PATH}") done xcodebuild -create-xcframework "${XC_FRAMEWORKS[@]}" -output "${BUILT_PRODUCTS_DIR}/${PRODUCT_NAME}.xcframework"
50,258
https://github.com/UtahRapter/FossilArcheology1.7/blob/master/src/main/java/com/github/revival/common/handler/PickupHandler.java
Github Open Source
Open Source
CC-BY-4.0, LicenseRef-scancode-unknown-license-reference
2,016
FossilArcheology1.7
UtahRapter
Java
Code
130
869
package com.github.revival.common.handler; import com.github.revival.common.block.FABlockRegistry; import com.github.revival.common.enums.EnumPrehistoric; import com.github.revival.common.item.FAItemRegistry; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.common.gameevent.PlayerEvent; import net.minecraft.item.Item; public class PickupHandler { @SubscribeEvent public void notifyPickup(PlayerEvent.ItemPickupEvent event) { } @SubscribeEvent public void notifyPickup(PlayerEvent.ItemCraftedEvent event) { } @SubscribeEvent public void notifyPickup(PlayerEvent.ItemSmeltedEvent event) { //Analyzer Achievements if (EnumPrehistoric.isDNA(event.smelting.getItem())) { event.player.addStat(FossilAchievementHandler.dinoDna, 1); } if (event.smelting.getItem() == FAItemRegistry.stoneboard) { event.player.addStat(FossilAchievementHandler.tablet, 1); } if (event.smelting.getItem() == FAItemRegistry.fossilSeed || event.smelting.getItem() == FAItemRegistry.fossilSeed_fern) { event.player.addStat(FossilAchievementHandler.fossilSeeds, 1); } if (event.smelting.getItem() == FAItemRegistry.failuresaurusFlesh) { event.player.addStat(FossilAchievementHandler.failuresaurusAnalyzer, 1); } //Cultivator Achievements if (EnumPrehistoric.isDinoEgg(event.smelting.getItem())) { event.player.addStat(FossilAchievementHandler.dinoEgg, 1); } if (EnumPrehistoric.isDNA(event.smelting.getItem())) { event.player.addStat(FossilAchievementHandler.mammalEmbryo, 1); } if (EnumPrehistoric.isBestBirdEgg(event.smelting.getItem())) { event.player.addStat(FossilAchievementHandler.birdEgg, 1); } //Workbench Achievements if (event.smelting.getItem() == FAItemRegistry.ancientSword) { event.player.addStat(FossilAchievementHandler.fixedSword, 1); } if (event.smelting.getItem() == FAItemRegistry.ancienthelmet) { event.player.addStat(FossilAchievementHandler.fixedHelmet, 1); } if (event.smelting.getItem() == Item.getItemFromBlock(FABlockRegistry.vaseAmphoraBlock) || event.smelting.getItem() == Item.getItemFromBlock(FABlockRegistry.vaseKylixBlock) || event.smelting.getItem() == Item.getItemFromBlock(FABlockRegistry.vaseVoluteBlock)) { event.player.addStat(FossilAchievementHandler.fixedVase, 1); } } }
7,567
https://github.com/DockBio/utilities/blob/master/src/Utils/Utils/Math/AutomaticDifferentiation/AutomaticDifferentiationHelpers.h
Github Open Source
Open Source
BSD-3-Clause
null
utilities
DockBio
C
Code
1,048
2,757
/** * @file * @copyright This code is licensed under the 3-clause BSD license.\n * Copyright ETH Zurich, Laboratory for Physical Chemistry, Reiher Group.\n * See LICENSE.txt for details. */ #ifndef AUTOMATICDIFFERENTIATION_AUTOMATICDIFFERENTIATIONHELPERS_H #define AUTOMATICDIFFERENTIATION_AUTOMATICDIFFERENTIATIONHELPERS_H #include "../DerivOrderEnum.h" #include "AutomaticDifferentiationTypesHelper.h" #include "TypeDefinitions.h" #include <Eigen/Core> /** * * This header file contains functions that allow for common notation for common * things that can be done at a different degree of derivatives. * */ namespace Scine { namespace Utils { namespace AutomaticDifferentiation { /** * @brief Get the enum corresponding to the derivative order. */ inline derivOrder getDerivativeOrderEnum(unsigned order) { return (order == 0) ? derivOrder::zero : order == 1 ? derivOrder::one : derivOrder::two; } /** * @brief Get the integer corresponding to the derivative order. */ inline int getDerivativeOrder(derivOrder order) { return (order == derivOrder::zero) ? 0 : order == derivOrder::one ? 1 : 2; } /** * @brief Create a value with derivatives in 1 dimension and neglect the unnecessary derivatives. */ template<derivOrder o> Value1DType<o> getFromFull(double v, double firstDer, double secondDer); /** * @brief Transform a double to a ValueWithDerivative in one dimension, with derivatives equal to zero. */ template<derivOrder o> Value1DType<o> constant1D(double c); /** * @brief Transform v to a ValueWithDerivative in one dimension, with first derivative 1 and second derivative 0. */ template<derivOrder o> Value1DType<o> variableWithUnitDerivative(double v); /** * @brief Transform a double to a ValueWithDerivative in three dimensions, with derivatives equal to zero. */ template<derivOrder o> Value3DType<o> constant3D(double c); /** * @brief Get X as a value with derivatives in three dimensions. The only non-zero derivative is the first derivative in * x-direction. */ template<derivOrder o> Value3DType<o> toX(double x); /** * @brief Get Y as a value with derivatives in three dimensions. The only non-zero derivative is the first derivative in * y-direction. */ template<derivOrder o> Value3DType<o> toY(double y); /** @brief Get Z as a value with derivatives in three dimensions. The only non-zero derivative is the first derivative * in z-direction. */ template<derivOrder o> Value3DType<o> toZ(double z); /** * @brief Get R-squared as a value with derivatives in three dimensions. */ template<derivOrder o> Value3DType<o> toRSquared(double x, double y, double z); /** * @brief Get a value with derivatives in 3 dimensions from the value with derivatives in one dimension, given a vector * R. */ template<derivOrder o> Value3DType<o> get3Dfrom1D(Value1DType<o> v, const Eigen::Vector3d& R); /** * @brief Get the value with inverted derivatives (useful for pairs of derivatives for two atoms). The sign of the first * derivatives changes. */ template<derivOrder o> Value3DType<o> getValueWithOppositeDerivative(const Value3DType<o>& v); /** * @brief Extract the value with derivatives in 1 dimension as a double. */ template<derivOrder o> double getValue1DAsDouble(const Value1DType<o>& v); /** * @brief Extract the value with derivatives in 3 dimension as a double. */ template<derivOrder o> double getValue3DAsDouble(const Value3DType<o>& v); /* * Inline implementations of all functions declared above. */ template<> inline double constant1D<derivOrder::zero>(double c) { return c; } template<> inline double variableWithUnitDerivative<derivOrder::zero>(double v) { return v; } template<> inline double getFromFull<derivOrder::zero>(double v, double /*firstDer*/, double /*secondDer*/) { return v; } template<> inline double constant3D<derivOrder::zero>(double c) { return c; } template<> inline double toX<derivOrder::zero>(double x) { return x; } template<> inline double toY<derivOrder::zero>(double y) { return y; } template<> inline double toZ<derivOrder::zero>(double z) { return z; } template<> inline double toRSquared<derivOrder::zero>(double x, double y, double z) { return x * x + y * y + z * z; } template<> inline double get3Dfrom1D<derivOrder::zero>(double v, const Eigen::Vector3d& /*R*/) { return v; } template<> inline double getValueWithOppositeDerivative<derivOrder::zero>(const double& v) { return v; } template<> inline double getValue1DAsDouble<derivOrder::zero>(const double& v) { return v; } template<> inline double getValue3DAsDouble<derivOrder::zero>(const double& v) { return v; } template<> inline First1D constant1D<derivOrder::one>(double c) { return {c, 0}; } template<> inline First1D variableWithUnitDerivative<derivOrder::one>(double v) { return {v, 1}; } template<> inline First1D getFromFull<derivOrder::one>(double v, double firstDer, double /*secondDer*/) { return {v, firstDer}; } template<> inline First3D constant3D<derivOrder::one>(double c) { return {c, 0, 0, 0}; } template<> inline First3D toX<derivOrder::one>(double x) { return {x, 1, 0, 0}; } template<> inline First3D toY<derivOrder::one>(double y) { return {y, 0, 1, 0}; } template<> inline First3D toZ<derivOrder::one>(double z) { return {z, 0, 0, 1}; } template<> inline First3D toRSquared<derivOrder::one>(double x, double y, double z) { return {x * x + y * y + z * z, 2 * x, 2 * y, 2 * z}; } template<> inline First3D get3Dfrom1D<derivOrder::one>(First1D v, const Eigen::Vector3d& R) { Eigen::Vector3d normalizedR = R.normalized(); return {v.value(), v.derivative() * normalizedR.x(), v.derivative() * normalizedR.y(), v.derivative() * normalizedR.z()}; } template<> inline First3D getValueWithOppositeDerivative<derivOrder::one>(const First3D& v) { return v.opposite(); } template<> inline double getValue1DAsDouble<derivOrder::one>(const First1D& v) { return v.value(); } template<> inline double getValue3DAsDouble<derivOrder::one>(const First3D& v) { return v.value(); } template<> inline Second1D constant1D<derivOrder::two>(double c) { return {c, 0, 0}; } template<> inline Second1D variableWithUnitDerivative<derivOrder::two>(double v) { return {v, 1, 0}; } template<> inline Second1D getFromFull<derivOrder::two>(double v, double firstDer, double secondDer) { return {v, firstDer, secondDer}; } template<> inline Second3D constant3D<derivOrder::two>(double c) { return {c, 0, 0, 0}; } template<> inline Second3D toX<derivOrder::two>(double x) { return {x, 1, 0, 0}; } template<> inline Second3D toY<derivOrder::two>(double y) { return {y, 0, 1, 0}; } template<> inline Second3D toZ<derivOrder::two>(double z) { return {z, 0, 0, 1}; } template<> inline Second3D toRSquared<derivOrder::two>(double x, double y, double z) { return {x * x + y * y + z * z, 2 * x, 2 * y, 2 * z, 2, 2, 2, 0, 0, 0}; } template<> inline Second3D get3Dfrom1D<derivOrder::two>(Second1D v, const Eigen::Vector3d& R) { double norm = R.norm(); Eigen::Vector3d normalizedR = R / norm; double firstDerivDividedByR = v.first() / norm; return {v.value(), v.first() * normalizedR.x(), v.first() * normalizedR.y(), v.first() * normalizedR.z(), v.second() * normalizedR.x() * normalizedR.x() + firstDerivDividedByR * (1 - normalizedR.x() * normalizedR.x()), v.second() * normalizedR.y() * normalizedR.y() + firstDerivDividedByR * (1 - normalizedR.y() * normalizedR.y()), v.second() * normalizedR.z() * normalizedR.z() + firstDerivDividedByR * (1 - normalizedR.z() * normalizedR.z()), v.second() * normalizedR.x() * normalizedR.y() - firstDerivDividedByR * normalizedR.x() * normalizedR.y(), v.second() * normalizedR.x() * normalizedR.z() - firstDerivDividedByR * normalizedR.x() * normalizedR.z(), v.second() * normalizedR.y() * normalizedR.z() - firstDerivDividedByR * normalizedR.y() * normalizedR.z()}; } template<> inline Second3D getValueWithOppositeDerivative<derivOrder::two>(const Second3D& v) { return v.opposite(); } template<> inline double getValue1DAsDouble<derivOrder::two>(const Second1D& v) { return v.value(); } template<> inline double getValue3DAsDouble<derivOrder::two>(const Second3D& v) { return v.value(); } } // namespace AutomaticDifferentiation } // namespace Utils } // namespace Scine #endif // AUTOMATICDIFFERENTIATION_AUTOMATICDIFFERENTIATIONHELPERS_H
49,138
https://github.com/dochong/beanstalk/blob/master/reader.go
Github Open Source
Open Source
MIT
2,012
beanstalk
dochong
Go
Code
15
40
package beanstalk import ( "net/textproto" ) type reader struct { p textproto.Pipeline id uint }
36,487
https://github.com/zhjilin/rmap/blob/master/Scripts-HTR/9.MotifMatchesEnrichment/MetaPlot_PerMotif-distance2020April05.r
Github Open Source
Open Source
MIT
2,020
rmap
zhjilin
R
Code
305
1,776
#upadte 20200419, shift the coordinate of motif matches on minus strand to the first base of the motif to generate the distance to feature histogram library(ggplot2) library(plyr) library(extrafont) library(pagenum) library(gridExtra) #change the span size from 0.1 to 0.05, which means the only 5 % of the points used for local smoothing per_motif=function(x,tag, barlen){ labeltext=" " if(any(grepl("DONOR",tag,ignore.case = T))){ labeltext="exon intron" deduction=1000 }else if(any(grepl("ACCEPTOR",tag,ignore.case = T))){ labeltext="intron exon" deduction=1002 }else{ deduction=1000 } ggplot(x,aes(position-deduction,count,fill=strand))+geom_bar(stat="identity",position="identity",alpha=0.4)+scale_color_brewer(aesthetics = "fill",palette = "Set1",direction = -1)+ scale_x_continuous("Distance to feature(base)",limits=c(-50,50))+ scale_y_continuous("Count")+ geom_segment(x=as.numeric(-barlen),xend=0,y=0.9*max(x$count),yend=0.9*max(x$count),col="#abdda4")+ theme(plot.title = element_text(hjust = 0.5,size=16,family = "Arial",face = "bold",vjust = 0),axis.title = element_text(size=16,family="Arial"),legend.text = element_text(size=14,family = "Arial"),axis.text = element_text(size=14,family="Arial"),axis.line = element_line(color="black"),panel.background = element_blank(),panel.grid.minor = element_blank(),panel.grid.major = element_line(color="grey"),legend.background = element_blank(),legend.key = element_blank(),legend.title = element_blank(),legend.direction = "horizontal",legend.position =c(0.5,0.98),legend.box = "horizontal")+ annotate("text",label=labeltext,x=0,y=0.8*max(x$count),family="Arial",size=14) } args=commandArgs(trailingOnly = TRUE) fsense=args[1] fanti=args[2] tag=args[3] name_map=args[4] winsize=as.numeric(args[5]) order=args[6] motif_length=args[7] #motif_length="/mnt/raid5/project/rnaselex/figures/GR-revision2020/distanceHistogram/motif_length.txt" tstring=Sys.Date() # fanti="DONOR-antisense-180120.freq" # fsense="DONOR-sense-180120.freq" # fsense="START-sense-180108.freq" # # fanti="START-antisense-180108.freq" # totalnum="total_number180120.table" # name_map="../../../../name_file.map.17Apr28.tsv" # tag="DONOR" # tag="TSS" tabsense=read.table(fsense,sep="\t",col.names = c("motif","position","count","feature"),quote = "") tabanti=read.table(fanti,sep="\t",col.names = c("motif","position","count","feature"),quote = "") #tnum=read.table(totalnum,sep="\t",col.names = c("motif","number"),quote = "") proteinname=read.table(name_map,sep="\t",quote = "",col.names = c("protein","barcode","batch","seed","multi","cycle","anno","motif")) motiflength=read.table(motif_length,sep="\t",col.names = c("motif","length")) orderfile=read.table(order,sep="\t",quote = "") motif_list=as.character(orderfile$V1) tabsense$strand="sense" tabanti$strand="antisense" sectype=c("antisense","lincRNA","protein_coding","processed_transcript","nonsense_mediated_decay","tRNA") pdf(paste(tag,"-distance-",tstring, ".pdf",sep=""),height=12,width=10) pnum=1 i=1 plot=list() actualwin=winsize+1 for ( n in 1:length(motif_list)){ outname=gsub("_short.pfm","", motif_list[n],perl = TRUE) namepro=paste(proteinname[grep(outname,proteinname$motif),1],proteinname[grep(outname,proteinname$motif),4],sep="-") mlen=as.numeric(motiflength[grep(pattern =motif_list[n] , motiflength[,1]),2]) hsense=subset(tabsense[tabsense$motif == motif_list[n],], ((position- 1000) >= -actualwin) & ((position- 1000) <= actualwin)) hanti=subset(tabanti[tabanti$motif == motif_list[n],], ((position- 1000)-(mlen-1) >= -actualwin) & ((position- 1000)-(mlen-1) <= actualwin)) # outname=gsub("_short.pfm","", motif_list[n],perl = TRUE) # namepro=paste(proteinname[grep(outname,proteinname$motif),1],proteinname[grep(outname,proteinname$motif),4],sep="-") # hsense=subset(tabsense[tabsense$motif == motif_list[n],], (position>=900 & position <=1102)) # hanti=subset(tabanti[tabanti$motif == motif_list[n],], (position>=900 & position <=1102)) alltab=rbind(hsense,hanti) pn=per_motif(alltab,tag,mlen)+ggtitle(namepro) plot[[i]]=pn if (i %% 6 == 0) { ## print 6 plots on a page print (do.call(grid.arrange, plot)) plot = list() # reset plot i = 0 # reset index pagenum(num="", text=pnum,x=0.5,y=0.01,cex=1.5) pnum=pnum+1 } i = i + 1 } if ( length(plot) != 0 ) { print (do.call(grid.arrange, plot)) pagenum(num="", text=pnum,x=0.5,y=0.01,cex=1.5) } dev.off()
42,254
https://github.com/adampash/coin_flip/blob/master/src/sass/app.sass
Github Open Source
Open Source
MIT
null
coin_flip
adampash
Sass
Code
311
1,040
@import "scss-mixins"; @import "typography"; @import "iframes"; body { width: 100%; padding: 0; margin: 0; .container { max-width: 700px; margin: 0 auto; } } .front { background: blue; background: url(images/heads.png); background-repeat: no-repeat; } .back { background: green; background: url(images/tails.png); background-repeat: no-repeat; } /* entire container, keeps perspective */ .flip-container { perspective: 1000; display: inline-block; float: left; cursor: pointer; } /* flip the pane when hovered */ .flip-container.hover .flipper { transform: rotateY(180deg); } .flip-container, .front, .back { width: 212px; height: 211px; } /* flip speed goes here */ .flipper { transition: 0.6s; transform-style: preserve-3d; position: relative; } /* hide back of pane during swap */ .front, .back { backface-visibility: hidden; position: absolute; top: 0; left: 0; } /* front pane, placed above back */ .front { z-index: 2; /* for firefox 31 */ transform: rotateY(0deg); } /* back, initially hidden pane */ .back { transform: rotateY(180deg); } .win { color: rgb(106, 179, 115); } .lose { color: rgb(224, 65, 59); } .vertical.flip-container { position: relative; } .vertical .back { transform: rotateX(180deg); } .vertical.flip-container .flipper { transform-origin: 100% 111px; /* half of height */ } .vertical.flip-container .flipper.flip { transform: rotateX(-180deg); } .text_container { padding: 0px 0; margin-left: 250px; font-family: ProximaNovaACond-Semibold; font-size: 24px; .call h3 a { padding: 0 10px; color: #2885E0; text-decoration: none; border: none; &:hover { color: #14599D; } } } .result { // float: right; } .share { height: 36px; display: none; } .share a, button.submit { background: #65C1FA; border: none; color: white; text-decoration: none; padding: 10px; &:hover { background: #2682BB; } } @media screen and (max-width : 480px) { body { .flip-container { display: block; float: none; margin: 0 auto; } .text_container { margin: 0 10px; padding: 0; h3 { text-align: center; } .result { font-size: 18px; } } } .share a, button.submit { font-size: 18px; &:hover { background: #2682BB; } } } @font-face {font-family: 'ProximaNovaACond-Semibold';src: url('webfonts/24FCCC_3_0.eot');src: url('webfonts/24FCCC_3_0.eot?#iefix') format('embedded-opentype'),url('webfonts/24FCCC_3_0.woff') format('woff'),url('webfonts/24FCCC_3_0.ttf') format('truetype');}
17,552
https://github.com/marinaoliveira96/uri-algorithms/blob/master/C/1009.cpp
Github Open Source
Open Source
MIT
null
uri-algorithms
marinaoliveira96
C++
Code
27
100
#include<stdio.h> int main() { char name[15]; double salary, sales; scanf("%s", &name); scanf("%lf", &salary); scanf("%lf", &sales); printf("TOTAL = R$ %.2lf\n", salary + (sales * 0.15)); return 0; }
8,979
https://github.com/tanishiking/dotty/blob/master/tests/neg-custom-args/no-experimental/experimentalTypes2.scala
Github Open Source
Open Source
Apache-2.0
2,022
dotty
tanishiking
Scala
Code
96
149
import scala.annotation.experimental @experimental class A @experimental type X @experimental type Y = Int @experimental opaque type Z = Int def test2: Unit = new A // error: class A is marked @experimental and therefore ... val i0: A = ??? // error: class A is marked @experimental and therefore ... val i1: X = ??? // error: type X is marked @experimental and therefore ... val i2: Y = ??? // error: type Y is marked @experimental and therefore ... val i3: Z = ??? // error: type Z is marked @experimental and therefore ... ()
45,889
https://github.com/iosifv/terminal-toolbelt/blob/master/sources/alpha-display.sh
Github Open Source
Open Source
MIT
2,022
terminal-toolbelt
iosifv
Shell
Code
134
453
#!/usr/bin/env bash # COLOR VARIABLES #---------------------------- C_RED=$(tput setaf 1) C_GREEN=$(tput setaf 2) C_YELLOW=$(tput setaf 3) C_BLUE=$(tput setaf 4) C_LIGHT_GREY="\033[0;37m" C_BOLD=$(tput bold) C_REVERSE=$(tput rev) C_RESET=$(tput sgr0) # stores number of columns available in the terminal C_COLS=$(tput cols) # Functions for printing pretty text #---------------------------- function print-status { echo "${C_YELLOW} => ${1}${C_RESET}" } function print-success { echo "${C_GREEN} => ${1}${C_RESET}" } function print-error { echo "${C_RED} => ${1}${C_RESET}" } function print-quote { echo "${C_BLUE}>" echo "${C_BLUE}>${C_RESET} \"${1}\"${C_RESET}" echo "${C_BLUE}>${C_RESET}" } # Functions for confirming dangerous actions #---------------------------- function confirmDragons { print-error "🐉 Here be Dragons!" read "brave?Continue? " if [[ "$brave" =~ ^[Yy]$ ]] then $1 $2 $3 $4 fi } function confirmStuff { print-status "⚠️ Please don't break stuff!" read "oath?Promise? " if [[ "$oath" =~ ^[Yy]$ ]] then $1 $2 $3 $4 fi }
21,253
https://github.com/sv-tools/bumptag/blob/master/go.mod
Github Open Source
Open Source
MIT
2,022
bumptag
sv-tools
Go Module
Code
32
187
module github.com/sv-tools/bumptag go 1.17 require ( github.com/coreos/go-semver v0.3.0 github.com/golang/mock v1.6.0 github.com/stretchr/testify v1.7.1 gopkg.in/yaml.v2 v2.3.0 // indirect ) require ( github.com/davecgh/go-spew v1.1.0 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c // indirect )
31,621
https://github.com/resource-watch/control-tower/blob/master/app/src/routes/api/v1/endpoint.router.js
Github Open Source
Open Source
MIT
null
control-tower
resource-watch
JavaScript
Code
70
208
const Router = require('koa-router'); const Endpoint = require('models/endpoint.model'); const logger = require('logger'); const Utils = require('utils'); const pick = require('lodash/pick'); const { getLoggedUser } = require('services/getUserFromToken.service'); const router = new Router({ prefix: '/endpoint', }); class EndpointRouter { static async getAll(ctx) { logger.info('Obtaining endpoints'); const query = pick(ctx.query, ['binary', 'path', 'method']); ctx.body = await Endpoint.find({ ...query }, { __v: 0 }); } } router.get('/', getLoggedUser, Utils.isLogged, Utils.isAdmin, EndpointRouter.getAll); module.exports = router;
44,000
https://github.com/percevalw/Term/blob/master/sublimeterm/sublimeterm_view_controller.py
Github Open Source
Open Source
MIT
2,017
Term
percevalw
Python
Code
2,083
7,143
# Copyright (C) 2016-2017 Perceval Wajsburt <perceval.wajsburt@gmail.com> # # This module is part of SublimeTerm and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php """ ################## For a user input |a b|c d|e f g h| BEFORE USER CHANGE -> cd surounded by view_mod_begin, view_mod_end | \__ | \ |a b|X X X X|e f g h| AFTER USER CHANGE -> XXXX surounded by view_mod_begin, view_mod_end + view_mod_delta ################## For process output |a|b c|d e f g h| BEFORE PROC CHANGE -> c surounded by proc_mod_begin, proc_mod_end - proc_mod_delta | \ | \ |a|O O O|d e f g h| AFTER PROC CHANGE -> OOO (proc_mod_content) surounded by proc_mod_begin, proc_mod_end ########## Correction |a:b|X X X X|e f g h| -> bXXXX surounded by corr_view_begin and corr_view_end | / | / |a|O O O|d:e f g h| -> 000d surounded by corr_proc_begin and corr_proc_end if (proc_mod_begin >= view_mod_begin and proc_mod_begin <= view_mod_end) or \ (proc_mod_end >= view_mod_begin and proc_mod_end <= view_mod_end): corr_view_begin = min(view_mod_begin, proc_mod_begin) corr_view_end = max(view_mod_end, proc_mod_end) """ import logging import time from threading import Event, Lock, Thread import sublime import sublime_api try: from Queue import Queue, Empty except ImportError: from queue import Queue, Empty # python 3.x logger = logging.getLogger() from .input_transcoder import * from .ansi_output_transcoder import * from .process_controller import * __all__ = ['SublimetermViewController'] logger = logging.getLogger() def debug(*args): logger.debug(" ".join(map(str, args))) try: # debug("stop potentially-existing SublimetermViewController...") c = SublimetermViewController.instance.close() except: # debug("and there was none") pass else: # debug("and there was one") pass class SublimetermViewController(): instance = None def __del__(self): debug("SublimetermViewController should have been deleted !") def __new__(cls, input_transcoder, output_transcoder, settings=None, output_panel=False): if isinstance(cls.instance, cls): cls.instance.close() cls.instance = object.__new__(cls) return cls.instance def __init__(self, input_transcoder, output_transcoder, settings=None, output_panel=False): self.master = None self.view_mod_begin = 0 self.input_transcoder = input_transcoder self.output_transcoder = output_transcoder self.cache_cursor_dep = False self.dont_notify_for_selection = False self.no_input_event = Event() self.no_input_event.set() self.last_sel = (0, 0) self.content_size = 0 self.view_mod_begin = 0 self.view_mod_end = 0 self.view_mod_delta = 0 self.is_content_dirty = False self.is_cursor_dirty = True self.last_width = 0 self.last_height = 0 self.last_size = 0 self.has_unprocessed_inputs = False self.has_just_changed_view = False self.console = None self.input_queue = Queue() self.lock = Lock() self.settings = settings self.output_panel = output_panel self.editing_thread = None self.listening_thread = None self.stop = False def start(self): """ Create and init the view and the listeners """ self.open_view() self.erase(0) self.place_cursor(0) self.editing_thread = Thread(target=self.keep_editing) self.listening_thread = Thread(target=self.keep_listening) size = (80, 24, 1, 12) self.input_transcoder.set_size(*size) self.output_transcoder.set_size(*size) self.editing_thread.start() self.listening_thread.start() def close(self): """Stops updating the view controller""" self.stop = True SublimetermViewController.instance = None def __enter__(self): self.start() return self def __exit__(self, exc_type, exc_val, exc_tb): self.close() def on_modified(self): """ View content modification listener method Called when the view content is modified To avoid that some content is written by the client during the execution, and therefore that the readed content is compromised, we clear an event that is being waited by the output writer """ debug("SIZES", self.console.size(), self.last_size, self.dont_notify_for_selection, self.has_just_changed_view) size = self.console.size() self.dont_notify_for_selection = True if self.has_just_changed_view: self.last_size = size self.has_just_changed_view = False return self.no_input_event.clear() # time.sleep(0.5) current_sel = self.console.sel() debug("ACC SIZES", self.console.size(), self.last_size) delta = size - self.last_size last_position = self.last_sel if delta > 0: new_position = current_sel[-1].b else: new_position = current_sel[0].a self.compute_change_interval(last_position, new_position, delta) debug("HAS UNPROCESS INPUTS", self.has_unprocessed_inputs) if delta > 0: # If the cursor moved forward, then some content has been added content = self.console.substr(sublime.Region(last_position, last_position + delta)) debug("ADDED CONTENT BETWEEN", last_position, last_position + delta, " : ", repr(content)) debug("PROCESS CONTENT SIZE", self.output_transcoder.content_size) # This part has been tranfered to the process controller """ # if new_position <= self.output_transcoder.max_cursor() + 1: # self.compute_change_interval(last_position, new_position) self.input_queue.put((0, content)) elif delta < 0: # Else, some content has been erased debug("ERASED CONTENT BETWEEN", last_position + delta, last_position) self.input_queue.put((1, -delta)) self.last_size = size self.last_sel = self.console.sel()[0].a self.no_input_event.set() def on_selection_modified(self): """ Cursor selection listener method Called when the view cursor is moved To avoid that some content is written by the client during the execution, we clear an event that is being waited by the output writer TODO : There is something todo here, regarding whether it is important or not to prevent a notification when the client changes the cursor """ # if self.has_just_changed_view: # self.has_just_changed_view = False # return if self.dont_notify_for_selection: self.dont_notify_for_selection = False return self.no_input_event.clear() last_position = self.last_sel self.last_sel = self.console.sel()[0].a debug("CURRENT SEL, [{}, {}]".format(self.console.sel()[0].a, self.console.sel()[0].b)) if last_position != self.last_sel: # self.compute_change_interval(last_position, self.last_sel) rel = self.last_sel - last_position debug("CHANGED CURSOR", rel) self.input_queue.put((2, rel)) self.no_input_event.set() def write_special_character(self, char): """ Write a special character Write a special character and update the known position of the cursor It is important to do it thread safely to avoid the content-modification-detector to invent/forget bits of strings TODO : find what may disturb other methods such as write_output when this one is fired """ self.no_input_event.clear() last_position = self.last_sel self.last_sel = self.console.sel()[0].a # self.compute_change_interval(last_position, self.last_sel) self.input_queue.put((0, char)) self.no_input_event.set() def compute_change_interval(self, last_position, new_position, delta): """Compute where the changes of the process on the view Arguments: last_position {int} -- last cursor position new_position {int} -- new cursor position delta {int} -- delta of the changes """ debug("COMPUTE CHANGE", last_position, new_position, "DELTA", delta) if not self.is_content_dirty: self.view_mod_begin = min(last_position, new_position) self.view_mod_end = max(last_position + delta, new_position) self.view_mod_delta = delta debug("FIRST INTERVAL BETWEEN", self.view_mod_begin, self.view_mod_end, "DELTA", self.view_mod_delta) self.is_content_dirty = True return # ie new_position < last_position self.view_mod_begin = min(self.view_mod_begin, new_position, last_position) self.view_mod_end = max(self.view_mod_end + delta, last_position + delta) self.view_mod_delta += delta debug("AFTER INTERVAL, BETWEEN", self.view_mod_begin, self.view_mod_end, "DELTA", self.view_mod_delta) def write_output(self, begin, end, string): """ Write output of the prcess to the screen Called when the process has some content to log We avoid to disturb any input detection process by waiting for a "no-input" event """ if self.stop: return """ We wait that a potential user input has been processed """ pos = self.console.sel()[0].a self.no_input_event.wait() self.has_just_changed_view = True will_make_selection = pos == begin == end # debug("POS0", self.console.sel()[0].a) sublime_api.view_run_command(self.console.view_id, "term_editor", { "action": 2, "begin": begin, "end": end, "string": string, "cursor": pos if will_make_selection else -1 }) # pos = self.console.sel()[0].a debug("NEW SEL IN CONSOLE", ', '.join(["[{}, {}]".format(sel.a, sel.b) for sel in self.console.sel()])) debug("NEW CONSOLE SIZE", self.console.size()) # if will_make_selection: # #debug("DIFFERENT SEL", self.console.sel()[0].a, self.console.sel()[0].b) # self.console.sel().add(sublime.Region(pos)) # debug("AFTER SEL CORR", ', '.join(["[{}, {}]".format(sel.a, sel.b) for sel in self.console.sel()])) # self.has_just_changed_view = True # sublime_api.view_run_command(self.console.view_id, "term_editor", {}) # debug("POS", self.console.sel()[0].a) # """ # """ # debug("POS2", self.console.sel()[0].a) # self.last_sel = self.console.sel()[0].a # We infer the future position of the cursor and sync it # in the class to avoid no-new content detection # added = pos+len(string)-size # if added > 0 and self.last_sel >= pos: # self.last_sel += added def erase(self, begin, end=-1): """ Erase everything after pos Useful when the typed key ends to be not displayed so we must hide it Ex : do you want ... ? y/n -> y -> y is not displayed """ if self.stop: return self.no_input_event.wait() if end == -1: end = self.console.size() if end <= begin: return self.has_just_changed_view = True sublime_api.view_run_command(self.console.view_id, "term_editor", { "action": 1, "begin": begin, "end": end, }) def place_cursor(self, pos): """ Change the cursor position Puts the cursor as the desired position in the view The wanted position should NOT be inferior the view size """ if self.stop: return self.no_input_event.wait() self.last_sel = self.console.sel()[0].a debug(str(("SCREEN SIZE", self.console.size(), "WANTED", pos, "CURRENT", self.last_sel))) if self.console.size() < pos: self.console.sel().clear() self.console.sel().add(sublime.Region(self.last_sel)) self.has_just_changed_view = True sublime_api.view_run_command(self.console.view_id, "term_editor", {}) debug("THERE MUST BE AN ERROR") time.sleep(2) self.cancel_view_mod() ## debug("INSERT TO FILL", "SIZE", self.console.size(), "POS", pos, "CURRENT", self.console.sel()[0].a) ## num = pos - self.console.size() ## sublime_api.view_run_command(self.console.view_id, "term_editor", { ## "action":0, ## "begin":self.console.size(), ## "string":''.join([' ' for i in range(num)]) ## }) ## self.console.sel().clear() ## self.console.sel().add(sublime.Region(pos)) # ## self.console.show_at_center(pos) elif self.last_sel != pos: self.console.sel().clear() self.console.sel().add(sublime.Region(pos)) self.has_just_changed_view = True sublime_api.view_run_command(self.console.view_id, "term_editor", {"begin": pos}) self.last_sel = pos self.show_cursor() ############################# # Sublime View helper methods ############################# def open_view(self): """ Open the view Open the view we're going to work in and lock it (read_only) until everything is set """ window = sublime.active_window() if not self.output_panel: self.console = window.open_file("sublimeterm.output") self.console.set_scratch(True) # self.console.set_name("Sublimeterm console") self.console.set_read_only(False) window.focus_view(self.console) else: self.console = window.find_output_panel("term") if not self.console: self.console = window.create_output_panel("term", True) window.run_command("show_panel", {"panel": "output.term"}) if (self.settings): self.console.set_syntax_file(self.settings.get('color_scheme')) self.console.set_read_only(False) window.focus_view(self.console) self.console.set_viewport_position((0, 0)) self.console.settings().set("auto_match_enabled", False) if len(self.console.sel()) > 0: self.last_sel = self.console.sel()[0].a else: self.console.sel().add(sublime.Region(0)) self.last_sel = 0 def show_cursor(self): """Show the cursor Puts the cursor at the end of the viewport if it is further """ if self.output_transcoder.asb_mode: return (w, h) = self.console.viewport_extent() (x, y) = self.console.text_to_layout(self.console.sel()[0].a) # viewport_position() (cx, cy) = self.console.viewport_position() next_cy = y - (h * 1 - self.console.line_height())#0.75 if cy < next_cy and y > (h * 1 - self.console.line_height()):#0.75: pass else: pass self.console.set_viewport_position((cx, next_cy)) def get_view_size(self): (w, h) = self.console.viewport_extent() if w == self.last_width and h == self.last_height: return None self.last_width = w self.last_height = h try: return (int(w / self.console.em_width()) - 3, int(h / self.console.line_height()) - 1, int(w), int(h)) except ZeroDivisionError: return None def keep_listening(self): cached_cursor_dep = None (action, content) = (-1, "") while True: if self.stop: break try: if self.has_unprocessed_inputs: (action, content) = self.input_queue.get(block=False) else: (action, content) = self.input_queue.get(timeout=1) except Empty: self.lock.acquire() size = self.get_view_size() if size: self.input_transcoder.set_size(*size) self.output_transcoder.set_size(*size) elif self.has_unprocessed_inputs: debug("INPUT QUEUE EMPTY") self.has_unprocessed_inputs = False self.lock.release() else: self.lock.acquire() # time.sleep(0.3) if action == 2 and self.cache_cursor_dep is True: if cached_cursor_dep is None: cached_cursor_dep = content else: cached_cursor_dep += content else: self.has_unprocessed_inputs = True if cached_cursor_dep is not None and self.cache_cursor_dep is True: self.input_transcoder.move(cached_cursor_dep) cached_cursor_dep = None if action == 0: self.input_transcoder.write(content) elif action == 1: self.input_transcoder.erase(content) elif action == 2 and self.cache_cursor_dep is False: self.input_transcoder.move(content) self.lock.release() debug("EDITING ENDED") def compute_correction(self, proc_mod_begin, proc_mod_end, proc_mod_delta, content=None): """ If the process inserted some characters, ie did not replace those under the cursor at there position, then the view should "insert" them, ie put them in a region smaller than the size of the content, thus '- proc_mod_delta' """ if 0 < proc_mod_delta < self.view_mod_begin > 0: pass elif self.view_mod_begin < proc_mod_delta < 0: pass if self.is_content_dirty: # Where will we change the content in the view ? corr_view_begin = min(proc_mod_begin, self.view_mod_begin) corr_view_end = max(self.view_mod_end, proc_mod_end - proc_mod_delta + self.view_mod_delta) # What are we going to put there corr_proc_begin = corr_view_begin corr_proc_end = corr_view_end - self.view_mod_delta + proc_mod_delta debug("VIEW MOD [", self.view_mod_begin, ",", self.view_mod_end, "]", "PROC MOD [", proc_mod_begin, ",", proc_mod_end, "]", "PROC DELTA", proc_mod_delta, "VIEW DELTA", self.view_mod_delta, "CORR VIEW : [", corr_proc_begin, ",", corr_view_end, "], ", "CORR PROC : [", corr_proc_begin, ",", corr_proc_end, "]") else: # Where will we change the content in the view ? corr_view_begin = min(proc_mod_begin, self.console.size()) corr_view_end = proc_mod_end - proc_mod_delta # What are we going to put there corr_proc_begin = corr_view_begin corr_proc_end = corr_view_end + proc_mod_delta debug("NOT DIRTY", "PROC MOD [", proc_mod_begin, ",", proc_mod_end, "]", "PROC DELTA", proc_mod_delta, "CORR VIEW : [", corr_view_begin, ",", corr_view_end, "], ", "CORR PROC : [", corr_proc_begin, ",", corr_proc_end, "]") # If we need more content that what has been given by the get_last_output function if content is None or corr_view_begin < proc_mod_begin or proc_mod_end < corr_proc_end: content = self.output_transcoder.get_between(corr_proc_begin, corr_proc_end) self.write_output(corr_view_begin, corr_view_end, content) debug("OUTPUT WRITTEN BEWTEEN {} and {}: {} (len {})".format(corr_view_begin, corr_view_end, content if len(content) <= 10 else content[:4] + '...' + content[-4:], len(content))) self.is_content_dirty = False def cancel_view_mod(self): self.compute_correction(self.view_mod_begin, self.view_mod_begin, 0) def keep_editing(self): """Keep the view in sync with the process buffer Keep reflecting changes of OutputTranscoder to the view """ position = 0 has_unprocessed_outputs = True while True: if self.stop: break try: # in those particuliar circumstances, we do not want to wait if has_unprocessed_outputs or self.has_unprocessed_inputs: (content, proc_mod_begin, position, proc_mod_end, proc_mod_delta, self.content_size) = self.output_transcoder.pop_output() else: (content, proc_mod_begin, position, proc_mod_end, proc_mod_delta, self.content_size) = self.output_transcoder.pop_output(timeout=0.1) debug( "TXT: {}, MIN:{}, POS:{}, MAX:{}, INSERT_NB:{}, TOTAL:{}".format(repr(content), proc_mod_begin, position, proc_mod_end, proc_mod_delta, self.content_size)) except Empty: self.lock.acquire() # debug("GOT HERE BECAUSE", self.has_unprocessed_inputs, has_unprocessed_outputs) if self.is_content_dirty and not self.has_unprocessed_inputs: debug("CONTENT DIRTY AND END OF INPUTS", has_unprocessed_outputs) self.cancel_view_mod() self.is_cursor_dirty = True if self.is_cursor_dirty: debug("END OF OUTPUT AND CURSOR DIRTY") self.place_cursor(position) self.is_cursor_dirty = False self.show_cursor() if self.console.size() > self.content_size: self.erase(self.content_size) if not self.has_unprocessed_inputs: has_unprocessed_outputs = False self.lock.release() pass else: self.lock.acquire() has_unprocessed_outputs = True self.compute_correction(proc_mod_begin, proc_mod_end, proc_mod_delta, content) # We replace the view content between those limits # if will_clean_to_min_change: # debug("CONTENT DIRTY, ERASE TO FIRST CHANGE") # self.erase(replace_view_end, self.view_mod_begin) # if will_clean_to_end: # debug("CONTENT NOT DIRTY, ERASE TO END") # self.erase(self.content_size) # self.is_content_dirty = False # If the changes between self.view_mod_begin, self.view_mod_end have # been overwritten # If there are no further user-interactions to treat # we update the cursor position # if not self.has_unprocessed_inputs: # debug("NO OTHER INPUTS TO TREAT") # self.place_cursor(position) # self.show_cursor() # else: self.is_cursor_dirty = True self.lock.release() debug("LISTENING ENDED") def main(): input_transcoder = InputTranscoder() output_transcoder = ANSIOutputTranscoder() pty = ProcessController(input_transcoder, output_transcoder) view_controller = SublimetermViewController(input_transcoder, output_transcoder) pty.start() view_controller.start() time.sleep(3) input_transcoder.write("ls\n") try: while True: time.sleep(10) except KeyboardInterrupt: debug("\nINTERRUPTION !") pty.close() view_controller.close() if __name__ == '__main__': main()
11,798
https://github.com/ota-meshi/stylelint4b/blob/master/packages/stylelint4b/build/script/index.js
Github Open Source
Open Source
MIT
2,021
stylelint4b
ota-meshi
JavaScript
Code
350
1,432
"use strict" const fs = require("fs") const path = require("path") const eslint = require("../../../../node_modules/eslint") const RULES_ROOT = path.resolve( __dirname, "../../node_modules/stylelint/lib/rules", ) const REFERENCE_ROOT = path.resolve( __dirname, "../../node_modules/stylelint/lib/reference", ) const UTILS_ROOT = path.resolve( __dirname, "../../node_modules/stylelint/lib/utils", ) const POSTCSS_LIB_ROOT = path.resolve( __dirname, "../../node_modules/postcss/lib", ) clearDir(path.resolve(__dirname, "../../lib/reference")) clearDir(path.resolve(__dirname, "../../lib/rules")) clearDir(path.resolve(__dirname, "../../lib/utils")) clearDir(path.resolve(__dirname, "../../packages/postcss")) const targets = [ { module: "stylelint", name: "index", }, { module: "./alias-module", name: "alias", }, ] // eslint-disable-next-line require-jsdoc function isDirectory(s) { return fs.lstatSync(s).isDirectory() } targets.push( ...fs .readdirSync(RULES_ROOT) .filter(file => isDirectory(path.resolve(RULES_ROOT, file))) .map(file => ({ module: `stylelint/lib/rules/${file}`, name: `lib/rules/${file}`, })), ) targets.push( ...fs .readdirSync(REFERENCE_ROOT) .filter(file => path.extname(file) === ".js") .map(file => path.basename(file, ".js")) .map(file => ({ module: `stylelint/lib/reference/${file}`, name: `lib/reference/${file}`, })), ) targets.push( ...fs .readdirSync(UTILS_ROOT) .filter(file => path.extname(file) === ".js") .map(file => path.basename(file, ".js")) .filter( file => file !== "getCacheFile" && file !== "getFileIgnorer" && file !== "FileCache", ) .map(file => ({ module: `stylelint/lib/utils/${file}`, name: `lib/utils/${file}`, })), ) targets.push( ...fs .readdirSync(POSTCSS_LIB_ROOT) .filter(file => path.extname(file) === ".js") .map(file => path.basename(file, ".js")) .map(file => ({ module: `postcss/lib/${file}`, name: `packages/postcss/lib/${file}`, })), { module: "postcss/lib/postcss", name: "packages/postcss/index", }, ) const indexPath = path.resolve(__dirname, "../../src/index.js") writeFileSync( indexPath, `"use strict" /* eslint-disable @mysticatea/node/no-extraneous-require */ module.exports = { ${targets .map(target => `"${target.name}": require("${target.module}")`) .join(",\n")} } /* eslint-enable @mysticatea/node/no-extraneous-require */`, ) const formatFiles = [indexPath] for (const target of targets) { const libPath = path.resolve(__dirname, `../../${target.name}.js`) const level = target.name.split("/").length - 1 writeFileSync( libPath, `"use strict" const bundle = require("${ level ? "../".repeat(level) : "./" }dist/bundle") module.exports = bundle["${target.name}"] `, ) formatFiles.push(libPath) } const linter = new eslint.CLIEngine({ fix: true }) const report = linter.executeOnFiles(formatFiles) eslint.CLIEngine.outputFixes(report) // eslint-disable-next-line require-jsdoc function clearDir(dir) { if (!isExist(dir)) { return } for (const file of fs.readdirSync(dir)) { const fp = path.join(dir, file) if (fs.statSync(fp).isDirectory()) { clearDir(fp) } else { fs.unlinkSync(fp) } } } // eslint-disable-next-line require-jsdoc function isExist(file) { try { fs.statSync(file) return true } catch (err) { if (err.code === "ENOENT") { return false } throw err } } // eslint-disable-next-line require-jsdoc function writeFileSync(file, ...args) { const parents = [] let parent = path.dirname(file) while (!isExist(parent)) { parents.push(parent) parent = path.dirname(parent) } while (parents.length) { fs.mkdirSync(parents.pop()) } fs.writeFileSync(file, ...args) }
28,359
https://github.com/yii2-tools/yii2-community-cms/blob/master/default_site/modules/site/modules/design/modules/packs/source/default/templates/index.twig
Github Open Source
Open Source
MIT
null
yii2-community-cms
yii2-tools
Twig
Code
81
307
{{ set(this, 'title', t(module('SITE'), 'Main page')) }} {# Example of containers activation {{ void(this.beginBlock('containers')) }} {{ render('_containers')|raw }} {{ void(this.endBlock()) }} #} {% if app.user.identity.isAdmin or app.user.can('NEWS_ACCESS') %} <div class="row margin-bottom-15"> <div class="col-xs-12"> <div class="btn-group pull-right"> <a href="{{ url({0: route('SITE_NEWS')}) }}" class="btn btn-default"> {{ t(module('NEWS'), 'All news') }} </a> {% if app.user.identity.isAdmin or app.user.can('NEWS_ADD') %} <a href="{{ url({0: route('SITE_NEWS_CREATE')}) }}" class="btn btn-success"> <i class="fa fa-plus"></i> </a> {% endif %} </div> </div> </div> {{ render('news/_list', {'news' : news})|raw }} {% endif %}
34,813
https://github.com/Ortus-Solutions/vagrant-lemtl/blob/master/webroot/WEB-INF/lib/lucee-server/context/library/function/throw.cfm
Github Open Source
Open Source
MIT
2,021
vagrant-lemtl
Ortus-Solutions
ColdFusion
Code
243
476
<!--- * * Copyright (c) 2014, the Railo Company Ltd. All rights reserved. * * This library 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. * * 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see <http://www.gnu.org/licenses/>. * ---><cffunction name="throw" output="no" returntype="void" hint="Throws a developer-specified exception, which can be caught with a cfcatch tag"><cfargument name="message" type="string" required="no" hint="Message that describes exception event."><cfargument name="type" type="string" required="no" default="application" hint="- A custom type - Application Do not enter another predefined type; types are not generated by CFML applications. If you specify Application, you need not specify a type for cfcatch."><cfargument name="detail" type="string" required="no" hint="addional detailed description of the exception."><cfargument name="errorcode" type="string" required="no" hint=" A custom error code that you supply."><cfargument name="extendedInfo" type="string" required="no" hint="extended information to the exception."><cfargument name="object" type="any" required="no" hint="Throws a Java exception from a CFML tag. This attribute is mutually exclusive with all other argments of this function."><!--- ---><cfthrow attributeCollection="#arguments#" contextlevel="2"><!--- ---></cffunction>
38,854
https://github.com/smashwidget/dl-1/blob/master/adv/lathna.py
Github Open Source
Open Source
Apache-2.0
null
dl-1
smashwidget
Python
Code
134
586
import adv.adv_test from adv import * def module(): return Lathna class Lathna(Adv): comment = 'no poison' a1 = ('k_poison',0.15) conf = {} conf['slot.d'] = slot.d.Shinobi() conf['acl'] = """ # s1a = this.s1a `s1a `s2, seq = 5 `s3, seq = 5 """ def prerun(this): this.s1tmp = Conf(this.conf.s1) # if this.conf['cond_afflict_res'] < 100: # from adv.adv_test import sim_duration # if this.condition('always poisoned'): # this.afflics.poison.resist=0 # this.afflics.poison.on('always_poisoned', 1, 0, duration=sim_duration, iv=sim_duration) def s1back(this, t): this.conf.s1.recovery = this.s1tmp.recovery this.conf.s1.dmg = this.s1tmp.dmg def s1a(this): if this.s1.check(): with Modifier("s1killer", "poison_killer", "hit", 0.5): this.dmg_make("s1", 2.37*4) this.conf.s1.recovery = 4.05 Timer(this.s1back).on(this.conf.s1.startup+0.01) this.hits += 4 return this.s1() else: return 0 def s1_proc(this, e): with Modifier("s1killer", "poison_killer", "hit", 0.5): this.dmg_make("s1", 2.37*3) this.hits += 3 def s2_proc(this, e): with Modifier("s2killer", "poison_killer", "hit", 0.5): this.dmg_make("s2", 17.26) if __name__ == '__main__': conf = {} adv.adv_test.test(module(), conf, verbose=0)
19,255
https://github.com/wanabe/xyzzy/blob/master/src/search.cc
Github Open Source
Open Source
RSA-MD
2,015
xyzzy
wanabe
C++
Code
4,596
14,150
#include "stdafx.h" #include "ed.h" #include "regex.h" #include "StrBuf.h" #define SF_CASE_FOLD 1 #define SF_NO_DUP 2 #define SF_REVERSE 4 #define SF_TAIL 8 #define SF_LWORD 16 #define SF_RWORD 32 #define SF_LSYMBOL 64 #define SF_RSYMBOL 128 #define SF_SMART_CASE_FOLD 256 static Regexp::sregs re_regs = {-1, {-1, -1}}; extern u_char char_no_translate_table[]; extern u_char char_translate_upcase_table[]; static inline void clear_regs () { re_regs.nregs = -1; } static void copy_regs0 (Regexp::sregs &d, const Regexp::sregs &s) { d.nregs = s.nregs; for (int i = 0; i <= d.nregs; i++) { d.start[i] = s.start[i]; d.end[i] = s.end[i]; } } static void check_regs () { int i; for (i = 0; i <= re_regs.nregs; i++) { if (re_regs.start[i] < 0) re_regs.end[i] = -1; else if (re_regs.end[i] < 0) re_regs.start[i] = -1; else { if (re_regs.end[i] < re_regs.start[i]) re_regs.end[i] = re_regs.start[i]; if (i) { if (re_regs.start[i] < re_regs.start[0]) re_regs.start[i] = re_regs.start[0]; if (re_regs.end[i] > re_regs.end[0]) re_regs.end[i] = re_regs.end[0]; } } } for (; i < MAX_REGS; i++) { re_regs.start[i] = -1; re_regs.end[i] = -1; } } static inline void save_search (point_t start, point_t end) { re_regs.nregs = 0; re_regs.start[0] = start; re_regs.end[0] = end; xsymbol_value (Vlast_match_string) = Qnil; } static inline void save_match (const Regexp &re, lisp str) { copy_regs0 (re_regs, re.re_regs); check_regs (); xsymbol_value (Vlast_match_string) = str; } static void bm_compilef (int *BM, const Char *pattern, int patlen, int case_fold) { for (int i = 0; i < 256; i++) BM[i] = patlen; for (int i = patlen - 1; i >= 0; i--) { Char cc = *pattern++; int c = DBCP (cc) ? cc >> 8 : cc; if (case_fold && alpha_char_p (cc)) BM[_char_transpose_case (c)] = i; BM[c] = i; } } static void bm_compileb (int *BM, const Char *pattern, int patlen, int case_fold) { int i; for (i = 0; i < 256; i++) BM[i] = patlen; for (i = patlen - 1, pattern += patlen; i >= 0; i--) { Char cc = *--pattern; int c = DBCP (cc) ? cc >> 8 : cc; if (case_fold && alpha_char_p (cc)) BM[_char_transpose_case (c)] = i; BM[c] = i; } } int Buffer::word_bound (const Point &point) const { const syntax_table *tab = xsyntax_table (lsyntax_table); if (bobp (point) || eobp (point)) return 1; Char c = point.ch (); if (!ascii_char_p (c) || xchar_syntax (tab, c) != SCword) return 1; c = point.prevch (); if (!ascii_char_p (c) || xchar_syntax (tab, c) != SCword) return 1; return 0; } int Buffer::symbol_bound (const Point &point) const { const syntax_table *tab = xsyntax_table (lsyntax_table); if (bobp (point) || eobp (point)) return 1; Char c = point.ch (); if (!ascii_char_p (c) || (xchar_syntax (tab, c) != SCword && xchar_syntax (tab, c) != SCsymbol)) return 1; c = point.prevch (); if (!ascii_char_p (c) || (xchar_syntax (tab, c) != SCword && xchar_syntax (tab, c) != SCsymbol)) return 1; return 0; } int Buffer::bm_execf (Point &point, const Char *pattern, int patlen, const int *BM, point_t limit, int flags) const { const Char *pate = pattern + patlen - 1; Char c0 = (flags & SF_CASE_FOLD) ? char_upcase (*pate) : *pate; Chunk *cp = point.p_chunk; const Char *pe = cp->c_text + cp->c_used; const Char *p = cp->c_text + point.p_offset; Char c = *p; int delta = BM[DBCP (c) ? c >> 8 : c]; while (1) { while (delta) { point.p_point += delta; if (point.p_point >= limit) return 0; while (pe - p <= delta) { delta -= pe - p; cp = cp->c_next; p = cp->c_text; pe = p + cp->c_used; } p += delta; c = *p; delta = BM[DBCP (c) ? c >> 8 : c]; } if (((flags & SF_CASE_FOLD) ? char_upcase (c) : c) != c0) { delta = 1; continue; } point_t opoint (point.p_point); for (const Char *pat = pate; pat > pattern;) { point.p_point--; if (p == cp->c_text) { cp = cp->c_prev; p = pe = cp->c_text + cp->c_used; } c = *--p; Char c2 = *--pat; if ((flags & SF_CASE_FOLD) ? char_upcase (c) != char_upcase (c2) : c != c2) goto fail; } point.p_chunk = cp; point.p_offset = p - cp->c_text; if ((flags & SF_LWORD && !word_bound (point)) || (flags & SF_LSYMBOL && !symbol_bound (point))) goto fail2; if (flags & (SF_RWORD | SF_RSYMBOL)) { Point tem (point); goto_char (tem, opoint + 1); if (flags & SF_RWORD ? !word_bound (tem) : !symbol_bound (tem)) goto fail2; } return 1; fail2: delta = opoint - point.p_point + 1; continue; fail: delta = max (BM[DBCP (c) ? c >> 8 : c], int (opoint - point.p_point + 1)); } } int Buffer::bm_execb (Point &point, const Char *pattern, int patlen, const int *BM, point_t limit, int flags) const { const Char *pate = pattern + patlen; Char c0 = (flags & SF_CASE_FOLD) ? char_upcase (*pattern) : *pattern; pattern++; Chunk *cp = point.p_chunk; const Char *p = cp->c_text + point.p_offset; const Char *pe = cp->c_text + cp->c_used; Char c = *p; int delta = BM[DBCP (c) ? c >> 8 : c]; while (1) { while (delta) { point.p_point -= delta; if (point.p_point < limit) return 0; while (p - cp->c_text < delta) { delta -= p - cp->c_text; cp = cp->c_prev; p = pe = cp->c_text + cp->c_used; } p -= delta; c = *p; delta = BM[DBCP (c) ? c >> 8 : c]; } if (((flags & SF_CASE_FOLD) ? char_upcase (c) : c) != c0) { delta = 1; continue; } point_t opoint (point.p_point); for (const Char *pat = pattern; pat < pate; pat++) { point.p_point++; if (++p == pe) { cp = cp->c_next; p = cp->c_text; pe = p + cp->c_used; } c = *p; Char c2 = *pat; if ((flags & SF_CASE_FOLD) ? char_upcase (c) != char_upcase (c2) : c != c2) goto fail; } point.p_chunk = cp; point.p_offset = p - cp->c_text; if (flags & (SF_RWORD | SF_RSYMBOL)) { Point tem (point); forward_char (tem, 1); if (flags & SF_RWORD ? !word_bound (tem) : !symbol_bound (tem)) goto fail2; } if (flags & (SF_LWORD | SF_LSYMBOL)) { Point tem (point); goto_char (tem, opoint); if (flags & SF_LWORD ? !word_bound (tem) : !symbol_bound (tem)) goto fail2; } return 1; fail2: delta = point.p_point - opoint + 1; continue; fail: delta = max (BM[DBCP (c) ? c >> 8 : c], int (point.p_point - opoint + 1)); } } int Buffer::scan_forward (Point &w_point, const Char *pattern, int patlen, const int *BM, point_t limit, int flags) const { int d = patlen - 1; if (flags & SF_NO_DUP) d++; if (w_point.p_point + d >= limit) return 0; Point point (w_point); forward_char (point, d); if (!bm_execf (point, pattern, patlen, BM, limit, flags)) return 0; save_search (point.p_point, point.p_point + patlen); if (flags & SF_TAIL) forward_char (point, patlen); w_point = point; return 1; } int Buffer::scan_backward (Point &w_point, const Char *pattern, int patlen, const int *BM, point_t limit, int flags) const { point_t t = w_point.p_point; if (flags & SF_NO_DUP) t--; t = min (t, point_t (b_contents.p2 - patlen)); if (t < limit) return 0; Point point (w_point); goto_char (point, t); if (!bm_execb (point, pattern, patlen, BM, limit, flags)) return 0; save_search (point.p_point - (patlen - 1), point.p_point + 1); if (flags & SF_TAIL) forward_char (point, 1); else forward_char (point, -(patlen - 1)); w_point = point; return 1; } int Buffer::re_scan_buffer (Point &w_point, lisp pattern, point_t limit, point_t last_match, lChar last_match_char, int flags) const { Point point (w_point); if (flags & SF_REVERSE) { if (flags & SF_NO_DUP && !forward_char (point, -1)) return 0; if (point.p_point < limit || point.p_point > b_contents.p2) return 0; } else { if (flags & SF_NO_DUP && !forward_char (point, 1)) return 0; if (point.p_point < b_contents.p1 || point.p_point > limit) return 0; } if (flags & SF_SMART_CASE_FOLD && stringp (pattern) && Regexp::smart_case_fold_p (xstring_contents (pattern), xstring_length (pattern))) flags |= SF_CASE_FOLD; Regexp re ((flags & SF_CASE_FOLD ? char_translate_upcase_table : char_no_translate_table), xsyntax_table (lsyntax_table)); if (regexpp (pattern)) re.compile (pattern, 1); else re.compile (xstring_contents (pattern), xstring_length (pattern), 1); if (flags & SF_REVERSE ? re.search_backward (this, point, limit, b_contents.p2, last_match, last_match_char) : re.search (this, point, b_contents.p1, limit, last_match, last_match_char)) { save_match (re, Qnil); goto_char (w_point, flags & SF_TAIL ? re_regs.end[0] : re_regs.start[0]); return 1; } return 0; } static int scan_flags (lisp keys) { int flags = 0; lisp x = find_keyword (Kcase_fold, keys); if (x == Ksmart) flags |= SF_SMART_CASE_FOLD; else if (x != Qnil) flags |= SF_CASE_FOLD; if (find_keyword_bool (Kno_dup, keys)) flags |= SF_NO_DUP; if (find_keyword_bool (Kreverse, keys)) flags |= SF_REVERSE; if (find_keyword_bool (Ktail, keys)) flags |= SF_TAIL; x = find_keyword (Kleft_bound, keys); if (x == Ksymbol) flags |= SF_LSYMBOL; else if (x != Qnil) flags |= SF_LWORD; x = find_keyword (Kright_bound, keys); if (x == Ksymbol) flags |= SF_RSYMBOL; else if (x != Qnil) flags |= SF_RWORD; return flags; } static point_t scan_limit (const Buffer *bp, int flags, lisp keys) { lisp t = find_keyword (Klimit, keys); return (t != Qnil ? bp->coerce_to_restricted_point (t) : flags & SF_REVERSE ? bp->b_contents.p1 : bp->b_contents.p2); } static point_t scan_last_match (const Buffer *bp, lisp keys, lChar &ch) { lisp t = find_keyword (Klast_match, keys); if (t != Qnil) { check_cons (t); lisp lpoint = xcar (t); if (lpoint != Qnil) { lisp lch = xcdr (t); if (lch == Qnil) ch = lChar_EOF; else { check_char (lch); ch = xchar_code (lch); } return bp->coerce_to_restricted_point (lpoint); } } ch = lChar_EOF; return -1; } static int smart_case_fold_string_p (lisp string) { const Char *s = xstring_contents (string); const Char *const se = s + xstring_length (string); for (; s < se; s++) if (upper_char_p (*s)) return 0; return 1; } lisp Fscan_buffer (lisp pattern, lisp keys) { int flags = scan_flags (keys); Window *wp = selected_window (); Buffer *bp = wp->w_bufp; point_t limit = scan_limit (bp, flags, keys); clear_regs (); if (!regexpp (pattern)) { check_string (pattern); if (!xstring_length (pattern)) return Qnil; } int result; if (find_keyword_bool (Kregexp, keys) || regexpp (pattern)) { lChar last_match_char; point_t last_match = scan_last_match (bp, keys, last_match_char); result = bp->re_scan_buffer (wp->w_point, pattern, limit, last_match, last_match_char, flags); } else { int BM[256]; if (flags & SF_SMART_CASE_FOLD && smart_case_fold_string_p (pattern)) flags |= SF_CASE_FOLD; if (flags & SF_REVERSE) { bm_compileb (BM, xstring_contents (pattern), xstring_length (pattern), flags & SF_CASE_FOLD); result = bp->scan_backward (wp->w_point, xstring_contents (pattern), xstring_length (pattern), BM, limit, flags); } else { bm_compilef (BM, xstring_contents (pattern), xstring_length (pattern), flags & SF_CASE_FOLD); result = bp->scan_forward (wp->w_point, xstring_contents (pattern), xstring_length (pattern), BM, limit, flags); } } wp->w_disp_flags |= Window::WDF_GOAL_COLUMN; return boole (result); } static int string_start_end (lisp string, lisp start, lisp end, int &offset, int &len) { if (start && start != Qnil) { offset = fixnum_value (start); if (offset < 0 || offset > xstring_length (string)) return 0; } else offset = 0; if (end && end != Qnil) { len = fixnum_value (end); if (len < offset || len > xstring_length (string)) return 0; } else len = xstring_length (string); return 1; } static lisp string_match (lisp regex, lisp string, lisp start, lisp end, const u_char *translate) { check_string (string); clear_regs (); Regexp re (translate, xsyntax_table (selected_buffer ()->lsyntax_table)); if (regexpp (regex)) re.compile (regex, 1); else { check_string (regex); if (!xstring_length (regex)) return Qnil; re.compile (xstring_contents (regex), xstring_length (regex), 1); } int offset, len; if (!string_start_end (string, start, end, offset, len)) return Qnil; if (!re.search (xstring_contents (string), len, offset)) return Qnil; save_match (re, string); return make_fixnum (re.re_regs.start[0]); } lisp Fstring_match (lisp regexp, lisp string, lisp start, lisp end) { return string_match (regexp, string, start, end, char_no_translate_table); } lisp Fstring_matchp (lisp regexp, lisp string, lisp start, lisp end) { return string_match (regexp, string, start, end, char_translate_upcase_table); } lisp Fmatch_beginning (lisp regno) { int r = fixnum_value (regno); if (r < 0 || r >= MAX_REGS) FErange_error (regno); if (r > re_regs.nregs || re_regs.start[r] < 0) return Qnil; return make_fixnum (re_regs.start[r]); } lisp Fmatch_end (lisp regno) { int r = fixnum_value (regno); if (r < 0 || r >= MAX_REGS) FErange_error (regno); if (r > re_regs.nregs || re_regs.start[r] < 0) return Qnil; return make_fixnum (re_regs.end[r]); } lisp Fmatch_string (lisp regno) { int r = fixnum_value (regno); if (r < 0 || r >= MAX_REGS) FErange_error (regno); if (r > re_regs.nregs || re_regs.start[r] < 0) return Qnil; lisp string = xsymbol_value (Vlast_match_string); if (string != Qnil) { int start = min ((int)re_regs.start[r], xstring_length (string)); int end = max (start, min ((int)re_regs.end[r], xstring_length (string))); return make_string (xstring_contents (string) + start, end - start); } return selected_buffer ()->substring (re_regs.start[r], re_regs.end[r]); } lisp Fcompile_regexp (lisp pattern, lisp case_fold) { if (regexpp (pattern)) return pattern; check_string (pattern); if (!xstring_length (pattern)) return Qnil; Regexp re (((case_fold == Ksmart ? Regexp::smart_case_fold_p (xstring_contents (pattern), xstring_length (pattern)) : case_fold && case_fold != Qnil) ? char_translate_upcase_table : char_no_translate_table), xsyntax_table (selected_buffer ()->lsyntax_table)); re.compile (xstring_contents (pattern), xstring_length (pattern), 1); return re.make_regexp (pattern); } lisp Fcompiled_regexp_source (lisp re) { check_regexp (re); return xregexp_source (re); } lisp Fcompiled_regexp_case_fold_p (lisp re) { check_regexp (re); return boole (xregexp_flags (re) & lregexp::TRANSLATE); } lisp Fregexp_quote (lisp string) { check_string (string); int count = 0; const Char *p = xstring_contents (string); const Char *pe = p + xstring_length (string); while (p < pe) switch (*p++) { case '^': case '$': case '.': case '[': case '*': case '+': case '?': case '\\': count++; break; default: break; } if (!count) return string; p = xstring_contents (string); lisp string2 = make_string (xstring_length (string) + count); Char *p2 = xstring_contents (string2); while (p < pe) { Char c = *p++; switch (c) { case '^': case '$': case '.': case '[': case '*': case '+': case '?': case '\\': *p2++ = '\\'; /* fall thru... */ default: *p2++ = c; break; } } return string2; } lisp Flooking_at (lisp regex, lisp case_fold) { Window *wp = selected_window (); Buffer *bp = wp->w_bufp; clear_regs (); Regexp re (((case_fold == Ksmart ? (stringp (regex) && Regexp::smart_case_fold_p (xstring_contents (regex), xstring_length (regex))) : case_fold && case_fold != Qnil) ? char_translate_upcase_table : char_no_translate_table), xsyntax_table (bp->lsyntax_table)); if (regexpp (regex)) re.compile (regex, 0); else { check_string (regex); if (!xstring_length (regex)) return Qnil; re.compile (xstring_contents (regex), xstring_length (regex), 0); } if (!re.match (bp, wp->w_point, bp->b_contents.p1, bp->b_contents.p2)) return Qnil; save_match (re, Qnil); return Qt; } lisp Flooking_for (lisp string, lisp case_fold) { check_string (string); Window *wp = selected_window (); if (wp->w_point.p_point + xstring_length (string) > wp->w_bufp->b_contents.p2) return Qnil; const Chunk *cp = wp->w_point.p_chunk; const Char *p = cp->c_text + wp->w_point.p_offset; const Char *pe = cp->c_text + cp->c_used; const Char *s = xstring_contents (string); const Char *se = s + xstring_length (string); int cf = (case_fold == Ksmart ? smart_case_fold_string_p (string) : case_fold && case_fold != Qnil); while (s < se) { if (p == pe) { cp = cp->c_next; p = cp->c_text; pe = p + cp->c_used; } Char c1 = *s++; Char c2 = *p++; if (cf ? char_upcase (c1) != char_upcase (c2) : c1 != c2) return Qnil; } return Qt; } lisp Flooking_back (lisp string, lisp case_fold) { check_string (string); Window *wp = selected_window (); if (wp->w_point.p_point - xstring_length (string) < wp->w_bufp->b_contents.p1) return Qnil; const Chunk *cp = wp->w_point.p_chunk; const Char *p = cp->c_text + wp->w_point.p_offset; const Char *s = xstring_contents (string); const Char *se = s + xstring_length (string); int cf = (case_fold == Ksmart ? smart_case_fold_string_p (string) : case_fold && case_fold != Qnil); while (se > s) { if (p == cp->c_text) { cp = cp->c_prev; p = cp->c_text + cp->c_used; } Char c1 = *--se; Char c2 = *--p; if (cf ? char_upcase (c1) != char_upcase (c2) : c1 != c2) return Qnil; } return Qt; } static lisp skip_chars (lisp chars, int dir) { check_string (chars); u_long hi[(256 + sizeof (u_long) - 1) / sizeof (u_long)]; bzero (hi, sizeof hi); u_long lo[256][(256 + sizeof (u_long) - 1) / sizeof (u_long)]; const Char *p = xstring_contents (chars); const Char *pe = p + xstring_length (chars); if (p == pe) return Qnil; int not_char = 0; if (*p == '^') { not_char = 1; if (p == pe) return Qnil; p++; } while (p < pe) { Char c = *p++; if (p < pe - 1 && *p == '-') { Char c2 = p[1]; p += 2; for (; c <= c2; c++) { int h = c >> 8; if (!bitisset (hi, h)) { bitset (hi, h); bzero (lo[h], sizeof lo[h]); } bitset (lo[h], c & 255); } } else { int h = c >> 8; if (!bitisset (hi, h)) { bitset (hi, h); bzero (lo[h], sizeof lo[h]); } bitset (lo[h], c & 255); } } Window *wp = selected_window (); wp->w_disp_flags |= Window::WDF_GOAL_COLUMN; Buffer *bp = wp->w_bufp; Point &point = wp->w_point; if (dir < 0 && !bp->forward_char (point, -1)) return Qnil; int nomatch = 1; if (!bp->eobp (point)) while (1) { Char c = point.ch (); if (not_char == (bitisset (hi, c >> 8) && bitisset (lo[c >> 8], c & 255))) break; if (!bp->forward_char (point, dir) || bp->eobp (point)) return Qt; nomatch = 0; } if (dir < 0) bp->forward_char (point, 1); return boole (!nomatch); } lisp Fskip_chars_forward (lisp chars) { return skip_chars (chars, 1); } lisp Fskip_chars_backward (lisp chars) { return skip_chars (chars, -1); } static lisp skip_syntax_spec (lisp syntax_spec, int dir) { u_char buf[SCmax]; bzero (buf, sizeof buf); check_string (syntax_spec); const Char *p = xstring_contents (syntax_spec); const Char *pe = p + xstring_length (syntax_spec); if (p == pe) return Qnil; int not_char = 0; if (*p == '^') { not_char = 1; if (p == pe) return Qnil; p++; } while (p < pe) { Char c = *p++; if (!ascii_char_p (c) || syntax_spec_table[c] == -1) FEsimple_error (Einvalid_syntax_spec, syntax_spec); buf[static_cast <u_char> (syntax_spec_table[c])] = 1; } if (not_char) for (u_int i = 0; i < sizeof buf; i++) buf[i]--; Window *wp = selected_window (); wp->w_disp_flags |= Window::WDF_GOAL_COLUMN; Buffer *bp = wp->w_bufp; const syntax_table *tab = xsyntax_table (bp->lsyntax_table); Point &point = wp->w_point; if (dir < 0 && !bp->forward_char (point, -1)) return Qnil; int nomatch = 1; if (!bp->eobp (point)) while (1) { Char c = point.ch (); if (c >= 256) c >>= 8; if (!buf[xchar_syntax (tab, c)]) break; if (!bp->forward_char (point, dir) || bp->eobp (point)) return Qt; nomatch = 0; } if (dir < 0) bp->forward_char (point, 1); return boole (!nomatch); } lisp Fskip_syntax_spec_forward (lisp syntax_spec) { return skip_syntax_spec (syntax_spec, 1); } lisp Fskip_syntax_spec_backward (lisp syntax_spec) { return skip_syntax_spec (syntax_spec, -1); } static int re_tag_p (lisp string) { for (const Char *p = xstring_contents (string), *pe = p + xstring_length (string) - 1; p < pe; p++) if (*p == '\\') return 1; return 0; } #define NOCASECONV 'E' #define UPCASE_ONE 'u' #define DOWNCASE_ONE 'l' #define UPCASE_CHARS 'U' #define DOWNCASE_CHARS 'L' static void case_conversion (int fconv, Point &from, const Point &end, Buffer *bp) { switch (fconv) { case UPCASE_ONE: if (from.p_point < end.p_point) bp->upcase_region_internal (from, from.p_point + 1); break; case DOWNCASE_ONE: if (from.p_point < end.p_point) bp->downcase_region_internal (from, from.p_point + 1); break; case UPCASE_CHARS: bp->upcase_region_internal (from, end.p_point); break; case DOWNCASE_CHARS: bp->downcase_region_internal (from, end.p_point); break; } } static void replace_match (Window *wp, lisp string, int literal) { Buffer *bp = wp->w_bufp; if (literal) { int l = min (xstring_length (string), int (re_regs.end[0] - re_regs.start[0])); if (l) { bp->goto_char (wp->w_point, re_regs.start[0]); bp->overwrite_chars (wp, xstring_contents (string), l); } if (re_regs.start[0] + l != re_regs.end[0]) bp->delete_region (wp, re_regs.start[0] + l, re_regs.end[0]); else if (l != xstring_length (string)) { bp->goto_char (wp->w_point, re_regs.start[0] + l); bp->insert_chars (wp, xstring_contents (string) + l, xstring_length (string) - l, 1); } else bp->goto_char (wp->w_point, re_regs.end[0]); } else { int l = (min (max (re_regs.end[0], bp->b_contents.p1), bp->b_contents.p2) - min (max (re_regs.start[0], bp->b_contents.p1), bp->b_contents.p2)); Char *b = (Char *)alloca (sizeof (Char) * l); bp->substring (re_regs.start[0], l, b); bp->delete_region (wp, re_regs.start[0], re_regs.end[0]); const Char *p = xstring_contents (string); const Char *pe = p + xstring_length (string); const Char *p0 = p; int fconv = NOCASECONV; Point conv_point; while (p < pe) { if (*p++ == '\\') { bp->insert_chars (wp, p0, p - p0 - 1, 1); if (p == pe) break; Char c = *p++; switch (c) { case '&': c = '0'; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': c -= '0'; if (re_regs.start[c] >= 0) bp->insert_chars (wp, b + min (int (re_regs.start[c] - re_regs.start[0]), l), min (int (re_regs.end[c] - re_regs.start[c]), l), 1); p0 = p; break; case NOCASECONV: case UPCASE_ONE: case DOWNCASE_ONE: case UPCASE_CHARS: case DOWNCASE_CHARS: case_conversion (fconv, conv_point, wp->w_point, bp); fconv = c; conv_point = wp->w_point; p0 = p; break; default: p0 = p - 1; break; } } } bp->insert_chars (wp, p0, p - p0, 1); case_conversion (fconv, conv_point, wp->w_point, bp); } } lisp Freplace_match (lisp string, lisp keys) { check_string (string); if (re_regs.start[0] < 0) return Qnil; Window *wp = selected_window (); wp->w_disp_flags |= Window::WDF_GOAL_COLUMN; wp->w_bufp->check_read_only (); replace_match (wp, string, (find_keyword (Kliteral, keys) != Qnil || !re_tag_p (string))); return Qt; } static lChar match_end_before (Buffer *bp, const Point &point) { Point p (point); bp->goto_char (p, re_regs.end[0]); if (bp->bobp (p)) return lChar_EOF; return p.prevch (); } lisp Freplace_buffer (lisp pattern, lisp replacement, lisp keys) { int flags = scan_flags (keys) & ~SF_REVERSE; int once = find_keyword_bool (Konce, keys); Window *wp = selected_window (); Buffer *bp = wp->w_bufp; point_t limit = scan_limit (bp, flags, keys); lChar last_match_char; point_t last_match = scan_last_match (bp, keys, last_match_char); clear_regs (); if (!regexpp (pattern)) { check_string (pattern); if (!xstring_length (pattern)) return make_fixnum (0); } check_string (replacement); int regexp = find_keyword_bool (Kregexp, keys) || regexpp (pattern); int literal = find_keyword (Kliteral, keys) != Qnil || !re_tag_p (replacement); wp->w_disp_flags |= Window::WDF_GOAL_COLUMN; wp->w_bufp->check_read_only (); int delete_regexp = 0; int BM[256]; if (!regexp) { if (flags & SF_SMART_CASE_FOLD && smart_case_fold_string_p (pattern)) flags |= SF_CASE_FOLD; bm_compilef (BM, xstring_contents (pattern), xstring_length (pattern), flags & SF_CASE_FOLD); } else if (!regexpp (pattern)) { pattern = Fcompile_regexp (pattern, (flags & SF_SMART_CASE_FOLD ? Ksmart : boole (flags & SF_CASE_FOLD))); delete_regexp = 1; } point_t last_pos = -1; int count = 0; while ((regexp ? bp->re_scan_buffer (wp->w_point, pattern, limit, last_match, last_match_char, flags) : bp->scan_forward (wp->w_point, xstring_contents (pattern), xstring_length (pattern), BM, limit, flags)) && re_regs.start[0] >= 0) { if (re_regs.start[0] != re_regs.end[0] || last_match != re_regs.start[0]) { long ochars = bp->b_nchars; last_match_char = match_end_before (bp, wp->w_point); replace_match (wp, replacement, literal); last_match = wp->w_point.p_point; limit += bp->b_nchars - ochars; count++; if (once) { last_pos = wp->w_point.p_point; bp->goto_eol (wp->w_point); flags |= SF_NO_DUP; } else if (re_regs.start[0] == re_regs.end[0]) flags |= SF_NO_DUP; else flags &= ~SF_NO_DUP; } else flags |= SF_NO_DUP; clear_regs (); if (bp->eobp (wp->w_point)) break; QUIT; } if (last_pos != -1) bp->goto_char (wp->w_point, last_pos); if (delete_regexp) destruct_regexp (pattern); return make_fixnum (count); } lisp Fmatch_data (lisp v) { if (re_regs.start[0] < 0) return Qnil; if (!v || v == Qnil) v = make_vector (2 * MAX_REGS + 1, Qnil); else { check_general_vector (v); if (xvector_length (v) != 2 * MAX_REGS + 1) FEtype_error (v, Smatch_data); } lisp *p = xvector_contents (v); for (int i = 0; i < MAX_REGS; i++) if (re_regs.start[i] >= 0) { *p++ = make_fixnum (re_regs.start[i]); *p++ = make_fixnum (re_regs.end[i]); } else { *p++ = Qnil; *p++ = Qnil; } *p = xsymbol_value (Vlast_match_string); return v; } lisp Fstore_match_data (lisp data) { if (data == Qnil) { clear_regs (); return Qnil; } check_general_vector (data); if (xvector_length (data) != 2 * MAX_REGS + 1) FEtype_error (data, Smatch_data); Regexp::sregs r; lisp *p = xvector_contents (data); for (int i = 0; i < MAX_REGS; i++, p += 2) if (*p == Qnil) r.start[i] = r.end[i] = -1; else { r.start[i] = fixnum_value (*p); r.end[i] = fixnum_value (p[1]); } r.nregs = MAX_REGS - 1; xsymbol_value (Vlast_match_string) = stringp (*p) ? *p : Qnil; copy_regs0 (re_regs, r); check_regs (); return Qt; } static void ss_add (StrBuf &sb, Char cc, int &fconv) { switch (fconv) { case UPCASE_ONE: sb.add (char_upcase (cc)); fconv = NOCASECONV; break; case DOWNCASE_ONE: sb.add (char_downcase (cc)); fconv = NOCASECONV; break; case UPCASE_CHARS: sb.add (char_upcase (cc)); break; case DOWNCASE_CHARS: sb.add (char_downcase (cc)); break; default: sb.add (cc); break; } } static void substitute_string (StrBuf &sb, lisp string, lisp replacement) { const Char *r = xstring_contents (replacement); const Char *const re = r + xstring_length (replacement); point_t l = xstring_length (string); int fconv = NOCASECONV; while (r < re) { Char c = *r++; if (c != '\\') ss_add (sb, c, fconv); else { if (r == re) break; c = *r++; switch (c) { case '&': c = '0'; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': c -= '0'; if (re_regs.start[c] >= 0) { int start = min (re_regs.start[c], l); int end = min (re_regs.end[c], l); for (; start < end; start++) ss_add (sb, xstring_contents (string)[start], fconv); } break; case NOCASECONV: case UPCASE_ONE: case DOWNCASE_ONE: case UPCASE_CHARS: case DOWNCASE_CHARS: fconv = c; break; default: ss_add (sb, c, fconv); break; } } } } lisp Fsubstitute_string (lisp string, lisp pattern, lisp replacement, lisp keys) { clear_regs (); lisp case_fold = find_keyword (Kcase_fold, keys); const u_char *const translate = ((case_fold == Ksmart ? (stringp (pattern) && Regexp::smart_case_fold_p (xstring_contents (pattern), xstring_length (pattern))) : case_fold != Qnil) ? char_translate_upcase_table : char_no_translate_table); check_string (string); check_string (replacement); Regexp re (translate, xsyntax_table (selected_buffer ()->lsyntax_table)); if (regexpp (pattern)) re.compile (pattern, 1); else { check_string (pattern); if (!xstring_length (pattern)) return string; re.compile (xstring_contents (pattern), xstring_length (pattern), 1); } int offset, len; if (!string_start_end (string, find_keyword (Kstart, keys, Qnil), find_keyword (Kend, keys, Qnil), offset, len)) return Qnil; int count; lisp lcount = find_keyword (Kcount, keys, Qnil); if (lcount == Qnil) count = -1; else { count = fixnum_value (lcount); if (!count) return string; } lisp lskip = find_keyword (Kskip, keys, Qnil); int skip = lskip == Qnil ? 0 : fixnum_value (lskip); char tem[1024]; StrBuf sb (tem, sizeof tem); if (offset) sb.add (xstring_contents (string), offset); int found = 0; while (re.search (xstring_contents (string), len, offset)) { save_match (re, Qnil); if (skip > 0) { sb.add (xstring_contents (string) + offset, re_regs.end[0] - offset); skip--; } else { sb.add (xstring_contents (string) + offset, re_regs.start[0] - offset); substitute_string (sb, string, replacement); count--; found++; } offset = re_regs.end[0]; if (re_regs.start[0] == re_regs.end[0]) break; if (offset == len) break; if (!count) break; clear_regs (); } sb.add (xstring_contents (string) + offset, xstring_length (string) - offset); multiple_value::count () = 2; multiple_value::value (1) = make_fixnum (found); return sb.make_string (); } lisp Fstring_replace_match (lisp string, lisp replacement) { check_string (string); check_string (replacement); if (re_regs.start[0] < 0) return Qnil; char tem[1024]; StrBuf sb (tem, sizeof tem); substitute_string (sb, string, replacement); return sb.make_string (); } lisp Fstring_looking_at (lisp regex, lisp string, lisp keys) { check_string (string); clear_regs (); lisp case_fold = find_keyword (Kcase_fold, keys); Regexp re (((case_fold == Ksmart ? (stringp (regex) && Regexp::smart_case_fold_p (xstring_contents (regex), xstring_length (regex))) : case_fold != Qnil) ? char_translate_upcase_table : char_no_translate_table), xsyntax_table (selected_buffer ()->lsyntax_table)); if (regexpp (regex)) re.compile (regex, 0); else { check_string (regex); if (!xstring_length (regex)) return Qnil; re.compile (xstring_contents (regex), xstring_length (regex), 0); } int offset, len; if (!string_start_end (string, find_keyword (Kstart, keys, Qnil), find_keyword (Kend, keys, Qnil), offset, len)) return Qnil; if (!re.match (xstring_contents (string), len, offset)) return Qnil; save_match (re, string); return make_fixnum (re.re_regs.start[0]); } lisp Fcompare_buffer_substrings (lisp buffer1, lisp start1, lisp end1, lisp buffer2, lisp start2, lisp end2, lisp case_fold) { Buffer *bp1 = Buffer::coerce_to_buffer (buffer1); Buffer *bp2 = Buffer::coerce_to_buffer (buffer2); point_t p1 = bp1->coerce_to_restricted_point (start1); point_t pe1 = bp1->coerce_to_restricted_point (end1); point_t p2 = bp2->coerce_to_restricted_point (start2); point_t pe2 = bp2->coerce_to_restricted_point (end2); if (p1 > pe1) swap (p1, pe1); if (p2 > pe2) swap (p2, pe2); if (case_fold == Qnil) case_fold = 0; Point point1, point2; bp1->set_point (point1, p1); bp2->set_point (point2, p2); point_t end = p1 + min (pe1 - p1, pe2 - p2); int diff = 0; while (point1.p_point < end) { Char c1 = point1.ch (); Char c2 = point2.ch (); diff = case_fold ? char_upcase (c1) - char_upcase (c2) : c1 - c2; if (diff) break; if (!bp1->forward_char (point1, 1) || !bp2->forward_char (point2, 1)) break; } if (!diff) diff = (pe1 - p1) - (pe2 - p2); return make_fixnum (diff < 0 ? -1 - (point1.p_point - p1) : 1 + (point1.p_point - p1)); }
44,778
https://github.com/fabiang/laminas-db/blob/master/src/TableGateway/Exception/ExceptionInterface.php
Github Open Source
Open Source
BSD-3-Clause
2,022
laminas-db
fabiang
PHP
Code
11
44
<?php namespace Laminas\Db\TableGateway\Exception; use Laminas\Db\Exception; interface ExceptionInterface extends Exception\ExceptionInterface { }
26,812
https://github.com/alexandred/catarse-1/blob/master/app/controllers/channels/profiles_controller.rb
Github Open Source
Open Source
MIT
2,013
catarse-1
alexandred
Ruby
Code
36
129
class Channels::ProfilesController < Channels::BaseController layout :user_catarse_bootstrap inherit_resources load_and_authorize_resource only: [:edit, :update] actions :show, :edit, :update custom_actions resource: [:how_it_works] def resource @profile ||= channel end private def user_catarse_bootstrap action_name == 'edit' ? 'application' : 'catarse_bootstrap' end end
25,493
https://github.com/neckerlein/Shopware-Trainning/blob/master/html/var/cache/dev_h89d500b84530a5dcf60d76ed1a15bcf1/twig/9c/9c6ad8b9a57c737c37e42e12b1deec30743f54627d6885f5ecbf8f45bd6f5230.php
Github Open Source
Open Source
MIT
2,021
Shopware-Trainning
neckerlein
PHP
Code
1,694
9,056
<?php use Twig\Environment; use Twig\Error\LoaderError; use Twig\Error\RuntimeError; use Twig\Extension\SandboxExtension; use Twig\Markup; use Twig\Sandbox\SecurityError; use Twig\Sandbox\SecurityNotAllowedTagError; use Twig\Sandbox\SecurityNotAllowedFilterError; use Twig\Sandbox\SecurityNotAllowedFunctionError; use Twig\Source; use Twig\Template; /* @Storefront/storefront/component/product/card/price-unit.html.twig */ class __TwigTemplate_e4d13bc5b009f16124755ca5078495cd592fc549c4ad118bb17b08b6c6a2c3b5 extends Template { private $source; private $macros = []; public function __construct(Environment $env) { parent::__construct($env); $this->source = $this->getSourceContext(); $this->parent = false; $this->blocks = [ 'component_product_box_price_info' => [$this, 'block_component_product_box_price_info'], 'component_product_box_price_unit' => [$this, 'block_component_product_box_price_unit'], 'component_product_box_price_purchase_unit' => [$this, 'block_component_product_box_price_purchase_unit'], 'component_product_box_price_reference_unit' => [$this, 'block_component_product_box_price_reference_unit'], 'component_product_box_price' => [$this, 'block_component_product_box_price'], ]; } protected function doDisplay(array $context, array $blocks = []) { $macros = $this->macros; $__internal_085b0142806202599c7fe3b329164a92397d8978207a37e79d70b8c52599e33e = $this->extensions["Symfony\\Bundle\\WebProfilerBundle\\Twig\\WebProfilerExtension"]; $__internal_085b0142806202599c7fe3b329164a92397d8978207a37e79d70b8c52599e33e->enter($__internal_085b0142806202599c7fe3b329164a92397d8978207a37e79d70b8c52599e33e_prof = new \Twig\Profiler\Profile($this->getTemplateName(), "template", "@Storefront/storefront/component/product/card/price-unit.html.twig")); $__internal_319393461309892924ff6e74d6d6e64287df64b63545b994e100d4ab223aed02 = $this->extensions["Symfony\\Bridge\\Twig\\Extension\\ProfilerExtension"]; $__internal_319393461309892924ff6e74d6d6e64287df64b63545b994e100d4ab223aed02->enter($__internal_319393461309892924ff6e74d6d6e64287df64b63545b994e100d4ab223aed02_prof = new \Twig\Profiler\Profile($this->getTemplateName(), "template", "@Storefront/storefront/component/product/card/price-unit.html.twig")); // line 1 $this->displayBlock('component_product_box_price_info', $context, $blocks); $__internal_085b0142806202599c7fe3b329164a92397d8978207a37e79d70b8c52599e33e->leave($__internal_085b0142806202599c7fe3b329164a92397d8978207a37e79d70b8c52599e33e_prof); $__internal_319393461309892924ff6e74d6d6e64287df64b63545b994e100d4ab223aed02->leave($__internal_319393461309892924ff6e74d6d6e64287df64b63545b994e100d4ab223aed02_prof); } public function block_component_product_box_price_info($context, array $blocks = []) { $macros = $this->macros; $__internal_085b0142806202599c7fe3b329164a92397d8978207a37e79d70b8c52599e33e = $this->extensions["Symfony\\Bundle\\WebProfilerBundle\\Twig\\WebProfilerExtension"]; $__internal_085b0142806202599c7fe3b329164a92397d8978207a37e79d70b8c52599e33e->enter($__internal_085b0142806202599c7fe3b329164a92397d8978207a37e79d70b8c52599e33e_prof = new \Twig\Profiler\Profile($this->getTemplateName(), "block", "component_product_box_price_info")); $__internal_319393461309892924ff6e74d6d6e64287df64b63545b994e100d4ab223aed02 = $this->extensions["Symfony\\Bridge\\Twig\\Extension\\ProfilerExtension"]; $__internal_319393461309892924ff6e74d6d6e64287df64b63545b994e100d4ab223aed02->enter($__internal_319393461309892924ff6e74d6d6e64287df64b63545b994e100d4ab223aed02_prof = new \Twig\Profiler\Profile($this->getTemplateName(), "block", "component_product_box_price_info")); // line 2 echo " "; $context["purchaseUnit"] = twig_get_attribute($this->env, $this->source, ($context["product"] ?? null), "purchaseUnit", [], "any", false, false, false, 2); // line 3 echo " "; $context["listingPrice"] = twig_get_attribute($this->env, $this->source, ($context["product"] ?? null), "calculatedListingPrice", [], "any", false, false, false, 3); // line 4 echo " "; $context["fromPrice"] = twig_get_attribute($this->env, $this->source, ($context["listingPrice"] ?? null), "from", [], "any", false, false, false, 4); // line 5 echo " "; // line 6 $context["cheapest"] = twig_get_attribute($this->env, $this->source, ($context["product"] ?? null), "calculatedCheapestPrice", [], "any", false, false, false, 6); // line 7 echo " "; // line 8 $context["real"] = twig_get_attribute($this->env, $this->source, ($context["product"] ?? null), "calculatedPrice", [], "any", false, false, false, 8); // line 9 echo " "; if ((1 === twig_compare(twig_get_attribute($this->env, $this->source, twig_get_attribute($this->env, $this->source, ($context["product"] ?? null), "calculatedPrices", [], "any", false, false, false, 9), "count", [], "any", false, false, false, 9), 0))) { // line 10 echo " "; $context["real"] = twig_get_attribute($this->env, $this->source, twig_get_attribute($this->env, $this->source, ($context["product"] ?? null), "calculatedPrices", [], "any", false, false, false, 10), "last", [], "any", false, false, false, 10); // line 11 echo " "; } // line 12 echo " "; // line 13 $context["referencePrice"] = twig_get_attribute($this->env, $this->source, ($context["real"] ?? null), "referencePrice", [], "any", false, false, false, 13); // line 14 echo " "; // line 15 $context["displayFrom"] = (1 === twig_compare(twig_get_attribute($this->env, $this->source, twig_get_attribute($this->env, $this->source, ($context["product"] ?? null), "calculatedPrices", [], "any", false, false, false, 15), "count", [], "any", false, false, false, 15), 1)); // line 16 echo " <div class=\"product-price-info\"> "; // line 18 $this->displayBlock('component_product_box_price_unit', $context, $blocks); // line 42 echo " "; // line 43 $this->displayBlock('component_product_box_price', $context, $blocks); // line 80 echo " </div> "; $__internal_319393461309892924ff6e74d6d6e64287df64b63545b994e100d4ab223aed02->leave($__internal_319393461309892924ff6e74d6d6e64287df64b63545b994e100d4ab223aed02_prof); $__internal_085b0142806202599c7fe3b329164a92397d8978207a37e79d70b8c52599e33e->leave($__internal_085b0142806202599c7fe3b329164a92397d8978207a37e79d70b8c52599e33e_prof); } // line 18 public function block_component_product_box_price_unit($context, array $blocks = []) { $macros = $this->macros; $__internal_085b0142806202599c7fe3b329164a92397d8978207a37e79d70b8c52599e33e = $this->extensions["Symfony\\Bundle\\WebProfilerBundle\\Twig\\WebProfilerExtension"]; $__internal_085b0142806202599c7fe3b329164a92397d8978207a37e79d70b8c52599e33e->enter($__internal_085b0142806202599c7fe3b329164a92397d8978207a37e79d70b8c52599e33e_prof = new \Twig\Profiler\Profile($this->getTemplateName(), "block", "component_product_box_price_unit")); $__internal_319393461309892924ff6e74d6d6e64287df64b63545b994e100d4ab223aed02 = $this->extensions["Symfony\\Bridge\\Twig\\Extension\\ProfilerExtension"]; $__internal_319393461309892924ff6e74d6d6e64287df64b63545b994e100d4ab223aed02->enter($__internal_319393461309892924ff6e74d6d6e64287df64b63545b994e100d4ab223aed02_prof = new \Twig\Profiler\Profile($this->getTemplateName(), "block", "component_product_box_price_unit")); // line 19 echo " <p class=\"product-price-unit\"> "; // line 21 echo " "; $this->displayBlock('component_product_box_price_purchase_unit', $context, $blocks); // line 31 echo " "; // line 33 echo " "; $this->displayBlock('component_product_box_price_reference_unit', $context, $blocks); // line 40 echo " </p> "; $__internal_319393461309892924ff6e74d6d6e64287df64b63545b994e100d4ab223aed02->leave($__internal_319393461309892924ff6e74d6d6e64287df64b63545b994e100d4ab223aed02_prof); $__internal_085b0142806202599c7fe3b329164a92397d8978207a37e79d70b8c52599e33e->leave($__internal_085b0142806202599c7fe3b329164a92397d8978207a37e79d70b8c52599e33e_prof); } // line 21 public function block_component_product_box_price_purchase_unit($context, array $blocks = []) { $macros = $this->macros; $__internal_085b0142806202599c7fe3b329164a92397d8978207a37e79d70b8c52599e33e = $this->extensions["Symfony\\Bundle\\WebProfilerBundle\\Twig\\WebProfilerExtension"]; $__internal_085b0142806202599c7fe3b329164a92397d8978207a37e79d70b8c52599e33e->enter($__internal_085b0142806202599c7fe3b329164a92397d8978207a37e79d70b8c52599e33e_prof = new \Twig\Profiler\Profile($this->getTemplateName(), "block", "component_product_box_price_purchase_unit")); $__internal_319393461309892924ff6e74d6d6e64287df64b63545b994e100d4ab223aed02 = $this->extensions["Symfony\\Bridge\\Twig\\Extension\\ProfilerExtension"]; $__internal_319393461309892924ff6e74d6d6e64287df64b63545b994e100d4ab223aed02->enter($__internal_319393461309892924ff6e74d6d6e64287df64b63545b994e100d4ab223aed02_prof = new \Twig\Profiler\Profile($this->getTemplateName(), "block", "component_product_box_price_purchase_unit")); // line 22 echo " "; if ((($context["referencePrice"] ?? null) && twig_get_attribute($this->env, $this->source, ($context["referencePrice"] ?? null), "unitName", [], "any", false, false, false, 22))) { // line 23 echo " <span class=\"product-unit-label\"> "; // line 24 echo $this->extensions['Shopware\Storefront\Framework\Twig\Extension\SwSanitizeTwigFilter']->sanitize($this->extensions['Symfony\Bridge\Twig\Extension\TranslationExtension']->trans("listing.boxUnitLabel")); echo " </span> <span class=\"price-unit-content\"> "; // line 27 echo twig_escape_filter($this->env, twig_get_attribute($this->env, $this->source, ($context["referencePrice"] ?? null), "purchaseUnit", [], "any", false, false, false, 27), "html", null, true); echo " "; echo twig_escape_filter($this->env, twig_get_attribute($this->env, $this->source, ($context["referencePrice"] ?? null), "unitName", [], "any", false, false, false, 27), "html", null, true); echo " </span> "; } // line 30 echo " "; $__internal_319393461309892924ff6e74d6d6e64287df64b63545b994e100d4ab223aed02->leave($__internal_319393461309892924ff6e74d6d6e64287df64b63545b994e100d4ab223aed02_prof); $__internal_085b0142806202599c7fe3b329164a92397d8978207a37e79d70b8c52599e33e->leave($__internal_085b0142806202599c7fe3b329164a92397d8978207a37e79d70b8c52599e33e_prof); } // line 33 public function block_component_product_box_price_reference_unit($context, array $blocks = []) { $macros = $this->macros; $__internal_085b0142806202599c7fe3b329164a92397d8978207a37e79d70b8c52599e33e = $this->extensions["Symfony\\Bundle\\WebProfilerBundle\\Twig\\WebProfilerExtension"]; $__internal_085b0142806202599c7fe3b329164a92397d8978207a37e79d70b8c52599e33e->enter($__internal_085b0142806202599c7fe3b329164a92397d8978207a37e79d70b8c52599e33e_prof = new \Twig\Profiler\Profile($this->getTemplateName(), "block", "component_product_box_price_reference_unit")); $__internal_319393461309892924ff6e74d6d6e64287df64b63545b994e100d4ab223aed02 = $this->extensions["Symfony\\Bridge\\Twig\\Extension\\ProfilerExtension"]; $__internal_319393461309892924ff6e74d6d6e64287df64b63545b994e100d4ab223aed02->enter($__internal_319393461309892924ff6e74d6d6e64287df64b63545b994e100d4ab223aed02_prof = new \Twig\Profiler\Profile($this->getTemplateName(), "block", "component_product_box_price_reference_unit")); // line 34 echo " "; if ( !(null === ($context["referencePrice"] ?? null))) { // line 35 echo " <span class=\"price-unit-reference\"> ("; // line 36 echo twig_escape_filter($this->env, $this->extensions['Shopware\Core\Framework\Adapter\Twig\Filter\CurrencyFilter']->formatCurrency($context, twig_get_attribute($this->env, $this->source, ($context["referencePrice"] ?? null), "price", [], "any", false, false, false, 36)), "html", null, true); echo $this->extensions['Shopware\Storefront\Framework\Twig\Extension\SwSanitizeTwigFilter']->sanitize($this->extensions['Symfony\Bridge\Twig\Extension\TranslationExtension']->trans("general.star")); echo " / "; echo twig_escape_filter($this->env, twig_get_attribute($this->env, $this->source, ($context["referencePrice"] ?? null), "referenceUnit", [], "any", false, false, false, 36), "html", null, true); echo " "; echo twig_escape_filter($this->env, twig_get_attribute($this->env, $this->source, ($context["referencePrice"] ?? null), "unitName", [], "any", false, false, false, 36), "html", null, true); echo ") </span> "; } // line 39 echo " "; $__internal_319393461309892924ff6e74d6d6e64287df64b63545b994e100d4ab223aed02->leave($__internal_319393461309892924ff6e74d6d6e64287df64b63545b994e100d4ab223aed02_prof); $__internal_085b0142806202599c7fe3b329164a92397d8978207a37e79d70b8c52599e33e->leave($__internal_085b0142806202599c7fe3b329164a92397d8978207a37e79d70b8c52599e33e_prof); } // line 43 public function block_component_product_box_price($context, array $blocks = []) { $macros = $this->macros; $__internal_085b0142806202599c7fe3b329164a92397d8978207a37e79d70b8c52599e33e = $this->extensions["Symfony\\Bundle\\WebProfilerBundle\\Twig\\WebProfilerExtension"]; $__internal_085b0142806202599c7fe3b329164a92397d8978207a37e79d70b8c52599e33e->enter($__internal_085b0142806202599c7fe3b329164a92397d8978207a37e79d70b8c52599e33e_prof = new \Twig\Profiler\Profile($this->getTemplateName(), "block", "component_product_box_price")); $__internal_319393461309892924ff6e74d6d6e64287df64b63545b994e100d4ab223aed02 = $this->extensions["Symfony\\Bridge\\Twig\\Extension\\ProfilerExtension"]; $__internal_319393461309892924ff6e74d6d6e64287df64b63545b994e100d4ab223aed02->enter($__internal_319393461309892924ff6e74d6d6e64287df64b63545b994e100d4ab223aed02_prof = new \Twig\Profiler\Profile($this->getTemplateName(), "block", "component_product_box_price")); // line 44 echo " <div class=\"product-price-wrapper\"> "; // line 45 $context["price"] = ($context["real"] ?? null); // line 46 echo " <div class=\"product-cheapest-price\"> "; // line 48 if ((0 !== twig_compare(twig_get_attribute($this->env, $this->source, ($context["cheapest"] ?? null), "unitPrice", [], "any", false, false, false, 48), twig_get_attribute($this->env, $this->source, ($context["real"] ?? null), "unitPrice", [], "any", false, false, false, 48)))) { // line 49 echo " <div>"; echo $this->extensions['Shopware\Storefront\Framework\Twig\Extension\SwSanitizeTwigFilter']->sanitize($this->extensions['Symfony\Bridge\Twig\Extension\TranslationExtension']->trans("listing.cheapestPriceLabel")); echo "<span class=\"product-cheapest-price-price\"> "; echo twig_escape_filter($this->env, $this->extensions['Shopware\Core\Framework\Adapter\Twig\Filter\CurrencyFilter']->formatCurrency($context, twig_get_attribute($this->env, $this->source, ($context["cheapest"] ?? null), "unitPrice", [], "any", false, false, false, 49)), "html", null, true); echo $this->extensions['Shopware\Storefront\Framework\Twig\Extension\SwSanitizeTwigFilter']->sanitize($this->extensions['Symfony\Bridge\Twig\Extension\TranslationExtension']->trans("general.star")); echo "</span></div> "; } // line 51 echo " </div> "; // line 53 if (($context["displayFrom"] ?? null)) { // line 54 echo " "; echo $this->extensions['Shopware\Storefront\Framework\Twig\Extension\SwSanitizeTwigFilter']->sanitize($this->extensions['Symfony\Bridge\Twig\Extension\TranslationExtension']->trans("listing.listingTextFrom")); echo " "; } // line 56 echo " "; // line 57 $context["isListPrice"] = (1 === twig_compare(twig_get_attribute($this->env, $this->source, twig_get_attribute($this->env, $this->source, ($context["price"] ?? null), "listPrice", [], "any", false, false, false, 57), "percentage", [], "any", false, false, false, 57), 0)); // line 58 echo " <span class=\"product-price"; // line 59 if ((($context["isListPrice"] ?? null) && !($context["displayFrom"] ?? null))) { echo " with-list-price"; } echo "\"> "; // line 60 echo twig_escape_filter($this->env, $this->extensions['Shopware\Core\Framework\Adapter\Twig\Filter\CurrencyFilter']->formatCurrency($context, twig_get_attribute($this->env, $this->source, ($context["price"] ?? null), "unitPrice", [], "any", false, false, false, 60)), "html", null, true); echo $this->extensions['Shopware\Storefront\Framework\Twig\Extension\SwSanitizeTwigFilter']->sanitize($this->extensions['Symfony\Bridge\Twig\Extension\TranslationExtension']->trans("general.star")); echo " "; // line 62 if ((($context["isListPrice"] ?? null) && !($context["displayFrom"] ?? null))) { // line 63 echo " "; $context["afterListPriceSnippetExists"] = (1 === twig_compare(twig_length_filter($this->env, $this->extensions['Symfony\Bridge\Twig\Extension\TranslationExtension']->trans("listing.afterListPrice")), 0)); // line 64 echo " "; $context["beforeListPriceSnippetExists"] = (1 === twig_compare(twig_length_filter($this->env, $this->extensions['Symfony\Bridge\Twig\Extension\TranslationExtension']->trans("listing.beforeListPrice")), 0)); // line 65 echo " "; $context["hideStrikeTrough"] = (($context["beforeListPriceSnippetExists"] ?? null) || ($context["afterListPriceSnippetExists"] ?? null)); // line 66 echo " <span class=\"list-price"; // line 67 if (($context["hideStrikeTrough"] ?? null)) { echo " list-price-no-line-through"; } echo "\"> "; // line 68 if (($context["beforeListPriceSnippetExists"] ?? null)) { echo $this->extensions['Shopware\Storefront\Framework\Twig\Extension\SwSanitizeTwigFilter']->sanitize(twig_trim_filter($this->extensions['Symfony\Bridge\Twig\Extension\TranslationExtension']->trans("listing.beforeListPrice"))); } // line 69 echo " <span class=\"list-price-price\">"; // line 70 echo twig_escape_filter($this->env, $this->extensions['Shopware\Core\Framework\Adapter\Twig\Filter\CurrencyFilter']->formatCurrency($context, twig_get_attribute($this->env, $this->source, twig_get_attribute($this->env, $this->source, ($context["price"] ?? null), "listPrice", [], "any", false, false, false, 70), "price", [], "any", false, false, false, 70)), "html", null, true); echo $this->extensions['Shopware\Storefront\Framework\Twig\Extension\SwSanitizeTwigFilter']->sanitize($this->extensions['Symfony\Bridge\Twig\Extension\TranslationExtension']->trans("general.star")); echo "</span> "; // line 72 if (($context["afterListPriceSnippetExists"] ?? null)) { echo $this->extensions['Shopware\Storefront\Framework\Twig\Extension\SwSanitizeTwigFilter']->sanitize(twig_trim_filter($this->extensions['Symfony\Bridge\Twig\Extension\TranslationExtension']->trans("listing.afterListPrice"))); } // line 73 echo " <span class=\"list-price-percentage\">"; // line 74 echo $this->extensions['Shopware\Storefront\Framework\Twig\Extension\SwSanitizeTwigFilter']->sanitize($this->extensions['Symfony\Bridge\Twig\Extension\TranslationExtension']->trans("detail.listPricePercentage", ["%price%" => twig_get_attribute($this->env, $this->source, twig_get_attribute($this->env, $this->source, ($context["price"] ?? null), "listPrice", [], "any", false, false, false, 74), "percentage", [], "any", false, false, false, 74)])); echo "</span> </span> "; } // line 77 echo " </span> </div> "; $__internal_319393461309892924ff6e74d6d6e64287df64b63545b994e100d4ab223aed02->leave($__internal_319393461309892924ff6e74d6d6e64287df64b63545b994e100d4ab223aed02_prof); $__internal_085b0142806202599c7fe3b329164a92397d8978207a37e79d70b8c52599e33e->leave($__internal_085b0142806202599c7fe3b329164a92397d8978207a37e79d70b8c52599e33e_prof); } public function getTemplateName() { return "@Storefront/storefront/component/product/card/price-unit.html.twig"; } public function getDebugInfo() { return array ( 345 => 77, 339 => 74, 336 => 73, 332 => 72, 326 => 70, 323 => 69, 319 => 68, 313 => 67, 310 => 66, 307 => 65, 304 => 64, 301 => 63, 299 => 62, 293 => 60, 287 => 59, 284 => 58, 282 => 57, 279 => 56, 273 => 54, 271 => 53, 267 => 51, 258 => 49, 256 => 48, 252 => 46, 250 => 45, 247 => 44, 237 => 43, 227 => 39, 216 => 36, 213 => 35, 210 => 34, 200 => 33, 190 => 30, 182 => 27, 176 => 24, 173 => 23, 170 => 22, 160 => 21, 149 => 40, 146 => 33, 143 => 31, 140 => 21, 137 => 19, 127 => 18, 116 => 80, 114 => 43, 111 => 42, 109 => 18, 105 => 16, 103 => 15, 100 => 14, 98 => 13, 95 => 12, 92 => 11, 89 => 10, 86 => 9, 84 => 8, 81 => 7, 79 => 6, 76 => 5, 73 => 4, 70 => 3, 67 => 2, 48 => 1,); } public function getSourceContext() { return new Source("{% block component_product_box_price_info %} {% set purchaseUnit = product.purchaseUnit %} {% set listingPrice = product.calculatedListingPrice %} {% set fromPrice = listingPrice.from %} {% set cheapest = product.calculatedCheapestPrice %} {% set real = product.calculatedPrice %} {% if product.calculatedPrices.count > 0 %} {% set real = product.calculatedPrices.last %} {% endif %} {% set referencePrice = real.referencePrice %} {% set displayFrom = product.calculatedPrices.count > 1 %} <div class=\"product-price-info\"> {% block component_product_box_price_unit %} <p class=\"product-price-unit\"> {# Price is based on the purchase unit #} {% block component_product_box_price_purchase_unit %} {% if referencePrice and referencePrice.unitName %} <span class=\"product-unit-label\"> {{ \"listing.boxUnitLabel\"|trans|sw_sanitize }} </span> <span class=\"price-unit-content\"> {{ referencePrice.purchaseUnit }} {{ referencePrice.unitName }} </span> {% endif %} {% endblock %} {# Item price is based on a reference unit #} {% block component_product_box_price_reference_unit %} {% if referencePrice is not null %} <span class=\"price-unit-reference\"> ({{ referencePrice.price|currency }}{{ \"general.star\"|trans|sw_sanitize }} / {{ referencePrice.referenceUnit }} {{ referencePrice.unitName }}) </span> {% endif %} {% endblock %} </p> {% endblock %} {% block component_product_box_price %} <div class=\"product-price-wrapper\"> {% set price = real %} <div class=\"product-cheapest-price\"> {% if cheapest.unitPrice != real.unitPrice %} <div>{{ \"listing.cheapestPriceLabel\"|trans|sw_sanitize }}<span class=\"product-cheapest-price-price\"> {{ cheapest.unitPrice|currency }}{{ \"general.star\"|trans|sw_sanitize }}</span></div> {% endif %} </div> {% if displayFrom %} {{ \"listing.listingTextFrom\"|trans|sw_sanitize }} {% endif %} {% set isListPrice = price.listPrice.percentage > 0 %} <span class=\"product-price{% if isListPrice and not displayFrom %} with-list-price{% endif %}\"> {{ price.unitPrice|currency }}{{ \"general.star\"|trans|sw_sanitize }} {% if isListPrice and not displayFrom %} {% set afterListPriceSnippetExists = \"listing.afterListPrice\"|trans|length > 0 %} {% set beforeListPriceSnippetExists = \"listing.beforeListPrice\"|trans|length > 0 %} {% set hideStrikeTrough = beforeListPriceSnippetExists or afterListPriceSnippetExists %} <span class=\"list-price{% if hideStrikeTrough %} list-price-no-line-through{% endif %}\"> {% if beforeListPriceSnippetExists %}{{ \"listing.beforeListPrice\"|trans|trim|sw_sanitize }}{% endif %} <span class=\"list-price-price\">{{ price.listPrice.price|currency }}{{ \"general.star\"|trans|sw_sanitize }}</span> {% if afterListPriceSnippetExists %}{{ \"listing.afterListPrice\"|trans|trim|sw_sanitize }}{% endif %} <span class=\"list-price-percentage\">{{ \"detail.listPricePercentage\"|trans({'%price%': price.listPrice.percentage })|sw_sanitize }}</span> </span> {% endif %} </span> </div> {% endblock %} </div> {% endblock %} ", "@Storefront/storefront/component/product/card/price-unit.html.twig", "/var/www/html/vendor/shopware/storefront/Resources/views/storefront/component/product/card/price-unit.html.twig"); } }
938
https://github.com/aanm/proxy/blob/master/go/envoy/service/discovery/v2/sds.pb.go
Github Open Source
Open Source
Apache-2.0
2,019
proxy
aanm
Go
Code
958
3,590
// Code generated by protoc-gen-go. DO NOT EDIT. // source: envoy/service/discovery/v2/sds.proto package v2 import ( context "context" fmt "fmt" v2 "github.com/cilium/proxy/go/envoy/api/v2" proto "github.com/golang/protobuf/proto" _ "google.golang.org/genproto/googleapis/api/annotations" grpc "google.golang.org/grpc" codes "google.golang.org/grpc/codes" status "google.golang.org/grpc/status" math "math" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package // [#not-implemented-hide:] Not configuration. Workaround c++ protobuf issue with importing // services: https://github.com/google/protobuf/issues/4221 type SdsDummy struct { XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *SdsDummy) Reset() { *m = SdsDummy{} } func (m *SdsDummy) String() string { return proto.CompactTextString(m) } func (*SdsDummy) ProtoMessage() {} func (*SdsDummy) Descriptor() ([]byte, []int) { return fileDescriptor_f2a4da2e99d9a3e6, []int{0} } func (m *SdsDummy) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_SdsDummy.Unmarshal(m, b) } func (m *SdsDummy) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_SdsDummy.Marshal(b, m, deterministic) } func (m *SdsDummy) XXX_Merge(src proto.Message) { xxx_messageInfo_SdsDummy.Merge(m, src) } func (m *SdsDummy) XXX_Size() int { return xxx_messageInfo_SdsDummy.Size(m) } func (m *SdsDummy) XXX_DiscardUnknown() { xxx_messageInfo_SdsDummy.DiscardUnknown(m) } var xxx_messageInfo_SdsDummy proto.InternalMessageInfo func init() { proto.RegisterType((*SdsDummy)(nil), "envoy.service.discovery.v2.SdsDummy") } func init() { proto.RegisterFile("envoy/service/discovery/v2/sds.proto", fileDescriptor_f2a4da2e99d9a3e6) } var fileDescriptor_f2a4da2e99d9a3e6 = []byte{ // 250 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x90, 0xb1, 0x4a, 0x03, 0x41, 0x10, 0x86, 0x5d, 0x0b, 0x91, 0x45, 0x9b, 0x03, 0x2d, 0x96, 0xa0, 0x72, 0x58, 0x04, 0x8b, 0x39, 0x39, 0xc1, 0x22, 0x65, 0x08, 0xd6, 0xc1, 0x03, 0xfb, 0xf5, 0x6e, 0x88, 0x0b, 0xde, 0xce, 0x66, 0x67, 0xb3, 0x78, 0xad, 0xaf, 0xe0, 0xa3, 0xf9, 0x08, 0xfa, 0x20, 0x72, 0xb7, 0x31, 0x62, 0x71, 0x5d, 0xea, 0xff, 0xff, 0xbf, 0x19, 0x3e, 0x79, 0x8d, 0x36, 0x52, 0x57, 0x30, 0xfa, 0x68, 0x6a, 0x2c, 0x1a, 0xc3, 0x35, 0x45, 0xf4, 0x5d, 0x11, 0xcb, 0x82, 0x1b, 0x06, 0xe7, 0x29, 0x50, 0xa6, 0x86, 0x16, 0x6c, 0x5b, 0xb0, 0x6b, 0x41, 0x2c, 0xd5, 0x24, 0x11, 0xb4, 0x33, 0xfd, 0xe6, 0x2f, 0x1a, 0x96, 0x6a, 0xb2, 0x22, 0x5a, 0xbd, 0xe2, 0x10, 0x6b, 0x6b, 0x29, 0xe8, 0x60, 0xc8, 0x6e, 0xb9, 0xb9, 0x94, 0xc7, 0x55, 0xc3, 0x8b, 0x4d, 0xdb, 0x76, 0xe5, 0x97, 0x90, 0xe7, 0x15, 0xd6, 0x1e, 0xc3, 0xe2, 0x97, 0x51, 0xa5, 0x7b, 0xd9, 0x93, 0x3c, 0xad, 0x82, 0x47, 0xdd, 0xa6, 0x9c, 0xb3, 0x0b, 0x48, 0x0f, 0x69, 0x67, 0x20, 0x96, 0xb0, 0x1b, 0x3c, 0xe2, 0x7a, 0x83, 0x1c, 0xd4, 0xe5, 0x68, 0xce, 0x8e, 0x2c, 0x63, 0x7e, 0x30, 0x15, 0xb7, 0x22, 0x5b, 0xcb, 0x93, 0x07, 0x0c, 0xf5, 0xcb, 0xde, 0xb0, 0x57, 0xef, 0x9f, 0xdf, 0x1f, 0x87, 0x2a, 0x3f, 0xfb, 0xa7, 0x62, 0xc6, 0x89, 0x3f, 0x13, 0x37, 0xf3, 0x7b, 0x39, 0x35, 0x94, 0x30, 0xce, 0xd3, 0x5b, 0x07, 0xe3, 0x66, 0xe7, 0xbd, 0x9b, 0x65, 0xef, 0x69, 0x29, 0x9e, 0x8f, 0x06, 0x61, 0x77, 0x3f, 0x01, 0x00, 0x00, 0xff, 0xff, 0xc4, 0xb6, 0x90, 0x6d, 0xb0, 0x01, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. var _ context.Context var _ grpc.ClientConn // This is a compile-time assertion to ensure that this generated file // is compatible with the grpc package it is being compiled against. const _ = grpc.SupportPackageIsVersion4 // SecretDiscoveryServiceClient is the client API for SecretDiscoveryService service. // // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. type SecretDiscoveryServiceClient interface { StreamSecrets(ctx context.Context, opts ...grpc.CallOption) (SecretDiscoveryService_StreamSecretsClient, error) FetchSecrets(ctx context.Context, in *v2.DiscoveryRequest, opts ...grpc.CallOption) (*v2.DiscoveryResponse, error) } type secretDiscoveryServiceClient struct { cc *grpc.ClientConn } func NewSecretDiscoveryServiceClient(cc *grpc.ClientConn) SecretDiscoveryServiceClient { return &secretDiscoveryServiceClient{cc} } func (c *secretDiscoveryServiceClient) StreamSecrets(ctx context.Context, opts ...grpc.CallOption) (SecretDiscoveryService_StreamSecretsClient, error) { stream, err := c.cc.NewStream(ctx, &_SecretDiscoveryService_serviceDesc.Streams[0], "/envoy.service.discovery.v2.SecretDiscoveryService/StreamSecrets", opts...) if err != nil { return nil, err } x := &secretDiscoveryServiceStreamSecretsClient{stream} return x, nil } type SecretDiscoveryService_StreamSecretsClient interface { Send(*v2.DiscoveryRequest) error Recv() (*v2.DiscoveryResponse, error) grpc.ClientStream } type secretDiscoveryServiceStreamSecretsClient struct { grpc.ClientStream } func (x *secretDiscoveryServiceStreamSecretsClient) Send(m *v2.DiscoveryRequest) error { return x.ClientStream.SendMsg(m) } func (x *secretDiscoveryServiceStreamSecretsClient) Recv() (*v2.DiscoveryResponse, error) { m := new(v2.DiscoveryResponse) if err := x.ClientStream.RecvMsg(m); err != nil { return nil, err } return m, nil } func (c *secretDiscoveryServiceClient) FetchSecrets(ctx context.Context, in *v2.DiscoveryRequest, opts ...grpc.CallOption) (*v2.DiscoveryResponse, error) { out := new(v2.DiscoveryResponse) err := c.cc.Invoke(ctx, "/envoy.service.discovery.v2.SecretDiscoveryService/FetchSecrets", in, out, opts...) if err != nil { return nil, err } return out, nil } // SecretDiscoveryServiceServer is the server API for SecretDiscoveryService service. type SecretDiscoveryServiceServer interface { StreamSecrets(SecretDiscoveryService_StreamSecretsServer) error FetchSecrets(context.Context, *v2.DiscoveryRequest) (*v2.DiscoveryResponse, error) } // UnimplementedSecretDiscoveryServiceServer can be embedded to have forward compatible implementations. type UnimplementedSecretDiscoveryServiceServer struct { } func (*UnimplementedSecretDiscoveryServiceServer) StreamSecrets(srv SecretDiscoveryService_StreamSecretsServer) error { return status.Errorf(codes.Unimplemented, "method StreamSecrets not implemented") } func (*UnimplementedSecretDiscoveryServiceServer) FetchSecrets(ctx context.Context, req *v2.DiscoveryRequest) (*v2.DiscoveryResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method FetchSecrets not implemented") } func RegisterSecretDiscoveryServiceServer(s *grpc.Server, srv SecretDiscoveryServiceServer) { s.RegisterService(&_SecretDiscoveryService_serviceDesc, srv) } func _SecretDiscoveryService_StreamSecrets_Handler(srv interface{}, stream grpc.ServerStream) error { return srv.(SecretDiscoveryServiceServer).StreamSecrets(&secretDiscoveryServiceStreamSecretsServer{stream}) } type SecretDiscoveryService_StreamSecretsServer interface { Send(*v2.DiscoveryResponse) error Recv() (*v2.DiscoveryRequest, error) grpc.ServerStream } type secretDiscoveryServiceStreamSecretsServer struct { grpc.ServerStream } func (x *secretDiscoveryServiceStreamSecretsServer) Send(m *v2.DiscoveryResponse) error { return x.ServerStream.SendMsg(m) } func (x *secretDiscoveryServiceStreamSecretsServer) Recv() (*v2.DiscoveryRequest, error) { m := new(v2.DiscoveryRequest) if err := x.ServerStream.RecvMsg(m); err != nil { return nil, err } return m, nil } func _SecretDiscoveryService_FetchSecrets_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(v2.DiscoveryRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(SecretDiscoveryServiceServer).FetchSecrets(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/envoy.service.discovery.v2.SecretDiscoveryService/FetchSecrets", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(SecretDiscoveryServiceServer).FetchSecrets(ctx, req.(*v2.DiscoveryRequest)) } return interceptor(ctx, in, info, handler) } var _SecretDiscoveryService_serviceDesc = grpc.ServiceDesc{ ServiceName: "envoy.service.discovery.v2.SecretDiscoveryService", HandlerType: (*SecretDiscoveryServiceServer)(nil), Methods: []grpc.MethodDesc{ { MethodName: "FetchSecrets", Handler: _SecretDiscoveryService_FetchSecrets_Handler, }, }, Streams: []grpc.StreamDesc{ { StreamName: "StreamSecrets", Handler: _SecretDiscoveryService_StreamSecrets_Handler, ServerStreams: true, ClientStreams: true, }, }, Metadata: "envoy/service/discovery/v2/sds.proto", }
47,612
https://github.com/chihsiliu1966/lcmsNET/blob/master/tests/lcmsNET.Tests/UcrBgTest.cs
Github Open Source
Open Source
MIT
2,021
lcmsNET
chihsiliu1966
C#
Code
418
1,238
using Microsoft.VisualStudio.TestTools.UnitTesting; using System; namespace lcmsNET.Tests { [TestClass()] public class UcrBgTest { private TestContext testContextInstance; /// <summary> ///Gets or sets the test context which provides ///information about and functionality for the current test run. ///</summary> public TestContext TestContext { get { return testContextInstance; } set { testContextInstance = value; } } #region Additional test attributes // //You can use the following additional attributes as you write your tests: // //Use ClassInitialize to run code before running the first test in the class //[ClassInitialize()] //public static void MyClassInitialize(TestContext testContext) //{ //} // //Use ClassCleanup to run code after all tests in a class have run //[ClassCleanup()] //public static void MyClassCleanup() //{ //} // //Use TestInitialize to run code before running each test //[TestInitialize()] //public void MyTestInitialize() //{ //} // //Use TestCleanup to run code after each test has run //[TestCleanup()] //public void MyTestCleanup() //{ //} // #endregion [TestMethod()] public void ConstructorTest() { // Arrange int type = 4; double[] parameters = new double[] { 2.4, 1.0 / 1.055, 0.055 / 1.055, 1.0 / 12.92, 0.04045 }; double gamma = 2.2; uint nItems = 0; string languageCode = "en"; string countryCode = "US"; string text = "constructor"; using (var context = Context.Create(IntPtr.Zero, IntPtr.Zero)) using (var ucr = ToneCurve.BuildParametric(context, type, parameters)) using (var bg = ToneCurve.BuildGamma(context, gamma)) using (var desc = MultiLocalizedUnicode.Create(context, nItems)) { desc.SetASCII(languageCode, countryCode, text); var expectedUcr = ucr.Handle; var expectedBg = bg.Handle; var expectedDesc = desc.Handle; // Act var target = new UcrBg(ucr, bg, desc); var actualUcr = target.Ucr; var actualBg = target.Bg; var actualDesc = target.Desc; // Assert Assert.AreEqual(expectedUcr, actualUcr); Assert.AreEqual(expectedBg, actualBg); Assert.AreEqual(expectedDesc, actualDesc); } } [TestMethod()] public void FromHandleTest() { // Arrange int type = 4; double[] parameters = new double[] { 2.4, 1.0 / 1.055, 0.055 / 1.055, 1.0 / 12.92, 0.04045 }; double gamma = 2.2; uint nItems = 0; string languageCode = "en"; string countryCode = "US"; string expectedText = "from-handle"; using (var context = Context.Create(IntPtr.Zero, IntPtr.Zero)) using (var ucr = ToneCurve.BuildParametric(context, type, parameters)) using (var bg = ToneCurve.BuildGamma(context, gamma)) using (var desc = MultiLocalizedUnicode.Create(context, nItems)) { desc.SetASCII(languageCode, countryCode, expectedText); var notExpectedUcr = IntPtr.Zero; var notExpectedBg = IntPtr.Zero; var notExpectedDesc = IntPtr.Zero; var target = new UcrBg(ucr, bg, desc); using (var profile = Profile.CreatePlaceholder(null)) { profile.WriteTag(TagSignature.UcrBg, target); IntPtr handle = profile.ReadTag(TagSignature.UcrBg); // Act var actual = UcrBg.FromHandle(handle); var actualUcr = actual.Ucr; var actualBg = actual.Bg; var actualDesc = actual.Desc; // Assert Assert.AreNotEqual(notExpectedUcr, actualUcr); Assert.AreNotEqual(notExpectedBg, actualBg); Assert.AreNotEqual(notExpectedDesc, actualDesc); var desc2 = MultiLocalizedUnicode.FromHandle(actualDesc); var actualText = desc2.GetASCII(languageCode, countryCode); Assert.AreEqual(expectedText, actualText); } } } } }
13,649
https://github.com/fatihky/fsocket/blob/master/src/core/global.h
Github Open Source
Open Source
MIT
2,020
fsocket
fatihky
C
Code
13
60
#pragma once #include "../utils/thread.h" struct fsock_thread *f_choose_thr(); void fsock_workers_lock(); void fsock_workers_unlock(); void fsock_workers_signal();
39,015
https://github.com/AlexRogalskiy/milan/blob/master/milan/milan-compilers/milan-flink-compiler/src/main/scala/com/amazon/milan/compiler/flink/runtime/IdentityFlatMapFunction.scala
Github Open Source
Open Source
Apache-2.0
2,022
milan
AlexRogalskiy
Scala
Code
68
315
package com.amazon.milan.compiler.flink.runtime import com.amazon.milan.compiler.flink.types.{RecordWrapper, RecordWrapperTypeInformation} import org.apache.flink.api.common.functions.FlatMapFunction import org.apache.flink.api.common.typeinfo.TypeInformation import org.apache.flink.api.java.typeutils.ResultTypeQueryable import org.apache.flink.util.Collector /** * A Flink [[FlatMapFunction]] that passes input records through as-is. */ class IdentityFlatMapFunction[T >: Null, TKey >: Null <: Product](recordTypeInformation: TypeInformation[T], keyTypeInformation: TypeInformation[TKey]) extends FlatMapFunction[RecordWrapper[T, TKey], RecordWrapper[T, TKey]] with ResultTypeQueryable[RecordWrapper[T, TKey]] { override def flatMap(record: RecordWrapper[T, TKey], collector: Collector[RecordWrapper[T, TKey]]): Unit = { collector.collect(record) } override def getProducedType: TypeInformation[RecordWrapper[T, TKey]] = RecordWrapperTypeInformation.wrap(this.recordTypeInformation, this.keyTypeInformation) }
18,362
https://github.com/GennadyMV/otus_java_2018_10/blob/master/L12.2-web-server/src/main/java/ru/otus/login/LoginServlet.java
Github Open Source
Open Source
MIT
2,019
otus_java_2018_10
GennadyMV
Java
Code
80
251
package ru.otus.login; import ru.otus.user.UserService; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; public class LoginServlet extends HttpServlet { private static final int EXPIRE_INTERVAL = 20; // seconds private final UserService userService; public LoginServlet(UserService userService) { this.userService = userService; } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { String name = request.getParameter("name"); String password = request.getParameter("password"); if (userService.authenticate(name, password)) { request.getSession(); } else { PrintWriter out = response.getWriter(); out.println("Either user name or password is wrong."); } } }
41,395
https://github.com/google/google-ctf/blob/master/third_party/edk2/MdePkg/Include/Guid/AprioriFileName.h
Github Open Source
Open Source
LicenseRef-scancode-generic-cla, Apache-2.0, BSD-2-Clause, OpenSSL
2,023
google-ctf
google
C
Code
201
482
/** @file The GUID PEI_APRIORI_FILE_NAME_GUID definition is the file name of the PEI a priori file that is stored in a firmware volume. Copyright (c) 2006 - 2018, Intel Corporation. All rights reserved.<BR> This program and the accompanying materials are licensed and made available under the terms and conditions of the BSD License which accompanies this distribution. The full text of the license may be found at http://opensource.org/licenses/bsd-license.php THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. @par Revision Reference: GUID introduced in PI Version 1.0. **/ #ifndef __PEI_APRIORI_FILE_NAME_H__ #define __PEI_APRIORI_FILE_NAME_H__ #define PEI_APRIORI_FILE_NAME_GUID \ { 0x1b45cc0a, 0x156a, 0x428a, { 0x62, 0XAF, 0x49, 0x86, 0x4d, 0xa0, 0xe6, 0xe6 } } /// /// This file must be of type EFI_FV_FILETYPE_FREEFORM and must /// contain a single section of type EFI_SECTION_RAW. For details on /// firmware volumes, firmware file types, and firmware file section /// types. /// typedef struct { /// /// An array of zero or more EFI_GUID type entries that match the file names of PEIM /// modules in the same Firmware Volume. The maximum number of entries. /// EFI_GUID FileNamesWithinVolume[1]; } PEI_APRIORI_FILE_CONTENTS; extern EFI_GUID gPeiAprioriFileNameGuid; #endif
37,362
https://github.com/filipcro/datagrid/blob/master/tests/Files/TestPresenter.php
Github Open Source
Open Source
MIT
2,018
datagrid
filipcro
PHP
Code
39
163
<?php declare(strict_types=1); namespace Ublaboo\DataGrid\Tests\Files; use Mockery; use Nette\Application\UI\ITemplate; use Nette\Application\UI\Presenter; final class TestPresenter extends Presenter { protected function createComponentGrid(): TestGridControl { return new TestGridControl(); } protected function createTemplate(): ITemplate { return Mockery::mock(ITemplate::class) ->shouldReceive('getFile') ->andReturn(__DIR__ . '/template.latte') ->getMock(); } }
47,614
https://github.com/SofenChowdhury/epc/blob/master/resources/js/components/Indent/addIndent.vue
Github Open Source
Open Source
MIT
null
epc
SofenChowdhury
Vue
Code
881
3,221
<!--<style>--> <!-- .md-menu-content.md-select-menu {--> <!-- width: auto;--> <!-- max-width: none;--> <!-- min-width: auto;--> <!-- }--> <!--</style>--> <!--<template>--> <!-- <div>--> <!-- <form @submit.prevent="create">--> <!-- <div class="row md-layout md-gutter">--> <!-- <div class="col-md-3 md-layout-item">--> <!-- <label for="" class="col-form-label">Indent Title:</label>--> <!-- <input type="text" class="form-control p-2" value="" name="title" id=""/>--> <!-- </div>--> <!-- <div class="col-md-3 md-layout-item">--> <!-- <label for="voucher_no" class="col-form-label">Voucher No:</label>--> <!-- <input type="text" class="form-control p-2" required readonly value="" name="voucher_no" id="voucher_no" :value="form.voucher"/>--> <!-- </div>--> <!-- <div class="col-md-3">--> <!-- <label for="transaction_date" class="col-form-label">Indent date:</label>--> <!-- <md-datepicker v-model="form.date" autocomplete="off" required id="transaction_date" name="transaction_date" class="form-control pt-1 m-0" md-immediately/>--> <!-- </div>--> <!-- </div>--> <!-- <div class="row">--> <!-- <div class="form-group col-md-6">--> <!-- <label for="description" class="col-form-label">Indent Remark: </label>--> <!-- <textarea v-model="form.description" class="form-control" name="description" id="description"></textarea>--> <!-- </div>--> <!-- </div>--> <!-- <div class="row">--> <!-- <div class="col-md-12 table-responsive">--> <!-- <table class="table table-sm voucher-table">--> <!-- <thead>--> <!-- <tr class="table-info">--> <!-- <th scope="col" width="20%">Name of vendor/Paid to</th>--> <!-- <th scope="col"width="20%">Purpose of Payment</th>--> <!-- <th scope="col"width="20%">Project Exp Code</th>--> <!-- <th scope="col"width="15%">Amount</th>--> <!-- <th scope="col"width="15%">Remark</th>--> <!-- <th scope="col"width="10%">Action</th>--> <!-- </tr>--> <!-- </thead>--> <!-- <tbody>--> <!-- <tr class="table pb-0">--> <!-- <td class="pb-0">--> <!-- <div class="form-group">--> <!-- <md-field>--> <!-- <input type="text" class="form-control" placeholder="Name of vendor/Paid to" v-model="keywords0"/>--> <!-- </md-field>--> <!-- </div>--> <!-- </td>--> <!-- <td class="pb-0">--> <!-- <div class="form-group">--> <!-- <md-field>--> <!-- <input type="text" class="form-control" placeholder="Purpose of Payment" v-model="keywords1"/>--> <!-- </md-field>--> <!-- </div>--> <!-- </td>--> <!-- <td class="pb-0">--> <!-- <div class="form-group">--> <!-- <md-field>--> <!-- <input type="text" class="form-control" placeholder="Project Exp Code" v-model="keywords2"/>--> <!-- </md-field>--> <!-- </div>--> <!-- </td>--> <!-- <td class="pb-0">--> <!-- <div class="form-group">--> <!-- <md-field>--> <!-- <input type="number" class="form-control" placeholder="Amount" v-model="keywords3"/>--> <!-- </md-field>--> <!-- </div>--> <!-- </td>--> <!-- <td class="pb-0">--> <!-- <div class="form-group">--> <!-- <md-field>--> <!-- <input type="text" class="form-control" placeholder="Remark" v-model="keywords4"/>--> <!-- </md-field>--> <!-- </div>--> <!-- </td>--> <!-- <td></td>--> <!-- </tr>--> <!-- <tr class="table pb-0" v-for="(field,index) in fields">--> <!-- <td class="pb-0">--> <!-- <div class="form-group">--> <!-- <md-field>--> <!-- <input value="" type="text" class="form-control" placeholder="Name of vendor/Paid to" v-model="keywords0"/>--> <!-- </md-field>--> <!-- </div>--> <!-- </td>--> <!-- <td class="pb-0">--> <!-- <div class="form-group">--> <!-- <md-field>--> <!-- <input value="" type="text" class="form-control" placeholder="Purpose of Payment" v-model="keywords1"/>--> <!-- </md-field>--> <!-- </div>--> <!-- </td>--> <!-- <td class="pb-0">--> <!-- <div class="form-group">--> <!-- <md-field>--> <!-- <input value="" type="text" class="form-control" placeholder="Project Exp Code" v-model="keywords2"/>--> <!-- </md-field>--> <!-- </div>--> <!-- </td>--> <!-- <td class="pb-0">--> <!-- <div class="form-group">--> <!-- <md-field>--> <!-- <input value="0" type="number" class="form-control" placeholder="Amount" v-model="keywords3"/>--> <!-- </md-field>--> <!-- </div>--> <!-- </td>--> <!-- <td class="pb-0">--> <!-- <div class="form-group">--> <!-- <md-field>--> <!-- <input value="" type="text" class="form-control" placeholder="Remark" v-model="keywords4"/>--> <!-- </md-field>--> <!-- </div>--> <!-- </td>--> <!-- <td> <input type="button" @click="dataRemove(index), reduceAmount(field)" required class="btn btn-md btn-danger mt-3" value="Delete" :disabled="disabledDelete(field)"/></td>--> <!-- </tr>--> <!-- </tbody>--> <!-- <tfoot>--> <!-- <tr>--> <!-- <td>--> <!-- <div class="row">--> <!-- <input type="button" @click="newfield" class="btn btn-info mt-3" id="addrow" value="Add New Field" />--> <!-- </div>--> <!-- </td>--> <!-- <td>--> <!-- <input type="submit" class="btn btn-info mt-3" value="Save Indent"/>--> <!-- </td>--> <!-- </tr>--> <!-- </tfoot>--> <!-- </table>--> <!-- </div>--> <!-- </div>--> <!-- </form>--> <!-- <div>{{auth}}</div>--> <!-- </div>--> <!--</template>--> <!--<script>--> <!-- export default {--> <!-- props:['user-id'],--> <!-- data() {--> <!-- return {--> <!-- categories: {},--> <!-- projects: {},--> <!-- fields: [],--> <!-- keywords: '',--> <!-- debit_sum:0,--> <!-- credit_sum:0,--> <!-- form:{--> <!-- voucher: 0,--> <!-- allDebit: 0,--> <!-- allCredit: 0,--> <!-- type1:0,--> <!-- type2:0,--> <!-- date: new Date().toISOString().slice(0,10),--> <!-- // date: new Date().toISOString().substr(0, 10),--> <!-- description:'',--> <!-- auth_id: 0,--> <!-- debit1: 0,--> <!-- credit1: 0,--> <!-- debit2: 0,--> <!-- credit2: 0,--> <!-- },--> <!-- };--> <!-- },--> <!-- created() {--> <!-- this.getCOAs();--> <!-- axios.get("/epc/api/transaction/project").then(res => (this.projects = res.data.data))--> <!-- .catch(error => (this.errors = error.response.data.errors));--> <!-- axios.get("/epc/api/transaction/voucher").then(res => (this.form.voucher = res.data))--> <!-- .catch(error => (this.errors = error.response.data.errors));--> <!-- },--> <!-- watch: {--> <!-- keywords(before, after){--> <!-- this.getCOAs();--> <!-- }--> <!-- },--> <!-- methods: {--> <!-- getCOAs(){--> <!-- axios.get("/epc/api/transaction/category", {params: {keywords: this.keywords}}).then(res => (this.categories = res.data.data))--> <!-- .catch(error => (this.errors = error.response.data.errors));--> <!-- },--> <!-- create() {--> <!-- axios--> <!-- .post("/epc/api/add_transactions",{--> <!-- form:this.form,--> <!-- fields: this.fields,--> <!-- }).then(function(response){--> <!-- window.location = response.data.redirect;--> <!-- }).catch(function (error) {--> <!-- console.log(error);--> <!-- });--> <!-- },--> <!-- newfield() {--> <!-- this.fields.push({--> <!-- debit: 0,--> <!-- credit: 0,--> <!-- type: 0,--> <!-- });--> <!-- },--> <!-- dataRemove(index) {--> <!-- Vue.delete(this.fields, index);--> <!-- },--> <!-- disabledDelete(field) {--> <!-- // if (field.debit != 0 || field.credit != 0) {--> <!-- // return true;--> <!-- // }--> <!-- },--> <!-- },--> <!-- computed: {--> <!-- // submitdisabled() {--> <!-- // if (this.form.allDebit == 0 && this.form.allCredit == 0) {--> <!-- // return true;--> <!-- // } else if (this.form.allDebit == this.form.allCredit) {--> <!-- // return false;--> <!-- // } else {--> <!-- // return false;--> <!-- // }--> <!-- // },--> <!-- // disabledDebit1() {--> <!-- // if (this.form.credit1 != 0) {--> <!-- // return true;--> <!-- // }--> <!-- // },--> <!-- // disabledCredit1() {--> <!-- // if (this.form.debit1 != 0) {--> <!-- // return true;--> <!-- // }--> <!-- // },--> <!-- // disabledDebit2() {--> <!-- // if (this.form.credit2 != 0) {--> <!-- // return true;--> <!-- // }--> <!-- // },--> <!-- // disabledCredit2() {--> <!-- // if (this.form.debit2 != 0) {--> <!-- // return true;--> <!-- // }--> <!-- // },--> <!-- // allDebits() {--> <!-- // this.debit_sum =parseFloat(this.form.debit1)+parseFloat(this.form.debit2);--> <!-- // return this.form.allDebit = (this.fields.reduce((acc, item) => acc + parseFloat(item.debit), 0))+ this.debit_sum;--> <!-- // },--> <!-- // allCredits() {--> <!-- // this.credit_sum=parseFloat(this.form.credit1)+parseFloat(this.form.credit2);--> <!-- // return this.form.allCredit = (this.fields.reduce((acc, item) => acc + parseFloat(item.credit), 0))+this.credit_sum;--> <!-- // },--> <!-- auth(){--> <!-- this.form.auth_id= this.userId;--> <!-- },--> <!-- },--> <!-- };--> <!--</script>-->
35,860
https://github.com/greck2908/dawnengine/blob/master/src/dawn/core/GameSession.h
Github Open Source
Open Source
MIT
2,019
dawnengine
greck2908
C
Code
235
672
/* * Dawn Engine * Written by David Avedissian (c) 2012-2019 (git@dga.dev) */ #pragma once #include "GameMode.h" #include "core/EventSystem.h" #include "scene/SceneManager.h" #include "net/NetInstance.h" #include "ui/UserInterface.h" namespace dw { struct DW_API GameSessionInfo { struct CreateLocalGame { String scene_name = "unknown"; }; struct CreateNetGame { String host = "localhost"; // host to bind to. usually 127.0.0.1. u16 port = 10000; u16 max_clients = 16; String scene_name = "unknown"; NetTransport transport = NetTransport::ReliableUDP; }; struct JoinNetGame { String host = "localhost"; u16 port = 10000; NetTransport transport = NetTransport::ReliableUDP; }; Variant<CreateLocalGame, CreateNetGame, JoinNetGame> start_info = CreateLocalGame{}; // Graphics settings. bool headless = false; // Other parameters. HashMap<String, String> params; }; class DW_API GameSession : public Object { public: DW_OBJECT(GameSession); GameSession(Context* ctx, const GameSessionInfo& gsi); virtual ~GameSession(); virtual void preUpdate(); virtual void update(float dt); virtual void postUpdate(); virtual void preRender(); virtual void render(float dt, float interpolation); virtual void postRender(); /// Access the current game mode. GameMode* gameMode() const; /// Access the user interface. UserInterface* ui() const; /// Access the scene graph. SceneGraph* sceneGraph() const; /// Access the scene manager. SceneManager* sceneManager() const; /// Access the event system for this game instance. EventSystem* eventSystem() const; /// Access the network instance. nullptr if networking is disabled. NetInstance* net() const; protected: GameSessionInfo gsi_; UniquePtr<EventSystem> event_system_; UniquePtr<UserInterface> ui_; UniquePtr<SceneGraph> scene_graph_; UniquePtr<SceneManager> scene_manager_; UniquePtr<NetInstance> net_instance_; /// Sets a new game mode. void setGameMode(SharedPtr<GameMode> game_mode); private: SharedPtr<GameMode> new_game_mode_; SharedPtr<GameMode> game_mode_; }; } // namespace dw
33,137
https://github.com/iAJTin/iXlsxWriter/blob/master/src/lib/iTin.Utilities/iTin.Utilities.Xlsx/iTin.Utilities.Xlsx.Design/Styles/Items/Cell/Content/DataType/DateTimeDataType.cs
Github Open Source
Open Source
MIT
2,021
iXlsxWriter
iAJTin
C#
Code
725
1,986
namespace iTin.Utilities.Xlsx.Design.Styles { using System; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Xml.Serialization; using Newtonsoft.Json; using iTin.Core; using iTin.Core.Helpers; using iTin.Core.Models.Design.Enums; /// <summary> /// A Specialization of <see cref="BaseDataType"/> class.<br/> /// Displays data field as datetime format. You can specify the output culture. /// </summary> public partial class DateTimeDataType : ICloneable { #region private constants [DebuggerBrowsable(DebuggerBrowsableState.Never)] private const KnownCulture DefaultLocale = KnownCulture.Current; [DebuggerBrowsable(DebuggerBrowsableState.Never)] private const KnownDateTimeFormat DefaultFormat = KnownDateTimeFormat.ShortDatePattern; #endregion #region private field members [DebuggerBrowsable(DebuggerBrowsableState.Never)] private KnownCulture _locale; [DebuggerBrowsable(DebuggerBrowsableState.Never)] private DateTimeError _error; [DebuggerBrowsable(DebuggerBrowsableState.Never)] private KnownDateTimeFormat _format; #endregion #region constructor/s #region [public] DateTimeDataType(): Initializes a new instance of this class /// <summary> /// Initializes a new instance of the <see cref="DateTimeDataType"/> class. /// </summary> public DateTimeDataType() { Locale = DefaultLocale; Format = DefaultFormat; } #endregion #endregion #region interfaces #region ICloneable #region explicit #region (object) ICloneable.Clone(): Creates a new object that is a copy of the current instance /// <inheritdoc /> /// <summary> /// Creates a new object that is a copy of the current instance. /// </summary> /// <returns> /// A new object that is a copy of this instance. /// </returns> object ICloneable.Clone() => Clone(); #endregion #endregion #endregion #endregion #region public readonly properties #region [public] (bool) ErrorSpecified: Gets a value that tells the serializer if the referenced item is to be included /// <summary> /// Gets a value that tells the serializer if the referenced item is to be included. /// </summary> /// <value> /// <b>true</b> if the serializer has to include the element; otherwise, <b>false</b>. /// </value> [XmlIgnore] [JsonIgnore] [Browsable(false)] [DebuggerBrowsable(DebuggerBrowsableState.Never)] public bool ErrorSpecified => !Error.IsDefault; #endregion #endregion #region public properties #region [public] (DateTimeError) Error: Gets or sets a reference that contains datetime data type error settings /// <summary> /// Gets or sets a reference that contains datetime data type error settings. /// </summary> /// <value> /// Datetime data type error settings /// </value> [XmlElement] [JsonProperty("error")] public DateTimeError Error { get => _error ?? (_error = new DateTimeError()); set => _error = value; } #endregion #region [public] (KnownDateTimeFormat) Format: Gets or sets preferred output date time format /// <summary> /// Gets or sets preferred output date time format. The default is <see cref="KnownDateTimeFormat.ShortDatePattern"/>. /// </summary> /// <value> /// One of the <see cref="KnownDateTimeFormat"/> values. /// </value> /// <exception cref="InvalidEnumArgumentException">The value specified is outside the range of valid values.</exception> [XmlAttribute] [JsonProperty("format")] [DefaultValue(DefaultFormat)] public KnownDateTimeFormat Format { get => _format; set { SentinelHelper.IsEnumValid(value); _format = value; } } #endregion #region [public] (KnownCulture) Locale: Gets or sets preferred culture /// <summary> /// Gets or sets preferred culture. The default is <see cref="KnownCulture.Current"/>. /// </summary> /// <value> /// Preferred culture. /// </value> [XmlAttribute] [JsonProperty("locale")] [DefaultValue(DefaultLocale)] public KnownCulture Locale { get => _locale; set { var isValidLocale = true; if (!value.Equals(KnownCulture.Current)) { var isValidCulture = IsValidCulture(value); if (!isValidCulture) { isValidLocale = false; } } _locale = isValidLocale ? value : DefaultLocale; } } #endregion #endregion #region public override properties #region [public] {overide} (bool) IsDefault: Gets a value indicating whether this instance is default /// <inheritdoc /> /// <summary> /// Gets a value indicating whether this instance is default. /// </summary> /// <value> /// <b>true</b> if this instance contains the default; otherwise, <b>false</b>. /// </value> public override bool IsDefault => base.IsDefault && Error.IsDefault && Format.Equals(DefaultFormat) && Locale.Equals(DefaultLocale); #endregion #endregion #region public new methods #region [public] {new} (DateTimeDataType) Clone(): Clones this instance /// <summary> /// Clones this instance. /// </summary> /// <returns>A new object that is a copy of this instance.</returns> public new DateTimeDataType Clone() { var datetimeCloned = (DateTimeDataType)MemberwiseClone(); datetimeCloned.Error = Error.Clone(); datetimeCloned.Properties = Properties.Clone(); return datetimeCloned; } #endregion #endregion #region public virtual methods #region [public] {virtual} (void) Combine(DateTimeDataType): Combines this instance with reference parameter /// <summary> /// Combines this instance with reference parameter. /// </summary> public virtual void Combine(DateTimeDataType reference) { if (reference == null) { return; } if (Locale.Equals(DefaultLocale)) { Locale = reference.Locale; } if (Format.Equals(DefaultFormat)) { Format = reference.Format; } Error.Combine(reference.Error); } #endregion #endregion #region private static methods #region [private] {static} (bool) IsValidCulture: Gets a value indicating whether specified culture is installed on this system /// <summary> /// Gets a value indicating whether specified culture is installed on this system. /// </summary> /// <param name="culture">Culture to check.</param> /// <returns> /// <b>true</b> if the specified culture is installed on the system; otherwise, <b>false</b>. /// </returns> private static bool IsValidCulture(KnownCulture culture) { var iw32C = CultureInfo.GetCultures(CultureTypes.InstalledWin32Cultures); return iw32C.Any(clt => clt.Name == culture.GetDescription()); } #endregion #endregion } }
38,930
https://github.com/lianwt115/qmqiu_sp/blob/master/src/main/kotlin/com/lwt/qmqiu_sps1/dao/IMChatRoomDao.kt
Github Open Source
Open Source
Apache-2.0
2,018
qmqiu_sp
lianwt115
Kotlin
Code
224
1,275
package com.lwt.qmqiu_sps1.dao import com.lwt.qmqiu_sps1.bean.BaseUser import com.lwt.qmqiu_sps1.bean.IMChatRoom import com.lwt.qmqiu_sps1.bean.LoginLog import com.lwt.qmqiu_sps1.myinterface.BaseDaoInterface import com.lwt.qmqiu_sps1.myinterface.BaseUserDaoInterface import com.lwt.qmqiu_sps1.myinterface.IMChatRoomDaoInterface import com.mongodb.client.result.DeleteResult import com.mongodb.client.result.UpdateResult import org.springframework.beans.factory.annotation.Autowired import org.springframework.data.mongodb.core.MongoTemplate import org.springframework.data.mongodb.core.query.Criteria import org.springframework.data.mongodb.core.query.Query import org.springframework.data.mongodb.core.query.Update import org.springframework.stereotype.Repository @Repository("imChatRoomDao") class IMChatRoomDao: BaseDaoInterface<IMChatRoom>,IMChatRoomDaoInterface<IMChatRoom> { private val MAP_PATH_LATITUDE = 0.006 private val MAP_PATH_LONGITUDE = 0.0025 private val RETURN_LIST_SIZE = 10 @Autowired private lateinit var mongoTemplate: MongoTemplate override fun getAll(key: String, value: Any?): List<IMChatRoom> { if (key == "" || value == null) return mongoTemplate.findAll(IMChatRoom::class.java) val query = Query(Criteria.where(key).`is`(value)) query.addCriteria(Criteria.where("status").`is`(true)) return getBackList(mongoTemplate.find(query,IMChatRoom::class.java)) } override fun getRoom(type: Int, latitude: Double, longitude: Double): List<IMChatRoom> { var query = Query(Criteria.where("roomType").`is`(type)) query.addCriteria(Criteria.where("status").`is`(true)) query.addCriteria(Criteria.where("latitude").gte(latitude-MAP_PATH_LATITUDE).lte(latitude+MAP_PATH_LATITUDE)) query.addCriteria(Criteria.where("longitude").gte(longitude-MAP_PATH_LONGITUDE).lte(longitude+MAP_PATH_LONGITUDE)) return getBackList(mongoTemplate.find(query,IMChatRoom::class.java)) } private fun getBackList(list:MutableList<IMChatRoom>):List<IMChatRoom>{ if (list.size >RETURN_LIST_SIZE){ list.shuffle() return list.subList(0,RETURN_LIST_SIZE) } return list } override fun getRoomOne(key: String, value: Any, latitude: Double, longitude: Double, check: Boolean): IMChatRoom? { var query = Query(Criteria.where(key).`is`(value)) query.addCriteria(Criteria.where("status").`is`(true)) if (check) { query.addCriteria(Criteria.where("latitude").gte(latitude-MAP_PATH_LATITUDE).lte(latitude+MAP_PATH_LATITUDE)) query.addCriteria(Criteria.where("longitude").gte(longitude-MAP_PATH_LONGITUDE).lte(longitude+MAP_PATH_LONGITUDE)) } return mongoTemplate.findOne(query,IMChatRoom::class.java) } override fun insert(imChatRoom: IMChatRoom) { return mongoTemplate.insert(imChatRoom) } override fun findByKey(key: String, value: Any): IMChatRoom? { val query = Query(Criteria.where(key).`is`(value)) return mongoTemplate.findOne(query,IMChatRoom::class.java) } override fun updata(roomNumber: String, data: HashMap<String, Any>): UpdateResult { val criteria = Criteria.where("roomNumber").`is`(roomNumber) val query = Query(criteria) var update :Update?=null data.forEach { key, value -> if (update === null) update = Update.update(key,value) else update!!.set(key,value) } return mongoTemplate.updateMulti(query, update!!, IMChatRoom::class.java) } override fun delete(_id: String): DeleteResult { val criteria = Criteria.where("_id").`is`(_id) val query = Query(criteria) return mongoTemplate.remove(query,IMChatRoom::class.java) } }
28,099
https://github.com/nirvanarsc/CompetitiveProgramming/blob/master/Java/leetcode/weekly_contests/weekly_137/P_1047.java
Github Open Source
Open Source
MIT
2,021
CompetitiveProgramming
nirvanarsc
Java
Code
63
157
package leetcode.weekly_contests.weekly_137; public class P_1047 { public String removeDuplicates(String s) { final int n = s.length(); final char[] res = new char[n]; int size = 0; for (int i = 0; i < n; i++) { if (size > 0 && res[size - 1] == s.charAt(i)) { size--; } else { res[size++] = s.charAt(i); } } return new String(res, 0, size); } }
19,316
https://github.com/git-the-cpan/CatalystX-AppBuilder/blob/master/lib/CatalystX/AppBuilder.pm
Github Open Source
Open Source
Artistic-1.0
null
CatalystX-AppBuilder
git-the-cpan
Perl
Code
1,330
3,175
package CatalystX::AppBuilder; use Moose; use namespace::clean -except => qw(meta); our $VERSION = '0.00011'; has appname => ( is => 'ro', isa => 'Str', required => 1, ); has appmeta => ( init_arg => undef, is => 'ro', isa => 'Moose::Meta::Class', lazy_build => 1 ); has debug => ( is => 'ro', isa => 'Bool', default => 0, ); has version => ( is => 'ro', isa => 'Str', required => 1, lazy_build => 1, ); has superclasses => ( is => 'ro', isa => 'Maybe[ArrayRef]', required => 1, lazy_build => 1, ); has config => ( is => 'ro', isa => 'HashRef', lazy_build => 1, ); has plugins => ( is => 'ro', isa => 'ArrayRef', lazy_build => 1, ); sub _build_version { '0.00001' } sub _build_superclasses { [ 'Catalyst' ] } sub _build_config { my $self = shift; my %config = ( name => $self->appname, ); return \%config; } sub _build_plugins { my $self = shift; my @plugins = qw(ConfigLoader); if ($self->debug) { unshift @plugins, '-Debug'; } return \@plugins; } sub BUILD { my $self = shift; my $appname = $self->appname; my $meta = Moose::Util::find_meta( $appname ); if (! $meta || ! $appname->isa('Catalyst') ) { if ($self->debug) { print STDERR "Defining $appname via " . (blessed $self) . "\n"; } $meta = Moose::Meta::Class->create( $appname => ( version => $self->version, superclasses => $self->superclasses ) ); if ($appname->isa('Catalyst')) { # Don't let the base class fool us! delete $appname->config->{home}; delete $appname->config->{root}; } # Fugly, I know, but we need to load Catalyst in the app's namespace # for many things to take effect. eval <<" EOCODE"; package $appname; use Catalyst; EOCODE die if $@; } return $meta; } sub bootstrap { my $self = shift; my $runsetup = shift; my $appclass = $self->appname; if (! $runsetup) { # newer catalyst now uses Catalyst::ScriptRunner. # run setup if we were explicitly asked for, or we were called from # within Catalyst::ScriptRunner my $i = 1; $runsetup = 1; while (my @caller = caller($i++)) { my $package = $caller[0]; my $sub = $caller[3]; # DO NOT run setup if we're being recursively called from # an inherited AppBuilder if ($package->isa('Class::MOP::Class')) { if ($sub =~ /superclasses$/) { $runsetup = 0; last; } } elsif ($package->isa('Catalyst::ScriptRunner')) { last; } elsif ($package->isa('Catalyst::Restarter')) { last; } } } if ($runsetup) { my @plugins; my %plugins; foreach my $plugin (@{ $self->plugins }) { if ($plugins{$plugin}++) { warn "$plugin appears multiple times in the plugin list! Ignoring..."; } else { push @plugins, $plugin; } } $appclass->config( $self->config ); $appclass->setup( @plugins ); } } sub inherited_path_to { my $self = shift; # XXX You have to have built the class my $meta = Moose::Util::find_meta($self->appname); my @inheritance; foreach my $class ($meta->linearized_isa) { next if ! $class->isa( 'Catalyst' ); next if $class eq 'Catalyst'; push @inheritance, $class; } my @paths = @_; return map { my $m = $_; $m =~ s/::/\//g; $m .= '.pm'; my $f = Path::Class::File->new($INC{$m})->parent; DESCENT: while ($f) { for my $stopper (qw(Makefile.PL Build.PL dist.ini minil.toml)) { if (-f $f->file($stopper)) { $f = $f->subdir(@paths)->stringify; last DESCENT; } } last if $f->stringify eq $f->parent->stringify; $f = $f->parent; } $f; } @inheritance; } sub app_path_to { my $self = shift; return $self->appname->path_to(@_)->stringify; } __PACKAGE__->meta->make_immutable(); 1; __END__ =head1 NAME CatalystX::AppBuilder - Build Your Application Instance Programatically =head1 SYNOPSIS # In MyApp.pm my $builder = CatalystX::AppBuilder->new( appname => 'MyApp', plugins => [ ... ], ) $builder->bootstrap(); =head1 DESCRIPTION WARNING: YMMV regarding this module. This module gives you a programatic interface to I<configuring> Catalyst applications. The main motivation to write this module is: to write reusable Catalyst appllications. For instance, if you build your MyApp::Base and you wanted to create a new application afterwards that is I<mostly> like MyApp::Base, but slightly tweaked. Perhaps you want to add or remove a plugin or two. Perhaps you want to tweak just a single parameter. Traditionally, your option then was to use catalyst.pl and create another scaffold, and copy/paste the necessary bits, and tweak what you need. After testing several approaches, it proved that the current Catalyst architecture (which is Moose based, but does not allow us to use Moose-ish initialization, since the Catalyst app instance does not materialize until dispatch time) did not allow the type of inheritance behavior we wanted, so we decided to create a builder module around Catalyst to overcome this. Therefore, if/when these obstacles (to us) are gone, this module may simply dissappear from CPAN. You've been warned. =head1 HOW TO USE =head2 DEFINING A CATALYST APP This module is NOT a "just-execute-this-command-and-you-get-catalyst-running" module. For the simple applications, please just follow what the Catalyst manual gives you. However, if you I<really> wanted to, you can define a simple Catalyst app like so: # in MyApp.pm use strict; use CatalystX::AppBuilder; my $builder = CatalystX::AppBuilder->new( debug => 1, # if you want appname => "MyApp", plugins => [ qw( Authentication Session # and others... ) ], config => { ... } ); $builder->bootstrap(); =head2 DEFINING YOUR CatalystX::AppBuilder SUBCLASS The originally intended approach to using this module is to create a subclass of CatalystX::AppBuilder and configure it to your own needs, and then keep reusing it. To build your own MyApp::Builder, you just need to subclass it: package MyApp::Builder; use Moose; extends 'CatalystX::AppBuilder'; Then you will be able to give it defaults to the various configuration parameters: override _build_config => sub { my $config = super(); # Get what CatalystX::AppBuilder gives you $config->{ SomeComponent } = { ... }; return $config; }; override _build_plugins => sub { my $plugins = super(); # Get what CatalystX::AppBuilder gives you push @$plugins, qw( Unicode Authentication Session Session::Store::File Session::State::Cookie ); return $plugins; }; Then you can simply do this instead of giving parameters to CatalystX::AppBuilder every time: # in MyApp.pm use MyApp::Builder; MyApp::Builder->new()->bootstrap(); =head2 EXTENDING A CATALYST APP USING CatalystX::AppBuilder Once you created your own MyApp::Builder, you can keep inheriting it to create custom Builders which in turn create more custom Catalyst applications: package MyAnotherApp::Builder; use Moose; extends 'MyApp::Builder'; override _build_superclasses => sub { return [ 'MyApp' ] } ... do your tweaking ... # in MyAnotherApp.pm use MyAnotherApp::Builder; MyAnotherApp::Builder->new()->bootstrap(); Voila, you just reused every inch of Catalyst app that you created via inheritance! =head2 INCLUDING EVERY PATH FROM YOUR INHERITANCE HIERARCHY Components like Catalyst::View::TT, which in turn uses Template Toolkit inside, allows you to include multiple directories to look for the template files. This can be used to recycle the templates that you used in a base application. CatalystX::AppBuilder gives you a couple of tools to easily include paths that are associated with all of the Catalyst applications that are inherited. For example, if you have MyApp::Base and MyApp::Extended, and MyApp::Extended is built using MyApp::Extended::Builder, you can do something like this: package MyApp::Extended::Builder; use Moose; extends 'CatalystX::AppBuilder'; override _build_superclasses => sub { return [ 'MyApp::Base' ] }; override _build_config => sub { my $self = shift; my $config = super(); $config->{'View::TT'}->{INCLUDE_PATH} = [ $self->inherited_path_to('root') ]; # Above is equivalent to # [ MyApp::Extended->path_to('root'), MyApp::Base->path_to('root') ] }; So now you can refer to some template, and it will first look under the first app, then the base app, thus allowing you to reuse the templates. =head1 ATTRIBUTES =head2 appname The module name of the Catalyst application. Required. =head2 appmeta The metaclass object of the Catalyst application. Users cannot set this. =head2 debug Boolean flag to enable debug output in the application =head2 version The version string to use (probably meaningless...) =head2 superclasses The list of superclasses of the Catalyst application. =head2 config The config hash to give to the Catalyst application. =head2 plugins The list of plugins to give to the Catalyst application. =head1 METHODS =head2 bootstrap($runsetup) Bootstraps the Catalyst app. =head2 inherited_path_to(@pathspec) Calls path_to() on all Catalyst applications in the inheritance tree. =head2 app_path_to(@pathspec); Calls path_to() on the curent Catalyst application. =head1 TODO Documentation. Samples. Tests. =head1 AUTHOR Daisuke Maki C<< <daisuke@endeworks.jp> >> =head1 LICENSE This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See http://www.perl.com/perl/misc/Artistic.html =cut
384
https://github.com/igiu1988/iOS13.4.1-Runtime-Headers/blob/master/PrivateFrameworks/ITMLKit.framework/IKCSSDeclarationInteger.h
Github Open Source
Open Source
MIT
2,020
iOS13.4.1-Runtime-Headers
igiu1988
Objective-C
Code
34
130
/* Generated by EzioChiu Image: /System/Library/PrivateFrameworks/ITMLKit.framework/ITMLKit */ @interface IKCSSDeclarationInteger : IKCSSDeclaration { long long _value; } @property long long value; - (id)description; - (id)initWithParseDeclaration:(id)arg1 info:(id)arg2; - (void)setValue:(long long)arg1; - (id)stringValue; - (long long)value; @end
45,705
https://github.com/cmprmsd/sway-netusage/blob/master/waybar-netusage.go
Github Open Source
Open Source
Unlicense
2,022
sway-netusage
cmprmsd
Go
Code
274
805
// Public domain. package main import ( "bytes" "flag" "fmt" "io/ioutil" "net" "regexp" "strconv" "strings" "time" "golang.org/x/net/nettest" ) var ( iface = flag.String("interface", "", "What interface to use") ) // stats fetches the cumulative rx/tx bytes for network interface // iface. func stats() (rx, tx uint64) { b, err := ioutil.ReadFile("/proc/net/dev") if err != nil { return 0, 0 } buff := bytes.NewBuffer(b) for l, err := buff.ReadString('\n'); err == nil; { l = strings.Trim(l, " \n") if !strings.HasPrefix(l, *iface) { l, err = buff.ReadString('\n') continue } re := regexp.MustCompile(" +") s := strings.Split(re.ReplaceAllString(l, " "), " ") rx, err := strconv.ParseUint(s[1], 10, 64) if err != nil { return 0, 0 } tx, err := strconv.ParseUint(s[9], 10, 64) if err != nil { return 0, 0 } return rx, tx } return 0, 0 } func getRoutedInterface() *net.Interface { val, _ := nettest.RoutedInterface("ip", net.FlagUp|net.FlagBroadcast) return val } // format converts a number of bytes in KiB or MiB. func format(counter, prevCounter uint64, window float64) string { if prevCounter == 0 { return "B" } r := float64(counter-prevCounter) / window if r < 1024 { return fmt.Sprintf("%.0f B", r) } if r < 1024*1024 { return fmt.Sprintf("%.0f KiB", r/1024) } return fmt.Sprintf("%.1f MiB", r/1024/1024) } func main() { flag.Parse() if *iface == "" { autoInterface := getRoutedInterface().Name fmt.Printf("Auto detected %s\n", autoInterface) *iface = autoInterface } prevRx, prevTx := uint64(0), uint64(0) prev := time.Now() for { time.Sleep(1 * time.Second) now := time.Now() window := now.Sub(prev).Seconds() prev = now rx, tx := stats() rxRate := format(rx, prevRx, window) txRate := format(tx, prevTx, window) fmt.Printf("%8s/s ↓ %8s/s ↑\n", rxRate, txRate) prevRx, prevTx = rx, tx } }
47,558
https://github.com/NoobTW/ui-kit/blob/master/src/components/buttons/secondary-icon-button/secondary-icon-button.spec.js
Github Open Source
Open Source
MIT
null
ui-kit
NoobTW
JavaScript
Code
352
1,192
import React from 'react'; import { shallow } from 'enzyme'; import { FilterIcon } from '../../icons'; import { SecondaryIconButton } from './secondary-icon-button'; const createTestProps = custom => ({ label: 'Accessible button', onClick: jest.fn(), icon: <FilterIcon />, // HoC isMouseOver: false, handleMouseOver: jest.fn(), handleMouseOut: jest.fn(), ...custom, }); describe('rendering', () => { let props; let wrapper; beforeEach(() => { props = createTestProps(); wrapper = shallow(<SecondaryIconButton {...props} />); }); it('outputs correct tree', () => { expect(wrapper).toMatchSnapshot(); }); it('should render a <AccessibleButton>', () => { expect(wrapper).toRender('AccessibleButton'); }); it('should render the icon', () => { expect(wrapper).toRender('FilterIcon'); }); it('renders an icon with black theme', () => { expect(wrapper.find('FilterIcon')).toHaveProp('theme', 'black'); }); describe('if mouse is over', () => { beforeEach(() => { props = createTestProps({ isMouseOver: true }); wrapper = shallow(<SecondaryIconButton {...props} />); }); it('renders an icon with green theme', () => { expect(wrapper.find('FilterIcon')).toHaveProp('theme', 'green'); }); }); describe('if disabled', () => { beforeEach(() => { props = createTestProps({ isDisabled: true }); wrapper = shallow(<SecondaryIconButton {...props} />); }); it('renders a <AccessibleButton> with disabled prop', () => { expect(wrapper.find('AccessibleButton')).toHaveProp('isDisabled', true); }); it('renders an icon with grey theme', () => { expect(wrapper.find('FilterIcon')).toHaveProp('theme', 'grey'); }); }); describe('with data-* props', () => { beforeEach(() => { props = createTestProps({ 'data-track-component': 'SecondaryIconButton', 'data-track-label': 'SecondaryIconButton', 'data-track-event': 'click', 'data-test': 'secondary-icon-button', }); wrapper = shallow(<SecondaryIconButton {...props} />); }); it('should apply given `data-track-component` to AccessibleButton', () => { expect(wrapper.find('AccessibleButton')).toHaveProp( 'buttonAttributes', expect.objectContaining({ 'data-track-component': 'SecondaryIconButton', }) ); }); it('should apply given `data-track-event` to AccessibleButton', () => { expect(wrapper.find('AccessibleButton')).toHaveProp( 'buttonAttributes', expect.objectContaining({ 'data-track-event': 'click', }) ); }); it('should apply given `data-track-label` to AccessibleButton', () => { expect(wrapper.find('AccessibleButton')).toHaveProp( 'buttonAttributes', expect.objectContaining({ 'data-track-label': 'SecondaryIconButton', }) ); }); it('should apply given `data-test` to AccessibleButton', () => { expect(wrapper.find('AccessibleButton')).toHaveProp( 'buttonAttributes', expect.objectContaining({ 'data-test': 'secondary-icon-button', }) ); }); }); describe('without data-* props', () => { beforeEach(() => { props = createTestProps(); wrapper = shallow(<SecondaryIconButton {...props} />); }); it('should apply default `data-track-component` to AccessibleButton', () => { expect(wrapper.find('AccessibleButton')).toHaveProp( 'buttonAttributes', expect.objectContaining({ 'data-track-component': 'SecondaryIconButton', }) ); }); }); }); describe('callbacks', () => { let wrapper; let props; describe('onClick', () => { beforeEach(() => { props = createTestProps(); wrapper = shallow(<SecondaryIconButton {...props} />); wrapper.find('AccessibleButton').prop('onClick')(); }); it('should invoke onClick', () => { expect(props.onClick).toHaveBeenCalledTimes(1); }); }); });
37,526
https://github.com/j5ik2o/scala-ddd-base-akka-http.g8/blob/master/src/main/g8/build.sbt
Github Open Source
Open Source
CC0-1.0
2,019
scala-ddd-base-akka-http.g8
j5ik2o
Scala
Code
531
2,301
import Dependencies._ import Utils._ import scala.concurrent.duration._ lazy val commonSettings = Seq( scalaVersion := "2.12.7", organization := "$organization$", version := "1.0.0-SNAPSHOT", libraryDependencies ++= Seq( beachape.enumeratum, beachape.enumeratumCirce, typelevel.catsCore, typelevel.catsFree, hashids.hashids, scalatest.scalatest % Test, j5ik2o.scalaTestPlusDb % Test, airframe.airframe, circe.circeCore, circe.circeGeneric, circe.circeParser, sisioh.baseunitsScala, akka.akkaStream, monix.monix ), scalafmtOnCompile in ThisBuild := true, scalafmtTestOnCompile in ThisBuild := true, parallelExecution in Test := false ) lazy val infrastructure = (project in file("infrastructure")) .settings(commonSettings).settings( name := "$name$-infrastructure" ) lazy val domain = (project in file("domain")) .settings(commonSettings).settings( name := "$name$-domain", libraryDependencies ++= Seq( j5ik2o.scalaDDDBaseCore ) ).dependsOn(infrastructure) val dbDriver = "com.mysql.jdbc.Driver" val dbName = "$name$" val dbUser = "$name$" val dbPassword = "passwd" val dbPort: Int = RandomPortSupport.temporaryServerPort() val dbUrl = s"jdbc:mysql://localhost:\$dbPort/\$dbName?useSSL=false" lazy val flyway = (project in file("tools/flyway")) .settings(commonSettings) .settings( libraryDependencies ++= Seq( mysql.mysqlConnectorJava ), parallelExecution in Test := false, wixMySQLVersion := com.wix.mysql.distribution.Version.v5_6_21, wixMySQLUserName := Some(dbUser), wixMySQLPassword := Some(dbPassword), wixMySQLSchemaName := dbName, wixMySQLPort := Some(dbPort), wixMySQLDownloadPath := Some(sys.env("HOME") + "/.wixMySQL/downloads"), wixMySQLTimeout := Some(2 minutes), flywayDriver := dbDriver, flywayUrl := dbUrl, flywayUser := dbUser, flywayPassword := dbPassword, flywaySchemas := Seq(dbName), flywayLocations := Seq( s"filesystem:\${baseDirectory.value}/src/test/resources/rdb-migration/" ), flywayMigrate := (flywayMigrate dependsOn wixMySQLStart).value ) .enablePlugins(FlywayPlugin) lazy val `use-case` = (project in file("use-case")) .settings(commonSettings).settings( name := "$name$-use-case", libraryDependencies ++= Seq( ) ).dependsOn(domain) lazy val interface = (project in file("interface")) .settings(commonSettings) .settings( name := "$name$-interface", // JDBCのドライバークラス名を指定します(必須) driverClassName in generator := dbDriver, // JDBCの接続URLを指定します(必須) jdbcUrl in generator := dbUrl, // JDBCの接続ユーザ名を指定します(必須) jdbcUser in generator := dbUser, // JDBCの接続ユーザのパスワードを指定します(必須) jdbcPassword in generator := dbPassword, // カラム型名をどのクラスにマッピングするかを決める関数を記述します(必須) propertyTypeNameMapper in generator := { case "INTEGER" | "INT" | "TINYINT" => "Int" case "BIGINT" => "Long" case "VARCHAR" => "String" case "BOOLEAN" | "BIT" => "Boolean" case "DATE" | "TIMESTAMP" | "DATETIME" => "java.time.ZonedDateTime" case "DECIMAL" => "BigDecimal" case "ENUM" => "String" }, tableNameFilter in generator := { tableName: String => (tableName.toUpperCase != "SCHEMA_VERSION") && (tableName .toUpperCase() != "FLYWAY_SCHEMA_HISTORY") && !tableName.toUpperCase .endsWith("ID_SEQUENCE_NUMBER") }, outputDirectoryMapper in generator := { case s if s.endsWith("Spec") => (sourceDirectory in Test).value case s => new java.io.File((scalaSource in Compile).value, "/$name$/interface/dao") }, // モデル名に対してどのテンプレートを利用するか指定できます。 templateNameMapper in generator := { case className if className.endsWith("Spec") => "template_spec.ftl" case _ => "template.ftl" }, generateAll in generator := Def .taskDyn { val ga = (generateAll in generator).value Def .task { (wixMySQLStop in flyway).value } .map(_ => ga) } .dependsOn(flywayMigrate in flyway) .value, compile in Compile := ((compile in Compile) dependsOn (generateAll in generator)).value, libraryDependencies ++= Seq( j5ik2o.scalaDDDBaseSlick, javax.rsApi, github.swaggerAkkaHttp, megard.akkaHttpCors, akka.akkaHttp, heikoseeberger.akkaHttpCirce, mysql.mysqlConnectorJava, slick.slick, slick.slickHikaricp, sisioh.baseunitsScala ) ) .dependsOn(`use-case`, flyway) .disablePlugins(WixMySQLPlugin) lazy val localMySQL = (project in file("tools/local-mysql")) .settings(commonSettings) .settings( name := "$name$-local-mysql", libraryDependencies ++= Seq( mysql.mysqlConnectorJava ), wixMySQLVersion := com.wix.mysql.distribution.Version.v5_6_21, wixMySQLUserName := Some(dbUser), wixMySQLPassword := Some(dbPassword), wixMySQLSchemaName := dbName, wixMySQLPort := Some(3306), wixMySQLDownloadPath := Some(sys.env("HOME") + "/.wixMySQL/downloads"), wixMySQLTimeout := Some((30 seconds) * sys.env.getOrElse("SBT_TEST_TIME_FACTOR", "1").toDouble), flywayDriver := dbDriver, flywayUrl := s"jdbc:mysql://localhost:3306/\$dbName?useSSL=false", flywayUser := dbUser, flywayPassword := dbPassword, flywaySchemas := Seq(dbName), flywayLocations := Seq( s"filesystem:\${(baseDirectory in flyway).value}/src/test/resources/rdb-migration/", s"filesystem:\${(baseDirectory in flyway).value}/src/test/resources/rdb-migration/test", s"filesystem:\${baseDirectory.value}/src/main/resources/dummy-migration" ), flywayPlaceholderReplacement := true, flywayPlaceholders := Map( "engineName" -> "InnoDB", "idSequenceNumberEngineName" -> "MyISAM" ), run := (flywayMigrate dependsOn wixMySQLStart).value ) .enablePlugins(FlywayPlugin) val boot = (project in file("boot")) .settings(commonSettings) .settings( name := "$name$-boot", libraryDependencies ++= Seq( "com.github.scopt" %% "scopt" % "3.7.0", "ch.qos.logback" % "logback-classic" % "1.2.3" ) ).dependsOn(interface) lazy val root = (project in file(".")).settings(commonSettings).settings( name := "$name$", version := "1.0.0-SNAPSHOT" ).aggregate(boot)
29,206
https://github.com/liujunsong68922/smalljava-v2/blob/master/smalljava-core/src/com/smalljava/core/classloader/JavaClassStaticInstanceMap.java
Github Open Source
Open Source
Apache-2.0
2,021
smalljava-v2
liujunsong68922
Java
Code
118
592
package com.smalljava.core.classloader; import java.util.HashMap; import com.smalljava.core.classloader.l2_class.vo.JavaClassStaticInstanceVO; import com.smalljava.core.common.logging.Logger; import com.smalljava.core.common.logging.LoggerFactory; /** * MEMO:这个类用来存放所有的JavaClassStaticInstance * MEMO:每个类只能有一个实例,暂时不考虑class的命名冲突问题, * MEMO:package关键词将在后续版本支持。 * @author liujunsong * */ public class JavaClassStaticInstanceMap { private static Logger logger = LoggerFactory.getLogger(JavaClassStaticInstanceMap.class); //对象存储定义,全局共享 private static HashMap<String,JavaClassStaticInstanceVO> staticInstanceMap = new HashMap<String,JavaClassStaticInstanceVO>(); /** * MEMO:构造函数 */ public JavaClassStaticInstanceMap() { } /** * get 方法 * @return */ public static HashMap<String, JavaClassStaticInstanceVO> getStaticInstanceMap() { return staticInstanceMap; } /** * MEMO:根据classname,从全局的存储表中检索静态实例 * MEMO:用来访问静态实例里面封装的静态变量表 * @param classname * @return */ public static JavaClassStaticInstanceVO getJavaClassStaticInstanceVO(String classname) { if (staticInstanceMap.containsKey(classname)) { return staticInstanceMap.get(classname); }else { return null; } } /** * MEMO:添加新对象进去 * @param vo */ public static void add(JavaClassStaticInstanceVO vo) { String classname = vo.getClassname(); if(! staticInstanceMap.containsKey(classname)) { staticInstanceMap.put(classname, vo); } logger.info("size:"+staticInstanceMap.size()); } }
33,063
https://github.com/nagineni/chromium-crosswalk/blob/master/chrome_frame/test/url_request_test.cc
Github Open Source
Open Source
BSD-3-Clause-No-Nuclear-License-2014, BSD-3-Clause
2,021
chromium-crosswalk
nagineni
C++
Code
717
3,771
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <atlbase.h> #include <atlcom.h> #include "base/bind.h" #include "base/bind_helpers.h" #include "chrome/common/automation_messages.h" #include "chrome_frame/test/chrome_frame_test_utils.h" #include "chrome_frame/test/test_server.h" #include "chrome_frame/test/test_with_web_server.h" #include "chrome_frame/urlmon_url_request.h" #include "chrome_frame/urlmon_url_request_private.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gmock_mutant.h" #include "testing/gtest/include/gtest/gtest.h" using testing::CreateFunctor; using chrome_frame_test::kChromeFrameLongNavigationTimeout; static void AppendToStream(IStream* s, void* buffer, ULONG cb) { ULONG bytes_written; LARGE_INTEGER current_pos; LARGE_INTEGER zero = {0}; // Remember current position. ASSERT_HRESULT_SUCCEEDED(s->Seek(zero, STREAM_SEEK_CUR, reinterpret_cast<ULARGE_INTEGER*>(&current_pos))); // Seek to the end. ASSERT_HRESULT_SUCCEEDED(s->Seek(zero, STREAM_SEEK_END, NULL)); ASSERT_HRESULT_SUCCEEDED(s->Write(buffer, cb, &bytes_written)); ASSERT_EQ(cb, bytes_written); // Seek to original position. ASSERT_HRESULT_SUCCEEDED(s->Seek(current_pos, STREAM_SEEK_SET, NULL)); } class MockUrlDelegate : public PluginUrlRequestDelegate { public: MOCK_METHOD9(OnResponseStarted, void(int request_id, const char* mime_type, const char* headers, int size, base::Time last_modified, const std::string& redirect_url, int redirect_status, const net::HostPortPair& socket_address, uint64 upload_size)); MOCK_METHOD2(OnReadComplete, void(int request_id, const std::string& data)); MOCK_METHOD2(OnResponseEnd, void(int request_id, const net::URLRequestStatus& status)); MOCK_METHOD4(OnCookiesRetrieved, void(bool success, const GURL& url, const std::string& cookie, int cookie_id)); void PostponeReadRequest(chrome_frame_test::TimedMsgLoop* loop, UrlmonUrlRequest* request, int bytes_to_read) { loop->PostTask(FROM_HERE, base::Bind(&MockUrlDelegate::RequestRead, base::Unretained(this), request, bytes_to_read)); } private: void RequestRead(UrlmonUrlRequest* request, int bytes_to_read) { request->Read(bytes_to_read); } }; // Simplest UrlmonUrlRequest. Retrieve a file from local web server. TEST(UrlmonUrlRequestTest, Simple1) { MockUrlDelegate mock; chrome_frame_test::TimedMsgLoop loop; testing::StrictMock<MockWebServer> mock_server(1337, ASCIIToWide(chrome_frame_test::GetLocalIPv4Address()), chrome_frame_test::GetTestDataFolder()); mock_server.ExpectAndServeAnyRequests(CFInvocation(CFInvocation::NONE)); CComObjectStackEx<UrlmonUrlRequest> request; request.AddRef(); request.Initialize(&mock, 1, // request_id WideToUTF8(mock_server.Resolve(L"chrome_frame_window_open.html")), "get", "", // referrer "", // extra request NULL, // upload data ResourceType::MAIN_FRAME, // resource type true, 0); // frame busting testing::InSequence s; EXPECT_CALL(mock, OnResponseStarted(1, testing::_, testing::_, testing::_, testing::_, testing::_, testing::_, testing::_, testing::_)) .Times(1) .WillOnce(testing::IgnoreResult(testing::InvokeWithoutArgs(CreateFunctor( &request, &UrlmonUrlRequest::Read, 512)))); EXPECT_CALL(mock, OnReadComplete(1, testing::Property(&std::string::size, testing::Gt(0u)))) .Times(testing::AtLeast(1)) .WillRepeatedly(testing::InvokeWithoutArgs(CreateFunctor(&mock, &MockUrlDelegate::PostponeReadRequest, &loop, &request, 64))); EXPECT_CALL(mock, OnResponseEnd(1, testing::_)) .Times(1) .WillOnce(QUIT_LOOP_SOON(loop, base::TimeDelta::FromSeconds(2))); request.Start(); loop.RunFor(kChromeFrameLongNavigationTimeout); request.Release(); } // Same as Simple1 except we use the HEAD verb to fetch only the headers // from the server. TEST(UrlmonUrlRequestTest, Head) { MockUrlDelegate mock; chrome_frame_test::TimedMsgLoop loop; // Use SimpleWebServer instead of the python server to support HEAD // requests. test_server::SimpleWebServer server(13337); test_server::SimpleResponse head_response("/head", ""); server.AddResponse(&head_response); CComObjectStackEx<UrlmonUrlRequest> request; request.AddRef(); request.Initialize(&mock, 1, // request_id base::StringPrintf("http://%s:13337/head", server.host().c_str()), "head", "", // referrer "", // extra request NULL, // upload data ResourceType::MAIN_FRAME, // resource type true, 0); // frame busting testing::InSequence s; EXPECT_CALL(mock, OnResponseStarted(1, testing::_, testing::_, testing::_, testing::_, testing::_, testing::_, testing::_, testing::_)) .Times(1) .WillOnce(testing::IgnoreResult(testing::InvokeWithoutArgs(CreateFunctor( &request, &UrlmonUrlRequest::Read, 512)))); // For HEAD requests we don't expect content reads. EXPECT_CALL(mock, OnReadComplete(1, testing::_)).Times(0); EXPECT_CALL(mock, OnResponseEnd(1, testing::_)) .Times(1) .WillOnce(QUIT_LOOP_SOON(loop, base::TimeDelta::FromSeconds(2))); request.Start(); loop.RunFor(kChromeFrameLongNavigationTimeout); request.Release(); } TEST(UrlmonUrlRequestTest, UnreachableUrl) { MockUrlDelegate mock; chrome_frame_test::TimedMsgLoop loop; CComObjectStackEx<UrlmonUrlRequest> request; testing::StrictMock<MockWebServer> mock_server(1337, ASCIIToWide(chrome_frame_test::GetLocalIPv4Address()), chrome_frame_test::GetTestDataFolder()); mock_server.ExpectAndServeAnyRequests(CFInvocation(CFInvocation::NONE)); GURL unreachable(WideToUTF8(mock_server.Resolve( L"non_existing.html"))); request.AddRef(); request.Initialize(&mock, 1, // request_id unreachable.spec(), "get", "", // referrer "", // extra request NULL, // upload data ResourceType::MAIN_FRAME, // resource type true, 0); // frame busting // Expect headers EXPECT_CALL(mock, OnResponseStarted(1, testing::_, testing::StartsWith("HTTP/1.1 404"), testing::_, testing::_, testing::_, testing::_, testing::_, testing::_)) .Times(1) .WillOnce(QUIT_LOOP_SOON(loop, base::TimeDelta::FromSeconds(2))); EXPECT_CALL(mock, OnResponseEnd(1, testing::Property( &net::URLRequestStatus::error, net::ERR_TUNNEL_CONNECTION_FAILED))) .Times(testing::AtMost(1)); request.Start(); loop.RunFor(kChromeFrameLongNavigationTimeout); request.Release(); } TEST(UrlmonUrlRequestTest, ZeroLengthResponse) { MockUrlDelegate mock; chrome_frame_test::TimedMsgLoop loop; testing::StrictMock<MockWebServer> mock_server(1337, ASCIIToWide(chrome_frame_test::GetLocalIPv4Address()), chrome_frame_test::GetTestDataFolder()); mock_server.ExpectAndServeAnyRequests(CFInvocation(CFInvocation::NONE)); CComObjectStackEx<UrlmonUrlRequest> request; request.AddRef(); request.Initialize(&mock, 1, // request_id WideToUTF8(mock_server.Resolve(L"empty.html")), "get", "", // referrer "", // extra request NULL, // upload data ResourceType::MAIN_FRAME, // resource type true, 0); // frame busting // Expect headers EXPECT_CALL(mock, OnResponseStarted(1, testing::_, testing::_, testing::_, testing::_, testing::_, testing::_, testing::_, testing::_)) .Times(1) .WillOnce(QUIT_LOOP(loop)); request.Start(); loop.RunFor(kChromeFrameLongNavigationTimeout); EXPECT_FALSE(loop.WasTimedOut()); // Should stay quiet, since we do not ask for anything for awhile. EXPECT_CALL(mock, OnResponseEnd(1, testing::_)).Times(0); loop.RunFor(base::TimeDelta::FromSeconds(3)); // Invoke read. Only now the response end ("server closed the connection") // is supposed to be delivered. EXPECT_CALL(mock, OnResponseEnd(1, testing::Property( &net::URLRequestStatus::is_success, true))).Times(1); request.Read(512); request.Release(); } ACTION_P4(ManagerRead, loop, mgr, request_id, bytes_to_read) { loop->PostTask(FROM_HERE, base::Bind(&UrlmonUrlRequestManager::ReadUrlRequest, base::Unretained(mgr), request_id, bytes_to_read)); } ACTION_P3(ManagerEndRequest, loop, mgr, request_id) { loop->PostTask(FROM_HERE, base::Bind(&UrlmonUrlRequestManager::EndUrlRequest, base::Unretained(mgr), request_id, net::URLRequestStatus())); } // Simplest test - retrieve file from local web server. TEST(UrlmonUrlRequestManagerTest, Simple1) { MockUrlDelegate mock; chrome_frame_test::TimedMsgLoop loop; testing::StrictMock<MockWebServer> mock_server(1337, ASCIIToWide(chrome_frame_test::GetLocalIPv4Address()), chrome_frame_test::GetTestDataFolder()); mock_server.ExpectAndServeAnyRequests(CFInvocation(CFInvocation::NONE)); scoped_ptr<UrlmonUrlRequestManager> mgr(new UrlmonUrlRequestManager()); mgr->set_delegate(&mock); AutomationURLRequest r1; r1.url = WideToUTF8(mock_server.Resolve(L"chrome_frame_window_open.html")); r1.method = "get"; r1.resource_type = 0; r1.load_flags = 0; EXPECT_CALL(mock, OnResponseStarted(1, testing::_, testing::_, testing::_, testing::_, testing::_, testing::_, testing::_, testing::_)) .Times(1) .WillOnce(ManagerRead(&loop, mgr.get(), 1, 512)); EXPECT_CALL(mock, OnReadComplete(1, testing::Property(&std::string::size, testing::Gt(0u)))) .Times(testing::AtLeast(1)) .WillRepeatedly(ManagerRead(&loop, mgr.get(), 1, 2)); EXPECT_CALL(mock, OnResponseEnd(1, testing::_)) .Times(1) .WillOnce(QUIT_LOOP_SOON(loop, base::TimeDelta::FromSeconds(2))); mgr->StartUrlRequest(1, r1); loop.RunFor(kChromeFrameLongNavigationTimeout); mgr.reset(); } TEST(UrlmonUrlRequestManagerTest, Abort1) { MockUrlDelegate mock; chrome_frame_test::TimedMsgLoop loop; testing::StrictMock<MockWebServer> mock_server(1337, ASCIIToWide(chrome_frame_test::GetLocalIPv4Address()), chrome_frame_test::GetTestDataFolder()); mock_server.ExpectAndServeAnyRequests(CFInvocation(CFInvocation::NONE)); scoped_ptr<UrlmonUrlRequestManager> mgr(new UrlmonUrlRequestManager()); mgr->set_delegate(&mock); AutomationURLRequest r1; r1.url = WideToUTF8(mock_server.Resolve(L"chrome_frame_window_open.html")); r1.method = "get"; r1.resource_type = 0; r1.load_flags = 0; EXPECT_CALL(mock, OnResponseStarted(1, testing::_, testing::_, testing::_, testing::_, testing::_, testing::_, testing::_, testing::_)) .Times(1) .WillOnce(testing::DoAll( ManagerEndRequest(&loop, mgr.get(), 1), QUIT_LOOP_SOON(loop, base::TimeDelta::FromSeconds(3)))); EXPECT_CALL(mock, OnReadComplete(1, testing::_)) .Times(0); EXPECT_CALL(mock, OnResponseEnd(1, testing::_)) .Times(0); mgr->StartUrlRequest(1, r1); loop.RunFor(kChromeFrameLongNavigationTimeout); mgr.reset(); }
11,097
https://github.com/ryanberger/BostonUniversityCoursework/blob/master/CS683_Mobile_App_Dev/PowerCostEstimator/src/edu/bu/powercostestimator/DatabaseAdapter.java
Github Open Source
Open Source
MIT
2,016
BostonUniversityCoursework
ryanberger
Java
Code
591
1,859
package edu.bu.powercostestimator; import java.util.ArrayList; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; /** * Adapter class for accessing PowerCostEstimator database. */ public class DatabaseAdapter { private static final DatabaseAdapter instance = new DatabaseAdapter(); // Database tables private static final String PROFILE_CREATE = "CREATE TABLE IF NOT EXISTS profile (_id INTEGER PRIMARY KEY AUTOINCREMENT, " + "profile_name TEXT UNIQUE NOT NULL, profile_price_per_kwh NUMERIC NOT NULL);"; private static final String DEVICE_CREATE = "CREATE TABLE IF NOT EXISTS device (_id INTEGER PRIMARY KEY AUTOINCREMENT, " + "device_name TEXT NOT NULL, device_power_full NUMERIC NOT NULL, device_time_full NUMERIC NOT NULL, " + "device_power_standby NUMERIC, device_time_standby NUMERIC);"; private static final String PROFILE_DEVICE_CREATE = "CREATE TABLE IF NOT EXISTS profile_device (profile_id INTEGER NOT NULL, " + "device_id INTEGER NOT NULL, FOREIGN KEY(profile_id) REFERENCES profile(_id) ON DELETE CASCADE, " + "FOREIGN KEY(device_id) REFERENCES device(_id) ON DELETE CASCADE, " + "PRIMARY KEY(profile_id, device_id));"; private Context context; private SQLiteDatabase _database; private DatabaseHelper _dbHelper; private DatabaseAdapter() {} public static DatabaseAdapter getInstance() { return instance; } public DatabaseAdapter open(Context context) throws SQLException { _dbHelper = new DatabaseHelper(context); _database = _dbHelper.getWritableDatabase(); return this; } /** * Open * Takes and keeps a reference of the passed context in order to access to the application assets and resources. * Accepts name and version for database. Useful for unit testing. * @param databaseName * @param databaseVersion */ public DatabaseAdapter open(String databaseName, int databaseVersion) throws SQLException { _dbHelper = new DatabaseHelper(context, databaseName, databaseVersion); _database = _dbHelper.getWritableDatabase(); return this; } public void close() { _dbHelper.close(); } public void createDatabase() { _database.execSQL(PROFILE_CREATE); _database.execSQL(DEVICE_CREATE); _database.execSQL(PROFILE_DEVICE_CREATE); } public void clearDatabase() { _database.execSQL("DROP TABLE profile;"); _database.execSQL("DROP TABLE device;"); _database.execSQL("DROP TABLE profile_device;"); } public void addProfile(String profileName, double costPerKwh) throws SQLException { _database.execSQL(String.format("INSERT INTO profile (profile_name, profile_price_per_kwh) VALUES('%1$s', %2$s);", profileName, costPerKwh)); } public void updateProfile(int profileId, String profileName, double costPerKwh) throws SQLException { _database.execSQL(String.format("UPDATE profile SET profile_name = '%1$s', profile_price_per_kwh = %2$s WHERE _id = '%3$s';", profileName, costPerKwh, profileId)); } public void deleteProfile(String profileName) { _database.execSQL(String.format("DELETE FROM profile WHERE profile_name = '%1$s';", profileName)); } public Cursor getProfiles() { return _database.rawQuery("SELECT * FROM profile;", null); } public ArrayList<String> getProfileNames() { return asStringArrayList(_database.rawQuery("SELECT profile_name FROM profile;", null)); } public Cursor getProfile(String profileName) { return _database.rawQuery(String.format("SELECT * FROM profile WHERE profile_name = '%1$s';", profileName), null); } public double getProfileCost(String profileName) { Cursor c = _database.rawQuery(String.format("SELECT profile_price_per_kwh FROM profile WHERE profile_name = '%1$s';", profileName), null); c.moveToFirst(); return c.getDouble(0); } public void addDeviceToProfile(String deviceName, double powerFull, double timeFull, double powerStandby, double timeStandby, String profileName) { // Add device ContentValues cv = new ContentValues(); cv.put("device_name", deviceName); cv.put("device_power_full", powerFull); cv.put("device_time_full", timeFull); cv.put("device_power_standby", powerStandby); cv.put("device_time_standby", timeStandby); long deviceId = _database.insert("device", null, cv); // Now, add device to profile _database.execSQL(String.format("INSERT INTO profile_device (profile_id, device_id) VALUES (%1$s, %2$s);", getProfileId(profileName), deviceId)); } public int getProfileId(String profileName) { return getId(_database.rawQuery(String.format("SELECT _id FROM profile WHERE profile_name='%1$s';", profileName), null)); } public Cursor getProfileDevices(String profileName) { return _database.rawQuery(String.format("SELECT * FROM device WHERE _id IN " + "(SELECT device_id FROM profile_device WHERE profile_id IN " + "(SELECT _id from profile WHERE profile_name = '%1$s'));", profileName), null); } public void deleteDevice(int deviceId) { _database.execSQL(String.format("DELETE FROM device WHERE _id = %1$s", deviceId)); } public void updateDevice(int deviceId, String deviceName, double powerFull, double timeFull, double powerStandby, double timeStandby) throws SQLException { _database.execSQL(String.format("UPDATE device SET device_name = '%1$s', device_power_full = %2$s, device_time_full = %3$s, device_power_standby = %4$s, " + "device_time_standby = %5$s WHERE _id = '%6$s';", deviceName, powerFull, timeFull, powerStandby, timeStandby, deviceId)); } private int getId(Cursor cursor) { cursor.moveToFirst(); return cursor.getInt(0); } private ArrayList<String> asStringArrayList(Cursor dbCursor) { ArrayList<String> outArrayList = new ArrayList<String>(); while (dbCursor.moveToNext()) { outArrayList.add(dbCursor.getString(dbCursor.getColumnIndex(dbCursor.getColumnName(0)))); } return outArrayList; } }
28,549
https://github.com/RichiCoder1/aws-cdk/blob/master/packages/@aws-cdk/aws-efs/lib/access-point.ts
Github Open Source
Open Source
Apache-2.0
2,022
aws-cdk
RichiCoder1
TypeScript
Code
911
2,118
import { ArnFormat, IResource, Resource, Stack } from '@aws-cdk/core'; import { Construct } from 'constructs'; import { IFileSystem } from './efs-file-system'; import { CfnAccessPoint } from './efs.generated'; /** * Represents an EFS AccessPoint */ export interface IAccessPoint extends IResource { /** * The ID of the AccessPoint * * @attribute */ readonly accessPointId: string; /** * The ARN of the AccessPoint * * @attribute */ readonly accessPointArn: string; /** * The EFS file system */ readonly fileSystem: IFileSystem; } /** * Permissions as POSIX ACL */ export interface Acl { /** * Specifies the POSIX user ID to apply to the RootDirectory. Accepts values from 0 to 2^32 (4294967295). */ readonly ownerUid: string; /** * Specifies the POSIX group ID to apply to the RootDirectory. Accepts values from 0 to 2^32 (4294967295). */ readonly ownerGid: string; /** * Specifies the POSIX permissions to apply to the RootDirectory, in the format of an octal number representing * the file's mode bits. */ readonly permissions: string; } /** * Represents the PosixUser */ export interface PosixUser { /** * The POSIX user ID used for all file system operations using this access point. */ readonly uid: string; /** * The POSIX group ID used for all file system operations using this access point. */ readonly gid: string; /** * Secondary POSIX group IDs used for all file system operations using this access point. * * @default - None */ readonly secondaryGids?: string[]; } /** * Options to create an AccessPoint */ export interface AccessPointOptions { /** * Specifies the POSIX IDs and permissions to apply when creating the access point's root directory. If the * root directory specified by `path` does not exist, EFS creates the root directory and applies the * permissions specified here. If the specified `path` does not exist, you must specify `createAcl`. * * @default - None. The directory specified by `path` must exist. */ readonly createAcl?: Acl; /** * Specifies the path on the EFS file system to expose as the root directory to NFS clients using the access point * to access the EFS file system * * @default '/' */ readonly path?: string; /** * The full POSIX identity, including the user ID, group ID, and any secondary group IDs, on the access point * that is used for all file system operations performed by NFS clients using the access point. * * Specify this to enforce a user identity using an access point. * * @see - [Enforcing a User Identity Using an Access Point](https://docs.aws.amazon.com/efs/latest/ug/efs-access-points.html) * * @default - user identity not enforced */ readonly posixUser?: PosixUser; } /** * Properties for the AccessPoint */ export interface AccessPointProps extends AccessPointOptions { /** * The efs filesystem */ readonly fileSystem: IFileSystem; } /** * Attributes that can be specified when importing an AccessPoint */ export interface AccessPointAttributes { /** * The ID of the AccessPoint * One of this, or {@link accessPointArn} is required * * @default - determined based on accessPointArn */ readonly accessPointId?: string; /** * The ARN of the AccessPoint * One of this, or {@link accessPointId} is required * * @default - determined based on accessPointId */ readonly accessPointArn?: string; /** * The EFS file system * * @default - no EFS file system */ readonly fileSystem?: IFileSystem; } abstract class AccessPointBase extends Resource implements IAccessPoint { /** * The ARN of the Access Point * @attribute */ public abstract readonly accessPointArn: string; /** * The ID of the Access Point * @attribute */ public abstract readonly accessPointId: string; /** * The file system of the access point */ public abstract readonly fileSystem: IFileSystem; } /** * Represents the AccessPoint */ export class AccessPoint extends AccessPointBase { /** * Import an existing Access Point by attributes */ public static fromAccessPointAttributes(scope: Construct, id: string, attrs: AccessPointAttributes): IAccessPoint { return new ImportedAccessPoint(scope, id, attrs); } /** * Import an existing Access Point by id */ public static fromAccessPointId(scope: Construct, id: string, accessPointId: string): IAccessPoint { return new ImportedAccessPoint(scope, id, { accessPointId: accessPointId, }); } /** * The ARN of the Access Point * @attribute */ public readonly accessPointArn: string; /** * The ID of the Access Point * @attribute */ public readonly accessPointId: string; /** * The file system of the access point */ public readonly fileSystem: IFileSystem; constructor(scope: Construct, id: string, props: AccessPointProps) { super(scope, id); const resource = new CfnAccessPoint(this, 'Resource', { fileSystemId: props.fileSystem.fileSystemId, rootDirectory: { creationInfo: props.createAcl ? { ownerGid: props.createAcl.ownerGid, ownerUid: props.createAcl.ownerUid, permissions: props.createAcl.permissions, } : undefined, path: props.path, }, posixUser: props.posixUser ? { uid: props.posixUser.uid, gid: props.posixUser.gid, secondaryGids: props.posixUser.secondaryGids, } : undefined, }); this.accessPointId = resource.ref; this.accessPointArn = Stack.of(scope).formatArn({ service: 'elasticfilesystem', resource: 'access-point', resourceName: this.accessPointId, }); this.fileSystem = props.fileSystem; } } class ImportedAccessPoint extends AccessPointBase { public readonly accessPointId: string; public readonly accessPointArn: string; private readonly _fileSystem?: IFileSystem; constructor(scope: Construct, id: string, attrs: AccessPointAttributes) { super(scope, id); if (!attrs.accessPointId) { if (!attrs.accessPointArn) { throw new Error('One of accessPointId or AccessPointArn is required!'); } this.accessPointArn = attrs.accessPointArn; let maybeApId = Stack.of(scope).splitArn(attrs.accessPointArn, ArnFormat.SLASH_RESOURCE_NAME).resourceName; if (!maybeApId) { throw new Error('ARN for AccessPoint must provide the resource name.'); } this.accessPointId = maybeApId; } else { if (attrs.accessPointArn) { throw new Error('Only one of accessPointId or AccessPointArn can be provided!'); } this.accessPointId = attrs.accessPointId; this.accessPointArn = Stack.of(scope).formatArn({ service: 'elasticfilesystem', resource: 'access-point', resourceName: attrs.accessPointId, }); } this._fileSystem = attrs.fileSystem; } public get fileSystem() { if (!this._fileSystem) { throw new Error("fileSystem is not available when 'fromAccessPointId()' is used. Use 'fromAccessPointAttributes()' instead"); } return this._fileSystem; } }
15,539
https://github.com/Micmaz/DTIControls/blob/master/DTIServerControl/DTIServerBaseDesigner.vb
Github Open Source
Open Source
MIT
null
DTIControls
Micmaz
Visual Basic
Code
172
624
Imports System Imports System.Collections.Generic Imports System.ComponentModel Imports System.Text Imports System.Web Imports System.Web.UI Imports System.Web.UI.WebControls Imports System.Web.SessionState Imports BaseClasses Imports DTIMiniControls Imports HighslideControls ''' <summary> ''' Design time support class. ''' </summary> ''' <remarks></remarks> <System.ComponentModel.Description("Design time support class."),ComponentModel.EditorBrowsable(ComponentModel.EditorBrowsableState.Never), ComponentModel.ToolboxItem(False)> _ Public Class DTIServerBaseDesigner Inherits System.Web.UI.Design.ControlDesigner Protected Overrides Function GetErrorDesignTimeHtml(ByVal e As Exception) As String 'Return error text in a placeholder 'Return Me.CreatePlaceHolderDesignTimeHtml("DTIServerControl: The control could not be loaded:<br>" & e.ToString() & "<br>" & e.StackTrace) Return "<div><div style='Position:relative;text-align:right;margin-bottom:-12px;margin-right:3px;font-size: 11px;font-weight:bold;'><span style='background-color: gray;color:white;'>" & CType(Component, DTIServerBase).GetType.FullName & "</span></div></div>" End Function Public Overrides Function GetDesignTimeHtml(ByVal regions As System.Web.UI.Design.DesignerRegionCollection) As String Return GetDesignTimeHtml() End Function Public Overrides Function GetDesignTimeHtml() As String Dim tmp As String = "" Dim tp As String = "" Try tp = CType(Component, DTIServerBase).GetType.FullName If CType(Component, DTIServerBase).getDesignTimeHtml Is Nothing Then tmp = MyBase.GetDesignTimeHtml Else tmp = CType(Component, DTIServerBase).getDesignTimeHtml End If tp = tp.Substring(tp.LastIndexOf(".") + 1) Catch ex As Exception tmp = ex.Message & ex.StackTrace End Try Return "<div><div style='Position:relative;text-align:right;margin-bottom:-12px;margin-right:3px;font-size: 11px;font-weight:bold;'><span style='background-color: gray;color:white;'>" & tp & "</span></div>" & tmp & "</div>" End Function End Class
42,851
https://github.com/Signiant/open-api/blob/master/go/porcelain/netlify_client.go
Github Open Source
Open Source
MIT, LicenseRef-scancode-unknown-license-reference
2,017
open-api
Signiant
Go
Code
122
413
package porcelain import ( "github.com/go-openapi/runtime" "github.com/go-openapi/strfmt" "github.com/netlify/open-api/go/plumbing" ) const DefaultSyncFileLimit = 7000 const DefaultConcurrentUploadLimit = 10 // Default netlify HTTP client. var Default = NewHTTPClient(nil) // NewHTTPClient creates a new netlify HTTP client. func NewHTTPClient(formats strfmt.Registry) *Netlify { n := plumbing.NewHTTPClient(formats) return &Netlify{ Netlify: n, syncFileLimit: DefaultSyncFileLimit, uploadLimit: DefaultConcurrentUploadLimit, } } // New creates a new netlify client func New(transport runtime.ClientTransport, formats strfmt.Registry) *Netlify { n := plumbing.New(transport, formats) return &Netlify{ Netlify: n, syncFileLimit: DefaultSyncFileLimit, uploadLimit: DefaultConcurrentUploadLimit, } } // Netlify is a client for netlify type Netlify struct { *plumbing.Netlify syncFileLimit int uploadLimit int } func (n *Netlify) SetSyncFileLimit(limit int) { n.syncFileLimit = limit } func (n *Netlify) SetConcurrentUploadLimit(limit int) { if limit > 0 { n.uploadLimit = limit } }
38,003
https://github.com/The-hated-one/chroma-react/blob/master/src/icons/lined/PhoneForwarded.tsx
Github Open Source
Open Source
MIT
2,021
chroma-react
The-hated-one
TSX
Code
30
79
import { PhoneForwarded as FeatherPhoneForwarded, Props } from 'react-feather'; import * as React from 'react'; export const PhoneForwarded: React.FC<Props> = ({ ...rootProps }) => ( <FeatherPhoneForwarded data-icon="phoneforwarded" {...rootProps} /> );
5,771
https://github.com/animesh/misccb/blob/master/rangt.py
Github Open Source
Open Source
BSL-1.0
2,015
misccb
animesh
Python
Code
10
18
print [(i + 2) % 3 for i in range(4)]
43,383
https://github.com/hadis2512/digitalk/blob/master/resources/views/super_admin/admins/add.blade.php
Github Open Source
Open Source
MIT
2,021
digitalk
hadis2512
Blade
Code
187
1,007
@section('head') @include('layouts.head') @show <body class="font-regular"> @section('loader') @include('layouts.loader') @show @section('admin_nav') @include('layouts.admin_nav') @show <div class="admin-body" style="margin-left: 260px;"> <div class="uk-container" style="padding-top: 20px;"> @section('account_bar') @include('layouts.account_bar') @show <div class="uk-width-1-2" style="margin-top: 30px;"> <div class="uk-card uk-card-default uk-card-body z-depth-15" style="border-radius: 6px;padding:30px 20px;"> <h5 class="grey-text-4 font-heavy" style="font-size: 1.8rem;">+ Add Admin</h5> <form action="{{ route('admins.store') }}" class="uk-grid" uk-grid method="post" enctype="multipart/form-data"> @csrf <div class="uk-inline uk-width-1-2"> <label class="uk-form-label" for="form-stacked-text">Username</label> <input class="uk-input uk-border-rounded font-light" placeholder="name" name="name" type="text" required> @error('name') <span class="accent-color font-light" style="top: 5px;font-size: 0.8rem;position:relative;">{{ $message }}</span> @enderror </div> <div class="uk-inline uk-width-1-2"> <label class="uk-form-label" for="form-stacked-text">Email</label> <input class="uk-input uk-border-rounded font-light" placeholder="email" name="email" type="email" required> @error('email') <span class="accent-color font-light" style="top: 5px;font-size: 0.8rem;position:relative;">{{ $message }}</span> @enderror </div> <div class="uk-inline uk-width-1-2"> <label class="uk-form-label" for="form-stacked-text">Password</label> <input class="uk-input uk-border-rounded font-light" placeholder="password" name="password" type="password" required> @error('password') <span class="accent-color font-light" style="top: 5px;font-size: 0.8rem;position:relative;">{{ $message }}</span> @enderror </div> <div class="uk-inline uk-width-1-2"> <label class="uk-form-label" for="form-stacked-text">Confirm Password</label> <input class="uk-input uk-border-rounded font-light" placeholder="retype password" name="confirm_password" type="password" required> @error('confirm_password') <span class="accent-color font-light" style="top: 5px;font-size: 0.8rem;position:relative;">{{ $message }}</span> @enderror </div> <div class="uk-inline uk-width-1-2"> <button type="submit" class="uk-button uk-button-default tm-button-default uk-icon uk-text-capitalize font-extrabold white-text uk-border-rounded bg-gradient" style="border: none;margin-bottom: 10px;"> Submit </button> </div> </form> </div> </div> </div> </div> @section('js') @include('layouts.js') @show <script> $('#datatable').dataTable(); // $('#form-stacked-select').select2(); </script> </body> </html>
40,741
https://github.com/dapangchi/laravel-vitality/blob/master/resources/views/frontend/account/profile/left.blade.php
Github Open Source
Open Source
MIT
2,016
laravel-vitality
dapangchi
Blade
Code
109
539
<div class="pm-overview c-overflow"> <div class="pmo-pic"> <div class="p-relative"> <a href=""> <img class="img-responsive" src="{{ asset('assets/frontend/img/temp/profile-pic-2.jpg') }}" alt=""> </a> <div class="dropdown pmop-message"> <a data-toggle="dropdown" href="" class="btn bgm-white btn-float z-depth-1"> <i class="zmdi zmdi-comment-text-alt"></i> </a> <div class="dropdown-menu"> <textarea placeholder="Write something..."></textarea> <button class="btn bgm-green btn-float"><i class="zmdi zmdi-mail-send"></i></button> </div> </div> <a href="" class="pmop-edit"> <i class="zmdi zmdi-camera"></i> <span class="hidden-xs">Update Profile Picture</span> </a> </div> <div class="pmo-stat"> <h2 class="m-0 c-white">1562</h2> Total Connections </div> </div> <div class="pmo-block pmo-contact hidden-xs"> <h2>Contact</h2> <ul> <li><i class="zmdi zmdi-phone"></i> {{ $currentCustomer->phone }}</li> <li><i class="zmdi zmdi-email"></i> {{ $currentCustomer->email }}</li> <li><i class="zmdi zmdi-facebook-box"></i> {{ $currentCustomer->facebook_name }}</li> <li><i class="zmdi zmdi-twitter"></i> {{ $currentCustomer->twitter_name }}</li> <li> <i class="zmdi zmdi-pin"></i> <address class="m-b-0 ng-binding"> {{ the_content($currentCustomer->address) }} </address> </li> </ul> </div> </div>
13,492
https://github.com/jeffmm/take_two/blob/master/v4-unit-tests/examples/example.cpp
Github Open Source
Open Source
MIT
null
take_two
jeffmm
C++
Code
22
62
#include <iostream> #include <take_two/take_two.hpp> int main() { std::cout << "7 + 4 = " << TakeTwo::Add(7, 4) << std::endl; return 0; }
10,639
https://github.com/Poketnans/capstone-q3/blob/master/app/controllers/clients_controllers/post_create.py
Github Open Source
Open Source
MIT
null
capstone-q3
Poketnans
Python
Code
139
544
from http import HTTPStatus from flask import jsonify from psycopg2.errors import UniqueViolation from sqlalchemy.exc import IntegrityError from sqlalchemy.orm import Session import werkzeug.exceptions from app.classes.app_with_db import current_app from app.models.clients_model import Client from app.decorators import verify_payload, validator from app.services import get_files, generate_image_default @validator(password="password", birthdate="birth_date", phone="phone", email="email") @verify_payload( fields_and_types={ 'name': str, 'email': str, 'password': str, 'birth_date': str, 'phone': str, "general_information": str, 'street': str, 'number': int, 'city': str }, optional=["general_information"] ) def post_create(payload): session: Session = current_app.db.session try: new_client = Client(**payload) files = get_files() if files: for file in files: new_client.image_bin = file.file_bin new_client.image_hash = file.filename new_client.image_mimetype = file.mimetype else: image = generate_image_default() new_client.image_mimetype = image.mimetype new_client.image_hash = image.filename new_client.image_bin = image.file_bin session.add(new_client) session.commit() except IntegrityError as error: if isinstance(error.orig, UniqueViolation): message = str(error.orig).split("Key")[1].split("=")[0] msg = {"msg": f"{message[2:-1]} already registered"} return jsonify(msg), HTTPStatus.CONFLICT except werkzeug.exceptions.UnsupportedMediaType as e: return e.description, HTTPStatus.UNSUPPORTED_MEDIA_TYPE return jsonify(new_client), HTTPStatus.CREATED
21,449
https://github.com/josh-barker/terraform-provider-azuredevops/blob/master/azuredevops/internal/service/taskagent/resource_agent_queue_test.go
Github Open Source
Open Source
MIT
2,022
terraform-provider-azuredevops
josh-barker
Go
Code
322
1,512
//go:build all || resource_agent_queue // +build all resource_agent_queue package taskagent import ( "context" "errors" "strconv" "testing" "github.com/golang/mock/gomock" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/microsoft/azure-devops-go-api/azuredevops/v6/taskagent" "github.com/microsoft/terraform-provider-azuredevops/azdosdkmocks" "github.com/microsoft/terraform-provider-azuredevops/azuredevops/internal/client" "github.com/microsoft/terraform-provider-azuredevops/azuredevops/internal/utils/converter" "github.com/stretchr/testify/require" ) var agentQueueProject = "project" var agentQueuePoolID = 100 var agentQueuePoolName = "foo-pool" var agentQueueID = 200 // If the pool lookup fails, an error should be reported func TestAgentQueue_DoesNotSwallowPoolLookupErrors(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() resourceData := generateResourceData(t, &agentQueueProject, &agentQueuePoolID, nil) agentClient, clients := generateMocks(ctrl) agentClient. EXPECT(). GetAgentPool(clients.Ctx, taskagent.GetAgentPoolArgs{ PoolId: &agentQueuePoolID, }). Return(nil, errors.New("GetAgentPool() Failed")) err := resourceAgentQueueCreate(resourceData, clients) require.NotNil(t, err) require.Contains(t, err.Error(), "GetAgentPool() Failed") } // If the queue create fails, an error should be reported func TestAgentQueue_DoesNotSwallowQueueCreateErrors(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() resourceData := generateResourceData(t, &agentQueueProject, &agentQueuePoolID, nil) agentClient, clients := generateMocks(ctrl) pool := &taskagent.TaskAgentPool{Id: &agentQueuePoolID, Name: &agentQueuePoolName} agentClient. EXPECT(). GetAgentPool(clients.Ctx, taskagent.GetAgentPoolArgs{ PoolId: &agentQueuePoolID, }). Return(pool, nil) agentClient. EXPECT(). AddAgentQueue(clients.Ctx, taskagent.AddAgentQueueArgs{ Queue: &taskagent.TaskAgentQueue{ Name: &agentQueuePoolName, Pool: &taskagent.TaskAgentPoolReference{ Id: &agentQueuePoolID, }, }, Project: &agentQueueProject, AuthorizePipelines: converter.Bool(false), }). Return(nil, errors.New("AddAgentQueue() Failed")) err := resourceAgentQueueCreate(resourceData, clients) require.NotNil(t, err) require.Contains(t, err.Error(), "AddAgentQueue() Failed") } // If a read fails, an error should be reported func TestAgentQueue_DoesNotSwallowReadErrors(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() resourceData := generateResourceData(t, &agentQueueProject, &agentQueuePoolID, &agentQueueID) agentClient, clients := generateMocks(ctrl) agentClient. EXPECT(). GetAgentQueue(clients.Ctx, taskagent.GetAgentQueueArgs{ QueueId: &agentQueueID, Project: &agentQueueProject, }). Return(nil, errors.New("GetAgentQueue() Failed")) err := resourceAgentQueueRead(resourceData, clients) require.NotNil(t, err) require.Contains(t, err.Error(), "GetAgentQueue() Failed") } func TestAgentQueue_DoesNotSwallowDeleteErrors(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() resourceData := generateResourceData(t, &agentQueueProject, &agentQueuePoolID, &agentQueueID) agentClient, clients := generateMocks(ctrl) agentClient. EXPECT(). DeleteAgentQueue(clients.Ctx, taskagent.DeleteAgentQueueArgs{ QueueId: &agentQueueID, Project: &agentQueueProject, }). Return(errors.New("DeleteAgentQueue() Failed")) err := resourceAgentQueueDelete(resourceData, clients) require.NotNil(t, err) require.Contains(t, err.Error(), "DeleteAgentQueue() Failed") } func generateResourceData(t *testing.T, project *string, poolID *int, resourceID *int) *schema.ResourceData { resourceData := schema.TestResourceDataRaw(t, ResourceAgentQueue().Schema, nil) if project != nil { resourceData.Set(projectID, *project) } if poolID != nil { resourceData.Set(agentPoolID, *poolID) } if resourceID != nil { resourceData.SetId(strconv.Itoa(*resourceID)) } return resourceData } func generateMocks(ctrl *gomock.Controller) (*azdosdkmocks.MockTaskagentClient, *client.AggregatedClient) { agentClient := azdosdkmocks.NewMockTaskagentClient(ctrl) return agentClient, &client.AggregatedClient{ TaskAgentClient: agentClient, Ctx: context.Background(), } }
27,548
https://github.com/maximilianotulian/frontend-freakcampus/blob/master/src/lib-vuex/specialities/getters.js
Github Open Source
Open Source
Apache-2.0
null
frontend-freakcampus
maximilianotulian
JavaScript
Code
11
30
export default { getSelectedSpeciality: state => { return state.specialities.selectedSpeciality } }
7,342
https://github.com/weiwei91/springboot/blob/master/springboot-webservice/src/main/java/com/example/springbootwebservice/config/client/WsClient.java
Github Open Source
Open Source
MIT
2,021
springboot
weiwei91
Java
Code
38
193
package com.example.springbootwebservice.config.client; import com.example.springbootwebservice.domain.GetCountryRequest; import com.example.springbootwebservice.domain.GetCountryResponse; import org.springframework.ws.client.core.support.WebServiceGatewaySupport; public class WsClient extends WebServiceGatewaySupport { public GetCountryResponse getCountry(String name) { GetCountryRequest request = new GetCountryRequest(); request.setName(name); //连接服务端 GetCountryResponse response = (GetCountryResponse) getWebServiceTemplate() .marshalSendAndReceive( "http://127.0.0.1:8080/ws/countries.wsdl", request); return response; } }
7,054
https://github.com/dram/metasfresh/blob/master/backend/de.metas.payment.esr/src/main/sql/postgresql/system/5477390_sys_gh2944_ESR_Wrong_Post_Bank_Acct_Message_Updated.sql
Github Open Source
Open Source
RSA-MD
2,022
metasfresh
dram
SQL
Code
30
125
-- 2017-11-16T18:35:43.463 -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator UPDATE AD_Message SET MsgText='Die Postbank-Konten dieses ESR-Importdatensatzes passen nicht zum Konto {0} der Import-Zeile.',Updated=TO_TIMESTAMP('2017-11-16 18:35:43','YYYY-MM-DD HH24:MI:SS'),UpdatedBy=100 WHERE AD_Message_ID=541112 ;
50,407
https://github.com/ale-cci/demo-oauth-openid/blob/master/backend/auth.py
Github Open Source
Open Source
MIT
null
demo-oauth-openid
ale-cci
Python
Code
98
332
from lib import flask_db import hashlib import string import random class AuthException(Exception): pass def _hash_matches(hashval, password): chunks = hashval.split('$') if len(chunks) != 3: raise AuthException('Wrong password format') _, salt, _ = hashval.split('$') return hash_password(password, salt) == hashval def _gen_salt(k=10): return ''.join(random.choices(string.printable[:36], k=k)) def hash_password(password, salt=None): if salt is None: salt = _gen_salt() salt_pass = (salt + password).encode('utf-8') hashed_pass = hashlib.sha256(salt_pass).hexdigest() return '$'.join(('sha256', salt, hashed_pass)) def check_password(email, password): match = flask_db.fetch_one( 'select id, passwd from users where email = %s', (email, ) ) if not match: raise AuthException('User not found') if not _hash_matches(match.passwd, password): raise AuthException('Wrong credentials') return match.id
45,507
https://github.com/jkreft-usgs/whitewater-gauges/blob/master/wsgi/wwosflaskapp.py
Github Open Source
Open Source
MIT
2,016
whitewater-gauges
jkreft-usgs
Python
Code
692
2,312
# WWOSFLASKAPP.PY # Main application code for WWOS # # Copyright Gordon Haff 2013 # Released under MIT License http://opensource.org/licenses/MIT import os import io import sys import string from flask import Flask from flask import request from flask import render_template import pymongo import json from bson import json_util from bson import objectid import re import urllib2 from time import time from time import sleep # Note order of coordinates is long/lat app = Flask(__name__) #add this so that flask doesn't swallow error messages app.config['PROPAGATE_EXCEPTIONS'] = True #a base urls that returns all the gauges in the collection (of course in the future we would implement paging) @app.route("/ws/gauges") def gauges(): #setup the connection to the gauges database conn = pymongo.Connection(os.environ['OPENSHIFT_MONGODB_DB_URL']) db = conn.gauges #query the DB for all the gaugepoints result = db.gaugepoints.find() #Now turn the results into valid JSON return str(json.dumps({'results':list(result)},default=json_util.default)) #find gauges within a lot/long bounding box passed in as query parameters (within?lat1=45.5&&lon1=-82&lat2=42&lon2=-84) @app.route("/ws/gauges/within") def within(): #setup the connection conn = pymongo.Connection(os.environ['OPENSHIFT_MONGODB_DB_URL']) db = conn.gauges #get the request parameters lat1 = float(request.args.get('lat1')) lon1 = float(request.args.get('lon1')) lat2 = float(request.args.get('lat2')) lon2 = float(request.args.get('lon2')) #use the request parameters in the query result = db.gaugepoints.find({"pos": {"$within": {"$box" : [[lon1,lat1],[lon2,lat2]]}}}) #turn the results into valid JSON return str(json.dumps(list(result),default=json_util.default)) # for manual updates of all states # This may not complete reliably if one or more requests to the Web service fail @app.route("/ws/gauges/update") def update(): statelist = ["al","ak","az","ar","ca","co","ct","de","dc","fl","ga","hi","id","il","in","ia","ks","ky","la","me","md","ma","mi","mn","ms","mo","mt","ne","nv","nh","nj","nm","ny","nc","nd","oh","ok","or","pa","ri","sc","sd","tn","tx","ut","vt","va","wa","wv","wi","wy","pr"] #setup the connection to the gauges database conn = pymongo.Connection(os.environ['OPENSHIFT_MONGODB_DB_URL']) db = conn.gauges # USGS requires a major filter. I'm using state name # Note that some filters seem to produce JSON responses that are too large to process for i in statelist: try: requesturl = "http://waterservices.usgs.gov/nwis/iv/?format=json,1.1&stateCd=" + i +"&parameterCd=00060,00065&siteType=ST" #code req = urllib2.Request(requesturl) opener = urllib2.build_opener() f = opener.open(req) entry = json.loads(f.read()) except: continue count = int (len(entry['value']['timeSeries']) - 1) while count >= 0: #We construct an array of the relevant values associated with a guage number #Note that gage height and discharge are in separate entries #Right here we're just filling out the "permanent" values #Gauge Number. This will be the dictionary index agaugenum = entry['value']['timeSeries'][count]['sourceInfo']['siteCode'][0]['value'] #Site Name #Going to assume that all the "permanent" attributes of a guage number are the #same across entries. # save the variable code variablecode = str(entry['value']['timeSeries'][count]['variable']['variableCode'][0]['variableID']) # save the variable value try: variablevalue = str(entry['value']['timeSeries'][count]['values'][0]['value'][0]['value']) except: variablevalue = "" # save the time stamp try: creationtime = str(entry['value']['timeSeries'][count]['values'][0]['value'][0]['dateTime']) except: creationtime = "" #Gage ht. ft. variableID 45807202 if variablecode == '45807202': db.gaugepoints.update({"_id":agaugenum},{"$set":{"height":variablevalue}}) #Discharge cfs variableID 45807197 if variablecode == '45807197': db.gaugepoints.update({"_id":agaugenum},{"$set":{"flow":variablevalue}}) #save creation time so that we can throw out any stale data db.gaugepoints.update({"_id":agaugenum},{"$set":{"timestamp":creationtime}}) count = count - 1 sleep(30) return "Update completed. " # for manual updates # Updates one state at a time # More relaible for remote script jobs @app.route("/ws/gauges/update/state") def updatestate(): statelist = ["al","ak","az","ar","ca","co","ct","de","dc","fl","ga","hi","id","il","in","ia","ks","ky","la","me","md","ma","mi","mn","ms","mo","mt","ne","nv","nh","nj","nm","ny","nc","nd","oh","ok","or","pa","ri","sc","sd","tn","tx","ut","vt","va","wa","wv","wi","wy","pr"] #setup the connection to the gauges database conn = pymongo.Connection(os.environ['OPENSHIFT_MONGODB_DB_URL']) db = conn.gauges i = request.args.get('st') requesturl = "http://waterservices.usgs.gov/nwis/iv/?format=json,1.1&stateCd=" + i +"&parameterCd=00060,00065&siteType=ST" #code req = urllib2.Request(requesturl) opener = urllib2.build_opener() f = opener.open(req) entry = json.loads(f.read()) count = int (len(entry['value']['timeSeries']) - 1) while count >= 0: #We construct an array of the relevant values associated with a guage number #Note that gage height and discharge are in separate entries #Right here we're just filling out the "permanent" values #Gauge Number. This will be the dictionary index agaugenum = entry['value']['timeSeries'][count]['sourceInfo']['siteCode'][0]['value'] #Site Name #Going to assume that all the "permanent" attributes of a guage number are the #same across entries. # save the variable code variablecode = str(entry['value']['timeSeries'][count]['variable']['variableCode'][0]['variableID']) # save the variable value try: variablevalue = str(entry['value']['timeSeries'][count]['values'][0]['value'][0]['value']) except: variablevalue = "" # save the time stamp try: creationtime = str(entry['value']['timeSeries'][count]['values'][0]['value'][0]['dateTime']) except: creationtime = "" #Gage ht. ft. variableID 45807202 if variablecode == '45807202': db.gaugepoints.update({"_id":agaugenum},{"$set":{"height":variablevalue}}) #Discharge cfs variableID 45807197 if variablecode == '45807197': db.gaugepoints.update({"_id":agaugenum},{"$set":{"flow":variablevalue}}) #save creation time so that we can throw out any stale data db.gaugepoints.update({"_id":agaugenum},{"$set":{"timestamp":creationtime}}) count = count - 1 updatemsg = "Update completed for state " + i + "\n" conn.close() return updatemsg @app.route("/") def test(): return render_template("index.html") #need this in a scalable app so that HAProxy thinks the app is up @app.route("/test") def blah(): return "hello world" if __name__ == "__main__": app.run()
21,771
https://github.com/SkyMcl/spring-framework-main/blob/master/spring-my-test/src/main/java/com/mclgyh/spring/annotition/MyAnnotition.java
Github Open Source
Open Source
Apache-2.0
2,021
spring-framework-main
SkyMcl
Java
Code
63
253
package com.mclgyh.spring.annotition; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Configuration; import org.springframework.stereotype.Component; import java.util.Map; /** * @Author: 牟春雷 * @Description: * @Date: 17:22 2021/7/29 * @Modified By: **/ public class MyAnnotition { public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); context.register(AnnotationTest.class); context.refresh(); Map<String, Object> beansWithAnnotation = context.getBeansWithAnnotation(CustomAnnotation.class); Object next = beansWithAnnotation.values().iterator().next(); CustomAnnotation annotation = next.getClass().getAnnotation(CustomAnnotation.class); String value = annotation.value(); System.out.println("value = "+value); } }
22,995
https://github.com/nhatminhship/shipthongminh/blob/master/routes/web.php
Github Open Source
Open Source
MIT
2,017
shipthongminh
nhatminhship
PHP
Code
615
3,855
<?php /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('/', 'HomePageController@homePage'); Route::get('/ho-tro/', 'HomePageController@homePage'); Auth::routes(); Route::get('/home', 'HomeController@index'); Route::get('/addon/template1', 'Customer\AddonController@get_template1'); Route::post('/cart/action', 'Customer\AddonController@executeAction'); Route::get('/san-pham-da-luu', 'Customer\ProductFavoriteController@indexs'); #region quan ly gio hang //Route::get('/cart/add', 'Customer\AddonController@addCart'); Route::post('/cart/add', 'Customer\AddonController@addCart'); Route::get('/gio-hang', 'Customer\CartController@showCart'); Route::get('/dat-coc', 'Customer\CartController@showDeposit'); Route::get('/dat-coc-thanh-cong', 'Customer\CartController@depositSuccess'); Route::post('/cart/quantity', 'Customer\CartController@updateQuantity'); Route::post('/cart/shop/service', 'Customer\CartController@updateService'); Route::post('/cart/item/comment', 'Customer\CartController@actionUpdate'); Route::post('/gio-hang/hanh-dong', 'Customer\CartController@action'); Route::delete('/cart/item', 'Customer\CartController@deleteItem'); Route::delete('/cart/shop', 'Customer\CartController@deleteShop'); Route::post('/dat-coc', 'Customer\CartController@depositOrder'); #endregion #region -- Mua hang -- Route::get('order_buying', 'OrderBuyingController@indexs'); Route::get('/order_buying/get_orders_data', 'OrderBuyingController@getOrdersData'); Route::post('/order_buying/set_crane_staff', 'OrderBuyingController@setCraneStaff'); #endregion #region quan ly nhan vien Route::get('/user', 'UserController@getUsers'); Route::get('/user/detail/{id}', 'UserController@detailUser'); Route::get('/nhan-vien/{id}', 'Customer\UserController@detail'); Route::post('/nhan-vien/dien-thoai', 'Customer\UserController@add_user_phone'); Route::put('/nhan-vien/dien-thoai', 'Customer\UserController@delete_user_phone'); Route::get('/nhan-vien/sua/{id}', 'Customer\UserController@get_user'); Route::post('/nhan-vien/sua/{id}', 'Customer\UserController@update_user'); Route::get('/user/edit/{id}', 'UserController@getUser'); Route::post('/user/edit/{id}', 'UserController@updateUser'); Route::post('/user/phone', 'UserController@addUserPhone'); Route::put('/user/phone', 'UserController@deleteUserPhone'); Route::get('/user/original_site', 'UserController@listUserOriginalSite'); Route::post('/user/original_site', 'UserController@addUserOriginalSite'); Route::put('/user/original_site/delete', 'UserController@removeUserOriginalSite'); #endregion #region quan ly dia chi nhan hang Route::post('/user/address', 'Customer\UserAddressController@addNewUserAddress'); Route::put('/user/address/delete', 'Customer\UserAddressController@deleteUserAddress'); Route::put('/user/address/default', 'Customer\UserAddressController@setDefaultUserAddress'); #endregion #region -- quet ma vach -- Route::get('/scan', 'ScanController@indexs'); Route::get('/scan/statistic', 'ScanController@statistic'); Route::post('/scan/action', 'ScanController@action'); #endregion #region -- kien hang -- Route::get('/packages', 'PackageController@indexs'); Route::get('/package', 'PackageController@index'); Route::post('/package/action', 'PackageController@action'); Route::get('/package/{code}', 'PackageController@detail'); #endregion #region quan ly don hang Route::get('/order', 'OrderController@orders'); Route::get('/order/get_orders_data', 'OrderController@getOrdersData'); Route::get('/order/{id}', 'OrderController@order'); Route::get('/order/detail/{id}', 'OrderController@order'); Route::post('/order/{id}/freight_bill', 'OrderController@insertFreightBill'); Route::put('/order/{id}/freight_bill', 'OrderController@removeFreightBill'); Route::post('/order/{id}/original_bill', 'OrderController@insertOriginalBill'); Route::put('/order/{id}/original_bill', 'OrderController@removeOriginalBill'); Route::post('/order/{id}/action', 'OrderController@action'); #endregion #region comment Route::post('/comment', 'CommentController@action'); #endregion #region he thong Route::get('/setting', 'SystemController@getList'); Route::post('/setting', 'SystemController@update'); Route::get('/setting/roles', 'SystemController@roles'); Route::get('/setting/role/{id}', 'SystemController@roleDetail'); Route::post('/setting/role/update/{id}', 'SystemController@updateRole'); Route::post('/setting/role', 'SystemController@addRole'); Route::post('/setting/role/permission', 'SystemController@savePermission'); Route::post('/setting/role/user', 'SystemController@updateUserRole'); Route::put('/setting/role/delete', 'SystemController@deleteRole'); //======== Warehouse ========== Route::get('/warehouses', 'WarehouseController@render'); Route::post('/warehouse', 'WarehouseController@insert'); Route::put('/warehouse/delete', 'WarehouseController@delete'); Route::get('/warehouses_manually', 'WarehouseController@render_manually'); Route::post('/warehouses_manually', 'WarehouseController@insert_manually'); Route::put('/warehouses_manually/delete', 'WarehouseController@delete_manually'); #endregion Route::get('hosivan', 'HoSiVanController@index'); #region -- giao dich -- Route::get('transaction/statistic', 'UserTransactionController@statisticTransaction'); Route::get('transactions', 'UserTransactionController@getTransactions'); Route::get('transaction/adjustment', 'UserTransactionController@renderTransactionAdjustment'); Route::post('transaction/adjustment', 'UserTransactionController@createTransactionAdjustment'); #endregion #region chuc nang nhap/xuat kho cua giang Route::get('warehouse','ExportWarehouseController@index'); Route::post('actionWarehouse', 'ExportWarehouseController@actionWarehouse'); #endregion Route::get('/404', 'OtherController@renderPageNotFound'); Route::get('/403', 'OtherController@renderPageNotPermission'); Route::get('/vue', 'OtherController@renderExampleVue'); //================ CUSTOMER ============== #region -- giao dich -- Route::get('giao-dich', 'Customer\UserTransactionController@getTransactions'); #endregion #region -- don hang -- Route::get('/don-hang', 'Customer\OrderController@orders'); Route::get('/don-hang/{id}', 'Customer\OrderController@order'); Route::post('/don-hang/{id}/hanh-dong', 'Customer\OrderController@action'); #endregion #region -- thong bao -- Route::get('/thong-bao', 'Customer\NotificationController@indexs'); #endregion #region -- bai viet -- Route::get('/taxonomies', 'TaxonomyController@indexs'); Route::get('/taxonomy', 'TaxonomyController@createTaxonomy'); Route::get('/posts', 'PostController@indexs'); Route::get('/post', 'PostController@createPost'); Route::get('/post/{id}', 'PostController@createPost'); Route::get('/post/preview/{id}', 'PostController@previewPost'); Route::post('/post/action', 'PostController@action'); #endregion #region -- ho tro -- Route::get('/ho-tro/danh-muc/{id}', 'Support\TaxonomyController@indexs'); Route::get('/ho-tro/{id}', 'Support\PostController@index'); #endregion Route::get('/tinh-phi', 'PreviewFeeController@index'); Route::get('/calculator_fee', 'PreviewFeeController@calculatorFee'); Route::get('/manager_addon_link_error', 'SystemController@managerAddonLinkError'); Route::post('/set_done_link_error', 'SystemController@setDoneLinkError'); Route::get('/statistic/users', 'StatisticController@users'); #region --thông báo cho khách hàng-- Route::get('/thong-bao','Customer\CustomerNotificationController@index'); Route::get('/change-type-notification','Customer\CustomerNotificationController@changeTypeNotification'); // send ajax // send code ajax Route::get('/view-notification','Customer\CustomerNotificationController@changeStatus'); Route::get('/view-notification-crane','NotificationController@changeStatus'); #endregion --end thong báo cho khách hàng-- #region --danh sách khiếu nại -- Route::get('/tao-khieu-nai/{order_id}','Customer\ComplaintServiceController@index'); Route::get('/danh-sach-khieu-nai','Customer\ComplaintServiceController@listComplaint'); #endregion --danh sách khiếu nại-- #region -- router tạo khiếu nại người bán-- Route::post('/create-complaint','Customer\ComplaintServiceController@createComplaint'); #region --chi tiết khiếu nại-- Route::get('/chi-tiet-khieu-nai/{complaint_id}','Customer\ComplaintServiceController@complaintDetail'); #endregion --chi tiết khiếu nại-- #region danh sach khieu nai tren trang quan trị Route::get('/complaint','ComplaintServiceController@index'); #region chi tiet khieu nại trên đơn Route::get('/complaint-detail/{complaint_id}','ComplaintServiceController@complaintDetail'); #region --thông báo dành cho quản trị viên-- Route::get('/notification','NotificationController@index'); #endregion --kết thúc thông báo cho quản trị viên-- #region --send sms-- Route::get('/send-sms','SendSmsController@index'); Route::post('/send-sms-2','SendSmsController@ondex'); Route::post('/gui-tin-nhan','SendSmsController@sendSms'); #endregion Route::get('/home/statistic', 'HomeController@homeStatistic'); Route::get('/package-weight','PackageWeightController@index'); Route::post('/save-package-weight','PackageWeightController@packageWeight'); Route::get('/send-email','SendMailerController@sendEmailToCustomer'); #region --thay thay đối trạng thái của đơn hàng và thời gian cập nh-ật- Route::post('/change-status-order','Customer\OrderController@changeOrderStatus'); #endregion #region --san luong van chuyen-- Route::get('/san-luong-van-chuyen','ReportController@index'); #endregion --ket thuc san luong van chuyen-- Route::get('iframe_random', 'SystemController@iframe_random'); #region --Thống kê doanh số khi click nút tìm kiếm-- Route::get('/san-luong-van-chuyen-dieu-kien','ReportController@reportCondition'); #endregion --kết thúc thống kê doanh số tìm kiếm-- #region -- chuc nang yeu cau giao hang -- Route::get('/DeliveryManage', 'DeliveryManageController@listView'); Route::get('/DeliveryManage/Create', 'DeliveryManageController@createView'); Route::post('/BillManage/Create', 'BillManageController@create'); Route::get('/BillManage/Detail/{id}', 'BillManageController@detailView'); Route::get('/BillManage', 'BillManageController@listView'); Route::post('/BillManage/UpdateFee', 'BillManageController@updateFee'); Route::get('/BillManage/Print/{id}', 'BillManageController@printBill'); #endregion #region --xuat excel tai chinh-- Route::get('/export-excel-finance','ExportExcelFinaceController@exportExcelOrderFee'); #endregion --ket thuc xuat excel tai chinh -- #region --xuat excel cho ke toan-- Route::get('/export-excel-accounting','AccountingReportController@exportExcelAccounting'); #endregion --xuat excel cho ke toan-- #region --xuất excel tài chính khách nợ-- Route::get('/accouting_finance','AccountingFinanceControlCustomerController@index'); #endregion --kết thúc xuất excel theo từng khách-- Route::post('/remove-package','PackageController@removePackage'); Route::post('/update_package_weight','PackageController@updatePackageWeight'); Route::get('/SystemRunCheck', 'SystemRunCheckController@index'); Route::get('/SystemRunCheck/ProblemTypeHtml', 'SystemRunCheckController@problemTypeHtml'); Route::get('/PaidStaffSaleValue', 'PaidStaffSaleValueController@index'); Route::post('/PaidStaffSaleValue/Setting', 'PaidStaffSaleValueController@setting'); Route::post('/user/SetupSaleBuying', 'UserController@setupSaleValue'); # Redesign Customer template Route::get('/home', 'OniHomeController@index'); Route::get('/gio-hang', 'OniDev\CartController@showCart'); Route::post('/gio-hang/hanh-dong', 'OniDev\CartController@action'); Route::get('/dat-coc', 'OniDev\CartController@showDeposit'); Route::post('/dat-coc', 'OniDev\CartController@depositOrder'); Route::get('/dat-coc-thanh-cong', 'OniDev\CartController@depositSuccess'); Route::get('/don-hang', 'OniDev\OrderController@orders'); Route::get('/don-hang/{id}', 'OniDev\OrderController@order'); Route::post('/don-hang/{id}/action', 'OniDev\OrderController@action'); Route::get('/san-pham-da-luu', 'OniDev\ProductFavoriteController@indexs'); Route::get('/nhan-vien/{id}', 'OniDev\UserController@detail'); Route::post('/nhan-vien/dien-thoai', 'OniDev\UserController@add_user_phone'); Route::put('/nhan-vien/dien-thoai', 'OniDev\UserController@delete_user_phone'); Route::get('/nhan-vien/sua/{id}', 'OniDev\UserController@get_user'); Route::post('/nhan-vien/sua/{id}', 'OniDev\UserController@update_user'); Route::get('giao-dich', 'OniDev\UserTransactionController@getTransactions');
13,893