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/pythonitalia/pycon/blob/master/frontend/src/helpers/olark.ts
Github Open Source
Open Source
MIT
2,023
pycon
pythonitalia
TypeScript
Code
258
625
/* eslint-disable @typescript-eslint/ban-ts-comment */ import { USER_INFO_CACHE } from "~/components/profile/hooks"; export const updateOlarkFields = (newData: any = null) => { // @ts-ignore if (typeof window.olark === "undefined") { return; } if (newData) { // If we have new data from GraphQL // update our local cache // this allows us to send to Olark the user name and email // and since we don't always fetch the user data // we need to store it temporally so we can restore it if needed // In the future this data might be used for other stuff, like showing "Hi X" window.localStorage.setItem( USER_INFO_CACHE, JSON.stringify({ email: newData.email, fullName: newData.fullName, name: newData.name, id: newData.id, }), ); } // Empty object just so we can assume those props always exist // and we can force the json const defaultUser = { email: null, fullName: null, name: null, id: null, }; let user; try { user = newData === null ? JSON.parse(window.localStorage.getItem(USER_INFO_CACHE)) : newData; } catch (e) { console.log("Unable to restore user cache", e); } if (!user) { // if we can't restore the user somehow, or it is invalid from JSON or whatever // set a default empty user user = defaultUser; } // If we have something, replace the data // if some information is missing, the one from previous session might be used if (user.email) { // @ts-ignore window.olark("api.visitor.updateEmailAddress", { emailAddress: user.email, }); } if (user.fullName || user.name) { // @ts-ignore window.olark("api.visitor.updateFullName", { fullName: user.fullName || user.name, }); } if (user.id) { // @ts-ignore window.olark("api.visitor.updateCustomFields", { userId: user.id, }); } };
34,753
https://github.com/sopiehalimah/shopiee/blob/master/resources/views/content/checkout/checkout1data.blade.php
Github Open Source
Open Source
MIT
null
shopiee
sopiehalimah
PHP
Code
285
1,407
@extends('layout.app') @section('content') <div id="all"> <div id="content"> <div class="container"> <div class="col-md-12"> <ul class="breadcrumb"> <li><a href="#">Home</a> </li> <li>Checkout - Address</li> </ul> </div> <div class="col-md-9" id="checkout"> <div class="box"> <form method="post" action="{{url('/checkout/address/update')}}" enctype="multipart/form-data"> {!! csrf_field() !!} <input type="hidden" name="id" value="{{ $data->id }}"> <input type="hidden" name="_token" value="{{ csrf_token() }}"> <h1>Checkout</h1> <ul class="nav nav-pills nav-justified"> <li class="active"><a href="#"><i class="fa fa-map-marker"></i><br>Address</a> </li> <li class="disabled"><a href="#"><i class="fa fa-truck"></i><br>Delivery Method</a> </li> <li class="disabled"><a href="#"><i class="fa fa-money"></i><br>Payment Method</a> </li> <li class="disabled"><a href="#"><i class="fa fa-eye"></i><br>Order Review</a> </li> </ul> <div class="content"> <div class="row"> <div class="col-sm-6"> <div class="form-group"> <label for="firstname">Name</label> <input type="text" name="name" value="{{$data->name}}" class="form-control" id="firstname" required> </div> </div> <div class="col-sm-6"> <div class="form-group"> <label for="state">State</label> <select class="form-control" value="{{$data->state}}" name="state" id="state" required> <option>klk</option> </select> </div> </div> </div> <!-- /.row --> <div class="row"> <div class="col-sm-6"> <div class="form-group"> <label for="email">Email</label> <input type="text" name="email" value="{{$data->email}}" class="form-control" id="email" required> </div> </div> <div class="col-sm-6"> <div class="form-group"> <label for="country">Country</label> <select class="form-control" name="country" value="{{$data->country}}" id="country" required> <option>klk</option> </select> </div> </div> <div class="col-sm-6"> <div class="form-group"> <label for="phone">Telephone</label> <input type="text" name="telp" value="{{$data->telp}}" class="form-control" id="phone" required> </div> </div> <div class="col-sm-6"> <div class="form-group"> <label for="street">Address</label> <textarea type="text" name="address" class="form-control" id="street" required>{{$data->address}}</textarea> </div> </div> </div> <!-- /.row --> </div> <div class="box-footer"> <div class="pull-left"> <a href="basket.html" class="btn btn-default"><i class="fa fa-chevron-left"></i>Back to basket</a> </div> <div class="pull-right"> <button type="submit" class="btn btn-primary">Continue to Delivery Method<i class="fa fa-chevron-right"></i> </button> </div> </div> </form> </div> <!-- /.box --> </div> <!-- /.col-md-9 --> <div class="col-md-3"> <div class="box" id="order-summary"> <div class="box-header"> <h3>Order summary</h3> </div> <p class="text-muted">Shipping and additional costs are calculated based on the values you have entered.</p> <div class="table-responsive"> <table class="table"> <tbody> <tr> <td>Order subtotal</td> <th>$446.00</th> </tr> <tr> <td>Shipping and handling</td> <th>$10.00</th> </tr> <tr> <td>Tax</td> <th>$0.00</th> </tr> <tr class="total"> <td>Total</td> <th>$456.00</th> </tr> </tbody> </table> </div> </div> </div> <!-- /.col-md-3 --> </div> <!-- /.container --> </div> <!-- /#content --> @endsection
50,166
https://github.com/jostarlink/sblog.net/blob/master/sBlog.Net.MetaData/MetaData/DatabaseSetupModelMetaData.cs
Github Open Source
Open Source
BSD-3-Clause
2,021
sblog.net
jostarlink
C#
Code
28
89
using System.ComponentModel; using System.ComponentModel.DataAnnotations; namespace sBlog.Net.MetaData.MetaData { public class DatabaseSetupModelMetaData { [Required(ErrorMessage = "Connction string is required")] [DisplayName("Connection String")] public object ConnectionString { get; set; } } }
4,531
https://github.com/ZoePorta/entregas-hab/blob/master/frontend/hackamusic/src/components/FooterCustom.vue
Github Open Source
Open Source
MIT
null
entregas-hab
ZoePorta
Vue
Code
25
93
<template> <div> <p class="footer">Zoe 2020</p> </div> </template> <script> export default { name: "FooterCustom", }; </script> <style scoped> p.footer { padding: 2rem; font-size: 0.75rem; } </style>
24,749
https://github.com/pedroqm/FOrder/blob/master/app/Resources/views/mesa/modificar_mesa.html.twig
Github Open Source
Open Source
MIT
null
FOrder
pedroqm
Twig
Code
38
110
{% extends '::index.html.twig' %} {% block title %}Modificar mesa {% endblock %} {% block content %} <h1 class="well">Modificar datos de mesa</h1> {{ form(formulario) }} <a href="{{ path('mesa_listar') }}" class="btn btn-info">Volver al listado de mesa </a> {% endblock %}
22,644
https://github.com/JuniorNunes15/PyMove/blob/master/pymove/utils/datetime.py
Github Open Source
Open Source
MIT
2,022
PyMove
JuniorNunes15
Python
Code
1,973
6,049
""" Datetime operations. date_to_str, str_to_datetime, datetime_to_str, datetime_to_min, min_to_datetime, to_day_of_week_int, working_day, now_str, deltatime_str, timestamp_to_millis, millis_to_timestamp, time_to_str, str_to_time, elapsed_time_dt, diff_time, create_time_slot_in_minute, generate_time_statistics, threshold_time_statistics """ from __future__ import annotations from datetime import datetime import holidays from pandas import DataFrame, Timestamp from pymove.utils.constants import ( COUNT, DATETIME, LOCAL_LABEL, MAX, MEAN, MIN, PREV_LOCAL, STD, SUM, THRESHOLD, TIME_SLOT, TIME_TO_PREV, ) def date_to_str(dt: datetime) -> str: """ Get date, in string format, from timestamp. Parameters ---------- dt : datetime Represents a date Returns ------- str Represents the date in string format Example ------- >>> from datetime import datatime >>> from pymove.utils.datetime import date_to_str >>> time_now = datetime.now() >>> print(time_now) '2021-04-29 11:01:29.909340' >>> print(type(time_now)) '<class 'datetime.datetime'>' >>> print(date_to_str(time_now), type(time_now)) '2021-04-29 <class 'str'>' """ return dt.strftime('%Y-%m-%d') def str_to_datetime(dt_str: str) -> datetime: """ Converts a datetime in string format to datetime format. Parameters ---------- dt_str : str Represents a datetime in string format, "%Y-%m-%d" or "%Y-%m-%d %H:%M:%S" Returns ------- datetime Represents a datetime in datetime format Example ------- >>> from pymove.utils.datetime import str_to_datetime >>> time_1 = '2020-06-29' >>> time_2 = '2020-06-29 12:45:59' >>> print(type(time_1), type(time_2)) '<class 'str'> <class 'str'>' >>> print( str_to_datetime(time_1), type(str_to_datetime(time_1))) '2020-06-29 00:00:00 <class 'datetime.datetime'>' >>> print(str_to_datetime(time_2), type(str_to_datetime(time_2))) '2020-06-29 12:45:59 <class 'datetime.datetime'>' """ if len(dt_str) == 10: return datetime.strptime(dt_str, '%Y-%m-%d') else: return datetime.strptime(dt_str, '%Y-%m-%d %H:%M:%S') def datetime_to_str(dt: datetime) -> str: """ Converts a date in datetime format to string format. Parameters ---------- dt : datetime Represents a datetime in datetime format. Returns ------- str Represents a datetime in string format "%Y-%m-%d %H:%M:%S". Example: ------- >>> from pymove.utils.datetime import datetime_to_str >>> from datetime import datetime >>> time_now = datetime.now() >>> print(time_now) '2021-04-29 14:15:29.708113' >>> print(type(time_now)) '<class 'datetime.datetime'>' >>> print(datetime_to_str(time_now), type(datetime_to_str(time_now))) '2021-04-29 14:15:29 <class 'str' >' """ return dt.strftime('%Y-%m-%d %H:%M:%S') def datetime_to_min(dt: datetime) -> int: """ Converts a datetime to an int representation in minutes. To do the reverse use: min_to_datetime. Parameters ---------- dt : datetime Represents a datetime in datetime format Returns ------- int Represents minutes from Example ------- >>> from pymove.utils.datetime import datetime_to_min >>> from datetime import datetime >>> time_now = datetime.now() >>> print(type(datetime_to_min(time_now))) '<class 'int'>' >>> datetime_to_min(time_now) '26996497' """ # get an integer time slot from a datetime return int( (dt - dt.utcfromtimestamp(0)).total_seconds() / 60 ) def min_to_datetime(minutes: int) -> datetime: """ Converts an int representation in minutes to a datetime. To do the reverse use: datetime_to_min. Parameters ---------- minutes : int Represents minutes Returns ------- datetime Represents minutes in datetime format Example ------- >>> from pymove.utils.datetime import min_to_datetime >>> print(min_to_datetime(26996497), type(min_to_datetime(26996497))) '2021-04-30 13:37:00 <class 'datetime.datetime'>' """ return datetime.utcfromtimestamp(minutes * 60) def to_day_of_week_int(dt: datetime) -> int: """ Get day of week of a date. Monday == 0...Sunday == 6. Parameters ---------- dt : datetime Represents a datetime in datetime format. Returns ------- int Represents day of week. Example ------- >>> from pymove.utils.datetime import str_to_datetime >>> monday = str_to_datetime('2021-05-3 12:00:01') >>> friday = str_to_datetime('2021-05-7 12:00:01') >>> print(to_day_of_week_int(monday), type(to_day_of_week_int(monday))) '0 <class 'int'>' >>> print(to_day_of_week_int(friday), type(to_day_of_week_int(friday))) '4 <class 'int'>' """ return dt.weekday() def working_day( dt: str | datetime, country: str = 'BR', state: str | None = None ) -> bool: """ Indices if a day specified by the user is a working day. Parameters ---------- dt : str or datetime Specifies the day the user wants to know if it is a business day. country : str Indicates country to check for vacation days, by default 'BR' state: str Indicates state to check for vacation days, by default None Returns ------- boolean if true, means that the day informed by the user is a working day. if false, means that the day is not a working day. Examples -------- >>> from pymove.utils.datetime import str_to_datetime >>> independence_day = str_to_datetime('2021-09-7 12:00:01') # Holiday in Brazil >>> next_day = str_to_datetime('2021-09-8 12:00:01') # Not a Holiday in Brazil >>> print(working_day(independence_day, 'BR')) False >>> print(type(working_day(independence_day, 'BR'))) <class 'bool'> >>> print(working_day(next_day, 'BR')) True >>> print(type(working_day(next_day, 'BR'))) '<class 'bool'>' References ---------- Countries and States names available in https://pypi.org/project/holidays/ """ result = True if isinstance(dt, str): dt = str_to_datetime(dt) if isinstance(dt, datetime): dt = datetime(dt.year, dt.month, dt.day) if dt in holidays.CountryHoliday(country=country, prov=None, state=state): result = False else: dow = to_day_of_week_int(dt) # 5 == Saturday, 6 == Sunday if dow == 5 or dow == 6: result = False return result def now_str() -> str: """ Get datetime of now. Returns ------- str Represents a date Examples -------- >>> from pymove.utils.datetime import now_str >>> now_str() '2019-09-02 13:54:16' """ return datetime_to_str(datetime.now()) def deltatime_str(deltatime_seconds: float) -> str: """ Convert time in a format appropriate of time. Parameters ---------- deltatime_seconds : float Represents the elapsed time in seconds Returns ------- time_str : str Represents time in a format hh:mm:ss Examples -------- >>> from pymove.utils.datetime import deltatime_str >>> deltatime_str(1082.7180936336517) '18m:02.718s' Notes ----- Output example if more than 24 hours: 25:33:57 https://stackoverflow.com/questions/3620943/measuring-elapsed-time-with-the-time-module """ hours, rem = divmod(deltatime_seconds, 3600) minutes, seconds = divmod(rem, 60) if hours: return f'{int(hours):0>2}h:{int(minutes):0>2}m:{seconds:05.2f}s' elif minutes: return f'{int(minutes):0>2}m:{seconds:05.2f}s' else: return f'{seconds:05.2f}s' def timestamp_to_millis(timestamp: str) -> int: """ Converts a local datetime to a POSIX timestamp in milliseconds (like in Java). Parameters ---------- timestamp : str Represents a date Returns ------- int Represents millisecond results Examples -------- >>> from pymove.utils.datetime import timestamp_to_millis >>> timestamp_to_millis('2015-12-12 08:00:00.123000') 1449907200123 (UTC) """ return Timestamp(timestamp).value // 1000000 def millis_to_timestamp(milliseconds: float) -> Timestamp: """ Converts milliseconds to timestamp. Parameters ---------- milliseconds : int Represents millisecond. Returns ------- Timestamp Represents the date corresponding. Examples -------- >>> from pymove.utils.datetime import millis_to_timestamp >>> millis_to_timestamp(1449907200123) '2015-12-12 08:00:00.123000' """ return Timestamp(milliseconds, unit='ms') def time_to_str(time: Timestamp) -> str: """ Get time, in string format, from timestamp. Parameters ---------- time : Timestamp Represents a time Returns ------- str Represents the time in string format Examples -------- >>> from pymove.utils.datetime import time_to_str >>> time_to_str("2015-12-12 08:00:00.123000") '08:00:00' """ return time.strftime('%H:%M:%S') def str_to_time(dt_str: str) -> datetime: """ Converts a time in string format "%H:%M:%S" to datetime format. Parameters ---------- dt_str : str Represents a time in string format Returns ------- datetime Represents a time in datetime format Examples -------- >>> from pymove.utils.datetime import str_to_time >>> str_to_time("08:00:00") datetime(1900, 1, 1, 8, 0) """ return datetime.strptime(dt_str, '%H:%M:%S') def elapsed_time_dt(start_time: datetime) -> int: """ Computes the elapsed time from a specific start time. Parameters ---------- start_time : datetime Specifies the start time of the time range to be computed Returns ------- int Represents the time elapsed from the start time to the current time (when the function was called). Examples -------- >>> from datetime import datetime >>> from pymove.utils.datetime import str_to_datetime >>> start_time_1 = datetime(2020, 6, 29, 0, 0) >>> start_time_2 = str_to_datetime('2020-06-29 12:45:59') >>> print(elapsed_time_dt(start_time_1)) 26411808666 >>> print(elapsed_time_dt(start_time_2)) 26365849667 """ return diff_time(start_time, datetime.now()) def diff_time(start_time: datetime, end_time: datetime) -> int: """ Computes the elapsed time from the start time to the end time specified by the user. Parameters ---------- start_time : datetime Specifies the start time of the time range to be computed end_time : datetime Specifies the start time of the time range to be computed Returns ------- int Represents the time elapsed from the start time to the current time (when the function was called). Examples -------- >>> from datetime import datetime >>> from pymove.utils.datetime import str_to_datetime >>> time_now = datetime.now() >>> start_time_1 = datetime(2020, 6, 29, 0, 0) >>> start_time_2 = str_to_datetime('2020-06-29 12:45:59') >>> print(diff_time(start_time_1, time_now)) 26411808665 >>> print(diff_time(start_time_2, time_now)) 26365849665 """ return int((end_time - start_time).total_seconds() * 1000) def create_time_slot_in_minute( data: DataFrame, slot_interval: int = 15, initial_slot: int = 0, label_datetime: str = DATETIME, label_time_slot: str = TIME_SLOT, inplace: bool = False ) -> DataFrame | None: """ Partitions the time in slot windows. Parameters ---------- data : DataFrame dataframe with datetime column slot_interval : int, optional size of the slot window in minutes, by default 5 initial_slot : int, optional initial window time, by default 0 label_datetime : str, optional name of the datetime column, by default DATETIME label_time_slot : str, optional name of the time slot column, by default TIME_SLOT inplace : boolean, optional wether the operation will be done in the original dataframe, by default False Returns ------- DataFrame data with converted time slots or None Examples -------- >>> from pymove.utils.datetime import create_time_slot_in_minute >>> from pymove import datetime >>> data lat lon datetime id 0 39.984094 116.319236 2008-10-23 05:44:05 1 1 39.984198 116.319322 2008-10-23 05:56:06 1 2 39.984224 116.319402 2008-10-23 05:56:11 1 3 39.984224 116.319402 2008-10-23 06:10:15 1 >>> datetime.create_time_slot_in_minute(data, inplace=False) lat lon datetime id time_slot 0 39.984094 116.319236 2008-10-23 05:44:05 1 22 1 39.984198 116.319322 2008-10-23 05:56:06 1 23 2 39.984224 116.319402 2008-10-23 05:56:11 1 23 3 39.984224 116.319402 2008-10-23 06:10:15 1 24 """ if data.dtypes[label_datetime] != 'datetime64[ns]': raise ValueError(f'{label_datetime} colum must be of type datetime') if not inplace: data = data.copy() minute_day = data[label_datetime].dt.hour * 60 + data[label_datetime].dt.minute data[label_time_slot] = minute_day // slot_interval + initial_slot if not inplace: return data def generate_time_statistics( data: DataFrame, local_label: str = LOCAL_LABEL ): """ Calculates time statistics of the pairwise local labels. (average, standard deviation, minimum, maximum, sum and count) of the pairwise local labels of a symbolic trajectory. Parameters ---------- data : DataFrame The input trajectories date. local_label : str, optional The name of the feature with local id, by default LOCAL_LABEL Return ------ DataFrame Statistics infomations of the pairwise local labels Example ------- >>> from pymove.utils.datetime import generate_time_statistics >>> df local_label prev_local time_to_prev id 0 house NaN NaN 1 1 market house 720.0 1 2 market market 5.0 1 3 market market 1.0 1 4 school market 844.0 1 >>> generate_time_statistics(df) local_label prev_local mean std \ min max sum count 0 house market 844.0 0.000000 \ 844.0 844.0 844.0 1 1 market house 720.0 0.000000 \ 720.0 720.0 720.0 1 2 market market 3.0 2.828427 \ 1.0 5.0 6.0 2 """ df_statistics = data.groupby( [local_label, PREV_LOCAL] ).agg({TIME_TO_PREV: [ MEAN, STD, MIN, MAX, SUM, COUNT ]}) df_statistics.columns = df_statistics.columns.droplevel(0) df_statistics.fillna(0, inplace=True) df_statistics.reset_index(inplace=True) return df_statistics def _calc_time_threshold(seg_mean: float, seg_std: float) -> float: """ Auxiliary function for calculating the threshold. Based on the mean and standard deviation of the time transitions between adjacent places on discrete MoveDataFrame. Parameters ---------- seg_mean : float The time mean between two local labels (segment). seg_std : float The time mean between two local labels (segment). Return ------ float The threshold based on the mean and standard deviation of transition time for the segment. Examples -------- >>> from pymove.utils.datetime import _calc_time_threshold >>> print(_calc_time_threshold(12.3, 2.1)) 14.4 >>> print(_calc_time_threshold(1, 1.5)) 2.5 >>> print(_calc_time_threshold(-2, 2)) 0.0 """ threshold = seg_std + seg_mean threshold = float(f'{threshold:.1f}') return threshold def threshold_time_statistics( df_statistics: DataFrame, mean_coef: float = 1.0, std_coef: float = 1.0, inplace: bool = False ) -> DataFrame | None: """ Calculates and creates the threshold column. The values are based in the time statistics dataframe for each segment. Parameters ---------- df_statistics : DataFrame Time Statistics of the pairwise local labels. mean_coef : float Multiplication coefficient of the mean time for the segment, by default 1.0 std_coef : float Multiplication coefficient of sdt time for the segment, by default 1.0 inplace : boolean, optional wether the operation will be done in the original dataframe, by default False Return ------ DataFrame DataFrame of time statistics with the aditional feature: threshold, which indicates the time limit of the trajectory segment, or None Example ------- >>> from pymove.utils.datetime import generate_time_statistics >>> df local_label prev_local time_to_prev id 0 house NaN NaN 1 1 market house 720.0 1 2 market market 5.0 1 3 market market 1.0 1 4 school market 844.0 1 >>> statistics = generate_time_statistics(df) >>> statistics local_label prev_local mean std min max sum count 0 house market 844.0 0.000000 844.0 844.0 844.0 1 1 market house 720.0 0.000000 720.0 720.0 720.0 1 2 market market 3.0 2.828427 1.0 5.0 6.0 2 >>> threshold_time_statistics(statistics) local_label prev_local mean std min \ max sum count threshold 0 house market 844.0 0.000000 844.0 \ 844.0 844.0 1 844.0 1 market house 720.0 0.000000 720.0 \ 720.0 720.0 1 720.0 2 market market 3.0 2.828427 1.0 \ 5.0 6.0 2 5.8 """ if not inplace: df_statistics = df_statistics.copy() df_statistics[THRESHOLD] = df_statistics.apply( lambda x: _calc_time_threshold(x[MEAN] * mean_coef, x[STD] * std_coef), axis=1 ) if not inplace: return df_statistics
25,454
https://github.com/fjtc/mvn-versions/blob/master/libs/maven-versions-core/src/main/java/br/com/brokenbits/mvn/versions/VersionString.java
Github Open Source
Open Source
BSD-2-Clause
2,014
mvn-versions
fjtc
Java
Code
65
177
package br.com.brokenbits.mvn.versions; /** * * @author fjtc * @since 2014.07.21 */ public class VersionString extends Version { private String version; public VersionString(String version) throws IllegalArgumentException { this.setString(version); } public void setString(String version){ if (version == null) { throw new IllegalArgumentException("The version string cannot be null."); } this.version = version; } public String getString(){ return this.version; } @Override public String toString() { return version; } }
34,199
https://github.com/IoTCrawler/Search-Enabler/blob/master/src/main/java/com/agtinternational/iotcrawler/graphqlEnabler/Wiring.java
Github Open Source
Open Source
Apache-2.0
null
Search-Enabler
IoTCrawler
Java
Code
137
297
package com.agtinternational.iotcrawler.graphqlEnabler; /*- * #%L * search-enabler * %% * Copyright (C) 2019 - 2020 AGT International. Author Pavel Smirnov (psmirnov@agtinternational.com) * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import graphql.schema.GraphQLSchema; import graphql.schema.idl.RuntimeWiring; import org.dataloader.DataLoaderRegistry; import java.io.IOException; public interface Wiring { public String getSchemaString(); public RuntimeWiring build(); public DataLoaderRegistry getDataLoaderRegistry(); }
10,752
https://github.com/benrey/ever-gauzy/blob/master/apps/gauzy/src/app/@shared/status-badge/status-badge.component.ts
Github Open Source
Open Source
PostgreSQL
2,022
ever-gauzy
benrey
TypeScript
Code
90
308
import { Component, OnInit, Input } from '@angular/core'; import { ComponentLayoutStyleEnum } from '@gauzy/contracts'; @Component({ selector: 'ga-status-badge', templateUrl: './status-badge.component.html', styleUrls: ['./status-badge.component.scss'] }) export class StatusBadgeComponent implements OnInit { @Input() value: any; text: string; badgeClass: string; @Input() layout?: ComponentLayoutStyleEnum | undefined; constructor() {} ngOnInit() { if (this.value) { if (this.layout === ComponentLayoutStyleEnum.CARDS_GRID) { if (typeof this.value === 'object') { this.text = this.value['text']; this.badgeClass = 'badge badge-' + this.value['class']; } else { this.text = this.value; } } else { this.text = this.value['text']; this.badgeClass = 'badge badge-' + this.value['class']; } } } }
49,776
https://github.com/heyogrady/jumpstart/blob/master/config/routes/contacts.rb
Github Open Source
Open Source
MIT
2,015
jumpstart
heyogrady
Ruby
Code
4
13
resources :contacts, only: [:create]
8,869
https://github.com/HakimFractal/shopsys/blob/master/packages/framework/src/Model/Sitemap/SitemapDumperFactory.php
Github Open Source
Open Source
PostgreSQL
null
shopsys
HakimFractal
PHP
Code
135
681
<?php namespace Shopsys\FrameworkBundle\Model\Sitemap; use League\Flysystem\FilesystemInterface; use League\Flysystem\MountManager; use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Symfony\Component\Filesystem\Filesystem; class SitemapDumperFactory { /** @access protected */ const MAX_ITEMS_IN_FILE = 50000; /** * @var \Symfony\Component\EventDispatcher\EventDispatcherInterface */ protected $eventDispatcher; /** * @var \Symfony\Component\Filesystem\Filesystem */ protected $localFilesystem; /** * @var \Shopsys\FrameworkBundle\Model\Sitemap\SitemapFilePrefixer */ protected $sitemapFilePrefixer; /** * @var \League\Flysystem\MountManager */ protected $mountManager; /** * @var \League\Flysystem\FilesystemInterface */ protected $filesystem; /** * @param \Symfony\Component\EventDispatcher\EventDispatcherInterface $eventDispatcher * @param \Symfony\Component\Filesystem\Filesystem $localFilesystem * @param \League\Flysystem\FilesystemInterface $filesystem * @param \League\Flysystem\MountManager $mountManager * @param \Shopsys\FrameworkBundle\Model\Sitemap\SitemapFilePrefixer $sitemapFilePrefixer */ public function __construct( EventDispatcherInterface $eventDispatcher, Filesystem $localFilesystem, FilesystemInterface $filesystem, MountManager $mountManager, SitemapFilePrefixer $sitemapFilePrefixer ) { $this->eventDispatcher = $eventDispatcher; $this->localFilesystem = $localFilesystem; $this->sitemapFilePrefixer = $sitemapFilePrefixer; $this->mountManager = $mountManager; $this->filesystem = $filesystem; } /** * @param int $domainId * @return \Shopsys\FrameworkBundle\Model\Sitemap\SitemapDumper */ public function createForDomain($domainId) { return new SitemapDumper( $this->eventDispatcher, $this->localFilesystem, $this->filesystem, $this->mountManager, $this->sitemapFilePrefixer->getSitemapFilePrefixForDomain($domainId), static::MAX_ITEMS_IN_FILE ); } }
41,113
https://github.com/tlklan/yii-bootstrap-git/blob/master/demo/yii/validators/CCompareValidator.php
Github Open Source
Open Source
BSD-3-Clause
2,021
yii-bootstrap-git
tlklan
PHP
Code
827
2,594
<?php /** * CCompareValidator class file. * * @author Qiang Xue <qiang.xue@gmail.com> * @link http://www.yiiframework.com/ * @copyright Copyright &copy; 2008-2011 Yii Software LLC * @license http://www.yiiframework.com/license/ */ /** * CCompareValidator compares the specified attribute value with another value and validates if they are equal. * * The value being compared with can be another attribute value * (specified via {@link compareAttribute}) or a constant (specified via * {@link compareValue}. When both are specified, the latter takes * precedence. If neither is specified, the attribute will be compared * with another attribute whose name is by appending "_repeat" to the source * attribute name. * * The comparison can be either {@link strict} or not. * * CCompareValidator supports different comparison operators. * Previously, it only compares to see if two values are equal or not. * * When using the {@link message} property to define a custom error message, the message * may contain additional placeholders that will be replaced with the actual content. In addition * to the "{attribute}" placeholder, recognized by all validators (see {@link CValidator}), * CCompareValidator allows for the following placeholders to be specified: * <ul> * <li>{compareValue}: replaced with the constant value being compared with {@link compareValue}.</li> * </ul> * * @author Qiang Xue <qiang.xue@gmail.com> * @version $Id$ * @package system.validators * @since 1.0 */ class CCompareValidator extends CValidator { /** * @var string the name of the attribute to be compared with */ public $compareAttribute; /** * @var string the constant value to be compared with */ public $compareValue; /** * @var boolean whether the comparison is strict (both value and type must be the same.) * Defaults to false. */ public $strict=false; /** * @var boolean whether the attribute value can be null or empty. Defaults to false. * If this is true, it means the attribute is considered valid when it is empty. */ public $allowEmpty=false; /** * @var string the operator for comparison. Defaults to '='. * The followings are valid operators: * <ul> * <li>'=' or '==': validates to see if the two values are equal. If {@link strict} is true, the comparison * will be done in strict mode (i.e. checking value type as well).</li> * <li>'!=': validates to see if the two values are NOT equal. If {@link strict} is true, the comparison * will be done in strict mode (i.e. checking value type as well).</li> * <li>'>': validates to see if the value being validated is greater than the value being compared with.</li> * <li>'>=': validates to see if the value being validated is greater than or equal to the value being compared with.</li> * <li>'<': validates to see if the value being validated is less than the value being compared with.</li> * <li>'<=': validates to see if the value being validated is less than or equal to the value being compared with.</li> * </ul> */ public $operator='='; /** * Validates the attribute of the object. * If there is any error, the error message is added to the object. * @param CModel $object the object being validated * @param string $attribute the attribute being validated */ protected function validateAttribute($object,$attribute) { $value=$object->$attribute; if($this->allowEmpty && $this->isEmpty($value)) return; if($this->compareValue!==null) $compareTo=$compareValue=$this->compareValue; else { $compareAttribute=$this->compareAttribute===null ? $attribute.'_repeat' : $this->compareAttribute; $compareValue=$object->$compareAttribute; $compareTo=$object->getAttributeLabel($compareAttribute); } switch($this->operator) { case '=': case '==': if(($this->strict && $value!==$compareValue) || (!$this->strict && $value!=$compareValue)) { $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} must be repeated exactly.'); $this->addError($object,$attribute,$message,array('{compareAttribute}'=>$compareTo)); } break; case '!=': if(($this->strict && $value===$compareValue) || (!$this->strict && $value==$compareValue)) { $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} must not be equal to "{compareValue}".'); $this->addError($object,$attribute,$message,array('{compareAttribute}'=>$compareTo,'{compareValue}'=>$compareValue)); } break; case '>': if($value<=$compareValue) { $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} must be greater than "{compareValue}".'); $this->addError($object,$attribute,$message,array('{compareAttribute}'=>$compareTo,'{compareValue}'=>$compareValue)); } break; case '>=': if($value<$compareValue) { $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} must be greater than or equal to "{compareValue}".'); $this->addError($object,$attribute,$message,array('{compareAttribute}'=>$compareTo,'{compareValue}'=>$compareValue)); } break; case '<': if($value>=$compareValue) { $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} must be less than "{compareValue}".'); $this->addError($object,$attribute,$message,array('{compareAttribute}'=>$compareTo,'{compareValue}'=>$compareValue)); } break; case '<=': if($value>$compareValue) { $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} must be less than or equal to "{compareValue}".'); $this->addError($object,$attribute,$message,array('{compareAttribute}'=>$compareTo,'{compareValue}'=>$compareValue)); } break; default: throw new CException(Yii::t('yii','Invalid operator "{operator}".',array('{operator}'=>$this->operator))); } } /** * Returns the JavaScript needed for performing client-side validation. * @param CModel $object the data object being validated * @param string $attribute the name of the attribute to be validated. * @return string the client-side validation script. * @see CActiveForm::enableClientValidation * @since 1.1.7 */ public function clientValidateAttribute($object,$attribute) { if($this->compareValue !== null) { $compareTo=$this->compareValue; $compareValue=CJSON::encode($this->compareValue); } else { $compareAttribute=$this->compareAttribute === null ? $attribute . '_repeat' : $this->compareAttribute; $compareValue="\$('#" . (CHtml::activeId($object, $compareAttribute)) . "').val()"; $compareTo=$object->getAttributeLabel($compareAttribute); } $message=$this->message; switch($this->operator) { case '=': case '==': if($message===null) $message=Yii::t('yii','{attribute} must be repeated exactly.'); $condition='value!='.$compareValue; break; case '!=': if($message===null) $message=Yii::t('yii','{attribute} must not be equal to "{compareValue}".'); $condition='value=='.$compareValue; break; case '>': if($message===null) $message=Yii::t('yii','{attribute} must be greater than "{compareValue}".'); $condition='parseFloat(value)<=parseFloat('.$compareValue.')'; break; case '>=': if($message===null) $message=Yii::t('yii','{attribute} must be greater than or equal to "{compareValue}".'); $condition='parseFloat(value)<parseFloat('.$compareValue.')'; break; case '<': if($message===null) $message=Yii::t('yii','{attribute} must be less than "{compareValue}".'); $condition='parseFloat(value)>=parseFloat('.$compareValue.')'; break; case '<=': if($message===null) $message=Yii::t('yii','{attribute} must be less than or equal to "{compareValue}".'); $condition='parseFloat(value)>parseFloat('.$compareValue.')'; break; default: throw new CException(Yii::t('yii','Invalid operator "{operator}".',array('{operator}'=>$this->operator))); } $message=strtr($message,array( '{attribute}'=>$object->getAttributeLabel($attribute), '{compareValue}'=>$compareTo, )); return " if(".($this->allowEmpty ? "$.trim(value)!='' && " : '').$condition.") { messages.push(".CJSON::encode($message)."); } "; } }
29,768
https://github.com/Vivekyadavgithub/ChernoLights/blob/master/Cherno2D/Basicvertex.glsl
Github Open Source
Open Source
MIT
2,021
ChernoLights
Vivekyadavgithub
GLSL
Code
60
148
layout(location = 0) in vec3 position; layout(location = 1) in vec3 aNormal; layout(location = 2) in vec2 texCoords; out vec3 Normal; out vec3 FragPos; out vec2 TexCoord; uniform mat4 model; uniform mat4 view; uniform mat4 projection; void main() { FragPos = vec3(model * vec4(position, 1.0)); TexCoord = texCoords; Normal = aNormal; gl_Position = projection * view * vec4(FragPos, 1.0f); };
39,039
https://github.com/wizzzet/github_backend/blob/master/apps/integrations/github/resources/__init__.py
Github Open Source
Open Source
MIT
null
github_backend
wizzzet
Python
Code
30
65
from .users import UsersListResource # NOQA from .users import UserResource # NOQA from .followers import FollowersListResource # NOQA from .repos import ReposListResource # NOQA from .repos import RepoResource # NOQA
2,625
https://github.com/veereshnm/ctscypress/blob/master/public/js/controllers.js
Github Open Source
Open Source
MIT
null
ctscypress
veereshnm
JavaScript
Code
37
128
'use strict'; /* Controllers */ angular.module('myApp.controllers', []). controller('AppCtrl', ['$timeout', '$location', '$scope', '$http', '$route', function ($timeout, $location, $scope, $http, $route) { }]).controller('childCtrl', ['$timeout', '$location', '$scope', '$http', '$route', function ($timeout, $location, $scope, $http, $route) { $scope.$parent.currentpage = $location.path(); }]);
32,752
https://github.com/jonj-src/jonj/blob/master/ext/mbstring/mbstring.h
Github Open Source
Open Source
PHP-3.01
null
jonj
jonj-src
C
Code
594
2,576
/* +----------------------------------------------------------------------+ | JONJ Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2016 The JONJ Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the JONJ license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.jonj.tk/license/3_01.txt | | If you did not receive a copy of the JONJ license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@jonj.tk so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Tsukada Takuya <tsukada@fminn.nagano.nagano.jp> | +----------------------------------------------------------------------+ */ /* $Id$ */ /* * JONJ 4 Multibyte String module "mbstring" (currently only for Japanese) * * History: * 2000.5.19 Release jonj-4.0RC2_jstring-1.0 * 2001.4.1 Release jonj4_jstring-1.0.91 * 2001.4.30 Release jonj4-jstring-1.1 (contribute to The JONJ Group) * 2001.5.1 Renamed from jstring to mbstring (hirokawa@jonj.tk) */ /* * JONJ3 Internationalization support program. * * Copyright (c) 1999,2000 by the JONJ3 internationalization team. * All rights reserved. * * See README_JONJ3-i18n-ja for more detail. * * Authors: * Hironori Sato <satoh@jpnnet.com> * Shigeru Kanemoto <sgk@happysize.co.jp> * Tsukada Takuya <tsukada@fminn.nagano.nagano.jp> */ #ifndef _MBSTRING_H #define _MBSTRING_H #ifdef COMPILE_DL_MBSTRING #undef HAVE_MBSTRING #define HAVE_MBSTRING 1 #endif #ifdef JONJ_WIN32 # undef MBSTRING_API # ifdef MBSTRING_EXPORTS # define MBSTRING_API __declspec(dllexport) # elif defined(COMPILE_DL_MBSTRING) # define MBSTRING_API __declspec(dllimport) # else # define MBSTRING_API /* nothing special */ # endif #elif defined(__GNUC__) && __GNUC__ >= 4 # undef MBSTRING_API # define MBSTRING_API __attribute__ ((visibility("default"))) #else # undef MBSTRING_API # define MBSTRING_API /* nothing special */ #endif #if HAVE_MBSTRING #include "libmbfl/mbfl/mbfilter.h" #include "SAPI.h" #define JONJ_MBSTRING_API 20021024 extern zend_module_entry mbstring_module_entry; #define mbstring_module_ptr &mbstring_module_entry JONJ_MINIT_FUNCTION(mbstring); JONJ_MSHUTDOWN_FUNCTION(mbstring); JONJ_RINIT_FUNCTION(mbstring); JONJ_RSHUTDOWN_FUNCTION(mbstring); JONJ_MINFO_FUNCTION(mbstring); /* functions in jonj_unicode.c */ JONJ_FUNCTION(mb_convert_case); JONJ_FUNCTION(mb_strtoupper); JONJ_FUNCTION(mb_strtolower); /* jonj function registration */ JONJ_FUNCTION(mb_language); JONJ_FUNCTION(mb_internal_encoding); JONJ_FUNCTION(mb_http_input); JONJ_FUNCTION(mb_http_output); JONJ_FUNCTION(mb_detect_order); JONJ_FUNCTION(mb_substitute_character); JONJ_FUNCTION(mb_preferred_mime_name); JONJ_FUNCTION(mb_parse_str); JONJ_FUNCTION(mb_output_handler); JONJ_FUNCTION(mb_strlen); JONJ_FUNCTION(mb_strpos); JONJ_FUNCTION(mb_strrpos); JONJ_FUNCTION(mb_stripos); JONJ_FUNCTION(mb_strripos); JONJ_FUNCTION(mb_strstr); JONJ_FUNCTION(mb_strrchr); JONJ_FUNCTION(mb_stristr); JONJ_FUNCTION(mb_strrichr); JONJ_FUNCTION(mb_substr_count); JONJ_FUNCTION(mb_substr); JONJ_FUNCTION(mb_strcut); JONJ_FUNCTION(mb_strwidth); JONJ_FUNCTION(mb_strimwidth); JONJ_FUNCTION(mb_convert_encoding); JONJ_FUNCTION(mb_detect_encoding); JONJ_FUNCTION(mb_list_encodings); JONJ_FUNCTION(mb_encoding_aliases); JONJ_FUNCTION(mb_convert_kana); JONJ_FUNCTION(mb_encode_mimeheader); JONJ_FUNCTION(mb_decode_mimeheader); JONJ_FUNCTION(mb_convert_variables); JONJ_FUNCTION(mb_encode_numericentity); JONJ_FUNCTION(mb_decode_numericentity); JONJ_FUNCTION(mb_send_mail); JONJ_FUNCTION(mb_get_info); JONJ_FUNCTION(mb_check_encoding); MBSTRING_API char *jonj_mb_safe_strrchr_ex(const char *s, unsigned int c, size_t nbytes, const mbfl_encoding *enc); MBSTRING_API char *jonj_mb_safe_strrchr(const char *s, unsigned int c, size_t nbytes TSRMLS_DC); MBSTRING_API char * jonj_mb_convert_encoding(const char *input, size_t length, const char *_to_encoding, const char *_from_encodings, size_t *output_len TSRMLS_DC); MBSTRING_API int jonj_mb_check_encoding_list(const char *encoding_list TSRMLS_DC); MBSTRING_API size_t jonj_mb_mbchar_bytes_ex(const char *s, const mbfl_encoding *enc); MBSTRING_API size_t jonj_mb_mbchar_bytes(const char *s TSRMLS_DC); MBSTRING_API int jonj_mb_encoding_detector_ex(const char *arg_string, int arg_length, char *arg_list TSRMLS_DC); MBSTRING_API int jonj_mb_encoding_converter_ex(char **str, int *len, const char *encoding_to, const char *encoding_from TSRMLS_DC); MBSTRING_API int jonj_mb_stripos(int mode, const char *old_haystack, unsigned int old_haystack_len, const char *old_needle, unsigned int old_needle_len, long offset, const char *from_encoding TSRMLS_DC); /* internal use only */ int _jonj_mb_ini_mbstring_internal_encoding_set(const char *new_value, uint new_value_length TSRMLS_DC); ZEND_BEGIN_MODULE_GLOBALS(mbstring) char *internal_encoding_name; enum mbfl_no_language language; const mbfl_encoding *internal_encoding; const mbfl_encoding *current_internal_encoding; const mbfl_encoding *http_output_encoding; const mbfl_encoding *current_http_output_encoding; const mbfl_encoding *http_input_identify; const mbfl_encoding *http_input_identify_get; const mbfl_encoding *http_input_identify_post; const mbfl_encoding *http_input_identify_cookie; const mbfl_encoding *http_input_identify_string; const mbfl_encoding **http_input_list; size_t http_input_list_size; const mbfl_encoding **detect_order_list; size_t detect_order_list_size; const mbfl_encoding **current_detect_order_list; size_t current_detect_order_list_size; enum mbfl_no_encoding *default_detect_order_list; size_t default_detect_order_list_size; int filter_illegal_mode; int filter_illegal_substchar; int current_filter_illegal_mode; int current_filter_illegal_substchar; long func_overload; zend_bool encoding_translation; long strict_detection; long illegalchars; mbfl_buffer_converter *outconv; void *http_output_conv_mimetypes; #if HAVE_MBREGEX struct _zend_mb_regex_globals *mb_regex_globals; #endif ZEND_END_MODULE_GLOBALS(mbstring) #define MB_OVERLOAD_MAIL 1 #define MB_OVERLOAD_STRING 2 #define MB_OVERLOAD_REGEX 4 struct mb_overload_def { int type; char *orig_func; char *ovld_func; char *save_func; }; #ifdef ZTS #define MBSTRG(v) TSRMG(mbstring_globals_id, zend_mbstring_globals *, v) #else #define MBSTRG(v) (mbstring_globals.v) #endif #else /* HAVE_MBSTRING */ #define mbstring_module_ptr NULL #endif /* HAVE_MBSTRING */ #define jonjext_mbstring_ptr mbstring_module_ptr #endif /* _MBSTRING_H */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: */
41,687
https://github.com/MikeyBurkman/fhclogs/blob/master/lib/commands/apps.js
Github Open Source
Open Source
MIT
2,017
fhclogs
MikeyBurkman
JavaScript
Code
25
68
'use strict'; const config = require('../config'); exports.command = 'apps'; exports.desc = 'List all apps found in the config file'; exports.handler = function() { console.log(config.getAllAppNames().join('\n')); };
1,777
https://github.com/corindwyer/titus-control-plane/blob/master/titus-server-master/src/test/java/com/netflix/titus/master/kubernetes/pod/legacy/PodContainerInfoFactoryTest.java
Github Open Source
Open Source
Apache-2.0
2,022
titus-control-plane
corindwyer
Java
Code
261
1,286
/* * Copyright 2021 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.titus.master.kubernetes.pod.legacy; import java.util.Collections; import java.util.Optional; import com.netflix.titus.api.jobmanager.JobAttributes; import com.netflix.titus.api.jobmanager.model.job.BatchJobTask; import com.netflix.titus.api.jobmanager.model.job.Job; import com.netflix.titus.api.jobmanager.model.job.LogStorageInfo; import com.netflix.titus.api.jobmanager.model.job.Task; import com.netflix.titus.api.jobmanager.model.job.ext.BatchJobExt; import com.netflix.titus.master.kubernetes.pod.KubePodConfiguration; import com.netflix.titus.testkit.model.job.JobGenerator; import io.titanframework.messages.TitanProtos; import org.junit.Before; import org.junit.Test; import static com.netflix.titus.master.kubernetes.pod.legacy.PodContainerInfoFactory.S3_BUCKET_NAME; import static com.netflix.titus.master.kubernetes.pod.legacy.PodContainerInfoFactory.S3_WRITER_ROLE; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class PodContainerInfoFactoryTest { private static final LogStorageInfo.S3LogLocation DEFAULT_S3_LOG_LOCATION = new LogStorageInfo.S3LogLocation( "myAccount", "myAccountId", "myRegion", "defaultBucket", "key" ); private final KubePodConfiguration configuration = mock(KubePodConfiguration.class); private final LogStorageInfo<Task> logStorageInfo = mock(LogStorageInfo.class); private PodContainerInfoFactory podContainerInfoFactory; @Before public void setUp() throws Exception { podContainerInfoFactory = new PodContainerInfoFactory(configuration, logStorageInfo); } @Test public void testDefaultWriterRoleAssignment() { BatchJobTask task = JobGenerator.oneBatchTask(); when(logStorageInfo.getS3LogLocation(task, false)).thenReturn(Optional.of(DEFAULT_S3_LOG_LOCATION)); when(configuration.getDefaultS3WriterRole()).thenReturn("defaultWriter"); when(configuration.isDefaultS3WriterRoleEnabled()).thenReturn(true); TitanProtos.ContainerInfo.Builder containerInfoBuilder = TitanProtos.ContainerInfo.newBuilder(); podContainerInfoFactory.appendS3WriterRole(containerInfoBuilder, JobGenerator.oneBatchJob(), task); assertThat(containerInfoBuilder.getPassthroughAttributesMap()).containsEntry(S3_WRITER_ROLE, "defaultWriter"); assertThat(containerInfoBuilder.getPassthroughAttributesMap()).containsEntry(S3_BUCKET_NAME, "defaultBucket"); } @Test public void testNullDefaultWriterRoleAssignment() { TitanProtos.ContainerInfo.Builder containerInfoBuilder = TitanProtos.ContainerInfo.newBuilder(); podContainerInfoFactory.appendS3WriterRole(containerInfoBuilder, JobGenerator.oneBatchJob(), JobGenerator.oneBatchTask()); assertThat(containerInfoBuilder.getPassthroughAttributesMap()).doesNotContainKey(S3_WRITER_ROLE); } @Test public void testCustomBucketWriterRoleAssignment() { when(configuration.isDefaultS3WriterRoleEnabled()).thenReturn(true); TitanProtos.ContainerInfo.Builder containerInfoBuilder = TitanProtos.ContainerInfo.newBuilder(); Job<BatchJobExt> job = JobGenerator.oneBatchJob(); job = job.toBuilder() .withJobDescriptor(job.getJobDescriptor().toBuilder() .withContainer(job.getJobDescriptor().getContainer().toBuilder() .withAttributes(Collections.singletonMap( JobAttributes.JOB_CONTAINER_ATTRIBUTE_S3_BUCKET_NAME, "myOwnBucket" )).build() ) .build() ) .build(); podContainerInfoFactory.appendS3WriterRole(containerInfoBuilder, job, JobGenerator.oneBatchTask()); assertThat(containerInfoBuilder.getPassthroughAttributesMap()).containsEntry( S3_WRITER_ROLE, job.getJobDescriptor().getContainer().getSecurityProfile().getIamRole() ); } }
47,224
https://github.com/benesch/cpp_demangle/blob/master/src/logging.rs
Github Open Source
Open Source
Apache-2.0, MIT
2,022
cpp_demangle
benesch
Rust
Code
51
144
#[cfg(feature = "logging")] macro_rules! log { ( $fmt:expr ) => { println!($fmt); }; ( $fmt:expr, $($x:tt)* ) => { println!($fmt, $($x)*); } } #[cfg(not(feature = "logging"))] macro_rules! log { ( $fmt:expr ) => {}; ( $fmt:expr, $($x:tt)* ) => { if false { let _ = format!($fmt, $($x)*); } }; }
33,395
https://github.com/KazanExpress/docker-images/blob/master/images/chproxy/v1.14.0/sources/main.go
Github Open Source
Open Source
MIT
null
docker-images
KazanExpress
Go
Code
867
3,071
package main import ( "context" "crypto/tls" "flag" "fmt" "net" "net/http" "os" "os/signal" "strings" "sync/atomic" "syscall" "time" "github.com/Vertamedia/chproxy/config" "github.com/Vertamedia/chproxy/log" "github.com/prometheus/client_golang/prometheus/promhttp" "golang.org/x/crypto/acme/autocert" ) var ( configFile = flag.String("config", "", "Proxy configuration filename") version = flag.Bool("version", false, "Prints current version and exits") ) var ( proxy = newReverseProxy() // networks allow lists allowedNetworksHTTP atomic.Value allowedNetworksHTTPS atomic.Value allowedNetworksMetrics atomic.Value ) func main() { http.DefaultTransport.(*http.Transport).TLSClientConfig = &tls.Config{InsecureSkipVerify: true} flag.Parse() if *version { fmt.Printf("%s\n", versionString()) os.Exit(0) } log.Infof("%s", versionString()) log.Infof("Loading config: %s", *configFile) cfg, err := loadConfig() if err != nil { log.Fatalf("error while loading config: %s", err) } if err = applyConfig(cfg); err != nil { log.Fatalf("error while applying config: %s", err) } log.Infof("Loading config %q: successful", *configFile) c := make(chan os.Signal) signal.Notify(c, syscall.SIGHUP) go func() { for { switch <-c { case syscall.SIGHUP: log.Infof("SIGHUP received. Going to reload config %s ...", *configFile) if err := reloadConfig(); err != nil { log.Errorf("error while reloading config: %s", err) continue } log.Infof("Reloading config %s: successful", *configFile) } } }() server := cfg.Server if len(server.HTTP.ListenAddr) == 0 && len(server.HTTPS.ListenAddr) == 0 { panic("BUG: broken config validation - `listen_addr` is not configured") } if server.HTTP.ForceAutocertHandler { autocertManager = newAutocertManager(server.HTTPS.Autocert) } if len(server.HTTPS.ListenAddr) != 0 { go serveTLS(server.HTTPS) } if len(server.HTTP.ListenAddr) != 0 { go serve(server.HTTP) } select {} } var autocertManager *autocert.Manager func newAutocertManager(cfg config.Autocert) *autocert.Manager { if len(cfg.CacheDir) > 0 { if err := os.MkdirAll(cfg.CacheDir, 0700); err != nil { log.Fatalf("error while creating folder %q: %s", cfg.CacheDir, err) } } var hp autocert.HostPolicy if len(cfg.AllowedHosts) != 0 { allowedHosts := make(map[string]struct{}, len(cfg.AllowedHosts)) for _, v := range cfg.AllowedHosts { allowedHosts[v] = struct{}{} } hp = func(_ context.Context, host string) error { if _, ok := allowedHosts[host]; ok { return nil } return fmt.Errorf("host %q doesn't match `host_policy` configuration", host) } } return &autocert.Manager{ Prompt: autocert.AcceptTOS, Cache: autocert.DirCache(cfg.CacheDir), HostPolicy: hp, } } func newListener(listenAddr string) net.Listener { ln, err := net.Listen("tcp4", listenAddr) if err != nil { log.Fatalf("cannot listen for %q: %s", listenAddr, err) } return ln } func serveTLS(cfg config.HTTPS) { ln := newListener(cfg.ListenAddr) h := http.HandlerFunc(serveHTTP) tlsCfg := newTLSConfig(cfg) tln := tls.NewListener(ln, tlsCfg) log.Infof("Serving https on %q", cfg.ListenAddr) if err := listenAndServe(tln, h, cfg.TimeoutCfg); err != nil { log.Fatalf("TLS server error on %q: %s", cfg.ListenAddr, err) } } func serve(cfg config.HTTP) { var h http.Handler ln := newListener(cfg.ListenAddr) h = http.HandlerFunc(serveHTTP) if cfg.ForceAutocertHandler { if autocertManager == nil { panic("BUG: autocertManager is not inited") } addr := ln.Addr().String() parts := strings.Split(addr, ":") if parts[len(parts)-1] != "80" { log.Fatalf("`letsencrypt` specification requires http server to listen on :80 port to satisfy http-01 challenge. " + "Otherwise, certificates will be impossible to generate") } h = autocertManager.HTTPHandler(h) } log.Infof("Serving http on %q", cfg.ListenAddr) if err := listenAndServe(ln, h, cfg.TimeoutCfg); err != nil { log.Fatalf("HTTP server error on %q: %s", cfg.ListenAddr, err) } } func newTLSConfig(cfg config.HTTPS) *tls.Config { tlsCfg := tls.Config{ PreferServerCipherSuites: true, CurvePreferences: []tls.CurveID{ tls.CurveP256, tls.X25519, }, } if len(cfg.KeyFile) > 0 && len(cfg.CertFile) > 0 { cert, err := tls.LoadX509KeyPair(cfg.CertFile, cfg.KeyFile) if err != nil { log.Fatalf("cannot load cert for `https.cert_file`=%q, `https.key_file`=%q: %s", cfg.CertFile, cfg.KeyFile, err) } tlsCfg.Certificates = []tls.Certificate{cert} } else { if autocertManager == nil { panic("BUG: autocertManager is not inited") } tlsCfg.GetCertificate = autocertManager.GetCertificate } return &tlsCfg } func listenAndServe(ln net.Listener, h http.Handler, cfg config.TimeoutCfg) error { s := &http.Server{ TLSNextProto: make(map[string]func(*http.Server, *tls.Conn, http.Handler)), Handler: h, ReadTimeout: time.Duration(cfg.ReadTimeout), WriteTimeout: time.Duration(cfg.WriteTimeout), IdleTimeout: time.Duration(cfg.IdleTimeout), // Suppress error logging from the server, since chproxy // must handle all these errors in the code. ErrorLog: log.NilLogger, } return s.Serve(ln) } var promHandler = promhttp.Handler() func serveHTTP(rw http.ResponseWriter, r *http.Request) { switch r.Method { case http.MethodGet, http.MethodPost: // Only GET and POST methods are supported. case http.MethodOptions: // This is required for CORS shit :) rw.Header().Set("Allow", "GET,POST") return default: err := fmt.Errorf("%q: unsupported method %q", r.RemoteAddr, r.Method) rw.Header().Set("Connection", "close") respondWith(rw, err, http.StatusMethodNotAllowed) return } switch r.URL.Path { case "/favicon.ico": case "/metrics": an := allowedNetworksMetrics.Load().(*config.Networks) if !an.Contains(r.RemoteAddr) { err := fmt.Errorf("connections to /metrics are not allowed from %s", r.RemoteAddr) rw.Header().Set("Connection", "close") respondWith(rw, err, http.StatusForbidden) return } proxy.refreshCacheMetrics() promHandler.ServeHTTP(rw, r) case "/", "/query": var err error var an *config.Networks if r.TLS != nil { an = allowedNetworksHTTPS.Load().(*config.Networks) err = fmt.Errorf("https connections are not allowed from %s", r.RemoteAddr) } else { an = allowedNetworksHTTP.Load().(*config.Networks) err = fmt.Errorf("http connections are not allowed from %s", r.RemoteAddr) } if !an.Contains(r.RemoteAddr) { rw.Header().Set("Connection", "close") respondWith(rw, err, http.StatusForbidden) return } proxy.ServeHTTP(rw, r) default: badRequest.Inc() err := fmt.Errorf("%q: unsupported path: %q", r.RemoteAddr, r.URL.Path) rw.Header().Set("Connection", "close") respondWith(rw, err, http.StatusBadRequest) } } func loadConfig() (*config.Config, error) { if *configFile == "" { log.Fatalf("Missing -config flag") } cfg, err := config.LoadFile(*configFile) if err != nil { configSuccess.Set(0) return nil, fmt.Errorf("can't load config %q: %s", *configFile, err) } configSuccess.Set(1) configSuccessTime.Set(float64(time.Now().Unix())) return cfg, nil } func applyConfig(cfg *config.Config) error { if err := proxy.applyConfig(cfg); err != nil { return err } allowedNetworksHTTP.Store(&cfg.Server.HTTP.AllowedNetworks) allowedNetworksHTTPS.Store(&cfg.Server.HTTPS.AllowedNetworks) allowedNetworksMetrics.Store(&cfg.Server.Metrics.AllowedNetworks) log.SetDebug(cfg.LogDebug) log.Infof("Loaded config:\n%s", cfg) return nil } func reloadConfig() error { cfg, err := loadConfig() if err != nil { return err } return applyConfig(cfg) } var ( buildTag = "unknown" buildRevision = "unknown" buildTime = "unknown" ) func versionString() string { ver := buildTag if len(ver) == 0 { ver = "unknown" } return fmt.Sprintf("chproxy ver. %s, rev. %s, built at %s", ver, buildRevision, buildTime) }
14,188
https://github.com/seil-smf/armsd/blob/master/Makefile.in
Github Open Source
Open Source
BSD-2-Clause
2,012
armsd
seil-smf
Makefile
Code
151
687
DESTDIR= prefix=@prefix@ exec_prefix=@exec_prefix@ sbindir=@sbindir@ datadir=@datadir@ sysconfdir=@sysconfdir@ localstatedir=@localstatedir@ cachedir=${localstatedir}/armsd exampledir=${datadir}/armsd CFLAGS= -O2 -Wall -Werror @DEFS@ @CPPFLAGS@ @CFLAGS@ CFLAGS_COV= $(CFLAGS) -fprofile-arcs -ftest-coverage LDFLAGS= -lexpat -lssl -lcrypto @LDFLAGS@ @LIBS@ SRCS= armsd.c @SYSSRC@ OBJS= armsd.o @SYSOBJ@ TESTBIN= runtest all: armsd armsd.o: armsd.c armsd.h $(CC) $(CFLAGS) -c -o $@ $< @SYSOBJ@: @SYSSRC@ armsd.h $(CC) $(CFLAGS) -c -o $@ $< armsd: $(OBJS) $(CC) -o armsd $(OBJS) $(LDFLAGS) install: install -d $(DESTDIR)${sbindir} install -c -s armsd $(DESTDIR)${sbindir} install -d $(DESTDIR)${sysconfdir}/armsd install -d $(DESTDIR)${sysconfdir}/armsd/scripts install -c -m 644 armsd.conf $(DESTDIR)${sysconfdir}/armsd/armsd.conf install -d $(DESTDIR)${cachedir} install -d $(DESTDIR)${exampledir} install -c examples/* $(DESTDIR)${exampledir} clean: -rm -f armsd $(TESTBIN) *.o coverage.xml *.gcda *.gcno *.lcov -rm -rf lcov t test:: $(CC) $(CFLAGS) -DTEST -o $(TESTBIN) $(SRCS) $(LDFLAGS) -lcheck ./$(TESTBIN) coverage:: $(CC) $(CFLAGS_COV) -DTEST -o $(TESTBIN) $(SRCS) $(LDFLAGS) -lcheck -./$(TESTBIN) gcovr -e '.*/test/' -e '/usr/include' -x -b -o coverage.xml lcov -c -d . -o armsd-all.lcov lcov -e armsd-all.lcov '*/armsd.c' -o armsd.lcov genhtml -o lcov armsd.lcov
22,122
https://github.com/inferno211/Warn-Info/blob/master/inc/languages/polish/warninfo.lang.php
Github Open Source
Open Source
Apache-2.0
2,018
Warn-Info
inferno211
PHP
Code
34
172
<?php $l['warninfo_info'] = '<strong>Autor tego posta otrzymał ostrzeżenie.</strong>'; $l['warninfo_reason'] = '<strong>Powód:</strong> '; $l['warninfo_date'] = '<strong>Data:</strong> '; $l['warninfo_expires'] = '<strong>Wygasa:</strong> '; $l['warninfo_expired'] = 'Wygasł'; $l['warninfo_admin'] = '<strong>Admin:</strong> '; $l['warninfo_value'] = '<strong>Wartość:</strong> '; $l['warninfo_never'] = 'Nigdy';
29,383
https://github.com/m6s/android-githubbrowser/blob/master/libraries/network/src/main/java/info/mschmitt/githubbrowser/network/responses/GetRepositoriesResponseItem.java
Github Open Source
Open Source
CC-BY-3.0, Unlicense, LicenseRef-scancode-public-domain
2,017
android-githubbrowser
m6s
Java
Code
109
318
package info.mschmitt.githubbrowser.network.responses; import com.google.gson.annotations.SerializedName; /** * @author Matthias Schmitt */ public class GetRepositoriesResponseItem { public long id; public User owner; public String name; public String fullName; public String description; @SerializedName("private") public boolean xPrivate; public boolean fork; public String url; public String htmlUrl; public String cloneUrl; public String gitUrl; public String sshUrl; public String svnUrl; public String mirrorUrl; public String homepage; public String language; public int forksCount; public int stargazersCount; public int watchersCount; public int size; public String defaultBranch; public int openIssuesCount; public boolean hasIssues; public boolean hasWiki; public boolean hasPages; public boolean hasDownloads; public String pushedAt; //2011-01-26T19:06:43Z public String createdAt; //2011-01-26T19:01:12Z public String updatedAt; //2011-01-26T19:14:43Z public Permissions permissions; }
38,067
https://github.com/Fractal-Idea/devilution/blob/master/Source/diablo.cpp
Github Open Source
Open Source
Unlicense
null
devilution
Fractal-Idea
C++
Code
6,330
21,476
//HEADER_GOES_HERE #include "../types.h" int diablo_cpp_init_value; // weak HWND ghMainWnd; int glMid1Seed[NUMLEVELS]; int glMid2Seed[NUMLEVELS]; int gnLevelTypeTbl[NUMLEVELS]; int MouseY; // idb int MouseX; // idb bool gbGameLoopStartup; // idb int glSeedTbl[NUMLEVELS]; int gbRunGame; // weak int glMid3Seed[NUMLEVELS]; int gbRunGameResult; // weak int zoomflag; // weak int gbProcessPlayers; // weak int glEndSeed[NUMLEVELS]; int dword_5256E8; // weak HINSTANCE ghInst; // idb int DebugMonsters[10]; char cineflag; // weak int drawpanflag; // weak int visiondebug; // weak int scrollflag; /* unused */ BOOL light4flag; int leveldebug; // weak int monstdebug; // weak int trigdebug; /* unused */ int setseed; // weak int debugmonsttypes; // weak int PauseMode; // weak int sgnTimeoutCurs; char sgbMouseDown; // weak int color_cycle_timer; // weak int diablo_inf = 0x7F800000; // weak /* rdata */ int fullscreen = 1; // weak #ifdef _DEBUG int showintrodebug = 1; int questdebug = -1; int debug_mode_key_s; int debug_mode_key_w; int debug_mode_key_inverted_v; int debug_mode_dollar_sign; int debug_mode_key_d; int debug_mode_key_i; int dbgplr; int dbgqst; int dbgmon; int arrowdebug; int frameflag; int frameend; int framerate; int framestart; #endif int FriendlyMode = 1; // weak char *spszMsgTbl[4] = { "I need help! Come Here!", "Follow me.", "Here's something for you.", "Now you DIE!" }; // weak char *spszMsgKeyTbl[4] = { "F9", "F10", "F11", "F12" }; // weak struct diablo_cpp_init { diablo_cpp_init() { diablo_cpp_init_value = diablo_inf; } } _diablo_cpp_init; // 479BF8: using guessed type int diablo_inf; // 525514: using guessed type int diablo_cpp_init_value; void __cdecl FreeGameMem() { void *v0; // ecx void *v1; // ecx void *v2; // ecx void *v3; // ecx void *v4; // ecx music_stop(); v0 = pDungeonCels; pDungeonCels = 0; mem_free_dbg(v0); v1 = pMegaTiles; pMegaTiles = 0; mem_free_dbg(v1); v2 = pLevelPieces; pLevelPieces = 0; mem_free_dbg(v2); v3 = level_special_cel; level_special_cel = 0; mem_free_dbg(v3); v4 = pSpeedCels; pSpeedCels = 0; mem_free_dbg(v4); FreeMissiles(); FreeMonsters(); FreeObjectGFX(); FreeEffects(); FreeTownerGFX(); } int __fastcall diablo_init_menu(int a1, int bSinglePlayer) { int v2; // esi int v3; // edi int v4; // ecx int pfExitProgram; // [esp+Ch] [ebp-4h] v2 = bSinglePlayer; v3 = a1; byte_678640 = 1; while ( 1 ) { pfExitProgram = 0; dword_5256E8 = 0; if ( !NetInit(v2, &pfExitProgram) ) break; byte_678640 = 0; if ( (v3 || !*(_DWORD *)&gbValidSaveFile) && (InitLevels(), InitQuests(), InitPortals(), InitDungMsgs(myplr), !*(_DWORD *)&gbValidSaveFile) || (v4 = WM_DIABLOADGAME, !dword_5256E8) ) { v4 = WM_DIABNEWGAME; } run_game_loop(v4); NetClose(); pfile_create_player_description(0, 0); if ( !gbRunGameResult ) goto LABEL_11; } gbRunGameResult = pfExitProgram == 0; LABEL_11: SNetDestroy(); return gbRunGameResult; } // 525698: using guessed type int gbRunGameResult; // 5256E8: using guessed type int dword_5256E8; // 678640: using guessed type char byte_678640; void __fastcall run_game_loop(int uMsg) { //int v3; // eax bool v5; // zf //int v6; // eax signed int v7; // [esp+8h] [ebp-24h] WNDPROC saveProc; // [esp+Ch] [ebp-20h] struct tagMSG msg; // [esp+10h] [ebp-1Ch] nthread_ignore_mutex(1); start_game(uMsg); saveProc = SetWindowProc(GM_Game); control_update_life_mana(); msg_process_net_packets(); gbRunGame = 1; gbProcessPlayers = 1; gbRunGameResult = 1; drawpanflag = 255; DrawAndBlit(); PaletteFadeIn(8); drawpanflag = 255; gbGameLoopStartup = 1; nthread_ignore_mutex(0); while ( gbRunGame ) { diablo_color_cyc_logic(); if ( PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE) ) { SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL); while ( PeekMessage(&msg, NULL, 0, 0, PM_REMOVE) ) { if ( msg.message == WM_QUIT ) { gbRunGameResult = 0; gbRunGame = 0; break; } TranslateMessage(&msg); DispatchMessage(&msg); } if ( !gbRunGame || (v7 = 1, !nthread_has_500ms_passed()) ) v7 = 0; SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_NORMAL); v5 = v7 == 0; } else { //_LOBYTE(v6) = nthread_has_500ms_passed(); v5 = nthread_has_500ms_passed() == 0; } if ( !v5 ) { multi_process_network_packets(); game_loop(gbGameLoopStartup); msgcmd_send_chat(); gbGameLoopStartup = 0; DrawAndBlit(); } #ifdef SLEEP Sleep(1); #endif } if ( (unsigned char)gbMaxPlayers > 1u ) pfile_write_hero(); pfile_flush_W(); PaletteFadeOut(8); SetCursor(0); ClearScreenBuffer(); drawpanflag = 255; scrollrt_draw_game_screen(1); SetWindowProc(saveProc); free_game(); if ( cineflag ) { cineflag = 0; DoEnding(); } } // 525650: using guessed type int gbRunGame; // 525698: using guessed type int gbRunGameResult; // 5256A0: using guessed type int gbProcessPlayers; // 525718: using guessed type char cineflag; // 52571C: using guessed type int drawpanflag; // 679660: using guessed type char gbMaxPlayers; void __fastcall start_game(int uMsg) { cineflag = 0; zoomflag = 1; InitCursor(); InitLightTable(); LoadDebugGFX(); music_stop(); ShowProgress(uMsg); gmenu_init_menu(); InitLevelCursor(); sgnTimeoutCurs = 0; sgbMouseDown = 0; track_repeat_walk(0); } // 52569C: using guessed type int zoomflag; // 525718: using guessed type char cineflag; // 525748: using guessed type char sgbMouseDown; void __cdecl free_game() { int i; // esi FreeControlPan(); FreeInvGFX(); FreeGMenu(); FreeQuestText(); FreeStoreMem(); for(i = 0; i < MAX_PLRS; i++) FreePlayerGFX(i); FreeItemGFX(); FreeCursor(); FreeLightTable(); FreeDebugGFX(); FreeGameMem(); } bool __cdecl diablo_get_not_running() { SetLastError(0); CreateEvent(NULL, FALSE, FALSE, "DiabloEvent"); return GetLastError() != ERROR_ALREADY_EXISTS; } int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { HINSTANCE v4; // esi char Filename[260]; // [esp+8h] [ebp-10Ch] char value_name[8]; // [esp+10Ch] [ebp-8h] v4 = hInstance; #ifndef DEBUGGER diablo_reload_process(hInstance); #endif ghInst = v4; if ( RestrictedTest() ) ErrOkDlg(IDD_DIALOG10, 0, "C:\\Src\\Diablo\\Source\\DIABLO.CPP", 877); if ( ReadOnlyTest() ) { if ( !GetModuleFileName(ghInst, Filename, 0x104u) ) *Filename = '\0'; DirErrorDlg(Filename); } ShowCursor(FALSE); srand(GetTickCount()); encrypt_init_lookup_table(); exception_get_filter(); if ( !diablo_find_window("DIABLO") && diablo_get_not_running() ) { diablo_init_screen(); diablo_parse_flags(lpCmdLine); init_create_window(nCmdShow); sound_init(); UiInitialize(); #ifdef _DEBUG if ( showintrodebug ) play_movie("gendata\\logo.smk", 1); #else play_movie("gendata\\logo.smk", 1); #endif strcpy(value_name, "Intro"); if ( !SRegLoadValue("Diablo", value_name, 0, (int *)&hInstance) ) hInstance = (HINSTANCE)1; if ( hInstance ) play_movie("gendata\\diablo1.smk", 1); SRegSaveValue("Diablo", value_name, 0, 0); #ifdef _DEBUG if ( showintrodebug ) { UiTitleDialog(7); BlackPalette(); } #else UiTitleDialog(7); BlackPalette(); #endif mainmenu_loop(); UiDestroy(); SaveGamma(); if ( ghMainWnd ) { Sleep(300); DestroyWindow(ghMainWnd); } } return 0; } void __fastcall diablo_parse_flags(char *args) { #ifdef _DEBUG int n; // edi int v15; // eax #endif while ( *args ) { for ( ; isspace(*args); ++args ) ; if ( !_strcmpi("dd_emulate", args) ) { gbEmulate = 1; args += strlen("dd_emulate"); } else if ( !_strcmpi("dd_backbuf", args) ) { gbBackBuf = 1; args += strlen("dd_backbuf"); } else if ( !_strcmpi("ds_noduplicates", args) ) { gbDupSounds = 0; args += strlen("ds_noduplicates"); } else { #ifdef _DEBUG switch ( tolower(*args++) ) { case '^': // god mod with all spells as skills debug_mode_key_inverted_v = 1; break; case '$': // demi-god debug_mode_dollar_sign = 1; break; /*case 'b': // enable drop log debug_mode_key_b = 1; break;*/ case 'd': // no startup video+??? showintrodebug = 0; debug_mode_key_d = 1; break; case 'f': // draw fps EnableFrameCount(); break; case 'i': // disable network timeout debug_mode_key_i = 1; break; /*case 'j': // <level>: init trigger at level for ( ; isspace(*args); ++args ) ; for ( n = 0; isdigit(*args); n = v15 + 10 * n - 48 ) v15 = *args++; debug_mode_key_J_trigger = n; break;*/ case 'l': // <dtype> <level>: start in level as type setlevel = 0; for ( leveldebug = 1; isspace(*args); ++args ) ; for ( n = 0; isdigit(*args); n = v15 + 10 * n - 48 ) v15 = *args++; for ( leveltype = n; isspace(*args); ++args ) ; for ( n = 0; isdigit(*args); n = v15 + 10 * n - 48 ) v15 = *args++; currlevel = n; plr[0].plrlevel = n; break; case 'm': // <mtype>: add debug monster, up to 10 allowed for ( monstdebug = 1; isspace(*args); ++args ) ; for ( n = 0; isdigit(*args); n = v15 + 10 * n - 48 ) v15 = *args++; DebugMonsters[debugmonsttypes++] = n; break; case 'n': // disable startup video showintrodebug = 0; break; case 'q': // <qnum>: force a certain quest for ( ; isspace(*args); ++args ) ; for ( n = 0; isdigit(*args); n = v15 + 10 * n - 48 ) v15 = *args++; questdebug = n; break; case 'r': // <seed>: set map seed to for ( ; isspace(*args); ++args ) ; for ( n = 0; isdigit(*args); n = v15 + 10 * n - 48 ) v15 = *args++; setseed = n; break; case 's': // unused debug_mode_key_s = 1; break; case 't': // <qlvl>: sets current quest level leveldebug = 1; for ( setlevel = 1; isspace(*args); ++args ) ; for ( n = 0; isdigit(*args); n = v15 + 10 * n - 48 ) v15 = *args++; setlvlnum = n; break; case 'v': // draw yellow debug tiles visiondebug = 1; break; case 'w': // rest of the cheats, some only in town debug_mode_key_w = 1; break; case 'x': fullscreen = 0; break; default: break; } #else tolower(*args++); #endif } } } // 4A22D6: using guessed type char gbDupSounds; // 52A548: using guessed type char gbBackBuf; // 52A549: using guessed type char gbEmulate; void __cdecl diablo_init_screen() { int v0; // ecx int *v1; // eax v0 = 0; MouseX = 320; MouseY = 240; ScrollInfo._sdx = 0; ScrollInfo._sdy = 0; ScrollInfo._sxoff = 0; ScrollInfo._syoff = 0; ScrollInfo._sdir = 0; v1 = screen_y_times_768; do { *v1 = v0; ++v1; v0 += 768; } while ( (signed int)v1 < (signed int)&screen_y_times_768[1024] ); ClrDiabloMsg(); } // 69CEFC: using guessed type int scrollrt_cpp_init_value; BOOL __fastcall diablo_find_window(LPCSTR lpClassName) { HWND result; // eax HWND v2; // esi HWND v3; // eax HWND v4; // edi result = FindWindow(lpClassName, 0); v2 = result; if ( !result ) return 0; v3 = GetLastActivePopup(result); if ( v3 ) v2 = v3; v4 = GetTopWindow(v2); if ( !v4 ) v4 = v2; SetForegroundWindow(v2); SetFocus(v4); return 1; } void __fastcall diablo_reload_process(HMODULE hModule) { char *i; // eax DWORD dwSize; // esi BOOL v3; // edi _DWORD *v4; // eax _DWORD *v5; // esi HWND v6; // eax char Name[276]; // [esp+Ch] [ebp-29Ch] char Filename[260]; // [esp+120h] [ebp-188h] STARTUPINFOA si; // [esp+224h] [ebp-84h] SYSTEM_INFO sinf; // [esp+268h] [ebp-40h] PROCESS_INFORMATION pi; // [esp+28Ch] [ebp-1Ch] DWORD dwProcessId; // [esp+29Ch] [ebp-Ch] HANDLE hMap; // [esp+2A0h] [ebp-8h] HWND hWnd; // [esp+2A4h] [ebp-4h] *Filename = empty_string; memset(Filename + 1, 0, sizeof(Filename) - 1); // *(_WORD *)&Filename[257] = 0; // Filename[259] = 0; GetModuleFileName(hModule, Filename, 0x104u); wsprintf(Name, "Reload-%s", Filename); for ( i = Name; *i; ++i ) { if ( *i == '\\' ) *i = '/'; } GetSystemInfo(&sinf); dwSize = sinf.dwPageSize; if ( sinf.dwPageSize < 4096 ) dwSize = 4096; hMap = CreateFileMapping((HANDLE)0xFFFFFFFF, NULL, SEC_COMMIT|PAGE_READWRITE, 0, dwSize, Name); v3 = GetLastError() != ERROR_ALREADY_EXISTS; if ( hMap ) { v4 = (unsigned int *)MapViewOfFile(hMap, FILE_MAP_ALL_ACCESS, 0, 0, dwSize); v5 = v4; if ( v4 ) { if ( v3 ) { *v4 = -1; v4[1] = 0; memset(&si, 0, sizeof(si)); si.cb = sizeof(si); CreateProcess(Filename, NULL, NULL, NULL, FALSE, CREATE_NEW_PROCESS_GROUP, NULL, NULL, &si, &pi); WaitForInputIdle(pi.hProcess, 0xFFFFFFFF); CloseHandle(pi.hThread); CloseHandle(pi.hProcess); while ( *v5 < 0 ) Sleep(1000); UnmapViewOfFile(v5); CloseHandle(hMap); ExitProcess(0); } if ( InterlockedIncrement((long *)v4) ) { v6 = GetForegroundWindow(); do { hWnd = v6; v6 = GetWindow(v6, 3u); } while ( v6 ); while ( 1 ) { GetWindowThreadProcessId(hWnd, &dwProcessId); if ( dwProcessId == v5[1] ) break; hWnd = GetWindow(hWnd, 2u); if ( !hWnd ) goto LABEL_23; } SetForegroundWindow(hWnd); LABEL_23: UnmapViewOfFile(v5); CloseHandle(hMap); ExitProcess(0); } v5[1] = GetCurrentProcessId(); } } } int __cdecl PressEscKey() { int result; // eax result = 0; if ( doomflag ) { doom_close(); result = 1; } if ( helpflag ) { helpflag = 0; result = 1; } if ( qtextflag ) { qtextflag = 0; sfx_stop(); } else { if ( !stextflag ) goto LABEL_10; STextESC(); } result = 1; LABEL_10: if ( msgflag ) { msgdelay = 0; result = 1; } if ( talkflag ) { control_reset_talk(); result = 1; } if ( dropGoldFlag ) { control_drop_gold(VK_ESCAPE); result = 1; } if ( spselflag ) { spselflag = 0; result = 1; } return result; } // 4B84DC: using guessed type int dropGoldFlag; // 4B8960: using guessed type int talkflag; // 4B8C98: using guessed type int spselflag; // 52575C: using guessed type int doomflag; // 52B9F0: using guessed type char msgdelay; // 52B9F1: using guessed type char msgflag; // 646D00: using guessed type char qtextflag; // 6AA705: using guessed type char stextflag; LRESULT __stdcall DisableInputWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { bool v5; // zf if ( uMsg <= WM_LBUTTONDOWN ) { if ( uMsg != WM_LBUTTONDOWN ) { if ( uMsg >= WM_KEYFIRST && (uMsg <= WM_CHAR || uMsg == WM_SYSKEYDOWN || uMsg == WM_SYSCOMMAND || uMsg == WM_MOUSEFIRST) ) { return 0; } return MainWndProc(hWnd, uMsg, wParam, lParam); } if ( !sgbMouseDown ) { sgbMouseDown = 1; LABEL_21: SetCapture(hWnd); return 0; } return 0; } if ( uMsg == WM_LBUTTONUP ) { v5 = sgbMouseDown == 1; goto LABEL_23; } if ( uMsg != WM_RBUTTONDOWN ) { if ( uMsg != WM_RBUTTONUP ) { if ( uMsg == WM_CAPTURECHANGED ) { if ( hWnd != (HWND)lParam ) sgbMouseDown = 0; return 0; } return MainWndProc(hWnd, uMsg, wParam, lParam); } v5 = sgbMouseDown == 2; LABEL_23: if ( v5 ) { sgbMouseDown = 0; ReleaseCapture(); } return 0; } if ( !sgbMouseDown ) { sgbMouseDown = 2; goto LABEL_21; } return 0; } // 525748: using guessed type char sgbMouseDown; LRESULT __stdcall GM_Game(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { if ( uMsg > WM_LBUTTONDOWN ) { if ( uMsg == WM_LBUTTONUP ) { MouseX = (unsigned short)lParam; MouseY = (unsigned int)lParam >> 16; if ( sgbMouseDown != 1 ) return 0; sgbMouseDown = 0; LeftMouseUp(); track_repeat_walk(0); } else { if ( uMsg == WM_RBUTTONDOWN ) { MouseX = (unsigned short)lParam; MouseY = (unsigned int)lParam >> 16; if ( !sgbMouseDown ) { sgbMouseDown = 2; SetCapture(hWnd); RightMouseDown(); } return 0; } if ( uMsg != WM_RBUTTONUP ) { if ( uMsg == WM_CAPTURECHANGED ) { if ( hWnd != (HWND)lParam ) { sgbMouseDown = 0; track_repeat_walk(0); } } else if ( uMsg > WM_DIAB && uMsg <= WM_DIABRETOWN ) { if ( (unsigned char)gbMaxPlayers > 1u ) pfile_write_hero(); nthread_ignore_mutex(1); PaletteFadeOut(8); FreeMonsterSnd(); music_stop(); track_repeat_walk(0); sgbMouseDown = 0; ReleaseCapture(); ShowProgress(uMsg); drawpanflag = 255; DrawAndBlit(); if ( gbRunGame ) PaletteFadeIn(8); nthread_ignore_mutex(0); gbGameLoopStartup = 1; return 0; } return MainWndProc(hWnd, uMsg, wParam, lParam); } MouseX = (unsigned short)lParam; MouseY = (unsigned int)lParam >> 16; if ( sgbMouseDown != 2 ) return 0; sgbMouseDown = 0; } ReleaseCapture(); return 0; } switch ( uMsg ) { case WM_LBUTTONDOWN: MouseX = (unsigned short)lParam; MouseY = (unsigned int)lParam >> 16; if ( !sgbMouseDown ) { sgbMouseDown = 1; SetCapture(hWnd); track_repeat_walk(LeftMouseDown(wParam)); } return 0; case WM_KEYFIRST: PressKey(wParam); return 0; case WM_KEYUP: ReleaseKey(wParam); return 0; case WM_CHAR: PressChar(wParam); return 0; case WM_SYSKEYDOWN: if ( PressSysKey(wParam) ) return 0; return MainWndProc(hWnd, uMsg, wParam, lParam); case WM_SYSCOMMAND: if ( wParam == SC_CLOSE ) { gbRunGame = 0; gbRunGameResult = 0; return 0; } return MainWndProc(hWnd, uMsg, wParam, lParam); } if ( uMsg != WM_MOUSEFIRST ) return MainWndProc(hWnd, uMsg, wParam, lParam); MouseX = (unsigned short)lParam; MouseY = (unsigned int)lParam >> 16; gmenu_on_mouse_move((unsigned short)lParam); return 0; } // 525650: using guessed type int gbRunGame; // 525698: using guessed type int gbRunGameResult; // 52571C: using guessed type int drawpanflag; // 525748: using guessed type char sgbMouseDown; // 679660: using guessed type char gbMaxPlayers; bool __fastcall LeftMouseDown(int a1) { int v1; // edi int v3; // eax bool v6; // zf int v7; // ecx int v8; // eax unsigned char v9; // dl unsigned char v11; // dl unsigned short v12; // ax unsigned char v13; // dl unsigned short v15; // [esp-8h] [ebp-10h] v1 = a1; if ( gmenu_left_mouse(1) || control_check_talk_btn() || sgnTimeoutCurs ) return 0; if ( deathflag ) { control_check_btn_press(); return 0; } if ( PauseMode == 2 ) return 0; if ( doomflag ) { doom_close(); return 0; } if ( spselflag ) { SetSpell(); return 0; } if ( stextflag ) { CheckStoreBtn(); return 0; } if ( MouseY >= 352 ) { if ( !talkflag && !dropGoldFlag ) { if ( !gmenu_exception() ) CheckInvScrn(); } DoPanBtn(); if ( pcurs <= 1 || pcurs >= 12 ) return 0; goto LABEL_48; } if ( gmenu_exception() || TryIconCurs() ) return 0; if ( questlog && MouseX > 32 && MouseX < 288 && MouseY > 32 && MouseY < 308 ) { QuestlogESC(); return 0; } if ( qtextflag ) { qtextflag = 0; sfx_stop(); return 0; } if ( chrflag && MouseX < 320 ) { CheckChrBtns(); return 0; } if ( invflag && MouseX > 320 ) { if ( !dropGoldFlag ) CheckInvItem(); return 0; } if ( sbookflag && MouseX > 320 ) { CheckSBook(); return 0; } if ( pcurs >= CURSOR_FIRSTITEM ) { if ( !TryInvPut() ) return 0; NetSendCmdPItem(1u, CMD_PUTITEM, cursmx, cursmy); LABEL_48: SetCursor(CURSOR_HAND); return 0; } v3 = 21720 * myplr; if ( plr[myplr]._pStatPts && !spselflag ) CheckLvlBtn(); if ( lvlbtndown ) return 0; if ( leveltype != DTYPE_TOWN ) { v7 = abs(plr[myplr].WorldX - cursmx) < 2 && abs(plr[myplr].WorldY - cursmy) < 2; _HIWORD(v8) = _HIWORD(pcurs); if ( pcursitem != -1 && pcurs == 1 && v1 != 5 ) { _LOWORD(v8) = pcursitem; NetSendCmdLocParam1(1u, (invflag == 0) + CMD_GOTOGETITEM, cursmx, cursmy, v8); LABEL_96: if ( pcursitem != -1 ) return 0; v6 = pcursobj == -1; goto LABEL_98; } if ( pcursobj != -1 ) { if ( v1 != 5 || v7 && object[pcursobj]._oBreak == 1 ) { NetSendCmdLocParam1(1u, (pcurs == 5) + CMD_OPOBJXY, cursmx, cursmy, pcursobj); goto LABEL_95; } } if ( plr[myplr]._pwtype == 1 ) { if ( v1 == 5 ) { v9 = CMD_RATTACKXY; LABEL_84: NetSendCmdLoc(1u, v9, cursmx, cursmy); goto LABEL_95; } if ( pcursmonst != -1 ) { v15 = pcursmonst; if ( !CanTalkToMonst(pcursmonst) ) { v11 = CMD_RATTACKID; LABEL_89: NetSendCmdParam1(1u, v11, v15); goto LABEL_96; } LABEL_88: v11 = CMD_ATTACKID; goto LABEL_89; } _LOBYTE(v12) = pcursplr; if ( pcursplr == -1 || FriendlyMode ) goto LABEL_96; v13 = CMD_RATTACKPID; } else { if ( v1 == 5 ) { if ( pcursmonst == -1 || !CanTalkToMonst(pcursmonst) ) { v9 = CMD_SATTACKXY; goto LABEL_84; } v12 = pcursmonst; v13 = CMD_ATTACKID; LABEL_94: NetSendCmdParam1(1u, v13, v12); LABEL_95: if ( v1 == 5 ) return 0; goto LABEL_96; } if ( pcursmonst != -1 ) { v15 = pcursmonst; goto LABEL_88; } _LOBYTE(v12) = pcursplr; if ( pcursplr == -1 || FriendlyMode ) goto LABEL_96; v13 = CMD_ATTACKPID; } v12 = (char)v12; goto LABEL_94; } if ( pcursitem != -1 && pcurs == 1 ) { _LOWORD(v3) = pcursitem; NetSendCmdLocParam1(1u, (invflag == 0) + CMD_GOTOGETITEM, cursmx, cursmy, v3); } if ( pcursmonst != -1 ) NetSendCmdLocParam1(1u, CMD_TALKXY, cursmx, cursmy, pcursmonst); v6 = pcursitem == -1; LABEL_98: if ( v6 && pcursmonst == -1 && pcursplr == -1 ) return 1; return 0; } // 484368: using guessed type int FriendlyMode; // 4B84DC: using guessed type int dropGoldFlag; // 4B851C: using guessed type int lvlbtndown; // 4B8960: using guessed type int talkflag; // 4B8968: using guessed type int sbookflag; // 4B8C98: using guessed type int spselflag; // 4B8CC0: using guessed type char pcursitem; // 4B8CC1: using guessed type char pcursobj; // 4B8CC2: using guessed type char pcursplr; // 525740: using guessed type int PauseMode; // 52575C: using guessed type int doomflag; // 5BB1ED: using guessed type char leveltype; // 646D00: using guessed type char qtextflag; // 69BD04: using guessed type int questlog; // 6AA705: using guessed type char stextflag; bool __cdecl TryIconCurs() { unsigned char v0; // dl int v1; // edx int v2; // eax int v3; // eax int v4; // ST0C_4 int v5; // eax switch ( pcurs ) { case CURSOR_RESURRECT: v0 = CMD_RESURRECT; LABEL_3: NetSendCmdParam1(1u, v0, pcursplr); return 1; case CURSOR_HEALOTHER: v0 = CMD_HEALOTHER; goto LABEL_3; case CURSOR_TELEKINESIS: DoTelekinesis(); return 1; case CURSOR_IDENTIFY: if ( pcursinvitem != -1 ) { CheckIdentify(myplr, pcursinvitem); return 1; } LABEL_26: SetCursor(CURSOR_HAND); return 1; case CURSOR_REPAIR: if ( pcursinvitem != -1 ) { DoRepair(myplr, pcursinvitem); return 1; } goto LABEL_26; case CURSOR_RECHARGE: if ( pcursinvitem != -1 ) { DoRecharge(myplr, pcursinvitem); return 1; } goto LABEL_26; case CURSOR_TELEPORT: v1 = plr[myplr]._pTSpell; if ( pcursmonst == -1 ) { if ( pcursplr == -1 ) { v4 = GetSpellLevel(myplr, v1); v5 = 21720 * myplr; _LOWORD(v5) = plr[myplr]._pTSpell; NetSendCmdLocParam2(1u, CMD_TSPELLXY, cursmx, cursmy, v5, v4); } else { v3 = GetSpellLevel(myplr, v1); NetSendCmdParam3(1u, CMD_TSPELLPID, pcursplr, plr[myplr]._pTSpell, v3); } } else { v2 = GetSpellLevel(myplr, v1); NetSendCmdParam3(1u, CMD_TSPELLID, pcursmonst, plr[myplr]._pTSpell, v2); } goto LABEL_26; } if ( pcurs == CURSOR_DISARM && pcursobj == -1 ) goto LABEL_26; return 0; } // 4B8CB8: using guessed type char pcursinvitem; // 4B8CC1: using guessed type char pcursobj; // 4B8CC2: using guessed type char pcursplr; void __cdecl LeftMouseUp() { gmenu_left_mouse(0); control_release_talk_btn(); if ( panbtndown ) CheckBtnUp(); if ( chrbtnactive ) ReleaseChrBtns(); if ( lvlbtndown ) ReleaseLvlBtn(); if ( stextflag ) ReleaseStoreBtn(); } // 4B851C: using guessed type int lvlbtndown; // 4B87A8: using guessed type int chrbtnactive; // 4B8C90: using guessed type int panbtndown; // 6AA705: using guessed type char stextflag; void __cdecl RightMouseDown() { if ( !gmenu_exception() && sgnTimeoutCurs == CURSOR_NONE && PauseMode != 2 && !plr[myplr]._pInvincible ) { if ( doomflag ) { doom_close(); } else if ( !stextflag ) { if ( spselflag ) { SetSpell(); } else if ( MouseY >= 352 || (!sbookflag || MouseX <= 320) && !TryIconCurs() && (pcursinvitem == -1 || !UseInvItem(myplr, pcursinvitem)) ) { if ( pcurs == 1 ) { if ( pcursinvitem == -1 || !UseInvItem(myplr, pcursinvitem) ) CheckPlrSpell(); } else if ( pcurs > 1 && pcurs < 12 ) { SetCursor(CURSOR_HAND); } } } } } // 4B8968: using guessed type int sbookflag; // 4B8C98: using guessed type int spselflag; // 4B8CB8: using guessed type char pcursinvitem; // 525740: using guessed type int PauseMode; // 52575C: using guessed type int doomflag; // 6AA705: using guessed type char stextflag; bool __fastcall PressSysKey(int wParam) { if ( gmenu_exception() || wParam != VK_F10 ) return 0; diablo_hotkey_msg(1); return 1; } void __fastcall diablo_hotkey_msg(int dwMsg) { int v1; // esi char *v2; // eax char Filename[260]; // [esp+4h] [ebp-154h] char ReturnedString[80]; // [esp+108h] [ebp-50h] v1 = dwMsg; if ( gbMaxPlayers != 1 ) { if ( !GetModuleFileName(ghInst, Filename, 0x104u) ) TermMsg("Can't get program name"); v2 = strrchr(Filename, '\\'); if ( v2 ) *v2 = 0; strcat(Filename, "\\Diablo.ini"); GetPrivateProfileString("NetMsg", spszMsgKeyTbl[v1], spszMsgTbl[v1], ReturnedString, 0x50u, Filename); NetSendCmdString(-1, ReturnedString); } } // 48436C: using guessed type char *spszMsgTbl[4]; // 48437C: using guessed type char *spszMsgKeyTbl[4]; // 679660: using guessed type char gbMaxPlayers; void __fastcall ReleaseKey(int vkey) { if ( vkey == VK_SNAPSHOT ) CaptureScreen(); } void __fastcall PressKey(int vkey) { int v1; // esi int v2; // ecx int v3; // ecx signed int v4; // eax v1 = vkey; if ( !gmenu_presskeys(vkey) && !control_presskeys(v1) ) { if ( !deathflag ) goto LABEL_113; if ( sgnTimeoutCurs == CURSOR_NONE ) { if ( v1 == VK_F9 ) diablo_hotkey_msg(0); if ( v1 == VK_F10 ) diablo_hotkey_msg(1); if ( v1 == VK_F11 ) diablo_hotkey_msg(2); if ( v1 == VK_F12 ) diablo_hotkey_msg(3); if ( v1 == VK_RETURN ) control_type_message(); if ( v1 == VK_ESCAPE ) { LABEL_113: if ( v1 == VK_ESCAPE ) { if ( !PressEscKey() ) { track_repeat_walk(0); gamemenu_previous(); } return; } if ( sgnTimeoutCurs == CURSOR_NONE && !dropGoldFlag ) { if ( v1 == VK_PAUSE ) { diablo_pause_game(); return; } if ( PauseMode != 2 ) { switch ( v1 ) { case VK_RETURN: if ( stextflag ) { STextEnter(); } else if ( questlog ) { QuestlogEnter(); } else { control_type_message(); } return; case VK_F1: if ( helpflag ) { helpflag = 0; return; } if ( stextflag ) { ClearPanel(); AddPanelString("No help available", 1); AddPanelString("while in stores", 1); track_repeat_walk(0); return; } invflag = 0; chrflag = 0; sbookflag = 0; spselflag = 0; if ( qtextflag && leveltype == DTYPE_TOWN) { qtextflag = 0; sfx_stop(); } questlog = 0; automapflag = 0; msgdelay = 0; gamemenu_off(); DisplayHelp(); LABEL_110: doom_close(); return; #ifdef _DEBUG case VK_F3: if ( pcursitem != -1 ) { sprintf(tempstr, "IDX = %i : Seed = %i : CF = %i", item[pcursitem].IDidx, item[pcursitem]._iSeed, item[pcursitem]._iCreateInfo); NetSendCmdString(1 << myplr, tempstr); } sprintf(tempstr, "Numitems : %i", numitems); NetSendCmdString(1 << myplr, tempstr); return; case VK_F4: PrintDebugQuest(); return; #endif case VK_F5: v2 = 0; goto LABEL_48; case VK_F6: v2 = 1; goto LABEL_48; case VK_F7: v2 = 2; goto LABEL_48; case VK_F8: v2 = 3; LABEL_48: if ( spselflag ) SetSpeedSpell(v2); else ToggleSpell(v2); return; case VK_F9: v3 = 0; LABEL_59: diablo_hotkey_msg(v3); return; case VK_F10: v3 = 1; goto LABEL_59; case VK_F11: v3 = 2; goto LABEL_59; case VK_F12: v3 = 3; goto LABEL_59; case VK_UP: if ( stextflag ) { STextUp(); } else if ( questlog ) { QuestlogUp(); } else if ( helpflag ) { HelpScrollUp(); } else if ( automapflag ) { AutomapUp(); } return; case VK_DOWN: if ( stextflag ) { STextDown(); } else if ( questlog ) { QuestlogDown(); } else if ( helpflag ) { HelpScrollDown(); } else if ( automapflag ) { AutomapDown(); } return; case VK_PRIOR: if ( stextflag ) STextPrior(); return; case VK_NEXT: if ( stextflag ) STextNext(); return; case VK_LEFT: if ( automapflag && !talkflag ) AutomapLeft(); return; case VK_RIGHT: if ( automapflag && !talkflag ) AutomapRight(); return; case VK_TAB: DoAutoMap(); return; case VK_SPACE: if ( !chrflag ) { if ( !invflag ) { LABEL_106: helpflag = 0; invflag = 0; chrflag = 0; sbookflag = 0; spselflag = 0; if ( qtextflag && leveltype == DTYPE_TOWN ) { qtextflag = 0; sfx_stop(); } questlog = 0; automapflag = 0; msgdelay = 0; gamemenu_off(); goto LABEL_110; } v4 = MouseX; if ( MouseX >= 480 || MouseY >= 352 ) { LABEL_101: if ( !invflag && chrflag && v4 > 160 && MouseY < 352 ) SetCursorPos(v4 - 160, MouseY); goto LABEL_106; } SetCursorPos(MouseX + 160, MouseY); } v4 = MouseX; goto LABEL_101; } } } } } } } // 4B84DC: using guessed type int dropGoldFlag; // 4B8960: using guessed type int talkflag; // 4B8968: using guessed type int sbookflag; // 4B8C98: using guessed type int spselflag; // 525740: using guessed type int PauseMode; // 52B9F0: using guessed type char msgdelay; // 5BB1ED: using guessed type char leveltype; // 646D00: using guessed type char qtextflag; // 69BD04: using guessed type int questlog; // 6AA705: using guessed type char stextflag; void __cdecl diablo_pause_game() { if ( (unsigned char)gbMaxPlayers <= 1u ) { if ( PauseMode ) { PauseMode = 0; } else { PauseMode = 2; FreeMonsterSnd(); track_repeat_walk(0); } drawpanflag = 255; } } // 52571C: using guessed type int drawpanflag; // 525740: using guessed type int PauseMode; // 679660: using guessed type char gbMaxPlayers; void __fastcall PressChar(int vkey) { int v1; // ebx BOOL v4; // ecx int v5; // ecx int v6; // eax BOOL v7; // ecx int v9; // ecx int v10; // eax int v11; // eax int v12; // eax int v13; // eax int v14; // eax int v15; // eax int v16; // eax int v18; // [esp-4h] [ebp-8h] v1 = vkey; if ( !gmenu_exception() && !control_talk_last_key(v1) && sgnTimeoutCurs == CURSOR_NONE && !deathflag ) { if ( (_BYTE)v1 == 'p' || (_BYTE)v1 == 'P' ) { diablo_pause_game(); } else if ( PauseMode != 2 ) { if ( doomflag ) { doom_close(); return; } if ( dropGoldFlag ) { control_drop_gold(v1); return; } switch ( v1 ) { case '!': case '1': v9 = myplr; v10 = plr[myplr].SpdList[0]._itype; if ( v10 != -1 && v10 != 11 ) { v18 = 47; goto LABEL_72; } return; case '#': case '3': v9 = myplr; v12 = plr[myplr].SpdList[2]._itype; if ( v12 != -1 && v12 != 11 ) { v18 = 49; goto LABEL_72; } return; case '$': case '4': v9 = myplr; v13 = plr[myplr].SpdList[3]._itype; if ( v13 != -1 && v13 != 11 ) { v18 = 50; goto LABEL_72; } return; case '%': case '5': v9 = myplr; v14 = plr[myplr].SpdList[4]._itype; if ( v14 != -1 && v14 != 11 ) { v18 = 51; goto LABEL_72; } return; case '&': case '7': v9 = myplr; v16 = plr[myplr].SpdList[6]._itype; if ( v16 != -1 && v16 != 11 ) { v18 = 53; goto LABEL_72; } return; case '*': case '8': #ifdef _DEBUG if ( debug_mode_key_inverted_v || debug_mode_key_w ) { NetSendCmd(1, CMD_CHEAT_EXPERIENCE); return; } #endif v9 = myplr; if ( plr[myplr].SpdList[7]._itype != -1 && plr[myplr].SpdList[7]._itype != 11 ) { v18 = 54; goto LABEL_72; } return; case '+': case '=': if ( automapflag ) AutomapZoomIn(); return; case '-': case '_': if ( automapflag ) AutomapZoomOut(); return; case '2': case '@': v9 = myplr; v11 = plr[myplr].SpdList[1]._itype; if ( v11 != -1 && v11 != 11 ) { v18 = 48; goto LABEL_72; } return; case '6': case '^': v9 = myplr; v15 = plr[myplr].SpdList[5]._itype; if ( v15 != -1 && v15 != 11 ) { v18 = 52; LABEL_72: UseInvItem(v9, v18); } return; case 'B': case 'b': if ( !stextflag ) { invflag = 0; sbookflag = sbookflag == 0; } return; case 'C': case 'c': if ( !stextflag ) { questlog = 0; v7 = chrflag == 0; chrflag = chrflag == 0; if ( !v7 || invflag ) goto LABEL_18; goto LABEL_24; } return; case 'F': case 'f': IncreaseGamma(); return; case 'G': case 'g': DecreaseGamma(); return; case 'I': case 'i': if ( stextflag ) return; sbookflag = 0; v4 = invflag == 0; invflag = invflag == 0; if ( !v4 || chrflag ) { LABEL_24: if ( MouseX < 480 ) { v5 = MouseY; if ( MouseY < 352 ) { v6 = MouseX + 160; goto LABEL_27; } } } else { LABEL_18: if ( MouseX > 160 ) { v5 = MouseY; if ( MouseY < 352 ) { v6 = MouseX - 160; LABEL_27: SetCursorPos(v6, v5); return; } } } break; case 'Q': case 'q': if ( !stextflag ) { chrflag = 0; if ( questlog ) questlog = 0; else StartQuestlog(); } return; case 'S': case 's': if ( !stextflag ) { invflag = 0; if ( spselflag ) spselflag = 0; else DoSpeedBook(); track_repeat_walk(0); } return; case 'V': NetSendCmdString(1 << myplr, gszVersionNumber); return; case 'v': NetSendCmdString(1 << myplr, gszProductName); return; case 'Z': case 'z': zoomflag = zoomflag == 0; return; #ifdef _DEBUG case ')': case '0': if ( debug_mode_key_inverted_v ) { if ( arrowdebug > 2 ) arrowdebug = 0; if ( !arrowdebug ) { plr[myplr]._pIFlags &= ~ISPL_FIRE_ARROWS; plr[myplr]._pIFlags &= ~ISPL_LIGHT_ARROWS; } if ( arrowdebug == 1 ) plr[myplr]._pIFlags |= ISPL_FIRE_ARROWS; if ( arrowdebug == 2 ) plr[myplr]._pIFlags |= ISPL_LIGHT_ARROWS; arrowdebug++; } return; case ':': if ( !currlevel && debug_mode_key_w ) SetAllSpellsCheat(); return; case '[': if ( !currlevel && debug_mode_key_w ) TakeGoldCheat(); return; case ']': if ( !currlevel && debug_mode_key_w ) MaxSpellsCheat(); return; case 'a': if ( debug_mode_key_inverted_v ) { spelldata[SPL_TELEPORT].sTownSpell = 1; plr[myplr]._pSplLvl[plr[myplr]._pSpell]++; } return; case 'D': PrintDebugPlayer(1); return; case 'd': PrintDebugPlayer(0); return; case 'e': if ( debug_mode_key_d ) { sprintf(tempstr, "EFlag = %i", plr[myplr]._peflag); NetSendCmdString(1 << myplr, tempstr); } return; case 'L': case 'l': if ( debug_mode_key_inverted_v ) ToggleLighting(); return; case 'M': NextDebugMonster(); return; case 'm': GetDebugMonster(); return; case 'R': case 'r': sprintf(tempstr, "seed = %i", glSeedTbl[currlevel]); NetSendCmdString(1 << myplr, tempstr); sprintf(tempstr, "Mid1 = %i : Mid2 = %i : Mid3 = %i", glMid1Seed[currlevel], glMid2Seed[currlevel], glMid3Seed[currlevel]); NetSendCmdString(1 << myplr, tempstr); sprintf(tempstr, "End = %i", glEndSeed[currlevel]); NetSendCmdString(1 << myplr, tempstr); return; case 'T': case 't': if ( debug_mode_key_inverted_v ) { sprintf(tempstr, "PX = %i PY = %i", plr[myplr].WorldX, plr[myplr].WorldY); NetSendCmdString(1 << myplr, tempstr); sprintf(tempstr, "CX = %i CY = %i DP = %i", cursmx, cursmy, dungeon[cursmx][cursmy]); NetSendCmdString(1 << myplr, tempstr); } return; case '|': if ( !currlevel && debug_mode_key_w ) GiveGoldCheat(); return; case '~': if ( !currlevel && debug_mode_key_w ) StoresCheat(); return; #endif default: return; } } } } // 4B84DC: using guessed type int dropGoldFlag; // 4B8968: using guessed type int sbookflag; // 4B8C98: using guessed type int spselflag; // 52569C: using guessed type int zoomflag; // 525740: using guessed type int PauseMode; // 52575C: using guessed type int doomflag; // 69BD04: using guessed type int questlog; // 6AA705: using guessed type char stextflag; void __cdecl LoadLvlGFX() { switch(leveltype) { case DTYPE_TOWN: pDungeonCels = LoadFileInMem("Levels\\TownData\\Town.CEL", 0); pMegaTiles = LoadFileInMem("Levels\\TownData\\Town.TIL", 0); pLevelPieces = LoadFileInMem("Levels\\TownData\\Town.MIN", 0); level_special_cel = LoadFileInMem("Levels\\TownData\\TownS.CEL", 0); break; case DTYPE_CATHEDRAL: pDungeonCels = LoadFileInMem("Levels\\L1Data\\L1.CEL", 0); pMegaTiles = LoadFileInMem("Levels\\L1Data\\L1.TIL", 0); pLevelPieces = LoadFileInMem("Levels\\L1Data\\L1.MIN", 0); level_special_cel = LoadFileInMem("Levels\\L1Data\\L1S.CEL", 0); break; case DTYPE_CATACOMBS: pDungeonCels = LoadFileInMem("Levels\\L2Data\\L2.CEL", 0); pMegaTiles = LoadFileInMem("Levels\\L2Data\\L2.TIL", 0); pLevelPieces = LoadFileInMem("Levels\\L2Data\\L2.MIN", 0); level_special_cel = LoadFileInMem("Levels\\L2Data\\L2S.CEL", 0); break; case DTYPE_CAVES: pDungeonCels = LoadFileInMem("Levels\\L3Data\\L3.CEL", 0); pMegaTiles = LoadFileInMem("Levels\\L3Data\\L3.TIL", 0); pLevelPieces = LoadFileInMem("Levels\\L3Data\\L3.MIN", 0); level_special_cel = LoadFileInMem("Levels\\L1Data\\L1S.CEL", 0); break; case DTYPE_HELL: pDungeonCels = LoadFileInMem("Levels\\L4Data\\L4.CEL", 0); pMegaTiles = LoadFileInMem("Levels\\L4Data\\L4.TIL", 0); pLevelPieces = LoadFileInMem("Levels\\L4Data\\L4.MIN", 0); level_special_cel = LoadFileInMem("Levels\\L2Data\\L2S.CEL", 0); break; default: TermMsg("LoadLvlGFX"); return; } } // 5BB1ED: using guessed type char leveltype; void __cdecl LoadAllGFX() { pSpeedCels = DiabloAllocPtr(0x100000); IncProgress(); IncProgress(); InitObjectGFX(); IncProgress(); InitMissileGFX(); IncProgress(); } void __fastcall CreateLevel(int lvldir) { int hnd; // cl switch ( leveltype ) { case DTYPE_TOWN: CreateTown(lvldir); InitTownTriggers(); hnd = 0; break; case DTYPE_CATHEDRAL: CreateL5Dungeon(glSeedTbl[currlevel], lvldir); InitL1Triggers(); Freeupstairs(); hnd = 1; break; case DTYPE_CATACOMBS: CreateL2Dungeon(glSeedTbl[currlevel], lvldir); InitL2Triggers(); Freeupstairs(); hnd = 2; break; case DTYPE_CAVES: CreateL3Dungeon(glSeedTbl[currlevel], lvldir); InitL3Triggers(); Freeupstairs(); hnd = 3; break; case DTYPE_HELL: CreateL4Dungeon(glSeedTbl[currlevel], lvldir); InitL4Triggers(); Freeupstairs(); hnd = 4; break; default: TermMsg("CreateLevel"); return; } LoadRndLvlPal(hnd); } // 5BB1ED: using guessed type char leveltype; void __fastcall LoadGameLevel(BOOL firstflag, int lvldir) { int v2; // ebp bool visited; // edx int i; // ecx int j; // eax v2 = 0; if ( setseed ) glSeedTbl[currlevel] = setseed; music_stop(); SetCursor(CURSOR_HAND); SetRndSeed(glSeedTbl[currlevel]); IncProgress(); MakeLightTable(); LoadLvlGFX(); IncProgress(); if ( firstflag ) { InitInv(); InitItemGFX(); InitQuestText(); if ( gbMaxPlayers ) { for(i = 0; i < gbMaxPlayers; i++) InitPlrGFXMem(i); } InitStores(); InitAutomapOnce(); InitHelp(); } SetRndSeed(glSeedTbl[currlevel]); if ( leveltype == DTYPE_TOWN) SetupTownStores(); IncProgress(); InitAutomap(); if ( leveltype != DTYPE_TOWN && lvldir != 4 ) { InitLighting(); InitVision(); } InitLevelMonsters(); IncProgress(); if ( !setlevel ) { CreateLevel(lvldir); IncProgress(); FillSolidBlockTbls(); SetRndSeed(glSeedTbl[currlevel]); if ( leveltype != DTYPE_TOWN ) { GetLevelMTypes(); InitThemes(); LoadAllGFX(); } else { InitMissileGFX(); } IncProgress(); if ( lvldir == 3 ) GetReturnLvlPos(); if ( lvldir == 5 ) GetPortalLvlPos(); IncProgress(); for(i = 0; i < MAX_PLRS; i++) { if ( plr[i].plractive ) { if ( currlevel == plr[i].plrlevel ) { InitPlayerGFX(v2); if ( lvldir != 4 ) InitPlayer(v2, firstflag); } } ++v2; } PlayDungMsgs(); InitMultiView(); IncProgress(); visited = 0; if ( gbMaxPlayers > 0 ) { for(i = 0; i < gbMaxPlayers; i++) { if ( plr[i].plractive ) visited = visited || plr[i]._pLvlVisited[currlevel]; } } SetRndSeed(glSeedTbl[currlevel]); if ( leveltype != DTYPE_TOWN) { if ( firstflag || lvldir == 4 || !plr[myplr]._pLvlVisited[currlevel] || gbMaxPlayers != 1 ) { HoldThemeRooms(); glMid1Seed[currlevel] = GetRndSeed(); InitMonsters(); glMid2Seed[currlevel] = GetRndSeed(); InitObjects(); InitItems(); CreateThemeRooms(); glMid3Seed[currlevel] = GetRndSeed(); InitMissiles(); InitDead(); glEndSeed[currlevel] = GetRndSeed(); if ( gbMaxPlayers != 1 ) DeltaLoadLevel(); IncProgress(); SavePreLighting(); goto LABEL_55; } InitMonsters(); InitMissiles(); InitDead(); IncProgress(); LoadLevel(); LABEL_54: IncProgress(); LABEL_55: if ( gbMaxPlayers == 1 ) ResyncQuests(); else ResyncMPQuests(); goto LABEL_72; } for(i = 0; i < 112; i++) { for(j = 0; j < 112; j++) dFlags[i][j] |= 0x40; } InitTowners(); InitItems(); InitMissiles(); IncProgress(); if ( !firstflag && lvldir != 4 && plr[myplr]._pLvlVisited[currlevel] ) { if ( gbMaxPlayers != 1 ) goto LABEL_53; LoadLevel(); } if ( gbMaxPlayers == 1 ) goto LABEL_54; LABEL_53: DeltaLoadLevel(); goto LABEL_54; } pSpeedCels = DiabloAllocPtr(0x100000); LoadSetMap(); IncProgress(); GetLevelMTypes(); InitMonsters(); InitMissileGFX(); InitDead(); FillSolidBlockTbls(); IncProgress(); if ( lvldir == 5 ) GetPortalLvlPos(); for(i = 0; i < MAX_PLRS; i++) { if ( plr[i].plractive ) { if ( currlevel == plr[i].plrlevel ) { InitPlayerGFX(v2); if ( lvldir != 4 ) InitPlayer(v2, firstflag); } } ++v2; } InitMultiView(); IncProgress(); if ( firstflag || lvldir == 4 || !plr[myplr]._pSLvlVisited[(unsigned char)setlvlnum] ) { InitItems(); SavePreLighting(); } else { LoadLevel(); } InitMissiles(); IncProgress(); LABEL_72: SyncPortals(); for(i = 0; i < MAX_PLRS; i++) { if ( plr[i].plractive && plr[i].plrlevel == currlevel && (!plr[i]._pLvlChanging || i == myplr) ) { if ( plr[i]._pHitPoints <= 0 ) dFlags[plr[i].WorldX][plr[i].WorldY] |= 4; else if ( gbMaxPlayers == 1 ) dPlayer[plr[i].WorldX][plr[i].WorldY] = i + 1; else SyncInitPlrPos(i); } } if ( leveltype != DTYPE_TOWN ) SetDungeonMicros(); InitLightMax(); IncProgress(); IncProgress(); if ( firstflag ) { InitControlPan(); IncProgress(); } if ( leveltype != DTYPE_TOWN) { ProcessLightList(); ProcessVisionList(); } music_start((unsigned char)leveltype); //do // _LOBYTE(v19) = IncProgress(); while ( !IncProgress() ); if ( setlevel && setlvlnum == SL_SKELKING && quests[12]._qactive == 2 ) PlaySFX(USFX_SKING1); } // 525738: using guessed type int setseed; // 5BB1ED: using guessed type char leveltype; // 5CCB10: using guessed type char setlvlnum; // 5CF31D: using guessed type char setlevel; // 679660: using guessed type char gbMaxPlayers; void __fastcall game_loop(bool bStartup) { int v1; // ecx int v2; // esi v1 = bStartup != 0 ? 0x39 : 0; v2 = v1 + 3; if ( v1 != -3 ) { while ( 1 ) { --v2; if ( !multi_handle_delta() ) break; timeout_cursor(0); game_logic(); if ( gbRunGame ) { if ( gbMaxPlayers != 1 ) { if ( nthread_has_500ms_passed() ) { if ( v2 ) continue; } } } return; } timeout_cursor(1); } } // 525650: using guessed type int gbRunGame; // 679660: using guessed type char gbMaxPlayers; void __cdecl game_logic() { if ( PauseMode != 2 ) { if ( PauseMode == 1 ) PauseMode = 2; if ( gbMaxPlayers == 1 && gmenu_exception() ) { drawpanflag |= 1u; } else { if ( !gmenu_exception() && sgnTimeoutCurs == CURSOR_NONE ) { CheckCursMove(); track_process(); } if ( gbProcessPlayers ) ProcessPlayers(); if ( leveltype != DTYPE_TOWN ) { ProcessMonsters(); ProcessObjects(); ProcessMissiles(); ProcessItems(); ProcessLightList(); ProcessVisionList(); } else { ProcessTowners(); ProcessItems(); ProcessMissiles(); } #ifdef _DEBUG if ( debug_mode_key_inverted_v ) { if ( GetAsyncKeyState(VK_SHIFT) & 0x8000 ) ScrollView(); } #endif sound_update(); ClearPlrMsg(); CheckTriggers(); CheckQuests(); drawpanflag |= 1u; pfile_update(0); } } } // 5256A0: using guessed type int gbProcessPlayers; // 525718: using guessed type char cineflag; // 52571C: using guessed type int drawpanflag; // 525740: using guessed type int PauseMode; // 5BB1ED: using guessed type char leveltype; // 679660: using guessed type char gbMaxPlayers; void __fastcall timeout_cursor(bool bTimeout) { if ( bTimeout ) { if ( sgnTimeoutCurs == CURSOR_NONE && !sgbMouseDown ) { sgnTimeoutCurs = pcurs; multi_net_ping(); ClearPanel(); AddPanelString("-- Network timeout --", 1); AddPanelString("-- Waiting for players --", 1); SetCursor(CURSOR_HOURGLASS); drawpanflag = 255; } scrollrt_draw_game_screen(1); } else if ( sgnTimeoutCurs ) { SetCursor(sgnTimeoutCurs); sgnTimeoutCurs = 0; ClearPanel(); drawpanflag = 255; } } // 52571C: using guessed type int drawpanflag; // 525748: using guessed type char sgbMouseDown; void __cdecl diablo_color_cyc_logic() { DWORD v0; // eax v0 = GetTickCount(); if ( v0 - color_cycle_timer >= 0x32 ) { color_cycle_timer = v0; if ( palette_get_colour_cycling() ) { if ( leveltype == DTYPE_HELL ) { lighting_color_cycling(); } else if ( leveltype == DTYPE_CAVES ) { if ( fullscreen ) palette_update_caves(); } } } } // 484364: using guessed type int fullscreen; // 52574C: using guessed type int color_cycle_timer; // 5BB1ED: using guessed type char leveltype;
45,997
https://github.com/ye-yeshun/box86/blob/master/src/wrapped/generated/wrappedlibx11defs.h
Github Open Source
Open Source
MIT
2,022
box86
ye-yeshun
C
Code
17
83
/******************************************************************* * File automatically generated by rebuild_wrappers.py (v2.0.0.10) * *******************************************************************/ #ifndef __wrappedlibx11DEFS_H_ #define __wrappedlibx11DEFS_H_ #endif // __wrappedlibx11DEFS_H_
23,502
https://github.com/toothedsword/.tmux/blob/master/src/gitstatus.pl
Github Open Source
Open Source
WTFPL, MIT
null
.tmux
toothedsword
Perl
Code
25
86
use strict; use warnings; use utf8; my $t = `git status -s`; $t =~ s/\n/|/g; $t =~ s/^\s*//; $t = "|$t"; $t =~ s/\s[^\|]\|//g; print($t);
42,070
https://github.com/DNikitenko/design-patterns/blob/master/Patterns/State/StateTest.cs
Github Open Source
Open Source
MIT
null
design-patterns
DNikitenko
C#
Code
47
143
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Patterns.State { class StateTest : IPatternTest { public void Run() { var wizard = new Wizard(); while (!wizard.IsCompleted()) { wizard.ProcessUserInput(); wizard.NextStep(); } Console.WriteLine("Wizard has been completed successfully; press any key to exit"); Console.ReadKey(); } } }
5,313
https://github.com/robertorlowski/video-downloader/blob/master/src/components/Title.vue
Github Open Source
Open Source
MIT
2,020
video-downloader
robertorlowski
Vue
Code
58
277
<template> <div class="discover-banner max-w-full text-white pl-8 rounded-bl-lg pt-4 mb-8 flex"> <div class="w-1/2 flex-1"> <h1 class="font-normal mb-2">Video Downloader</h1> <h3 class="font-normal w-64 leading-normal text-grey-lighter">{{title}}</h3> </div> <div class="w-1/2 py-1 px-1 pr-12 text-white text-right"> <svg fill="currentColor" xmlns="http://www.w3.org/2000/svg" width="40" height="40" viewBox="0 0 20 20" > <path d="M13 8V2H7v6H2l8 8 8-8h-5zM0 18h20v2H0v-2z"></path> </svg> </div> </div> </template> <script> export default { props: ["title"] }; </script>
15,228
https://github.com/jonathanortegacardenas/mailcreator/blob/master/app/Http/Controllers/BlocksController.php
Github Open Source
Open Source
MIT
2,021
mailcreator
jonathanortegacardenas
PHP
Code
497
3,496
<?php namespace mailCreator\Http\Controllers; use Symfony\Component\HttpFoundation\Session\Session; use mailCreator\Blocks; use mailCreator\Campaigns; use Illuminate\Http\Request; use Illuminate\Support\Facades\Storage; use Illuminate\Support\Facades\File; use Illuminate\Http\Response; class BlocksController extends Controller{ public function listBlocks($id){ \Session::put('campaign_id',$id); $bl = new Blocks; $html = ""; $blocks = Blocks::where('campaign_id','=',$id)->orderBy('position')->get(); $campaign = Campaigns::find($id); $view = null; foreach($blocks as $b){ $html = $bl->getTemplate($b->type); $data = json_decode($b->content,true); foreach($data as $row => $value){ if(strstr($row,"image")){ $value = asset("uploads/".$value); } $html = str_replace("$$".$row."$$",$value,$html); } $html = str_replace("\$\$edit\$\$",asset('blocks/edit/'.$b->id),$html); $html = str_replace("\$\$trash\$\$",asset('blocks/delete/'.$b->id),$html); $html = str_replace("images/shadow.png",asset('img/shadow.png'),$html); $html = str_replace("\$\$shadow\$\$",asset('img/shadow.png'),$html); if(isset($campaign->color)){ $html = str_replace("\$\$color\$\$",$campaign->color,$html); } $html = str_replace("\$\$position\$\$",$b->position,$html); $view[] = $html; } return View('blocks/view',array('title'=>"Previsualizaci&oacute;n del Correo - Campa&ntilde;a ".$campaign->title,'message'=>"Previsualiza el correo electrónico que será enviado",'campaign'=>$campaign,'blocks'=>$view)); } public function addBlock(Request $request){ if($request->has('_token')){ $blockInfo = $request->all(); $saveArray = null; unset($blockInfo['_token']); $saveArray['type']=$blockInfo['type_selected']; unset($blockInfo['type_selected']); if($request->hasFile('image')){ $file = $request->file('image'); $extension = $file->getClientOriginalExtension(); $mime = $file->getClientMimeType(); $name = date('YmdGis').'_'.$file->getClientOriginalName(); $file->move(public_path().'/uploads/',$name); $blockInfo['image']=$name; } if($request->hasFile('image_right')){ $file = $request->file('image_right'); $extension = $file->getClientOriginalExtension(); $mime = $file->getClientMimeType(); $name = date('YmdGis').'_right_'.$file->getClientOriginalName(); $file->move(public_path().'/uploads/',$name); $blockInfo['image_right']=$name; } if($request->hasFile('image_left')){ $file = $request->file('image_left'); $extension = $file->getClientOriginalExtension(); $mime = $file->getClientMimeType(); $name = date('YmdGis').'_left_'.$file->getClientOriginalName(); $file->move(public_path().'/uploads/',$name); $blockInfo['image_left']=$name; } if($request->hasFile('image_1')){ $file = $request->file('image_1'); $extension = $file->getClientOriginalExtension(); $mime = $file->getClientMimeType(); $name = date('YmdGis').'_1_'.$file->getClientOriginalName(); $file->move(public_path().'/uploads/',$name); $blockInfo['image_1']=$name; } if($request->hasFile('image_2')){ $file = $request->file('image_2'); $extension = $file->getClientOriginalExtension(); $mime = $file->getClientMimeType(); $name = date('YmdGis').'_2_'.$file->getClientOriginalName(); $file->move(public_path().'/uploads/',$name); $blockInfo['image_2']=$name; } if($request->hasFile('image_3')){ $file = $request->file('image_3'); $extension = $file->getClientOriginalExtension(); $mime = $file->getClientMimeType(); $name = date('YmdGis').'_3_'.$file->getClientOriginalName(); $file->move(public_path().'/uploads/',$name); $blockInfo['image_3']=$name; } if($request->hasFile('image_4')){ $file = $request->file('image_4'); $extension = $file->getClientOriginalExtension(); $mime = $file->getClientMimeType(); $name = date('YmdGis').'_4_'.$file->getClientOriginalName(); $file->move(public_path().'/uploads/',$name); $blockInfo['image_4']=$name; } $saveArray['content']=json_encode($blockInfo); $saveArray['campaign_id'] = \Session::get('campaign_id'); $blocks = new Blocks(); $last = $blocks->getMaxPosition($saveArray['campaign_id'] ); $saveArray['position']=((is_null($last))?0:$last)+1; Blocks::create($saveArray); return Redirect('blocks/list/'.\Session::get('campaign_id')); } return View('blocks/create',array('title'=>"Agregar Bloque al correo",'message'=>'Puede agregar nuevos bloques para aumentar el contenido del correo electr&oacute;nico desde esta p&aacute;gina')); } public function editBlock($id,Request $request){ $bl = new Blocks; $block = Blocks::find($id); $html_form = $bl->getForm($block->type); $campaign = Campaigns::find($block->campaign_id); if($_POST){ $content = json_decode($block->content,true); $blockInfo = $request->all(); unset($blockInfo['_token']); unset($blockInfo['type_selected']); if($request->hasFile('image')){ $file = $request->file('image'); $extension = $file->getClientOriginalExtension(); $mime = $file->getClientMimeType(); $name = date('YmdGis').'_'.$file->getClientOriginalName(); $file->move(public_path().'/uploads/',$name); $blockInfo['image']=$name; }else{ if(isset($content['image'])) $blockInfo['image']=$content['image']; } if($request->hasFile('image_right')){ $file = $request->file('image_right'); $extension = $file->getClientOriginalExtension(); $mime = $file->getClientMimeType(); $name = date('YmdGis').'_right_'.$file->getClientOriginalName(); $file->move(public_path().'/uploads/',$name); $blockInfo['image_right']=$name; }else{ if(isset($content['image_right'])) $blockInfo['image_right']=$content['image_right']; } if($request->hasFile('image_left')){ $file = $request->file('image_left'); $extension = $file->getClientOriginalExtension(); $mime = $file->getClientMimeType(); $name = date('YmdGis').'_left_'.$file->getClientOriginalName(); $file->move(public_path().'/uploads/',$name); $blockInfo['image_left']=$name; }else{ if(isset($content['image_left'])) $blockInfo['image_left']=$content['image_left']; } if($request->hasFile('image_1')){ $file = $request->file('image_1'); $extension = $file->getClientOriginalExtension(); $mime = $file->getClientMimeType(); $name = date('YmdGis').'_1_'.$file->getClientOriginalName(); $file->move(public_path().'/uploads/',$name); $blockInfo['image_1']=$name; }else{ if(isset($content['image_1'])) $blockInfo['image_1']=$content['image_1']; } if($request->hasFile('image_2')){ $file = $request->file('image_2'); $extension = $file->getClientOriginalExtension(); $mime = $file->getClientMimeType(); $name = date('YmdGis').'_2_'.$file->getClientOriginalName(); $file->move(public_path().'/uploads/',$name); $blockInfo['image_2']=$name; }else{ if(isset($content['image_2'])) $blockInfo['image_2']=$content['image_2']; } if($request->hasFile('image_3')){ $file = $request->file('image_3'); $extension = $file->getClientOriginalExtension(); $mime = $file->getClientMimeType(); $name = date('YmdGis').'_3_'.$file->getClientOriginalName(); $file->move(public_path().'/uploads/',$name); $blockInfo['image_3']=$name; }else{ if(isset($content['image_3'])) $blockInfo['image_3']=$content['image_3']; } if($request->hasFile('image_4')){ $file = $request->file('image_4'); $extension = $file->getClientOriginalExtension(); $mime = $file->getClientMimeType(); $name = date('YmdGis').'_4_'.$file->getClientOriginalName(); $file->move(public_path().'/uploads/',$name); $blockInfo['image_4']=$name; }else{ if(isset($content['image_4'])) $blockInfo['image_4']=$content['image_4']; } $block->content = json_encode($blockInfo); $block->position = $blockInfo['position']; $block->save(); return Redirect('/blocks/list/'.$campaign->id); } $htmlData = $bl->getTemplate($block->type); $block = Blocks::find($id); $content = json_decode($block->content,true); foreach($content as $row=>$value){ if(strstr($row,'image')){ $value = asset('uploads/'.$value); } $htmlData = str_replace("\$\$".$row."\$\$",$value, $htmlData); $html_form = str_replace("\$\$".$row."\$\$",$value,$html_form); $html_form = str_replace("\$\$position\$\$",$block->position,$html_form); $htmlData = str_replace("\$\$edit\$\$",asset('blocks/edit/'.$bl->id),$htmlData); $htmlData = str_replace("\$\$trash\$\$",asset('blocks/delete/'.$bl->id),$htmlData); $htmlData = str_replace("images/shadow.png",asset('img/shadow.png'),$htmlData); $htmlData = str_replace("\$\$shadow\$\$",asset('img/shadow.png'),$htmlData); $htmlData = str_replace("\$\$color\$\$",$campaign->color,$htmlData); } return View('blocks/edit',array('title'=>'Editar bloque','message'=>'Realiza edici&oacute;n de un bloque previamente creado','form'=>$html_form,'html_data'=>$htmlData,'id'=>$id)); } public function deleteBlock($id){ $block = Blocks::find($id); $block->delete(); return Redirect('campaigns/list'); } }
26,472
https://github.com/stari-kashka/gatling-picatinny/blob/master/src/main/scala/ru/tinkoff/gatling/feeders/CurrentDateFeeder.scala
Github Open Source
Open Source
Apache-2.0
null
gatling-picatinny
stari-kashka
Scala
Code
28
141
package ru.tinkoff.gatling.feeders import io.gatling.core.feeder.Feeder import ru.tinkoff.gatling.utils.RandomDataGenerators import java.time.ZoneId import java.time.format.DateTimeFormatter object CurrentDateFeeder { def apply(paramName: String, datePattern: DateTimeFormatter, timezone: ZoneId = ZoneId.systemDefault()): Feeder[String] = feeder[String](paramName)( RandomDataGenerators.currentDate(datePattern, timezone)) }
7,404
https://github.com/laashub/LaasOps/blob/master/distribution/service/data/struct.py
Github Open Source
Open Source
Apache-2.0
2,020
LaasOps
laashub
Python
Code
186
649
import json from flask import Blueprint from ...component import form from ...component import mymysql app = Blueprint('distribution_data_struct', __name__, url_prefix='/distribution/data/struct') @app.route('/select', methods=['POST']) def select(): request_data = form.check(["did"]) return json.dumps(mymysql.execute(""" select id, code, meaning, reference_type from designer_data_struct where did = %(did)s """, request_data)) @app.route('/insert', methods=['POST']) def insert(): request_data = form.check(["did", "code", "meaning", "reference_type"]) code = request_data['code'] # insert column to data data mymysql.execute( 'ALTER TABLE designer_data_data_%(did)s ADD COLUMN ' + code + ' VARCHAR(255) DEFAULT NULL COMMENT %(meaning)s;', request_data) return json.dumps(mymysql.execute(""" insert into designer_data_struct(did, code, meaning, reference_type ) values (%(did)s, %(code)s, %(meaning)s, %(reference_type)s) """, request_data)) @app.route('/update', methods=['POST']) def update(): request_data = form.check(["did", "code", "meaning", "reference_type"]) code = request_data['code'] # update column to data data mymysql.execute( 'ALTER TABLE designer_data_data_%(did)s change ' + code + ' ' + code + ' VARCHAR(255) DEFAULT NULL COMMENT %(meaning)s;', request_data) return json.dumps(mymysql.execute(""" update designer_data_struct set code = %(code)s ,meaning = %(meaning)s where id = %(id)s """, request_data)) @app.route('/delete', methods=['POST']) def delete(): request_data = form.check(["id"]) code = request_data['code'] # delete column to data data mymysql.execute( 'ALTER TABLE designer_data_data_%(did)s drop ' + code, request_data) return json.dumps(mymysql.execute(""" delete from designer_data_struct where id = %(id)s """, request_data))
34,780
https://github.com/solgenomics/sgn/blob/master/.gitignore
Github Open Source
Open Source
MIT
2,023
sgn
solgenomics
Ignore List
Code
50
290
*~ TAGS static/documents/tempfiles !exists !.exists _build /Build MYMETA.yml *.sw? test.sh blib/* .#* *.bak static/data static/static_content cover_db lib/MyDevLibs.pm static/documents/img/secretom/.directory programs/*.o programs/draw_contigalign programs/fast_mapping sgn_local.conf sgn_testing.conf sgn_fixture.conf t/data/data/prod/tmp/ t/data/vigstool/vigs* *.log logfile*.txt MANIFEST* ./cgi-bin/secretom MYMETA.json tags .prove .Rhistory sgn_local_zea.conf nytprof.out system_message.txt #sgn_local.conf# sgn_local.conf.old export/* temp_images/* js/node_modules js/build js/test_build js/package-lock.json typescript docs/Gemfile.lock docs/_site/ .DS_Store sgn.iml
12,004
https://github.com/bugaoshuni/WeChatSportTweak/blob/master/WeChatHeads/APBase.h
Github Open Source
Open Source
MIT
2,018
WeChatSportTweak
bugaoshuni
Objective-C
Code
330
1,059
// // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard. // #import "MMObject.h" #import "WCTTableCoding.h" @class NSString, PublicWifiCache, PublicWifiPageInfo; @interface APBase : MMObject <WCTTableCoding> { NSString *ssid; NSString *mac; unsigned int opCode; PublicWifiCache *cache; unsigned int scene; NSString *qrCode; NSString *mpUrl; NSString *mid; NSString *checkUrl; NSString *sessionKey; NSString *password; unsigned int retcode; NSString *errMsg; int _state; int _actionCode; unsigned int _protocolType; NSString *_bannerText; NSString *_showUrl; double _expiredTime; NSString *_retMsg; PublicWifiPageInfo *_pageInfo; } + (const struct WCTProperty *)retMsg; + (const struct WCTProperty *)retcode; + (const struct WCTProperty *)protocolType; + (const struct WCTProperty *)checkUrl; + (const struct WCTProperty *)mid; + (const struct WCTProperty *)mpUrl; + (const struct WCTProperty *)qrCode; + (const struct WCTProperty *)expiredTime; + (const struct WCTProperty *)showUrl; + (const struct WCTProperty *)bannerText; + (const struct WCTProperty *)actionCode; + (const struct WCTProperty *)opCode; + (const struct WCTProperty *)mac; + (const struct WCTProperty *)ssid; + (const struct WCTAnyProperty *)AnyProperty; + (const list_2812bee2 *)AllProperties; + (const struct WCTBinding *)objectRelationalMappingForWCDB; @property(retain, nonatomic) PublicWifiPageInfo *pageInfo; // @synthesize pageInfo=_pageInfo; @property(copy, nonatomic) NSString *retMsg; // @synthesize retMsg=_retMsg; @property(nonatomic) unsigned int protocolType; // @synthesize protocolType=_protocolType; @property(nonatomic) double expiredTime; // @synthesize expiredTime=_expiredTime; @property(copy, nonatomic) NSString *showUrl; // @synthesize showUrl=_showUrl; @property(copy, nonatomic) NSString *bannerText; // @synthesize bannerText=_bannerText; @property(nonatomic) int actionCode; // @synthesize actionCode=_actionCode; @property(nonatomic) int state; // @synthesize state=_state; @property(copy, nonatomic) NSString *checkUrl; // @synthesize checkUrl; @property(copy, nonatomic) NSString *mid; // @synthesize mid; @property(nonatomic) unsigned int opCode; // @synthesize opCode; @property(copy, nonatomic) NSString *mpUrl; // @synthesize mpUrl; @property(nonatomic) unsigned int retcode; // @synthesize retcode; @property(copy, nonatomic) NSString *qrCode; // @synthesize qrCode; @property(retain, nonatomic) NSString *mac; // @synthesize mac; @property(retain, nonatomic) NSString *ssid; // @synthesize ssid; @property(copy, nonatomic) NSString *password; // @synthesize password; @property(copy, nonatomic) NSString *sessionKey; // @synthesize sessionKey; @property(nonatomic) unsigned int scene; // @synthesize scene; @property(nonatomic) __weak PublicWifiCache *cache; // @synthesize cache; - (void).cxx_destruct; - (void)handleHomeBarClicked:(id)arg1; - (_Bool)canStartWithCurrSSID:(id)arg1; - (void)cancel; - (void)start; - (id)description; - (id)init; - (void)dealloc; // Remaining properties @property(nonatomic) _Bool isAutoIncrement; @property(nonatomic) long long lastInsertedRowID; @end
18,128
https://github.com/cecelo01/ServiceLocatorPatternDI-LocalizadorDeServico/blob/master/build/classes/service/locator/pattern/di/localiazadordeservico/ServicoEmail.rs
Github Open Source
Open Source
MIT
null
ServiceLocatorPatternDI-LocalizadorDeServico
cecelo01
Rust
Code
1
12
service.locator.pattern.ServicoEmail
32,336
https://github.com/VaibhavBhujade/Blockchain-ERP-interoperability/blob/master/odoo-13.0/addons/im_livechat/models/mail_channel.py
Github Open Source
Open Source
MIT
null
Blockchain-ERP-interoperability
VaibhavBhujade
Python
Code
697
2,440
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models, _ class ChannelPartner(models.Model): _inherit = 'mail.channel.partner' @api.model def unpin_old_livechat_sessions(self): """ Unpin livechat sessions with no activity for at least one day to clean the operator's interface """ self.env.cr.execute(""" UPDATE mail_channel_partner SET is_pinned = false WHERE id in ( SELECT cp.id FROM mail_channel_partner cp INNER JOIN mail_channel c on c.id = cp.channel_id WHERE c.channel_type = 'livechat' AND cp.is_pinned is true AND cp.write_date < current_timestamp - interval '1 day' ) """) class MailChannel(models.Model): """ Chat Session Reprensenting a conversation between users. It extends the base method for anonymous usage. """ _name = 'mail.channel' _inherit = ['mail.channel', 'rating.mixin'] anonymous_name = fields.Char('Anonymous Name') channel_type = fields.Selection(selection_add=[('livechat', 'Livechat Conversation')]) livechat_channel_id = fields.Many2one('im_livechat.channel', 'Channel') livechat_operator_id = fields.Many2one('res.partner', string='Operator', help="""Operator for this specific channel""") country_id = fields.Many2one('res.country', string="Country", help="Country of the visitor of the channel") _sql_constraints = [('livechat_operator_id', "CHECK((channel_type = 'livechat' and livechat_operator_id is not null) or (channel_type != 'livechat'))", 'Livechat Operator ID is required for a channel of type livechat.')] def _compute_is_chat(self): super(MailChannel, self)._compute_is_chat() for record in self: if record.channel_type == 'livechat': record.is_chat = True def _channel_message_notifications(self, message, message_format=False): """ When a anonymous user create a mail.channel, the operator is not notify (to avoid massive polling when clicking on livechat button). So when the anonymous person is sending its FIRST message, the channel header should be added to the notification, since the user cannot be listining to the channel. """ livechat_channels = self.filtered(lambda x: x.channel_type == 'livechat') other_channels = self.filtered(lambda x: x.channel_type != 'livechat') notifications = super(MailChannel, livechat_channels)._channel_message_notifications(message.with_context(im_livechat_use_username=True)) + \ super(MailChannel, other_channels)._channel_message_notifications(message, message_format) for channel in self: # add uuid for private livechat channels to allow anonymous to listen if channel.channel_type == 'livechat' and channel.public == 'private': notifications.append([channel.uuid, notifications[0][1]]) if not message.author_id: unpinned_channel_partner = self.mapped('channel_last_seen_partner_ids').filtered(lambda cp: not cp.is_pinned) if unpinned_channel_partner: unpinned_channel_partner.write({'is_pinned': True}) notifications = self._channel_channel_notifications(unpinned_channel_partner.mapped('partner_id').ids) + notifications return notifications def channel_fetch_message(self, last_id=False, limit=20): """ Override to add the context of the livechat username.""" channel = self.with_context(im_livechat_use_username=True) if self.channel_type == 'livechat' else self return super(MailChannel, channel).channel_fetch_message(last_id=last_id, limit=limit) def channel_info(self, extra_info=False): """ Extends the channel header by adding the livechat operator and the 'anonymous' profile :rtype : list(dict) """ channel_infos = super(MailChannel, self).channel_info(extra_info) channel_infos_dict = dict((c['id'], c) for c in channel_infos) for channel in self: # add the last message date if channel.channel_type == 'livechat': # add the operator id if channel.livechat_operator_id: res = channel.livechat_operator_id.with_context(im_livechat_use_username=True).name_get()[0] channel_infos_dict[channel.id]['operator_pid'] = (res[0], res[1].replace(',', '')) # add the anonymous or partner name channel_infos_dict[channel.id]['correspondent_name'] = channel._channel_get_livechat_partner_name() last_msg = self.env['mail.message'].search([("channel_ids", "in", [channel.id])], limit=1) if last_msg: channel_infos_dict[channel.id]['last_message_date'] = last_msg.date return list(channel_infos_dict.values()) @api.model def channel_fetch_slot(self): values = super(MailChannel, self).channel_fetch_slot() pinned_channels = self.env['mail.channel.partner'].search([('partner_id', '=', self.env.user.partner_id.id), ('is_pinned', '=', True)]).mapped('channel_id') values['channel_livechat'] = self.search([('channel_type', '=', 'livechat'), ('id', 'in', pinned_channels.ids)]).channel_info() return values def _channel_get_livechat_partner_name(self): if self.livechat_operator_id in self.channel_partner_ids: partners = self.channel_partner_ids - self.livechat_operator_id if partners: partner_name = False for partner in partners: if not partner_name: partner_name = partner.name else: partner_name += ', %s' % partner.name if partner.country_id: partner_name += ' (%s)' % partner.country_id.name return partner_name if self.anonymous_name: return self.anonymous_name return _("Visitor") @api.model def remove_empty_livechat_sessions(self): hours = 1 # never remove empty session created within the last hour self.env.cr.execute(""" SELECT id as id FROM mail_channel C WHERE NOT EXISTS ( SELECT * FROM mail_message_mail_channel_rel R WHERE R.mail_channel_id = C.id ) AND C.channel_type = 'livechat' AND livechat_channel_id IS NOT NULL AND COALESCE(write_date, create_date, (now() at time zone 'UTC'))::timestamp < ((now() at time zone 'UTC') - interval %s)""", ("%s hours" % hours,)) empty_channel_ids = [item['id'] for item in self.env.cr.dictfetchall()] self.browse(empty_channel_ids).unlink() def _define_command_history(self): return { 'channel_types': ['livechat'], 'help': _('See 15 last visited pages') } def _execute_command_history(self, **kwargs): notification = [] notification_values = { '_type': 'history_command', } notification.append([self.uuid, dict(notification_values)]) return self.env['bus.bus'].sendmany(notification) def _send_history_message(self, pid, page_history): message_body = _('No history found') if page_history: html_links = ['<li><a href="%s" target="_blank">%s</a></li>' % (page, page) for page in page_history] message_body = '<span class="o_mail_notification"><ul>%s</ul></span>' % (''.join(html_links)) self.env['bus.bus'].sendone((self._cr.dbname, 'res.partner', pid), { 'body': message_body, 'channel_ids': self.ids, 'info': 'transient_message', }) # Rating Mixin def _rating_get_parent_field_name(self): return 'livechat_channel_id' def _email_livechat_transcript(self, email): company = self.env.user.company_id render_context = { "company": company, "channel": self, } template = self.env.ref('im_livechat.livechat_email_template') mail_body = template.render(render_context, engine='ir.qweb', minimal_qcontext=True) mail_body = self.env['mail.thread']._replace_local_links(mail_body) mail = self.env['mail.mail'].create({ 'subject': _('Conversation with %s') % self.livechat_operator_id.name, 'email_from': self.env.company.email, 'email_to': email, 'body_html': mail_body, }) mail.send()
23,157
https://github.com/flixtechs-labs/laravel-bytepoint/blob/master/config/bytepoint.php
Github Open Source
Open Source
MIT
2,023
laravel-bytepoint
flixtechs-labs
PHP
Code
16
76
<?php // config for FlixtechsLabs/Bytepoint return [ 'token' => env('BYTEPOINT_TOKEN', ''), 'url' => env('BYTEPOINT_URL', 'https://bytepoint.flixtechs.co.zw/api/v1/images'), ];
28,235
https://github.com/wenleix/presto/blob/master/presto-main/src/main/java/com/facebook/presto/sql/planner/iterative/rule/PruneIndexSourceColumns.java
Github Open Source
Open Source
Apache-2.0
2,022
presto
wenleix
Java
Code
198
784
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.sql.planner.iterative.rule; import com.facebook.presto.spi.ColumnHandle; import com.facebook.presto.spi.plan.PlanNodeIdAllocator; import com.facebook.presto.spi.predicate.TupleDomain; import com.facebook.presto.sql.planner.Symbol; import com.facebook.presto.sql.planner.plan.IndexSourceNode; import com.facebook.presto.sql.planner.plan.PlanNode; import com.google.common.collect.Maps; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import static com.facebook.presto.sql.planner.plan.Patterns.indexSource; import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.collect.ImmutableSet.toImmutableSet; public class PruneIndexSourceColumns extends ProjectOffPushDownRule<IndexSourceNode> { public PruneIndexSourceColumns() { super(indexSource()); } @Override protected Optional<PlanNode> pushDownProjectOff(PlanNodeIdAllocator idAllocator, IndexSourceNode indexSourceNode, Set<Symbol> referencedOutputs) { Set<Symbol> prunedLookupSymbols = indexSourceNode.getLookupSymbols().stream() .filter(referencedOutputs::contains) .collect(toImmutableSet()); Map<Symbol, ColumnHandle> prunedAssignments = Maps.filterEntries( indexSourceNode.getAssignments(), entry -> referencedOutputs.contains(entry.getKey()) || tupleDomainReferencesColumnHandle(indexSourceNode.getCurrentConstraint(), entry.getValue())); List<Symbol> prunedOutputList = indexSourceNode.getOutputSymbols().stream() .filter(referencedOutputs::contains) .collect(toImmutableList()); return Optional.of( new IndexSourceNode( indexSourceNode.getId(), indexSourceNode.getIndexHandle(), indexSourceNode.getTableHandle(), prunedLookupSymbols, prunedOutputList, prunedAssignments, indexSourceNode.getCurrentConstraint())); } private static boolean tupleDomainReferencesColumnHandle( TupleDomain<ColumnHandle> tupleDomain, ColumnHandle columnHandle) { return tupleDomain.getDomains() .map(domains -> domains.containsKey(columnHandle)) .orElse(false); } }
15,396
https://github.com/buxinzeyou/vue-music/blob/master/src/components/tabbar/hotsong.vue
Github Open Source
Open Source
MIT
null
vue-music
buxinzeyou
Vue
Code
247
1,060
<template> <div class="hot-container"> <div class="header"> <div class="header"> <img src="http://s3.music.126.net/mobile-new/img/hot_music_bg_2x.jpg?f01a252389c26bcf016816242eaa6aee=" alt /> </div> <div class="jingling title"></div> <span>更新时间:04月13日</span> </div> <div class="hotsong-list"> <router-link :to="'/song/'+item.id" class="hotsong-item" v-for="(item, index) in hotsong" :key="index" tag="div"> <div class="index">{{index+1}}</div> <div class="info"> <div class="left"> <h3>{{item.name}}{{item.alia[0] ? '('+item.alia[0]+')' : ''}}</h3> <p>{{item.ar[0].name}}-{{item.name}}</p> </div> <div class="right"> <span class="jingling play"></span> </div> </div> </router-link> </div> </div> </template> <script> export default { data() { return { hotsong: [] }; }, created() { this.getHotSongList(); }, methods: { getHotSongList() { this.$http.get("top/list?idx=1").then(result => { this.hotsong = result.body.playlist.tracks; }); } } }; </script> <style lang="scss" scoped> .hot-container { .jingling { background: url("http://s3.music.126.net/mobile-new/img/index_icon_2x.png?5207a28c3767992ca4bb6d4887c74880=") no-repeat; } .header { margin-top: 119px; position: relative; img { width: 100%; height: 100%; } .title { background-position: -24px -30px; background-size: 166px 97px; position: absolute; top: 25px; left: 20px; width: 142px; height: 67px; } span { color: #fff; font-size: 12px; -webkit-transform: scale(0.9); margin: 0; position: absolute; top: 100px; left: 17px; } } .hotsong-list { // padding-left: 10px; padding-bottom: 0; .hotsong-item { display: flex; flex: 1; .index { width: 40px; display: flex; align-items: center; justify-content: center; color: #999; } .info { flex: 0 0 90%; display: flex; justify-content: space-between; border-bottom: 1px solid #eee; .left { padding: 5px 0; h3 { font-size: 17px; font-weight: 400; } p { font-size: 12px; margin: 0; } hr { font-size: 0px; line-height: 0px; padding: 0px; margin: 0px; } } .right { width: 35px; display: flex; align-items: center; .play { display: inline-block; // background-color: red; width: 22px; height: 22px; background-position: -24px 0; background-size: 166px 97px; } } } } } } </style>
40
https://github.com/rajeshroy402/DeepStream-6.0-dGPU-Installation/blob/master/03_install_deepstream.sh
Github Open Source
Open Source
CC0-1.0
null
DeepStream-6.0-dGPU-Installation
rajeshroy402
Shell
Code
136
932
#! /bin/bash #author - rajeshroy402@gmail.com sudo echo "Hey, let's do the final hooby-dooby here!" cd ~/nvidia-debians-by-rajesh # Installing CUDA sudo sh cuda_11.4.3_470.82.01_linux.run sudo printf "export PATH=/usr/local/cuda-11.4/bin${PATH:+:${PATH}}\nexport LD_LIBRARY_PATH=/usr/local/cuda-11.4/lib64\${LD_LIBRARY_PATH:+:${LD_LIBRARY_PATH}}" >> /home/$USER/.bashrc source /home/$USER/.bashrc sudo ldconfig echo "Printing your CUDA details to confirm" nvcc --version #Installing NVIDIA driver Optimius sudo apt-get install nvidia-prime sudo prime-select nvidia #Installing TensorRT cd ~/nvidia-debians-by-rajesh sudo echo "deb https://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64 /" | sudo tee /etc/apt/sources.list.d/cuda-repo.list wget https://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64/7fa2af80.pub sudo apt-key add 7fa2af80.pub sudo apt-get update -y sudo apt-key adv --fetch-keys https://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64/3bf863cc.pub sudo apt-key adv --fetch-keys https://developer.download.nvidia.com/compute/machine-learning/repos/ubuntu1804/x86_64/7fa2af80.pub sudo dpkg -i nv-tensorrt-repo-ubuntu1804-cuda11.3-trt8.0.1.6-ga-20210626_1-1_amd64.deb sudo apt-key add /var/nv-tensorrt-repo-ubuntu1804-cuda11.3-trt8.0.1.6-ga-20210626/7fa2af80.pub sudo apt-get update -y sudo apt-get install libnvinfer8=8.0.1-1+cuda11.3 libnvinfer-plugin8=8.0.1-1+cuda11.3 libnvparsers8=8.0.1-1+cuda11.3 libnvonnxparsers8=8.0.1-1+cuda11.3 libnvinfer-bin=8.0.1-1+cuda11.3 libnvinfer-dev=8.0.1-1+cuda11.3 libnvinfer-plugin-dev=8.0.1-1+cuda11.3 libnvparsers-dev=8.0.1-1+cuda11.3 libnvonnxparsers-dev=8.0.1-1+cuda11.3 libnvinfer-samples=8.0.1-1+cuda11.3 libnvinfer-doc=8.0.1-1+cuda11.3 -y # Installing DeepStream SDK 6.0 cd ~/nvidia-debians-by-rajesh sudo apt-get install ./deepstream-6.0_6.0.0-1_amd64.deb rm ${HOME}/.cache/gstreamer-1.0/registry.x86_64.bin echo "Installation is completed !!!" echo "Please reboot your device"
9,018
https://github.com/Demivan/unplugin-auto-import/blob/master/test/fixtures/vue.js
Github Open Source
Open Source
MIT
2,022
unplugin-auto-import
Demivan
JavaScript
Code
4
9
const a = ref(0)
9,892
https://github.com/lainproliant/xeno/blob/master/xeno/recipe.py
Github Open Source
Open Source
BSD-3-Clause
2,023
xeno
lainproliant
Python
Code
2,135
6,987
# -------------------------------------------------------------------- # recipe.py # # Author: Lain Musgrove (lain.proliant@gmail.com) # Date: Thursday March 9, 2023 # # Distributed under terms of the MIT license. # -------------------------------------------------------------------- import asyncio import inspect import sys import uuid from dataclasses import dataclass from datetime import datetime, timedelta from enum import Enum from pathlib import Path from typing import Any, Callable, Generator, Iterable, Optional from xeno.events import Event, EventBus from xeno.shell import PathSpec, remove_paths from xeno.utils import async_map, async_vwrap, async_wrap, is_iterable # -------------------------------------------------------------------- UNICODE_SUPPORT = sys.stdout.encoding.lower().startswith("utf") # -------------------------------------------------------------------- class Events: CLEAN = "clean" DEBUG = "debug" ERROR = "error" FAIL = "fail" INFO = "info" START = "start" SUCCESS = "success" WARNING = "warning" END = "end" # -------------------------------------------------------------------- class BuildError(Exception): def __init__(self, recipe: "Recipe", msg=""): super().__init__(f"[{recipe.sigil()}] {msg}") self.recipe = recipe # -------------------------------------------------------------------- class CompositeError(Exception): def __init__( self, exceptions: Iterable[Exception], msg: str = "Multiple errors occurred." ): self.msg = msg self.exceptions = list(exceptions) super().__init__(self._compose_message()) def _indent_line(self, line: str, indent: int): return (" " * indent) + line def _compose_message(self, indent=0): sb = [] sb.append(self.msg) for exc in self.exceptions: header = f"{exc.__class__.__qualname__}: " lines = str(exc).split("\n") lines[0] = header + lines[0] for line in lines: sb.append(" " + line) return "\n".join(sb) # -------------------------------------------------------------------- ListedComponents = list["Recipe"] ComponentIterable = Iterable["Recipe"] MappedComponents = dict[str, "Recipe" | Iterable["Recipe"]] FormatF = Callable[["Recipe"], str] # -------------------------------------------------------------------- class Recipe: DEFAULT_TARGET_PARAM = "target" SIGIL_DELIMITER = ":" active: set["Recipe"] = set() class Format: @dataclass class Symbols: target: str start: str ok: str fail: str warning: str def __init__(self, unicode_symbols=True): if UNICODE_SUPPORT and unicode_symbols: self.symbols = self.Symbols( target="->", start="⚙", ok="✓", fail="✗", warning="⚠" ) else: self.symbols = self.Symbols( target="->", start="(*)", ok=":)", fail=":(", warning="/!\\" ) def clean(self, recipe: "Recipe") -> str: sb: list[str | Path] = [] sb.append("cleaned") if recipe.has_target(): sb.append(recipe.target) return " ".join([str(s) for s in sb]) def fail(self, recipe: "Recipe") -> str: return f"{self.symbols.fail} fail" def ok(self, recipe: "Recipe") -> str: return f"{self.symbols.ok} ok" def sigil(self, recipe: "Recipe") -> str: if recipe.has_target(): return f"{recipe.name}{Recipe.SIGIL_DELIMITER}{recipe.rtarget()}" return recipe.name def start(self, recipe: "Recipe") -> str: return f"{self.symbols.start} start" class FormatOverride(Format): def __init__(self, fmt: "Recipe.Format", **overrides): self.fmt = fmt for key in overrides.keys(): if not hasattr(fmt, key): raise ValueError(key) self.overrides = overrides def add_override(self, key: str, value: Any): self.overrides[key] = value def __getattribute__(self, name): if name in ("overrides", "fmt", "add_override"): return super().__getattribute__(name) if name in self.overrides: return self.overrides[name] else: return self.fmt.__getattribute__(name) class PassMode(Enum): NORMAL = 0 RESULTS = 1 TARGETS = 2 class ParamType(Enum): NORMAL = 0 RECIPE = 1 PATH = 2 class Scanner: def __init__(self): self._args: list[Any] = [] self._kwargs: dict[str, Any] = {} self._arg_offsets: list[int] = [] self._kwarg_keys: list[str] = [] self._paths: list[Path] = [] def clear(self): self._args.clear() self._kwargs.clear() self._arg_offsets.clear() self._kwarg_keys.clear() self._paths.clear() def _scan_one(self, arg) -> tuple[Any, "Recipe.ParamType"]: if isinstance(arg, Recipe): return arg, Recipe.ParamType.RECIPE if is_iterable(arg): arg = [*arg] if all(isinstance(x, Recipe) for x in arg): return arg, Recipe.ParamType.RECIPE if all(isinstance(x, Path) for x in arg): return arg, Recipe.ParamType.PATH if isinstance(arg, Path): return arg, Recipe.ParamType.PATH return arg, Recipe.ParamType.NORMAL def has_recipes(self): return self._arg_offsets or self._kwarg_keys def num_recipes(self): return len(self._arg_offsets) + len(self._kwarg_keys) async def gather_args(self): """ Await resolution of recipes in args and update args with their results. """ results = await asyncio.gather( *[v() if isinstance(v, Recipe) else async_vwrap(v) for v in self._args] ) self.scan_params(*results) def bind(self, f: Callable, mode: "Recipe.PassMode"): """ Bind args and kwargs to the given callable. """ return inspect.signature(f).bind(*self.args(mode), **self.kwargs(mode)) async def gather_kwargs(self): """ Await resolution of recipes in kwargs and update with their results. """ result_tuples = asyncio.gather( *[ async_map(k, v() if isinstance(v, Recipe) else async_vwrap(v)) for k, v in self._kwargs.items() ] ) results = {k: v for k, v in result_tuples} self.scan_params(**results) def gather_all(self): """ Await resolution of recipes in args and kwargs and update both with their results. """ return asyncio.gather(self.gather_args(), self.gather_kwargs()) def scan_params(self, *args, **kwargs): self.clear() for i, arg in enumerate(args): self.scan(arg, offset=i) for k, arg in kwargs.items(): self.scan(arg, key=k) def scan( self, arg, offset: Optional[int] = None, key: Optional[str] = None ) -> "Recipe.ParamType": arg, param_type = self._scan_one(arg) if param_type == Recipe.ParamType.PATH: if is_iterable(arg): self._paths.extend(arg) else: self._paths.append(arg) if offset is not None: self._args.append(arg) if param_type == Recipe.ParamType.RECIPE: self._arg_offsets.append(offset) elif key is not None: self._kwargs[key] = arg if param_type == Recipe.ParamType.RECIPE: self._kwarg_keys.append(key) return param_type def args(self, pass_mode: "Recipe.PassMode") -> list[Any]: match pass_mode: case Recipe.PassMode.NORMAL: return self._args case Recipe.PassMode.RESULTS: results = [*self._args] for offset in self._arg_offsets: value = results[offset] if is_iterable(value): results[offset] = [r.result() for r in value] else: results[offset] = value.result() return results case Recipe.PassMode.TARGETS: results = [*self._args] for offset in self._arg_offsets: value = results[offset] if is_iterable(value): results[offset] = [r.target_or(r) for r in value] else: results[offset] = value.target_or(value) return results def kwargs(self, pass_mode: "Recipe.PassMode") -> dict[str, Any]: match pass_mode: case Recipe.PassMode.NORMAL: return self._kwargs case Recipe.PassMode.RESULTS: results = {**self._kwargs} for key in self._kwarg_keys: value = results[key] if is_iterable(value): results[key] = [r.result() for r in value] else: results[key] = value.result() return results case Recipe.PassMode.TARGETS: results = {**self._kwargs} for key in self._kwarg_keys: value = results[key] if is_iterable(value): results[key] = [r.target_or(r) for r in value] else: results[key] = value.target_or(value) return results def paths(self): return self._paths def component_list(self) -> ListedComponents: return [self._args[x] for x in self._arg_offsets] def component_map(self) -> MappedComponents: return {k: self._kwargs[k] for k in self._kwarg_keys} def _flat_listed_components(self) -> Generator["Recipe", None, None]: for c in self.component_list(): if isinstance(c, Recipe): yield c else: yield from c def _flat_mapped_components(self) -> Generator["Recipe", None, None]: for c in self.component_map().values(): if isinstance(c, Recipe): yield c else: yield from c def components(self) -> Generator["Recipe", None, None]: yield from self._flat_listed_components() yield from self._flat_mapped_components() @classmethod def scan(cls, args: Iterable[Any], kwargs: dict[str, Any]) -> Scanner: """ Scan the given arguments for recipes, and return a tuple of offsets and keys where the recipes or recipe lists were found. Iterators are copied and instances of generators are expanded. Returns the scan results, consisting of a new args, kwargs, and lists of offsets and keys where recipes or recipe lists can be found. """ scanner = Recipe.Scanner() for i, arg in enumerate(args): scanner.scan(arg, offset=i) for k, arg in kwargs.items(): scanner.scan(arg, key=k) return scanner @classmethod def flat( cls, recipes: Iterable["Recipe"], visited: Optional[set["Recipe"]] = None ) -> Generator["Recipe", None, None]: visited = visited or set() for recipe in recipes: if recipe not in visited: visited.add(recipe) yield recipe yield from cls.flat(recipe.children, visited) def __init__( self, component_list: ComponentIterable = [], component_map: MappedComponents = {}, *, as_user: Optional[str] = None, deps: Iterable["Recipe"] = [], docs: Optional[str] = None, fmt: Format = Format(), keep=False, memoize=False, name="(nameless)", parent: Optional["Recipe"] = None, setup: Optional["Recipe"] = None, sigil: Optional[FormatF] = None, static_files: Iterable[PathSpec] = [], cleanup_files: Iterable[PathSpec] = [], sync=False, target: Optional[PathSpec] = None, ): self.component_list = [*component_list] self.component_map = component_map self.id = uuid.uuid4() self._callsign = "" self._children: list["Recipe"] = [] self._deps = [*deps] self._parent: Optional["Recipe"] = None self._target = None if target is None else Path(target) self.as_user = as_user self.docs = docs self.fmt = fmt self.keep = keep self.memoize = memoize self.name = name self.setup = setup self.static_files = [ Path(s) for s in static_files if target is None or Path(s) != Path(target) ] self.cleanup_files = [ Path(s) for s in cleanup_files if target is None or Path(s) != Path(target) ] self.sync = sync if parent: self.parent = parent if sigil: self.fmt = Recipe.FormatOverride(self.fmt, sigil=sigil) self.lock = asyncio.Lock() self.saved_result = None def __hash__(self): return hash(self.id) def __repr__(self): return f"<{self.callsign}>" def __iter__(self): yield from self.components() def arg(self, name: str | int): if isinstance(name, int): return self.component_list[name] elif isinstance(name, str): return self.component_map[name] else: raise ValueError(f"Invalid arg type: {type(name)}") @property def target(self) -> Path: assert self._target is not None, "There is no target." return self._target @target.setter def target(self, path: Path): self._target = path def has_target(self): return self._target is not None @property def parent(self) -> "Recipe": assert self._parent, "Recipe has no parent." return self._parent @parent.setter def parent(self, recipe: "Recipe"): self._parent = recipe if self not in self._parent._children: self._parent._children.append(self) @property def children(self) -> Iterable["Recipe"]: return [*self._children] @property def callsign(self) -> str: if not self._callsign: return self.sigil() return self._callsign @callsign.setter def callsign(self, sign: str): self._callsign = sign def has_parent(self): return self._parent is not None def sigil(self) -> str: return self.fmt.sigil(self) def log(self, event_name: str, data: Any = None): bus = EventBus.get() event = Event(event_name, self, data) bus.send(event) def error(self, msg) -> RuntimeError: exc = RuntimeError(msg) self.log(Events.ERROR, exc) return exc def has_components(self): try: next(self.components()) return True except StopIteration: return False def components(self) -> Generator["Recipe", None, None]: yield from self.component_list for c in self.component_map.values(): if isinstance(c, Recipe): yield c else: yield from c def composite_error(self, exceptions: Iterable[Exception], msg: str): exc = CompositeError(exceptions, msg) self.log(Events.ERROR, exc) return exc def age(self, ref: datetime) -> timedelta: if self.has_target() and self.target.exists(): return ref - datetime.fromtimestamp(self.target.stat().st_mtime) if self.has_target() and self.target.is_symlink(): return timedelta.min return timedelta.min def static_files_age(self, ref: datetime) -> timedelta: if not self.static_files: return timedelta.max else: return min( ref - datetime.fromtimestamp(f.stat().st_mtime) for f in self.static_files ) def components_age(self, ref: datetime) -> timedelta: if not self.has_components(): return timedelta.max else: return min(max(c.age(ref), c.inputs_age(ref)) for c in self.components()) def add_dependency(self, dep: "Recipe"): assert isinstance(dep, Recipe), f"Value `{dep}` is not a recipe." self._deps.append(dep) for component in self.components(): component.add_dependency(dep) def dependencies(self) -> Generator["Recipe", None, None]: yield from self._deps if self.has_parent(): yield from self.parent.dependencies() def dependencies_age(self, ref: datetime) -> timedelta: if not self.has_components(): return timedelta.max else: return min( max(dep.age(ref), dep.inputs_age(ref)) for dep in self.dependencies() ) def inputs_age(self, ref: datetime) -> timedelta: return min( self.static_files_age(ref), self.components_age(ref), self.dependencies_age(ref), ) def components_results(self) -> tuple[list[Any], dict[str, Any]]: results = [c.result() for c in self.component_list] mapped_results = {} for k, c in self.component_map.items(): if isinstance(c, Recipe): mapped_results[k] = c.result() else: mapped_results[k] = [r.result() for r in c] return results, mapped_results def done(self) -> bool: if self.has_target(): if self.target.is_symlink(): return True return self.target.exists() and not self.outdated(datetime.now()) return self.saved_result is not None def components_done(self) -> bool: return all(c.done() for c in self.components()) def outdated(self, ref: datetime) -> bool: if self.has_target() and self.target.is_symlink(): return False return self.age(ref) > self.inputs_age(ref) async def clean(self): remove_paths(*self.cleanup_files, as_user=self.as_user) if ( not self.has_target() or (not self.target.exists() and not self.target.is_symlink()) or self.keep ): return try: remove_paths(self.target, as_user=self.as_user) except Exception as e: raise self.error("Failed to clean target.") from e self.saved_result = None self.log(Events.CLEAN, self.target) async def clean_components(self, recursive=False): recipes = [*self.components()] if recursive: recipes.extend(self._deps) results = await asyncio.gather( *[c.clean() for c in recipes], *[c.clean_components(recursive=True) for c in recipes], ) else: results = await asyncio.gather( *(c.clean() for c in recipes), return_exceptions=True ) exceptions = [e for e in results if isinstance(e, Exception)] if exceptions: raise self.composite_error( exceptions, "Failed to clean one or more components." ) async def make_dependencies(self): recipes = [*self.dependencies()] if self.sync: for c in recipes: try: await c() except Exception as e: raise self.error("Failed to make a dependency.") from e else: results = await asyncio.gather( *(c() for c in recipes), return_exceptions=True ) exceptions = [e for e in results if isinstance(e, Exception)] if exceptions: raise self.composite_error( exceptions, "Failed to make one or more dependencies." ) async def make_components(self) -> tuple[list[Any], dict[str, Any]]: recipes = [*self.components()] if self.sync: results = [] for c in recipes: try: results.append(await c()) except Exception as e: raise self.error("Failed to make component.") from e return self.components_results() else: results = await asyncio.gather( *(c() for c in recipes), return_exceptions=True ) exceptions = [e for e in results if isinstance(e, Exception)] if exceptions: raise self.composite_error( exceptions, "Failed to make one or more components." ) return self.components_results() async def make(self): return [r.result() for r in self.components()] def result(self): if self.done() and self.has_target(): return self.target if self.saved_result is None: raise ValueError("Recipe result has not yet been recorded.") return self.saved_result def result_or(self, other): try: return self.result() except ValueError: return other def rtarget(self): try: return self.target.relative_to(Path.cwd()) except ValueError: return self.target def rtarget_or(self, other): if self._target is None: return other return self.rtarget() def target_or(self, other): if self._target is None: return other return self.target async def _resolve(self): await self.make_dependencies() self.log(Events.START) await self.make_components() result = await self.make() if is_iterable(result): scanner = Recipe.Scanner() scanner.scan_params(*result) while scanner.has_recipes(): await scanner.gather_all() result = scanner.args(pass_mode=Recipe.PassMode.RESULTS) elif isinstance(result, Recipe): result = await result() if self.has_target(): assert isinstance( result, str | Path ), "Recipe declared a file target, but the result was not a string or Path object." result = Path(result) assert ( result.resolve() == self.target.resolve() ), f"Recipe declared a file target, but the result path differs: {result} != {self.target}." self.saved_result = result if not self.done(): self.saved_result = None raise self.error("Recipe make() didn't complete successfully.") return result async def __call__(self): async with self.lock: if self.done(): if self.has_target(): return self.target elif self.memoize: return self.saved_result try: Recipe.active.add(self) if self.setup is not None: await self.setup() result = await self._resolve() self.log(Events.SUCCESS) return result except Exception as e: self.log(Events.FAIL, e) raise BuildError(self, str(e)) from e finally: Recipe.active.remove(self) # -------------------------------------------------------------------- class Lambda(Recipe): def __init__( self, f: Callable, lambda_args: list[Any], lambda_kwargs: dict[str, Any], docs: Optional[str] = None, pass_mode=Recipe.PassMode.RESULTS, target_param=Recipe.DEFAULT_TARGET_PARAM, **kwargs, ): if "name" not in kwargs: kwargs = {**kwargs, "name": f.__name__} scanner = Recipe.scan(lambda_args, lambda_kwargs) sig = inspect.signature(f) self.bound_args = sig.bind(*lambda_args, **lambda_kwargs) target = self.bound_args.arguments.get(target_param, None) super().__init__( scanner.component_list(), scanner.component_map(), static_files=scanner.paths(), target=target, docs=docs or f.__doc__, **kwargs, ) self.f = f self.pass_mode = pass_mode self.scanner = scanner def arg(self, name: str | int): if isinstance(name, str): return self.bound_args.arguments.get(name, None) else: return [*self.bound_args.arguments.values()][name] async def make(self): return await async_wrap( self.f, *self.scanner.args(self.pass_mode), **self.scanner.kwargs(self.pass_mode), )
15,350
https://github.com/naughty7878/spring-framework-5.2.4/blob/master/spring-my/src/main/java/com/test/circulardependence/doc/ObjectFactory.java
Github Open Source
Open Source
Apache-2.0
null
spring-framework-5.2.4
naughty7878
Java
Code
54
154
package com.test.circulardependence.doc; import org.springframework.beans.BeansException; /*** * @Author 徐庶 QQ:1092002729 * @Slogan 致敬大师,致敬未来的你 */ @FunctionalInterface public interface ObjectFactory<T> { /** * Return an instance (possibly shared or independent) * of the object managed by this factory. * @return the resulting instance * @throws BeansException in case of creation errors */ T getObject() throws BeansException; }
15,408
https://github.com/andela/ah-backend-stark/blob/master/authors/apps/profiles/urls.py
Github Open Source
Open Source
BSD-3-Clause
null
ah-backend-stark
andela
Python
Code
33
177
"""profile app url file""" from django.urls import path from .views import (UserProfile, ListProfiles, UserFollow, UserFollowers, UserFollowing, UserUnfollow) urlpatterns = [ path('profile/<str:username>/', UserProfile.as_view()), path('profiles/', ListProfiles.as_view()), path('profile/<str:username>/followers/', UserFollowers.as_view()), path('profile/<str:username>/following/', UserFollowing.as_view()), path('profile/<str:username>/follow/', UserFollow.as_view()), path('profile/<str:username>/unfollow/', UserUnfollow.as_view()) ]
8,393
https://github.com/commodityfx/weivim/blob/master/exchange/src/test/java/town/lost/examples/exchange/dto/OpeningBalanceEventTest.java
Github Open Source
Open Source
MIT
null
weivim
commodityfx
Java
Code
105
547
package town.lost.examples.exchange.dto; import net.openhft.chronicle.bytes.BytesStore; import net.openhft.chronicle.core.time.SetTimeProvider; import net.openhft.chronicle.decentred.util.DecentredUtil; import net.openhft.chronicle.decentred.util.KeyPair; import net.openhft.chronicle.wire.Marshallable; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; final class OpeningBalanceEventTest { static { DtoAliases.addAliases(); } @Test void balances() { KeyPair kp7 = new KeyPair(7); BytesStore publicKey1 = kp7.publicKey; BytesStore secretKey1 = kp7.secretKey; OpeningBalanceEvent obe = new OpeningBalanceEvent() .protocol(1).messageType(1) .balanceAddress(DecentredUtil.toAddress(publicKey1)); obe.balances().put(Currency.XCL, 128.0); obe.balances().put(Currency.USD, 10000.0); obe.balances().put(Currency.KRW, 11_000_000.0); obe.sign(secretKey1, new SetTimeProvider("2018-08-20T11:31:15.379010")); assertEquals("!OpeningBalanceEvent {\n" + " timestampUS: 2018-08-20T11:31:15.37901,\n" + " address: nphccofmpy6ci,\n" + " balanceAddress: nphccofmpy6ci,\n" + " balances: {\n" + " ? XCL: 128.0,\n" + " ? USD: 10E3,\n" + " ? KRW: 11E6\n" + " }\n" + "}\n", obe.toString()); OpeningBalanceEvent obe2 = Marshallable.fromString(obe.toString()); assertEquals(obe2, obe); } }
5,087
https://github.com/sliverTwo/vue-panel-selector/blob/master/src/App.vue
Github Open Source
Open Source
Unlicense
null
vue-panel-selector
sliverTwo
Vue
Code
249
923
<template> <div id="app" style="margin:5% auto;"> <h1>ok</h1> <vue-panel-selector :items="items"></vue-panel-selector> </div> </template> <script> let myCityData = [{ id: '100', name: '湖南', children: [{ id: '102', name: '湘潭', children: [] }, { id: '110', name: '长沙', children: [{ id: '111', name: '岳麓区' }, { id: '112', name: '开福区' }, { id: '113', name: '高新区' }, { id: '114', name: '望城区' }, { id: '115', name: '雨花区' }, { id: '116', name: '天心区' }, { id: '116', name: '宁乡县' }, { id: '116', name: '芙蓉区' }, { id: '116', name: '浏阳市' }, ] }, { id: '103', name: '邵阳', children: [] }, { id: '101', name: '岳阳', children: [] }, { id: '102', name: '衡阳', children: [] }, { id: '103', name: '怀化', children: [] }, ] }, { id: '002', name: '广东', children: [{ id: '201', name: '广州', children: [] }, { id: '202', name: '深圳', children: [] }, { id: '203', name: '韶关', children: [] }, { id: '204', name: '东莞', children: [] }, ] }, { id: '003', name: '四川', children: [{ id: '301', name: '成都', children: [] }, { id: '302', name: '绵阳', children: [] }, { id: '303', name: '自贡', children: [] }, ] }, { id: '004', name: '贵州', children: [] }, { id: '005', name: '江西', children: [] }] export default { name: 'app', data () { return { items: myCityData } } } </script> <style lang="scss"> #app { font-family: 'Avenir', Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px; } </style>
41,661
https://github.com/sathishid/PTS/blob/master/app/src/main/java/com/ara/approvalshipment/models/OrderItem.java
Github Open Source
Open Source
Apache-2.0
null
PTS
sathishid
Java
Code
88
308
package com.ara.approvalshipment.models; import com.google.gson.annotations.SerializedName; public class OrderItem { @SerializedName("oa_goods_id") private int gradeId; @SerializedName("oa_goods_code") private String gradeCode; @SerializedName("oa_goods_name") private String gradeName; private double soldQty; public int getGradeId() { return gradeId; } public void setGradeId(int gradeId) { this.gradeId = gradeId; } public String getGradeCode() { return gradeCode; } public void setGradeCode(String gradeCode) { this.gradeCode = gradeCode; } public String getGradeName() { return gradeName; } public void setGradeName(String gradeName) { this.gradeName = gradeName; } public double getSoldQty() { return soldQty; } public void setSoldQty(double soldQty) { this.soldQty = soldQty; } }
32,068
https://github.com/Tiger-Team-01/DSA-A-Z-Practice/blob/master/Sid's Levels/Level - 2/Greedy/FractionalKnapsack.cpp
Github Open Source
Open Source
MIT
2,022
DSA-A-Z-Practice
Tiger-Team-01
C++
Code
200
599
// { Driver Code Starts #include <bits/stdc++.h> using namespace std; struct Item{ int value; int weight; }; // } Driver Code Ends //class implemented /* struct Item{ int value; int weight; }; */ // function to return fractionalweights class Solution { public: //OM GAN GANAPATHAYE NAMO NAMAH //JAI SHRI RAM //JAI BAJRANGBALI //AMME NARAYANA, DEVI NARAYANA, LAKSHMI NARAYANA, BHADRE NARAYANA static bool cmp(struct Item a, struct Item b) { double r1 = (double) a.value/ (double) a.weight; double r2 = (double) b.value/ (double) b.weight; return r1 > r2; } double fractionalKnapsack(int W, Item arr[], int n) { sort(arr, arr+n, cmp); int curWeight = 0; double value = 0.0; for(int i = 0; i < n; i++) { if(curWeight + arr[i].weight <= W) { curWeight += arr[i].weight; value += arr[i].value; } else { int remain = W - curWeight; value += arr[i].value*((double)remain/ (double)arr[i].weight); break; } } return value; } }; // { Driver Code Starts. int main() { int t; //taking testcases cin>>t; cout<<setprecision(2)<<fixed; while(t--){ //size of array and weight int n, W; cin>>n>>W; Item arr[n]; //value and weight of each item for(int i=0;i<n;i++){ cin>>arr[i].value>>arr[i].weight; } //function call Solution ob; cout<<ob.fractionalKnapsack(W, arr, n)<<endl; } return 0; } // } Driver Code Ends
3,045
https://github.com/UCLA-SEAL/JShrink/blob/master/code/jshrink/jshrink-app/src/test/resources/bukkit/src/main/java/org/bukkit/event/vehicle/VehicleUpdateEvent.java
Github Open Source
Open Source
BSD-3-Clause
2,021
JShrink
UCLA-SEAL
Java
Code
52
150
package org.bukkit.event.vehicle; import org.bukkit.entity.Vehicle; import org.bukkit.event.HandlerList; /** * Called when a vehicle updates */ public class VehicleUpdateEvent extends VehicleEvent { private static final HandlerList handlers = new HandlerList(); public VehicleUpdateEvent(final Vehicle vehicle) { super(vehicle); } @Override public HandlerList getHandlers() { return handlers; } public static HandlerList getHandlerList() { return handlers; } }
14,752
ERROR: type should be string, got "https://github.com/dxg4268/pyExercises/blob/master/cbseBoard%.py"
Github Open Source
Open Source
MIT
null
pyExercises
dxg4268
Python
Code
143
287
# Program to find persentage acc to the input print("Enter Marks in 5 subjects accordingly !") # subjectsNum = str(input("Enter No. of Subjects from 5 to 10 : ")) sub1 = int(input("Subject 1 : ")) sub2 = int(input("Subject 2 : ")) sub3 = int(input("Subject 3 : ")) sub4 = int(input("Subject 4 : ")) sub5 = int(input("Subject 5 : ")) totalMarksObtained = sub1 + sub2 + sub3 + sub4 + sub5 print("Total Marks out of 500 : " + str(totalMarksObtained)) totalMarks = int(input("Enter Total Marks Possible : ")) percentage = totalMarksObtained/totalMarks * 100 print("Percentage is : " + str(percentage) + "%") if percentage >= 90 < 100: print("Congratulations you have got A grade !") elif percentage >= 80 < 90: print("You have got B Grade") elif percentage >= 70 < 80: print("You have got C Grade. Need Little improvement") else: print("Better Luck next Time")
44,392
https://github.com/IndahSeptiana/tugasweb/blob/master/application/views/admin/v_tambah_dosen.php
Github Open Source
Open Source
MIT
null
tugasweb
IndahSeptiana
PHP
Code
46
242
<div class="col-md-6 offset-md-3"> <div class="card"> <div class="card-header" style="background-color:pink"> <?php echo $sub_judul ?> </div> <div class="card-body"> <form action="" method="post"> <div class="form-group"> <label>Nik</label> <input type="text" class="form-control" name="nim"> </div> <div class="form-group"> <label>Nama Dosen</label> <input type="text" class="form-control" name="nama_mahasiswa"> </div> <div class="form-group"> <button class="btn btn-primary" type="submit">Simpan</button> </div> </form> </div> </div> </div>
6,373
https://github.com/NanoFabricFX/asset-manager/blob/master/src/AssetManager.Web/Views/StatusLabels/Delete.cshtml
Github Open Source
Open Source
MIT
2,020
asset-manager
NanoFabricFX
HTML+Razor
Code
102
464
@model AssetManager.Web.ViewModels.StatusLabelViewModel @{ ViewData["Title"] = "Delete"; } <div class="header-content"> <div class="row"> <div class="col-md-6 col-sm-6 col-xs-8"> <p class="header-content-title">Delete Status Label</p> </div> <div class="col-md-6 col-sm-6 col-xs-4"> <a asp-action="Index" class="pull-right btn btn-primary btn-create-new">Back</a> </div> </div> </div> <h3>Are you sure you want to delete this?</h3> <div> <hr /> <dl class="dl-horizontal"> <dt> @Html.DisplayNameFor(model => model.Name) </dt> <dd> @Html.DisplayFor(model => model.Name) </dd> <dt> @Html.DisplayNameFor(model => model.Type) </dt> <dd> @Html.DisplayFor(model => model.Type) </dd> <dt> @Html.DisplayNameFor(model => model.Notes) </dt> <dd> @Html.DisplayFor(model => model.Notes) </dd> <dt> @Html.DisplayNameFor(model => model.ShowInNav) </dt> <dd> @Html.DisplayFor(model => model.ShowInNav) </dd> </dl> <form asp-action="Delete"> <input type="submit" value="Delete" class="btn btn-default" /> | <a asp-action="Index">Back to List</a> </form> </div>
34,155
https://github.com/UVA-DSA/OpenPilot0.3.5/blob/master/selfdrive/common/params.h
Github Open Source
Open Source
MIT
2,017
OpenPilot0.3.5
UVA-DSA
C
Code
143
351
#ifndef _SELFDRIVE_COMMON_PARAMS_H_ #define _SELFDRIVE_COMMON_PARAMS_H_ #include <stddef.h> #ifdef __cplusplus extern "C" { #endif int write_db_value(const char* params_path, const char* key, const char* value, size_t value_size); // Reads a value from the params database. // Inputs: // params_path: The path of the database, eg /sdcard/params. // key: The key to read. // value: A pointer where a newly allocated string containing the db value will // be written. // value_sz: A pointer where the size of value will be written. Does not // include the NULL terminator. // // Returns: Negative on failure, otherwise 0. int read_db_value(const char* params_path, const char* key, char** value, size_t* value_sz); // Reads a value from the params database, blocking until successful. // Inputs are the same as read_db_value. void read_db_value_blocking(const char* params_path, const char* key, char** value, size_t* value_sz); #ifdef __cplusplus } // extern "C" #endif #endif // _SELFDRIVE_COMMON_PARAMS_H_
34,462
https://github.com/madedit/aclang/blob/master/src/yyparser.cpp
Github Open Source
Open Source
MIT
2,021
aclang
madedit
C++
Code
14,368
48,988
/* A Bison parser, made by GNU Bison 3.0.2. */ /* Bison implementation for Yacc-like parsers in C Copyright (C) 1984, 1989-1990, 2000-2013 Free Software Foundation, Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* As a special exception, you may create a larger work that contains part or all of the Bison parser skeleton and distribute that work under terms of your choice, so long as that work isn't itself a parser generator using the skeleton or a modified version thereof as a parser skeleton. Alternatively, if you modify or redistribute the parser skeleton itself, you may (at your option) remove this special exception, which will cause the skeleton and the resulting Bison output files to be licensed under the GNU General Public License without this special exception. This special exception was added by the Free Software Foundation in version 2.2 of Bison. */ /* C LALR(1) parser skeleton written by Richard Stallman, by simplifying the original so-called "semantic" parser. */ /* All symbols defined below should begin with yy or YY, to avoid infringing on user name space. This should be done even for local variables, as they might otherwise be expanded by user macros. There are some unavoidable exceptions within include files to define necessary library symbols; they are noted "INFRINGES ON USER NAME SPACE" below. */ /* Identify Bison output. */ #define YYBISON 1 /* Bison version. */ #define YYBISON_VERSION "3.0.2" /* Skeleton name. */ #define YYSKELETON_NAME "yacc.c" /* Pure parsers. */ #define YYPURE 2 /* Push parsers. */ #define YYPUSH 0 /* Pull parsers. */ #define YYPULL 1 /* Copy the first part of user declarations. */ #line 1 "yyparser.y" /* yacc.c:339 */ /* see copyright notice in aclang.h */ #include "ac_ast.h" #include "ac_token.h" #include "ac_parser.h" extern int yylex(YYSTYPE* yylval, void* parser); extern int yyparse(void* parser); #define PARSER ((acParser*)parser) #define yyerror(P, MSG) ((acParser*)P)->getMsgHandler()->error(yylval.token, MSG) //int yyerror(const char *s) { std::printf("Error: %s\n", s); return 1; } #line 82 "yyparser.cpp" /* yacc.c:339 */ # ifndef YY_NULLPTR # if defined __cplusplus && 201103L <= __cplusplus # define YY_NULLPTR nullptr # else # define YY_NULLPTR 0 # endif # endif /* Enabling verbose error messages. */ #ifdef YYERROR_VERBOSE # undef YYERROR_VERBOSE # define YYERROR_VERBOSE 1 #else # define YYERROR_VERBOSE 1 #endif /* In a future release of Bison, this section will be replaced by #include "yyparser.hpp". */ #ifndef YY_YY_YYPARSER_HPP_INCLUDED # define YY_YY_YYPARSER_HPP_INCLUDED /* Debug traces. */ #ifndef YYDEBUG # define YYDEBUG 1 #endif #if YYDEBUG extern int yydebug; #endif /* Token type. */ #ifndef YYTOKENTYPE # define YYTOKENTYPE enum yytokentype { IFX = 258, TOK_ELSE = 259, THISX = 260, TOK_DOT = 261, TOK_LBRACKET = 262, TOK_UNKNOWN = 263, TOK_EOF = 264, TOK_EOL = 265, TOK_SPACE = 266, TOK_COMMENT = 267, TOK_IDENTIFIER = 268, TOK_STRING = 269, TOK_CHAR = 270, TOK_UNS32 = 271, TOK_UNS64 = 272, TOK_FLOAT32 = 273, TOK_FLOAT64 = 274, TOK_DIV = 275, TOK_DIVASS = 276, TOK_DOTDOT = 277, TOK_DOTDOTDOT = 278, TOK_AND = 279, TOK_ANDASS = 280, TOK_ANDAND = 281, TOK_OR = 282, TOK_ORASS = 283, TOK_OROR = 284, TOK_MINUS = 285, TOK_MINUSASS = 286, TOK_MINUSMINUS = 287, TOK_PLUS = 288, TOK_PLUSASS = 289, TOK_PLUSPLUS = 290, TOK_LT = 291, TOK_LE = 292, TOK_SHL = 293, TOK_SHLASS = 294, TOK_LG = 295, TOK_LEG = 296, TOK_GT = 297, TOK_GE = 298, TOK_SHRASS = 299, TOK_USHRASS = 300, TOK_SHR = 301, TOK_USHR = 302, TOK_NOT = 303, TOK_NOTEQUAL = 304, TOK_UE = 305, TOK_UNORD = 306, TOK_UGE = 307, TOK_UG = 308, TOK_ULE = 309, TOK_UL = 310, TOK_LPAREN = 311, TOK_RPAREN = 312, TOK_RBRACKET = 313, TOK_LCURLY = 314, TOK_RCURLY = 315, TOK_QUESTION = 316, TOK_COMMA = 317, TOK_SEMICOLON = 318, TOK_COLON = 319, TOK_COLONCOLON = 320, TOK_DOLLAR = 321, TOK_ASSIGN = 322, TOK_EQUAL = 323, TOK_MUL = 324, TOK_MULASS = 325, TOK_MOD = 326, TOK_MODASS = 327, TOK_XOR = 328, TOK_XORASS = 329, TOK_CAT = 330, TOK_CATASS = 331, TOK_BASE = 332, TOK_BREAK = 333, TOK_CASE = 334, TOK_CATCH = 335, TOK_CONST = 336, TOK_CONTINUE = 337, TOK_DEFAULT = 338, TOK_DELEGATE = 339, TOK_DELETE = 340, TOK_DO = 341, TOK_ENUM = 342, TOK_EXTENDS = 343, TOK_FALSE = 344, TOK_FOR = 345, TOK_FOREACH = 346, TOK_FUNCTION = 347, TOK_IF = 348, TOK_IN = 349, TOK_INT = 350, TOK_LOCAL = 351, TOK_METAFUNCTION = 352, TOK_NAMESPACE = 353, TOK_NEW = 354, TOK_NULL = 355, TOK_RESUME = 356, TOK_RETURN = 357, TOK_SWITCH = 358, TOK_THIS = 359, TOK_THROW = 360, TOK_TRUE = 361, TOK_TRY = 362, TOK_VAR = 363, TOK_WHILE = 364, TOK_YIELD = 365, STOK_FILE = 366, STOK_LINE = 367, STOK_DATE = 368, STOK_TIME = 369, STOK_TIMESTAMP = 370, STOK_VENDOR = 371, STOK_VERSION = 372 }; #endif /* Value type. */ #if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED typedef union YYSTYPE YYSTYPE; union YYSTYPE { #line 33 "yyparser.y" /* yacc.c:355 */ acToken token; NodeAST* node; BlockAST* block; GetVarAST* getvar; FunctionAST* func; StringList* arglist; NodeASTList* nodelist; #line 250 "yyparser.cpp" /* yacc.c:355 */ }; # define YYSTYPE_IS_TRIVIAL 1 # define YYSTYPE_IS_DECLARED 1 #endif int yyparse (void* parser); #endif /* !YY_YY_YYPARSER_HPP_INCLUDED */ /* Copy the second part of user declarations. */ #line 264 "yyparser.cpp" /* yacc.c:358 */ #ifdef short # undef short #endif #ifdef YYTYPE_UINT8 typedef YYTYPE_UINT8 yytype_uint8; #else typedef unsigned char yytype_uint8; #endif #ifdef YYTYPE_INT8 typedef YYTYPE_INT8 yytype_int8; #else typedef signed char yytype_int8; #endif #ifdef YYTYPE_UINT16 typedef YYTYPE_UINT16 yytype_uint16; #else typedef unsigned short int yytype_uint16; #endif #ifdef YYTYPE_INT16 typedef YYTYPE_INT16 yytype_int16; #else typedef short int yytype_int16; #endif #ifndef YYSIZE_T # ifdef __SIZE_TYPE__ # define YYSIZE_T __SIZE_TYPE__ # elif defined size_t # define YYSIZE_T size_t # elif ! defined YYSIZE_T # include <stddef.h> /* INFRINGES ON USER NAME SPACE */ # define YYSIZE_T size_t # else # define YYSIZE_T unsigned int # endif #endif #define YYSIZE_MAXIMUM ((YYSIZE_T) -1) #ifndef YY_ # if defined YYENABLE_NLS && YYENABLE_NLS # if ENABLE_NLS # include <libintl.h> /* INFRINGES ON USER NAME SPACE */ # define YY_(Msgid) dgettext ("bison-runtime", Msgid) # endif # endif # ifndef YY_ # define YY_(Msgid) Msgid # endif #endif #ifndef YY_ATTRIBUTE # if (defined __GNUC__ \ && (2 < __GNUC__ || (__GNUC__ == 2 && 96 <= __GNUC_MINOR__))) \ || defined __SUNPRO_C && 0x5110 <= __SUNPRO_C # define YY_ATTRIBUTE(Spec) __attribute__(Spec) # else # define YY_ATTRIBUTE(Spec) /* empty */ # endif #endif #ifndef YY_ATTRIBUTE_PURE # define YY_ATTRIBUTE_PURE YY_ATTRIBUTE ((__pure__)) #endif #ifndef YY_ATTRIBUTE_UNUSED # define YY_ATTRIBUTE_UNUSED YY_ATTRIBUTE ((__unused__)) #endif #if !defined _Noreturn \ && (!defined __STDC_VERSION__ || __STDC_VERSION__ < 201112) # if defined _MSC_VER && 1200 <= _MSC_VER # define _Noreturn __declspec (noreturn) # else # define _Noreturn YY_ATTRIBUTE ((__noreturn__)) # endif #endif /* Suppress unused-variable warnings by "using" E. */ #if ! defined lint || defined __GNUC__ # define YYUSE(E) ((void) (E)) #else # define YYUSE(E) /* empty */ #endif #if defined __GNUC__ && 407 <= __GNUC__ * 100 + __GNUC_MINOR__ /* Suppress an incorrect diagnostic about yylval being uninitialized. */ # define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN \ _Pragma ("GCC diagnostic push") \ _Pragma ("GCC diagnostic ignored \"-Wuninitialized\"")\ _Pragma ("GCC diagnostic ignored \"-Wmaybe-uninitialized\"") # define YY_IGNORE_MAYBE_UNINITIALIZED_END \ _Pragma ("GCC diagnostic pop") #else # define YY_INITIAL_VALUE(Value) Value #endif #ifndef YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN # define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN # define YY_IGNORE_MAYBE_UNINITIALIZED_END #endif #ifndef YY_INITIAL_VALUE # define YY_INITIAL_VALUE(Value) /* Nothing. */ #endif #if ! defined yyoverflow || YYERROR_VERBOSE /* The parser invokes alloca or malloc; define the necessary symbols. */ # ifdef YYSTACK_USE_ALLOCA # if YYSTACK_USE_ALLOCA # ifdef __GNUC__ # define YYSTACK_ALLOC __builtin_alloca # elif defined __BUILTIN_VA_ARG_INCR # include <alloca.h> /* INFRINGES ON USER NAME SPACE */ # elif defined _AIX # define YYSTACK_ALLOC __alloca # elif defined _MSC_VER # include <malloc.h> /* INFRINGES ON USER NAME SPACE */ # define alloca _alloca # else # define YYSTACK_ALLOC alloca # if ! defined _ALLOCA_H && ! defined EXIT_SUCCESS # include <stdlib.h> /* INFRINGES ON USER NAME SPACE */ /* Use EXIT_SUCCESS as a witness for stdlib.h. */ # ifndef EXIT_SUCCESS # define EXIT_SUCCESS 0 # endif # endif # endif # endif # endif # ifdef YYSTACK_ALLOC /* Pacify GCC's 'empty if-body' warning. */ # define YYSTACK_FREE(Ptr) do { /* empty */; } while (0) # ifndef YYSTACK_ALLOC_MAXIMUM /* The OS might guarantee only one guard page at the bottom of the stack, and a page size can be as small as 4096 bytes. So we cannot safely invoke alloca (N) if N exceeds 4096. Use a slightly smaller number to allow for a few compiler-allocated temporary stack slots. */ # define YYSTACK_ALLOC_MAXIMUM 4032 /* reasonable circa 2006 */ # endif # else # define YYSTACK_ALLOC YYMALLOC # define YYSTACK_FREE YYFREE # ifndef YYSTACK_ALLOC_MAXIMUM # define YYSTACK_ALLOC_MAXIMUM YYSIZE_MAXIMUM # endif # if (defined __cplusplus && ! defined EXIT_SUCCESS \ && ! ((defined YYMALLOC || defined malloc) \ && (defined YYFREE || defined free))) # include <stdlib.h> /* INFRINGES ON USER NAME SPACE */ # ifndef EXIT_SUCCESS # define EXIT_SUCCESS 0 # endif # endif # ifndef YYMALLOC # define YYMALLOC malloc # if ! defined malloc && ! defined EXIT_SUCCESS void *malloc (YYSIZE_T); /* INFRINGES ON USER NAME SPACE */ # endif # endif # ifndef YYFREE # define YYFREE free # if ! defined free && ! defined EXIT_SUCCESS void free (void *); /* INFRINGES ON USER NAME SPACE */ # endif # endif # endif #endif /* ! defined yyoverflow || YYERROR_VERBOSE */ #if (! defined yyoverflow \ && (! defined __cplusplus \ || (defined YYSTYPE_IS_TRIVIAL && YYSTYPE_IS_TRIVIAL))) /* A type that is properly aligned for any stack member. */ union yyalloc { yytype_int16 yyss_alloc; YYSTYPE yyvs_alloc; }; /* The size of the maximum gap between one aligned stack and the next. */ # define YYSTACK_GAP_MAXIMUM (sizeof (union yyalloc) - 1) /* The size of an array large to enough to hold all stacks, each with N elements. */ # define YYSTACK_BYTES(N) \ ((N) * (sizeof (yytype_int16) + sizeof (YYSTYPE)) \ + YYSTACK_GAP_MAXIMUM) # define YYCOPY_NEEDED 1 /* Relocate STACK from its old location to the new one. The local variables YYSIZE and YYSTACKSIZE give the old and new number of elements in the stack, and YYPTR gives the new location of the stack. Advance YYPTR to a properly aligned location for the next stack. */ # define YYSTACK_RELOCATE(Stack_alloc, Stack) \ do \ { \ YYSIZE_T yynewbytes; \ YYCOPY (&yyptr->Stack_alloc, Stack, yysize); \ Stack = &yyptr->Stack_alloc; \ yynewbytes = yystacksize * sizeof (*Stack) + YYSTACK_GAP_MAXIMUM; \ yyptr += yynewbytes / sizeof (*yyptr); \ } \ while (0) #endif #if defined YYCOPY_NEEDED && YYCOPY_NEEDED /* Copy COUNT objects from SRC to DST. The source and destination do not overlap. */ # ifndef YYCOPY # if defined __GNUC__ && 1 < __GNUC__ # define YYCOPY(Dst, Src, Count) \ __builtin_memcpy (Dst, Src, (Count) * sizeof (*(Src))) # else # define YYCOPY(Dst, Src, Count) \ do \ { \ YYSIZE_T yyi; \ for (yyi = 0; yyi < (Count); yyi++) \ (Dst)[yyi] = (Src)[yyi]; \ } \ while (0) # endif # endif #endif /* !YYCOPY_NEEDED */ /* YYFINAL -- State number of the termination state. */ #define YYFINAL 111 /* YYLAST -- Last index in YYTABLE. */ #define YYLAST 1409 /* YYNTOKENS -- Number of terminals. */ #define YYNTOKENS 118 /* YYNNTS -- Number of nonterminals. */ #define YYNNTS 54 /* YYNRULES -- Number of rules. */ #define YYNRULES 177 /* YYNSTATES -- Number of states. */ #define YYNSTATES 319 /* YYTRANSLATE[YYX] -- Symbol number corresponding to YYX as returned by yylex, with out-of-bounds checking. */ #define YYUNDEFTOK 2 #define YYMAXUTOK 372 #define YYTRANSLATE(YYX) \ ((unsigned int) (YYX) <= YYMAXUTOK ? yytranslate[YYX] : YYUNDEFTOK) /* YYTRANSLATE[TOKEN-NUM] -- Symbol number corresponding to TOKEN-NUM as returned by yylex, without out-of-bounds checking. */ static const yytype_uint8 yytranslate[] = { 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117 }; #if YYDEBUG /* YYRLINE[YYN] -- Source line where rule number YYN was defined. */ static const yytype_uint16 yyrline[] = { 0, 176, 176, 177, 181, 182, 186, 187, 188, 189, 190, 191, 195, 196, 200, 201, 202, 203, 207, 208, 209, 210, 212, 213, 215, 216, 217, 221, 222, 223, 224, 225, 226, 230, 231, 232, 233, 234, 235, 236, 240, 241, 242, 243, 247, 248, 249, 250, 254, 255, 256, 257, 261, 262, 263, 267, 268, 269, 273, 274, 275, 276, 277, 281, 282, 283, 287, 288, 292, 293, 297, 298, 302, 303, 307, 308, 312, 313, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 333, 334, 335, 336, 340, 344, 345, 346, 350, 351, 355, 356, 357, 358, 362, 366, 372, 378, 384, 397, 405, 406, 410, 411, 412, 416, 420, 421, 425, 426, 427, 431, 432, 438, 439, 440, 444, 448, 449, 450, 451, 457, 458, 459, 463, 471, 479, 486, 496, 502, 508, 517, 529, 535, 544, 548, 554, 563, 565, 567, 572, 578, 590, 591, 592, 593, 597, 598, 599, 600, 601, 602, 606, 607, 608, 609, 610, 611, 612, 616, 627, 638, 675, 676, 680, 681, 685 }; #endif #if YYDEBUG || YYERROR_VERBOSE || 1 /* YYTNAME[SYMBOL-NUM] -- String name of the symbol SYMBOL-NUM. First, the terminals, then, starting at YYNTOKENS, nonterminals. */ static const char *const yytname[] = { "$end", "error", "$undefined", "IFX", "TOK_ELSE", "THISX", "TOK_DOT", "TOK_LBRACKET", "TOK_UNKNOWN", "TOK_EOF", "TOK_EOL", "TOK_SPACE", "TOK_COMMENT", "TOK_IDENTIFIER", "TOK_STRING", "TOK_CHAR", "TOK_UNS32", "TOK_UNS64", "TOK_FLOAT32", "TOK_FLOAT64", "TOK_DIV", "TOK_DIVASS", "TOK_DOTDOT", "TOK_DOTDOTDOT", "TOK_AND", "TOK_ANDASS", "TOK_ANDAND", "TOK_OR", "TOK_ORASS", "TOK_OROR", "TOK_MINUS", "TOK_MINUSASS", "TOK_MINUSMINUS", "TOK_PLUS", "TOK_PLUSASS", "TOK_PLUSPLUS", "TOK_LT", "TOK_LE", "TOK_SHL", "TOK_SHLASS", "TOK_LG", "TOK_LEG", "TOK_GT", "TOK_GE", "TOK_SHRASS", "TOK_USHRASS", "TOK_SHR", "TOK_USHR", "TOK_NOT", "TOK_NOTEQUAL", "TOK_UE", "TOK_UNORD", "TOK_UGE", "TOK_UG", "TOK_ULE", "TOK_UL", "TOK_LPAREN", "TOK_RPAREN", "TOK_RBRACKET", "TOK_LCURLY", "TOK_RCURLY", "TOK_QUESTION", "TOK_COMMA", "TOK_SEMICOLON", "TOK_COLON", "TOK_COLONCOLON", "TOK_DOLLAR", "TOK_ASSIGN", "TOK_EQUAL", "TOK_MUL", "TOK_MULASS", "TOK_MOD", "TOK_MODASS", "TOK_XOR", "TOK_XORASS", "TOK_CAT", "TOK_CATASS", "TOK_BASE", "TOK_BREAK", "TOK_CASE", "TOK_CATCH", "TOK_CONST", "TOK_CONTINUE", "TOK_DEFAULT", "TOK_DELEGATE", "TOK_DELETE", "TOK_DO", "TOK_ENUM", "TOK_EXTENDS", "TOK_FALSE", "TOK_FOR", "TOK_FOREACH", "TOK_FUNCTION", "TOK_IF", "TOK_IN", "TOK_INT", "TOK_LOCAL", "TOK_METAFUNCTION", "TOK_NAMESPACE", "TOK_NEW", "TOK_NULL", "TOK_RESUME", "TOK_RETURN", "TOK_SWITCH", "TOK_THIS", "TOK_THROW", "TOK_TRUE", "TOK_TRY", "TOK_VAR", "TOK_WHILE", "TOK_YIELD", "STOK_FILE", "STOK_LINE", "STOK_DATE", "STOK_TIME", "STOK_TIMESTAMP", "STOK_VENDOR", "STOK_VERSION", "$accept", "program", "stmts", "stmt", "block", "expr_stmt", "primary_expr", "argument_expr_list", "postfix_expr", "unary_op", "unary_expr", "multiplicative_expr", "additive_expr", "shift_expr", "relational_expr", "equality_expr", "and_expr", "exclusive_or_expr", "inclusive_or_expr", "logical_and_expr", "logical_or_expr", "conditional_expr", "assignment_op", "assignment_expr", "expr", "inner_expr", "boolean", "numeric", "string", "keyvalue", "keyvalue_list", "table", "element", "element_list", "array", "type_specifier", "decl_stmt", "var_decl_stmt", "getvar_primary_expr", "getvar_postfix_expr", "var_decl", "func_decl_arglist", "func_decl", "local_func_decl", "anony_func_decl", "selection_stmt", "labeled_stmts", "labeled_stmt", "jump_stmt", "iteration_stmt", "foreach_stmt", "namespace_block", "new_expr", "delete_expr", YY_NULLPTR }; #endif # ifdef YYPRINT /* YYTOKNUM[NUM] -- (External) token number corresponding to the (internal) symbol number NUM (which must be that of a token). */ static const yytype_uint16 yytoknum[] = { 0, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372 }; # endif #define YYPACT_NINF -151 #define yypact_value_is_default(Yystate) \ (!!((Yystate) == (-151))) #define YYTABLE_NINF -1 #define yytable_value_is_error(Yytable_value) \ 0 /* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing STATE-NUM. */ static const yytype_int16 yypact[] = { 721, 819, -151, -151, -151, -151, -151, -151, -151, 1303, -151, 1303, -151, 1144, 329, -151, 19, -151, 26, 47, 3, 721, -151, 39, 3, 60, 44, 3, 3, -151, 872, 75, 53, -151, -151, 96, 122, 721, -151, -151, -151, -151, 32, 1303, 825, 5, 24, 10, 120, -3, 42, 14, 128, 138, -10, -151, -151, 106, -151, -151, -151, -151, 3, -151, -151, -151, 80, -151, -151, -151, -151, -151, -151, -151, -151, 119, -151, 21, 127, -151, -151, -151, -151, 87, -151, -151, -151, 130, -151, 427, -151, -151, -151, 53, -151, 73, 83, 85, 76, 1303, -151, 34, 79, -151, 125, -151, -151, 1303, 182, 1303, 1303, -151, -151, 184, 1303, -151, -151, 925, -151, -151, -151, -151, -151, -151, -151, -151, -151, -151, -151, -151, -151, -151, 1144, 1303, 1303, 1303, 1303, 1303, 1303, 1303, 1303, 1303, 1303, 1303, 1303, 1303, 1303, 1303, 1303, 1303, 1303, 1144, -151, 17, 3, -151, -151, 1303, 136, -151, 140, -151, -40, -151, 13, -151, 978, -151, -151, 192, 1303, 150, -151, 1031, 202, 1031, 116, 16, 153, 525, 1091, -151, 155, -151, 149, 156, -151, 159, -151, -13, -151, -151, -151, -151, -151, -151, -151, -151, -151, -151, 5, 5, 24, 24, 10, 10, 10, 10, 120, 120, -3, 42, 14, 128, 138, 160, 1144, 30, 162, 1144, 1144, -151, 48, -151, 166, 214, 1, -151, -151, -151, 172, 1303, 1197, 3, 1144, 1250, 1144, 166, 15, 721, -151, 623, -151, 66, 173, -151, 721, -151, -151, 1144, 1144, -151, 1144, 168, -151, -151, -151, -151, -151, -151, 166, 18, -151, 176, 721, 181, 36, 186, 721, 189, 193, -151, 166, 237, -151, -151, 89, -151, -151, -151, -151, -151, -151, 1144, -151, -151, 229, 190, -151, 721, 1144, 721, -151, 721, 721, -151, 721, 1303, 195, -8, -151, -151, -151, -151, -151, 200, -151, -151, -151, -151, 196, 721, -151, -151, 721, 721, 721, -151, 721 }; /* YYDEFACT[STATE-NUM] -- Default reduction number in state STATE-NUM. Performed when YYTABLE does not specify something else to do. Zero means the default is an error. */ static const yytype_uint8 yydefact[] = { 2, 0, 128, 105, 101, 102, 103, 104, 41, 0, 40, 0, 43, 0, 0, 14, 0, 42, 0, 0, 0, 0, 100, 0, 0, 0, 123, 0, 0, 18, 0, 0, 25, 99, 122, 0, 0, 3, 4, 17, 6, 33, 44, 0, 48, 52, 55, 58, 63, 66, 68, 70, 72, 74, 76, 91, 95, 0, 19, 20, 21, 22, 0, 7, 124, 23, 0, 125, 126, 8, 9, 10, 169, 11, 26, 0, 119, 0, 0, 96, 116, 97, 117, 0, 98, 46, 45, 0, 13, 0, 129, 158, 157, 0, 132, 177, 0, 0, 0, 0, 145, 0, 0, 159, 0, 161, 162, 0, 0, 0, 0, 1, 5, 0, 0, 39, 38, 0, 47, 79, 80, 81, 82, 83, 84, 85, 86, 78, 87, 88, 89, 90, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15, 135, 0, 127, 16, 0, 106, 113, 0, 111, 0, 109, 0, 120, 0, 24, 12, 0, 0, 0, 123, 0, 44, 0, 0, 0, 0, 0, 0, 160, 0, 130, 0, 0, 34, 0, 36, 0, 27, 28, 29, 92, 93, 94, 50, 49, 51, 48, 54, 53, 56, 57, 59, 61, 60, 62, 65, 64, 67, 69, 71, 73, 75, 0, 0, 137, 0, 0, 0, 114, 0, 139, 0, 0, 0, 121, 118, 133, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 174, 0, 175, 0, 0, 131, 0, 35, 37, 0, 0, 136, 0, 0, 107, 110, 115, 112, 146, 140, 0, 0, 134, 0, 0, 0, 0, 0, 0, 0, 0, 143, 0, 149, 173, 176, 0, 163, 30, 31, 32, 77, 138, 0, 147, 141, 0, 0, 165, 0, 0, 0, 167, 0, 0, 144, 0, 0, 0, 0, 151, 108, 142, 164, 166, 0, 170, 168, 172, 148, 0, 156, 150, 152, 0, 154, 155, 171, 153 }; /* YYPGOTO[NTERM-NUM]. */ static const yytype_int16 yypgoto[] = { -151, -151, -14, -20, -99, -79, -151, 69, 164, -151, 185, 22, 28, 59, 31, 117, 115, 129, 118, 131, -151, -151, -151, -102, 20, -5, -151, -151, -71, 43, -151, -27, 102, -151, -151, -150, -151, 178, -15, -17, 183, 105, -24, -151, -26, -151, -151, -16, -151, -151, -151, -151, -151, -151 }; /* YYDEFGOTO[NTERM-NUM]. */ static const yytype_int16 yydefgoto[] = { -1, 36, 37, 38, 39, 40, 41, 189, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 132, 56, 57, 80, 58, 59, 60, 161, 162, 81, 82, 83, 61, 62, 63, 64, 65, 95, 66, 226, 67, 68, 84, 69, 299, 300, 70, 71, 72, 73, 74, 75 }; /* YYTABLE[YYPACT[STATE-NUM]] -- What to do in state STATE-NUM. If positive, shift that token. If negative, reduce the rule whose number is the opposite. If YYTABLE_NINF, syntax error. */ static const yytype_uint16 yytable[] = { 89, 96, 100, 105, 106, 94, 160, 98, 87, 94, 101, 102, 94, 94, 225, 190, 2, 112, 173, 150, 221, 79, 222, 169, 170, 133, 223, 225, 157, 223, 193, 285, 90, 79, 158, 3, 169, 170, 113, 114, 169, 170, 169, 170, 248, 153, 144, 94, 138, 249, 104, 151, 312, 163, 136, 157, 139, 137, 260, 108, 109, 158, 3, 261, 115, 145, 146, 116, 16, 112, 224, 297, 272, 237, 134, 298, 135, 261, 190, 169, 170, 159, 169, 170, 216, 169, 170, 147, 117, 91, 191, 192, 1, 179, 232, 97, 235, 252, 2, 3, 290, 4, 5, 6, 7, 194, 195, 93, 256, 172, 92, 286, 172, 24, 172, 8, 99, 9, 10, 178, 11, 34, 111, 275, 34, 258, 34, 182, 249, 184, 185, 107, 177, 12, 187, 180, 24, 217, 271, 94, 24, 13, 154, 155, 14, 165, 215, 278, 15, 166, 16, 160, 110, 191, 192, 148, 140, 141, 200, 201, 17, 284, 142, 143, 149, 241, 202, 203, 297, 152, 20, 79, 298, 295, 22, 208, 209, 218, 154, 155, 236, 172, 156, 164, 28, 29, 79, 167, 181, 32, 230, 33, 171, 34, 85, 183, 86, 186, 163, 204, 205, 206, 207, 219, 220, 229, 231, 245, 113, 114, 239, 251, 244, 246, 254, 255, 266, 247, 94, 273, 253, 112, 279, 280, 250, 14, 277, 259, 118, 267, 262, 270, 276, 287, 115, 283, 79, 116, 289, 79, 79, 296, 302, 291, 288, 281, 293, 282, 292, 243, 294, 263, 265, 303, 79, 269, 79, 314, 117, 311, 315, 174, 211, 210, 233, 257, 234, 213, 228, 304, 79, 306, 79, 307, 308, 175, 309, 212, 301, 0, 176, 214, 238, 313, 0, 305, 0, 0, 0, 0, 0, 0, 0, 0, 317, 0, 112, 316, 112, 0, 0, 318, 0, 79, 0, 0, 0, 0, 0, 0, 79, 0, 0, 0, 0, 0, 0, 310, 196, 197, 198, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 1, 0, 0, 0, 0, 0, 2, 3, 0, 4, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 9, 10, 0, 11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 0, 0, 0, 0, 0, 0, 0, 13, 0, 0, 14, 88, 0, 0, 15, 0, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 17, 0, 0, 18, 0, 0, 0, 19, 0, 0, 20, 21, 0, 0, 22, 23, 0, 24, 25, 0, 0, 26, 0, 27, 28, 29, 0, 30, 31, 32, 1, 33, 0, 34, 35, 0, 2, 3, 0, 4, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 9, 10, 0, 11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 0, 0, 0, 0, 0, 0, 0, 13, 0, 0, 14, 168, 0, 0, 15, 0, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 17, 0, 0, 18, 0, 0, 0, 19, 0, 0, 20, 21, 0, 0, 22, 23, 0, 24, 25, 0, 0, 26, 0, 27, 28, 29, 0, 30, 31, 32, 1, 33, 0, 34, 35, 0, 2, 3, 0, 4, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 9, 10, 0, 11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 0, 0, 0, 0, 0, 0, 0, 13, 0, 0, 14, 240, 0, 0, 15, 0, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 17, 0, 0, 18, 0, 0, 0, 19, 0, 0, 20, 21, 0, 0, 22, 23, 0, 24, 25, 0, 0, 26, 0, 27, 28, 29, 0, 30, 31, 32, 1, 33, 0, 34, 35, 0, 2, 3, 0, 4, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 9, 10, 0, 11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 0, 0, 0, 0, 0, 0, 0, 13, 0, 0, 14, 274, 0, 0, 15, 0, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 17, 0, 0, 18, 0, 0, 0, 19, 0, 0, 20, 21, 0, 0, 22, 23, 0, 24, 25, 0, 0, 26, 0, 27, 28, 29, 0, 30, 31, 32, 1, 33, 0, 34, 35, 0, 2, 3, 0, 4, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 9, 10, 0, 11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 0, 0, 0, 0, 0, 0, 0, 13, 0, 0, 14, 0, 0, 0, 15, 0, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 17, 0, 0, 18, 0, 0, 0, 19, 0, 0, 20, 21, 0, 0, 22, 23, 0, 24, 25, 0, 0, 26, 0, 27, 28, 29, 0, 30, 31, 32, 1, 33, 0, 34, 35, 0, 2, 3, 0, 4, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 119, 0, 0, 8, 120, 9, 10, 121, 11, 0, 122, 0, 0, 123, 0, 0, 0, 0, 124, 0, 0, 12, 0, 125, 126, 0, 0, 0, 0, 13, 0, 76, 77, 1, 0, 0, 0, 0, 16, 2, 3, 0, 4, 5, 6, 7, 127, 0, 17, 128, 0, 129, 0, 130, 0, 131, 8, 0, 9, 10, 0, 11, 22, 0, 0, 78, 0, 0, 0, 0, 0, 0, 28, 29, 12, 0, 0, 32, 0, 33, 0, 0, 13, 0, 0, 77, 1, 0, 0, 103, 0, 16, 2, 3, 0, 4, 5, 6, 7, 0, 0, 17, 0, 0, 0, 0, 0, 0, 0, 8, 0, 9, 10, 0, 11, 22, 0, 0, 78, 0, 0, 0, 0, 0, 0, 28, 29, 12, 0, 0, 32, 0, 33, 0, 0, 13, 188, 0, 77, 1, 0, 0, 0, 0, 16, 2, 3, 0, 4, 5, 6, 7, 0, 0, 17, 0, 0, 0, 0, 0, 0, 0, 8, 0, 9, 10, 0, 11, 22, 0, 0, 78, 0, 0, 0, 0, 0, 0, 28, 29, 12, 0, 0, 32, 0, 33, 0, 0, 13, 0, 227, 77, 1, 0, 0, 0, 0, 16, 2, 3, 0, 4, 5, 6, 7, 0, 0, 17, 0, 0, 0, 0, 0, 0, 0, 8, 0, 9, 10, 0, 11, 22, 0, 0, 78, 0, 0, 0, 0, 0, 0, 28, 29, 12, 0, 0, 32, 0, 33, 0, 0, 13, 0, 0, 14, 0, 0, 0, 15, 0, 16, 0, 1, 0, 0, 0, 0, 0, 2, 3, 17, 4, 5, 6, 7, 0, 0, 0, 0, 0, 20, 0, 0, 0, 22, 8, 0, 9, 10, 0, 11, 0, 0, 0, 28, 29, 0, 0, 0, 32, 0, 33, 0, 12, 0, 0, 0, 0, 0, 0, 0, 13, 242, 0, 77, 1, 0, 0, 0, 0, 16, 2, 3, 0, 4, 5, 6, 7, 0, 0, 17, 0, 0, 0, 0, 0, 0, 0, 8, 0, 9, 10, 0, 11, 22, 0, 0, 78, 0, 0, 0, 0, 0, 0, 28, 29, 12, 0, 0, 32, 0, 33, 0, 0, 13, 0, 0, 77, 1, 0, 0, 0, 0, 16, 2, 3, 0, 4, 5, 6, 7, 0, 0, 17, 0, 0, 0, 0, 0, 0, 0, 8, 0, 9, 10, 0, 11, 22, 0, 0, 78, 0, 0, 0, 0, 0, 0, 28, 29, 12, 0, 0, 32, 0, 33, 0, 0, 13, 264, 0, 0, 1, 0, 0, 0, 0, 16, 2, 3, 0, 4, 5, 6, 7, 0, 0, 17, 0, 0, 0, 0, 0, 0, 0, 8, 0, 9, 10, 0, 11, 22, 0, 0, 0, 0, 0, 0, 0, 0, 0, 28, 29, 12, 0, 0, 32, 0, 33, 0, 0, 13, 268, 0, 0, 1, 0, 0, 0, 0, 16, 2, 3, 0, 4, 5, 6, 7, 0, 0, 17, 0, 0, 0, 0, 0, 0, 0, 8, 0, 9, 10, 0, 11, 22, 0, 0, 0, 0, 0, 0, 0, 0, 0, 28, 29, 12, 0, 0, 32, 0, 33, 0, 0, 13, 0, 0, 0, 0, 0, 0, 0, 0, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 17, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 22, 0, 0, 0, 0, 0, 0, 0, 0, 0, 28, 29, 0, 0, 0, 32, 0, 33 }; static const yytype_int16 yycheck[] = { 14, 21, 26, 30, 30, 20, 77, 24, 13, 24, 27, 28, 27, 28, 164, 117, 13, 37, 97, 29, 60, 1, 62, 6, 7, 20, 13, 177, 7, 13, 132, 13, 13, 13, 13, 14, 6, 7, 6, 7, 6, 7, 6, 7, 57, 62, 49, 62, 38, 62, 30, 61, 60, 77, 30, 7, 46, 33, 57, 6, 7, 13, 14, 62, 32, 68, 24, 35, 65, 89, 57, 79, 57, 57, 69, 83, 71, 62, 180, 6, 7, 60, 6, 7, 67, 6, 7, 73, 56, 63, 117, 117, 7, 59, 173, 56, 175, 67, 13, 14, 64, 16, 17, 18, 19, 132, 132, 104, 60, 96, 63, 261, 96, 92, 96, 30, 56, 32, 33, 99, 35, 108, 0, 57, 108, 224, 108, 107, 62, 109, 110, 56, 56, 48, 114, 56, 92, 154, 237, 154, 92, 56, 62, 63, 59, 58, 151, 249, 63, 62, 65, 222, 56, 180, 180, 27, 36, 37, 136, 137, 75, 260, 42, 43, 26, 179, 138, 139, 79, 63, 85, 151, 83, 272, 89, 144, 145, 157, 62, 63, 64, 96, 63, 56, 99, 100, 166, 57, 63, 104, 170, 106, 109, 108, 9, 13, 11, 13, 222, 140, 141, 142, 143, 67, 64, 13, 56, 58, 6, 7, 57, 216, 57, 57, 219, 220, 233, 58, 233, 239, 58, 241, 249, 249, 64, 59, 246, 13, 43, 234, 58, 236, 59, 57, 32, 67, 216, 35, 57, 219, 220, 4, 13, 57, 264, 250, 57, 252, 268, 180, 57, 231, 232, 63, 234, 235, 236, 57, 56, 64, 64, 97, 147, 146, 62, 222, 64, 149, 166, 289, 250, 291, 252, 293, 294, 97, 296, 148, 283, -1, 97, 150, 177, 299, -1, 290, -1, -1, -1, -1, -1, -1, -1, -1, 314, -1, 316, 311, 318, -1, -1, 315, -1, 283, -1, -1, -1, -1, -1, -1, 290, -1, -1, -1, -1, -1, -1, 297, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 7, -1, -1, -1, -1, -1, 13, 14, -1, 16, 17, 18, 19, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 30, -1, 32, 33, -1, 35, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 48, -1, -1, -1, -1, -1, -1, -1, 56, -1, -1, 59, 60, -1, -1, 63, -1, 65, -1, -1, -1, -1, -1, -1, -1, -1, -1, 75, -1, -1, 78, -1, -1, -1, 82, -1, -1, 85, 86, -1, -1, 89, 90, -1, 92, 93, -1, -1, 96, -1, 98, 99, 100, -1, 102, 103, 104, 7, 106, -1, 108, 109, -1, 13, 14, -1, 16, 17, 18, 19, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 30, -1, 32, 33, -1, 35, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 48, -1, -1, -1, -1, -1, -1, -1, 56, -1, -1, 59, 60, -1, -1, 63, -1, 65, -1, -1, -1, -1, -1, -1, -1, -1, -1, 75, -1, -1, 78, -1, -1, -1, 82, -1, -1, 85, 86, -1, -1, 89, 90, -1, 92, 93, -1, -1, 96, -1, 98, 99, 100, -1, 102, 103, 104, 7, 106, -1, 108, 109, -1, 13, 14, -1, 16, 17, 18, 19, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 30, -1, 32, 33, -1, 35, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 48, -1, -1, -1, -1, -1, -1, -1, 56, -1, -1, 59, 60, -1, -1, 63, -1, 65, -1, -1, -1, -1, -1, -1, -1, -1, -1, 75, -1, -1, 78, -1, -1, -1, 82, -1, -1, 85, 86, -1, -1, 89, 90, -1, 92, 93, -1, -1, 96, -1, 98, 99, 100, -1, 102, 103, 104, 7, 106, -1, 108, 109, -1, 13, 14, -1, 16, 17, 18, 19, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 30, -1, 32, 33, -1, 35, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 48, -1, -1, -1, -1, -1, -1, -1, 56, -1, -1, 59, 60, -1, -1, 63, -1, 65, -1, -1, -1, -1, -1, -1, -1, -1, -1, 75, -1, -1, 78, -1, -1, -1, 82, -1, -1, 85, 86, -1, -1, 89, 90, -1, 92, 93, -1, -1, 96, -1, 98, 99, 100, -1, 102, 103, 104, 7, 106, -1, 108, 109, -1, 13, 14, -1, 16, 17, 18, 19, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 30, -1, 32, 33, -1, 35, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 48, -1, -1, -1, -1, -1, -1, -1, 56, -1, -1, 59, -1, -1, -1, 63, -1, 65, -1, -1, -1, -1, -1, -1, -1, -1, -1, 75, -1, -1, 78, -1, -1, -1, 82, -1, -1, 85, 86, -1, -1, 89, 90, -1, 92, 93, -1, -1, 96, -1, 98, 99, 100, -1, 102, 103, 104, 7, 106, -1, 108, 109, -1, 13, 14, -1, 16, 17, 18, 19, -1, -1, -1, -1, -1, -1, -1, 21, -1, -1, 30, 25, 32, 33, 28, 35, -1, 31, -1, -1, 34, -1, -1, -1, -1, 39, -1, -1, 48, -1, 44, 45, -1, -1, -1, -1, 56, -1, 58, 59, 7, -1, -1, -1, -1, 65, 13, 14, -1, 16, 17, 18, 19, 67, -1, 75, 70, -1, 72, -1, 74, -1, 76, 30, -1, 32, 33, -1, 35, 89, -1, -1, 92, -1, -1, -1, -1, -1, -1, 99, 100, 48, -1, -1, 104, -1, 106, -1, -1, 56, -1, -1, 59, 7, -1, -1, 63, -1, 65, 13, 14, -1, 16, 17, 18, 19, -1, -1, 75, -1, -1, -1, -1, -1, -1, -1, 30, -1, 32, 33, -1, 35, 89, -1, -1, 92, -1, -1, -1, -1, -1, -1, 99, 100, 48, -1, -1, 104, -1, 106, -1, -1, 56, 57, -1, 59, 7, -1, -1, -1, -1, 65, 13, 14, -1, 16, 17, 18, 19, -1, -1, 75, -1, -1, -1, -1, -1, -1, -1, 30, -1, 32, 33, -1, 35, 89, -1, -1, 92, -1, -1, -1, -1, -1, -1, 99, 100, 48, -1, -1, 104, -1, 106, -1, -1, 56, -1, 58, 59, 7, -1, -1, -1, -1, 65, 13, 14, -1, 16, 17, 18, 19, -1, -1, 75, -1, -1, -1, -1, -1, -1, -1, 30, -1, 32, 33, -1, 35, 89, -1, -1, 92, -1, -1, -1, -1, -1, -1, 99, 100, 48, -1, -1, 104, -1, 106, -1, -1, 56, -1, -1, 59, -1, -1, -1, 63, -1, 65, -1, 7, -1, -1, -1, -1, -1, 13, 14, 75, 16, 17, 18, 19, -1, -1, -1, -1, -1, 85, -1, -1, -1, 89, 30, -1, 32, 33, -1, 35, -1, -1, -1, 99, 100, -1, -1, -1, 104, -1, 106, -1, 48, -1, -1, -1, -1, -1, -1, -1, 56, 57, -1, 59, 7, -1, -1, -1, -1, 65, 13, 14, -1, 16, 17, 18, 19, -1, -1, 75, -1, -1, -1, -1, -1, -1, -1, 30, -1, 32, 33, -1, 35, 89, -1, -1, 92, -1, -1, -1, -1, -1, -1, 99, 100, 48, -1, -1, 104, -1, 106, -1, -1, 56, -1, -1, 59, 7, -1, -1, -1, -1, 65, 13, 14, -1, 16, 17, 18, 19, -1, -1, 75, -1, -1, -1, -1, -1, -1, -1, 30, -1, 32, 33, -1, 35, 89, -1, -1, 92, -1, -1, -1, -1, -1, -1, 99, 100, 48, -1, -1, 104, -1, 106, -1, -1, 56, 57, -1, -1, 7, -1, -1, -1, -1, 65, 13, 14, -1, 16, 17, 18, 19, -1, -1, 75, -1, -1, -1, -1, -1, -1, -1, 30, -1, 32, 33, -1, 35, 89, -1, -1, -1, -1, -1, -1, -1, -1, -1, 99, 100, 48, -1, -1, 104, -1, 106, -1, -1, 56, 57, -1, -1, 7, -1, -1, -1, -1, 65, 13, 14, -1, 16, 17, 18, 19, -1, -1, 75, -1, -1, -1, -1, -1, -1, -1, 30, -1, 32, 33, -1, 35, 89, -1, -1, -1, -1, -1, -1, -1, -1, -1, 99, 100, 48, -1, -1, 104, -1, 106, -1, -1, 56, -1, -1, -1, -1, -1, -1, -1, -1, 65, -1, -1, -1, -1, -1, -1, -1, -1, -1, 75, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 89, -1, -1, -1, -1, -1, -1, -1, -1, -1, 99, 100, -1, -1, -1, 104, -1, 106 }; /* YYSTOS[STATE-NUM] -- The (internal number of the) accessing symbol of state STATE-NUM. */ static const yytype_uint8 yystos[] = { 0, 7, 13, 14, 16, 17, 18, 19, 30, 32, 33, 35, 48, 56, 59, 63, 65, 75, 78, 82, 85, 86, 89, 90, 92, 93, 96, 98, 99, 100, 102, 103, 104, 106, 108, 109, 119, 120, 121, 122, 123, 124, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 141, 142, 144, 145, 146, 152, 153, 154, 155, 156, 158, 160, 161, 163, 166, 167, 168, 169, 170, 171, 58, 59, 92, 142, 143, 149, 150, 151, 162, 128, 128, 143, 60, 120, 13, 63, 63, 104, 156, 157, 121, 56, 157, 56, 160, 157, 157, 63, 142, 149, 162, 56, 6, 7, 56, 0, 121, 6, 7, 32, 35, 56, 128, 21, 25, 28, 31, 34, 39, 44, 45, 67, 70, 72, 74, 76, 140, 20, 69, 71, 30, 33, 38, 46, 36, 37, 42, 43, 49, 68, 24, 73, 27, 26, 29, 61, 63, 157, 62, 63, 63, 7, 13, 60, 146, 147, 148, 160, 56, 58, 62, 57, 60, 6, 7, 109, 96, 123, 126, 155, 158, 56, 142, 59, 56, 63, 142, 13, 142, 142, 13, 142, 57, 125, 141, 149, 162, 141, 149, 162, 128, 128, 128, 128, 129, 129, 130, 130, 131, 131, 131, 131, 132, 132, 133, 134, 135, 136, 137, 143, 67, 157, 142, 67, 64, 60, 62, 13, 57, 153, 159, 58, 150, 13, 142, 56, 123, 62, 64, 123, 64, 57, 159, 57, 60, 120, 57, 125, 57, 58, 57, 58, 57, 62, 64, 143, 67, 58, 143, 143, 60, 147, 122, 13, 57, 62, 58, 142, 57, 142, 157, 143, 57, 142, 143, 122, 57, 121, 60, 57, 59, 121, 141, 149, 162, 143, 143, 67, 122, 13, 153, 57, 121, 57, 64, 57, 121, 57, 57, 122, 4, 79, 83, 164, 165, 143, 13, 63, 121, 143, 121, 121, 121, 121, 142, 64, 60, 165, 57, 64, 120, 121, 120 }; /* YYR1[YYN] -- Symbol number of symbol that rule YYN derives. */ static const yytype_uint8 yyr1[] = { 0, 118, 119, 119, 120, 120, 121, 121, 121, 121, 121, 121, 122, 122, 123, 123, 123, 123, 124, 124, 124, 124, 124, 124, 124, 124, 124, 125, 125, 125, 125, 125, 125, 126, 126, 126, 126, 126, 126, 126, 127, 127, 127, 127, 128, 128, 128, 128, 129, 129, 129, 129, 130, 130, 130, 131, 131, 131, 132, 132, 132, 132, 132, 133, 133, 133, 134, 134, 135, 135, 136, 136, 137, 137, 138, 138, 139, 139, 140, 140, 140, 140, 140, 140, 140, 140, 140, 140, 140, 140, 140, 141, 141, 141, 141, 142, 143, 143, 143, 144, 144, 145, 145, 145, 145, 146, 147, 147, 147, 147, 147, 148, 148, 149, 149, 149, 150, 151, 151, 152, 152, 152, 153, 153, 154, 154, 154, 155, 156, 156, 156, 156, 157, 157, 157, 158, 158, 158, 158, 159, 159, 159, 159, 160, 160, 161, 162, 162, 163, 163, 163, 164, 164, 165, 165, 165, 165, 166, 166, 166, 166, 166, 166, 167, 167, 167, 167, 167, 167, 167, 168, 168, 168, 169, 169, 170, 170, 171 }; /* YYR2[YYN] -- Number of symbols on the right hand side of rule YYN. */ static const yytype_uint8 yyr2[] = { 0, 2, 0, 1, 1, 2, 1, 1, 1, 1, 1, 1, 3, 2, 1, 2, 2, 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 1, 1, 3, 3, 3, 1, 3, 4, 3, 4, 2, 2, 1, 1, 1, 1, 1, 2, 2, 2, 1, 3, 3, 3, 1, 3, 3, 1, 3, 3, 1, 3, 3, 3, 3, 1, 3, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 5, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 3, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 5, 1, 3, 1, 3, 2, 3, 4, 1, 1, 3, 2, 3, 4, 1, 1, 1, 1, 1, 2, 1, 2, 3, 4, 1, 3, 4, 2, 4, 3, 5, 1, 2, 3, 4, 5, 6, 2, 4, 5, 7, 5, 7, 1, 2, 4, 3, 3, 2, 2, 2, 2, 3, 2, 2, 5, 7, 6, 7, 6, 7, 1, 7, 9, 7, 5, 4, 4, 5, 2 }; #define yyerrok (yyerrstatus = 0) #define yyclearin (yychar = YYEMPTY) #define YYEMPTY (-2) #define YYEOF 0 #define YYACCEPT goto yyacceptlab #define YYABORT goto yyabortlab #define YYERROR goto yyerrorlab #define YYRECOVERING() (!!yyerrstatus) #define YYBACKUP(Token, Value) \ do \ if (yychar == YYEMPTY) \ { \ yychar = (Token); \ yylval = (Value); \ YYPOPSTACK (yylen); \ yystate = *yyssp; \ goto yybackup; \ } \ else \ { \ yyerror (parser, YY_("syntax error: cannot back up")); \ YYERROR; \ } \ while (0) /* Error token number */ #define YYTERROR 1 #define YYERRCODE 256 /* Enable debugging if requested. */ #if YYDEBUG # ifndef YYFPRINTF # include <stdio.h> /* INFRINGES ON USER NAME SPACE */ # define YYFPRINTF fprintf # endif # define YYDPRINTF(Args) \ do { \ if (yydebug) \ YYFPRINTF Args; \ } while (0) /* This macro is provided for backward compatibility. */ #ifndef YY_LOCATION_PRINT # define YY_LOCATION_PRINT(File, Loc) ((void) 0) #endif # define YY_SYMBOL_PRINT(Title, Type, Value, Location) \ do { \ if (yydebug) \ { \ YYFPRINTF (stderr, "%s ", Title); \ yy_symbol_print (stderr, \ Type, Value, parser); \ YYFPRINTF (stderr, "\n"); \ } \ } while (0) /*----------------------------------------. | Print this symbol's value on YYOUTPUT. | `----------------------------------------*/ static void yy_symbol_value_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep, void* parser) { FILE *yyo = yyoutput; YYUSE (yyo); YYUSE (parser); if (!yyvaluep) return; # ifdef YYPRINT if (yytype < YYNTOKENS) YYPRINT (yyoutput, yytoknum[yytype], *yyvaluep); # endif YYUSE (yytype); } /*--------------------------------. | Print this symbol on YYOUTPUT. | `--------------------------------*/ static void yy_symbol_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep, void* parser) { YYFPRINTF (yyoutput, "%s %s (", yytype < YYNTOKENS ? "token" : "nterm", yytname[yytype]); yy_symbol_value_print (yyoutput, yytype, yyvaluep, parser); YYFPRINTF (yyoutput, ")"); } /*------------------------------------------------------------------. | yy_stack_print -- Print the state stack from its BOTTOM up to its | | TOP (included). | `------------------------------------------------------------------*/ static void yy_stack_print (yytype_int16 *yybottom, yytype_int16 *yytop) { YYFPRINTF (stderr, "Stack now"); for (; yybottom <= yytop; yybottom++) { int yybot = *yybottom; YYFPRINTF (stderr, " %d", yybot); } YYFPRINTF (stderr, "\n"); } # define YY_STACK_PRINT(Bottom, Top) \ do { \ if (yydebug) \ yy_stack_print ((Bottom), (Top)); \ } while (0) /*------------------------------------------------. | Report that the YYRULE is going to be reduced. | `------------------------------------------------*/ static void yy_reduce_print (yytype_int16 *yyssp, YYSTYPE *yyvsp, int yyrule, void* parser) { unsigned long int yylno = yyrline[yyrule]; int yynrhs = yyr2[yyrule]; int yyi; YYFPRINTF (stderr, "Reducing stack by rule %d (line %lu):\n", yyrule - 1, yylno); /* The symbols being reduced. */ for (yyi = 0; yyi < yynrhs; yyi++) { YYFPRINTF (stderr, " $%d = ", yyi + 1); yy_symbol_print (stderr, yystos[yyssp[yyi + 1 - yynrhs]], &(yyvsp[(yyi + 1) - (yynrhs)]) , parser); YYFPRINTF (stderr, "\n"); } } # define YY_REDUCE_PRINT(Rule) \ do { \ if (yydebug) \ yy_reduce_print (yyssp, yyvsp, Rule, parser); \ } while (0) /* Nonzero means print parse trace. It is left uninitialized so that multiple parsers can coexist. */ int yydebug; #else /* !YYDEBUG */ # define YYDPRINTF(Args) # define YY_SYMBOL_PRINT(Title, Type, Value, Location) # define YY_STACK_PRINT(Bottom, Top) # define YY_REDUCE_PRINT(Rule) #endif /* !YYDEBUG */ /* YYINITDEPTH -- initial size of the parser's stacks. */ #ifndef YYINITDEPTH # define YYINITDEPTH 200 #endif /* YYMAXDEPTH -- maximum size the stacks can grow to (effective only if the built-in stack extension method is used). Do not make this value too large; the results are undefined if YYSTACK_ALLOC_MAXIMUM < YYSTACK_BYTES (YYMAXDEPTH) evaluated with infinite-precision integer arithmetic. */ #ifndef YYMAXDEPTH # define YYMAXDEPTH 10000 #endif #if YYERROR_VERBOSE # ifndef yystrlen # if defined __GLIBC__ && defined _STRING_H # define yystrlen strlen # else /* Return the length of YYSTR. */ static YYSIZE_T yystrlen (const char *yystr) { YYSIZE_T yylen; for (yylen = 0; yystr[yylen]; yylen++) continue; return yylen; } # endif # endif # ifndef yystpcpy # if defined __GLIBC__ && defined _STRING_H && defined _GNU_SOURCE # define yystpcpy stpcpy # else /* Copy YYSRC to YYDEST, returning the address of the terminating '\0' in YYDEST. */ static char * yystpcpy (char *yydest, const char *yysrc) { char *yyd = yydest; const char *yys = yysrc; while ((*yyd++ = *yys++) != '\0') continue; return yyd - 1; } # endif # endif # ifndef yytnamerr /* Copy to YYRES the contents of YYSTR after stripping away unnecessary quotes and backslashes, so that it's suitable for yyerror. The heuristic is that double-quoting is unnecessary unless the string contains an apostrophe, a comma, or backslash (other than backslash-backslash). YYSTR is taken from yytname. If YYRES is null, do not copy; instead, return the length of what the result would have been. */ static YYSIZE_T yytnamerr (char *yyres, const char *yystr) { if (*yystr == '"') { YYSIZE_T yyn = 0; char const *yyp = yystr; for (;;) switch (*++yyp) { case '\'': case ',': goto do_not_strip_quotes; case '\\': if (*++yyp != '\\') goto do_not_strip_quotes; /* Fall through. */ default: if (yyres) yyres[yyn] = *yyp; yyn++; break; case '"': if (yyres) yyres[yyn] = '\0'; return yyn; } do_not_strip_quotes: ; } if (! yyres) return yystrlen (yystr); return yystpcpy (yyres, yystr) - yyres; } # endif /* Copy into *YYMSG, which is of size *YYMSG_ALLOC, an error message about the unexpected token YYTOKEN for the state stack whose top is YYSSP. Return 0 if *YYMSG was successfully written. Return 1 if *YYMSG is not large enough to hold the message. In that case, also set *YYMSG_ALLOC to the required number of bytes. Return 2 if the required number of bytes is too large to store. */ static int yysyntax_error (YYSIZE_T *yymsg_alloc, char **yymsg, yytype_int16 *yyssp, int yytoken) { YYSIZE_T yysize0 = yytnamerr (YY_NULLPTR, yytname[yytoken]); YYSIZE_T yysize = yysize0; enum { YYERROR_VERBOSE_ARGS_MAXIMUM = 5 }; /* Internationalized format string. */ const char *yyformat = YY_NULLPTR; /* Arguments of yyformat. */ char const *yyarg[YYERROR_VERBOSE_ARGS_MAXIMUM]; /* Number of reported tokens (one for the "unexpected", one per "expected"). */ int yycount = 0; /* There are many possibilities here to consider: - If this state is a consistent state with a default action, then the only way this function was invoked is if the default action is an error action. In that case, don't check for expected tokens because there are none. - The only way there can be no lookahead present (in yychar) is if this state is a consistent state with a default action. Thus, detecting the absence of a lookahead is sufficient to determine that there is no unexpected or expected token to report. In that case, just report a simple "syntax error". - Don't assume there isn't a lookahead just because this state is a consistent state with a default action. There might have been a previous inconsistent state, consistent state with a non-default action, or user semantic action that manipulated yychar. - Of course, the expected token list depends on states to have correct lookahead information, and it depends on the parser not to perform extra reductions after fetching a lookahead from the scanner and before detecting a syntax error. Thus, state merging (from LALR or IELR) and default reductions corrupt the expected token list. However, the list is correct for canonical LR with one exception: it will still contain any token that will not be accepted due to an error action in a later state. */ if (yytoken != YYEMPTY) { int yyn = yypact[*yyssp]; yyarg[yycount++] = yytname[yytoken]; if (!yypact_value_is_default (yyn)) { /* Start YYX at -YYN if negative to avoid negative indexes in YYCHECK. In other words, skip the first -YYN actions for this state because they are default actions. */ int yyxbegin = yyn < 0 ? -yyn : 0; /* Stay within bounds of both yycheck and yytname. */ int yychecklim = YYLAST - yyn + 1; int yyxend = yychecklim < YYNTOKENS ? yychecklim : YYNTOKENS; int yyx; for (yyx = yyxbegin; yyx < yyxend; ++yyx) if (yycheck[yyx + yyn] == yyx && yyx != YYTERROR && !yytable_value_is_error (yytable[yyx + yyn])) { if (yycount == YYERROR_VERBOSE_ARGS_MAXIMUM) { yycount = 1; yysize = yysize0; break; } yyarg[yycount++] = yytname[yyx]; { YYSIZE_T yysize1 = yysize + yytnamerr (YY_NULLPTR, yytname[yyx]); if (! (yysize <= yysize1 && yysize1 <= YYSTACK_ALLOC_MAXIMUM)) return 2; yysize = yysize1; } } } } switch (yycount) { # define YYCASE_(N, S) \ case N: \ yyformat = S; \ break YYCASE_(0, YY_("syntax error")); YYCASE_(1, YY_("syntax error, unexpected %s")); YYCASE_(2, YY_("syntax error, unexpected %s, expecting %s")); YYCASE_(3, YY_("syntax error, unexpected %s, expecting %s or %s")); YYCASE_(4, YY_("syntax error, unexpected %s, expecting %s or %s or %s")); YYCASE_(5, YY_("syntax error, unexpected %s, expecting %s or %s or %s or %s")); # undef YYCASE_ } { YYSIZE_T yysize1 = yysize + yystrlen (yyformat); if (! (yysize <= yysize1 && yysize1 <= YYSTACK_ALLOC_MAXIMUM)) return 2; yysize = yysize1; } if (*yymsg_alloc < yysize) { *yymsg_alloc = 2 * yysize; if (! (yysize <= *yymsg_alloc && *yymsg_alloc <= YYSTACK_ALLOC_MAXIMUM)) *yymsg_alloc = YYSTACK_ALLOC_MAXIMUM; return 1; } /* Avoid sprintf, as that infringes on the user's name space. Don't have undefined behavior even if the translation produced a string with the wrong number of "%s"s. */ { char *yyp = *yymsg; int yyi = 0; while ((*yyp = *yyformat) != '\0') if (*yyp == '%' && yyformat[1] == 's' && yyi < yycount) { yyp += yytnamerr (yyp, yyarg[yyi++]); yyformat += 2; } else { yyp++; yyformat++; } } return 0; } #endif /* YYERROR_VERBOSE */ /*-----------------------------------------------. | Release the memory associated to this symbol. | `-----------------------------------------------*/ static void yydestruct (const char *yymsg, int yytype, YYSTYPE *yyvaluep, void* parser) { YYUSE (yyvaluep); YYUSE (parser); if (!yymsg) yymsg = "Deleting"; YY_SYMBOL_PRINT (yymsg, yytype, yyvaluep, yylocationp); YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN YYUSE (yytype); YY_IGNORE_MAYBE_UNINITIALIZED_END } /*----------. | yyparse. | `----------*/ int yyparse (void* parser) { /* The lookahead symbol. */ int yychar; /* The semantic value of the lookahead symbol. */ /* Default value used for initialization, for pacifying older GCCs or non-GCC compilers. */ YY_INITIAL_VALUE (static YYSTYPE yyval_default;) YYSTYPE yylval YY_INITIAL_VALUE (= yyval_default); /* Number of syntax errors so far. */ int yynerrs; int yystate; /* Number of tokens to shift before error messages enabled. */ int yyerrstatus; /* The stacks and their tools: 'yyss': related to states. 'yyvs': related to semantic values. Refer to the stacks through separate pointers, to allow yyoverflow to reallocate them elsewhere. */ /* The state stack. */ yytype_int16 yyssa[YYINITDEPTH]; yytype_int16 *yyss; yytype_int16 *yyssp; /* The semantic value stack. */ YYSTYPE yyvsa[YYINITDEPTH]; YYSTYPE *yyvs; YYSTYPE *yyvsp; YYSIZE_T yystacksize; int yyn; int yyresult; /* Lookahead token as an internal (translated) token number. */ int yytoken = 0; /* The variables used to return semantic value and location from the action routines. */ YYSTYPE yyval; #if YYERROR_VERBOSE /* Buffer for error messages, and its allocated size. */ char yymsgbuf[128]; char *yymsg = yymsgbuf; YYSIZE_T yymsg_alloc = sizeof yymsgbuf; #endif #define YYPOPSTACK(N) (yyvsp -= (N), yyssp -= (N)) /* The number of symbols on the RHS of the reduced rule. Keep to zero when no symbol should be popped. */ int yylen = 0; yyssp = yyss = yyssa; yyvsp = yyvs = yyvsa; yystacksize = YYINITDEPTH; YYDPRINTF ((stderr, "Starting parse\n")); yystate = 0; yyerrstatus = 0; yynerrs = 0; yychar = YYEMPTY; /* Cause a token to be read. */ goto yysetstate; /*------------------------------------------------------------. | yynewstate -- Push a new state, which is found in yystate. | `------------------------------------------------------------*/ yynewstate: /* In all cases, when you get here, the value and location stacks have just been pushed. So pushing a state here evens the stacks. */ yyssp++; yysetstate: *yyssp = yystate; if (yyss + yystacksize - 1 <= yyssp) { /* Get the current used size of the three stacks, in elements. */ YYSIZE_T yysize = yyssp - yyss + 1; #ifdef yyoverflow { /* Give user a chance to reallocate the stack. Use copies of these so that the &'s don't force the real ones into memory. */ YYSTYPE *yyvs1 = yyvs; yytype_int16 *yyss1 = yyss; /* Each stack pointer address is followed by the size of the data in use in that stack, in bytes. This used to be a conditional around just the two extra args, but that might be undefined if yyoverflow is a macro. */ yyoverflow (YY_("memory exhausted"), &yyss1, yysize * sizeof (*yyssp), &yyvs1, yysize * sizeof (*yyvsp), &yystacksize); yyss = yyss1; yyvs = yyvs1; } #else /* no yyoverflow */ # ifndef YYSTACK_RELOCATE goto yyexhaustedlab; # else /* Extend the stack our own way. */ if (YYMAXDEPTH <= yystacksize) goto yyexhaustedlab; yystacksize *= 2; if (YYMAXDEPTH < yystacksize) yystacksize = YYMAXDEPTH; { yytype_int16 *yyss1 = yyss; union yyalloc *yyptr = (union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize)); if (! yyptr) goto yyexhaustedlab; YYSTACK_RELOCATE (yyss_alloc, yyss); YYSTACK_RELOCATE (yyvs_alloc, yyvs); # undef YYSTACK_RELOCATE if (yyss1 != yyssa) YYSTACK_FREE (yyss1); } # endif #endif /* no yyoverflow */ yyssp = yyss + yysize - 1; yyvsp = yyvs + yysize - 1; YYDPRINTF ((stderr, "Stack size increased to %lu\n", (unsigned long int) yystacksize)); if (yyss + yystacksize - 1 <= yyssp) YYABORT; } YYDPRINTF ((stderr, "Entering state %d\n", yystate)); if (yystate == YYFINAL) YYACCEPT; goto yybackup; /*-----------. | yybackup. | `-----------*/ yybackup: /* Do appropriate processing given the current state. Read a lookahead token if we need one and don't already have one. */ /* First try to decide what to do without reference to lookahead token. */ yyn = yypact[yystate]; if (yypact_value_is_default (yyn)) goto yydefault; /* Not known => get a lookahead token if don't already have one. */ /* YYCHAR is either YYEMPTY or YYEOF or a valid lookahead symbol. */ if (yychar == YYEMPTY) { YYDPRINTF ((stderr, "Reading a token: ")); yychar = yylex (&yylval, parser); } if (yychar <= YYEOF) { yychar = yytoken = YYEOF; YYDPRINTF ((stderr, "Now at end of input.\n")); } else { yytoken = YYTRANSLATE (yychar); YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc); } /* If the proper action on seeing token YYTOKEN is to reduce or to detect an error, take that action. */ yyn += yytoken; if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken) goto yydefault; yyn = yytable[yyn]; if (yyn <= 0) { if (yytable_value_is_error (yyn)) goto yyerrlab; yyn = -yyn; goto yyreduce; } /* Count tokens shifted since error; after three, turn off error status. */ if (yyerrstatus) yyerrstatus--; /* Shift the lookahead token. */ YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc); /* Discard the shifted token. */ yychar = YYEMPTY; yystate = yyn; YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN *++yyvsp = yylval; YY_IGNORE_MAYBE_UNINITIALIZED_END goto yynewstate; /*-----------------------------------------------------------. | yydefault -- do the default action for the current state. | `-----------------------------------------------------------*/ yydefault: yyn = yydefact[yystate]; if (yyn == 0) goto yyerrlab; goto yyreduce; /*-----------------------------. | yyreduce -- Do a reduction. | `-----------------------------*/ yyreduce: /* yyn is the number of a rule to reduce with. */ yylen = yyr2[yyn]; /* If YYLEN is nonzero, implement the default value of the action: '$$ = $1'. Otherwise, the following line sets YYVAL to garbage. This behavior is undocumented and Bison users should not rely upon it. Assigning to YYVAL unconditionally makes the parser a bit smaller, and it avoids a GCC warning that YYVAL may be used uninitialized. */ yyval = yyvsp[1-yylen]; YY_REDUCE_PRINT (yyn); switch (yyn) { case 2: #line 176 "yyparser.y" /* yacc.c:1646 */ { PARSER->setProgramBlockAST(NULL); } #line 1825 "yyparser.cpp" /* yacc.c:1646 */ break; case 3: #line 177 "yyparser.y" /* yacc.c:1646 */ { PARSER->setProgramBlockAST((yyvsp[0].block)); } #line 1831 "yyparser.cpp" /* yacc.c:1646 */ break; case 4: #line 181 "yyparser.y" /* yacc.c:1646 */ { (yyval.block) = new BlockAST(); PARSER->addNodeAST((yyval.block)); if((yyvsp[0].node) != NULL) (yyval.block)->m_statements.push_back((yyvsp[0].node)); } #line 1837 "yyparser.cpp" /* yacc.c:1646 */ break; case 5: #line 182 "yyparser.y" /* yacc.c:1646 */ { if((yyvsp[0].node) != NULL) (yyvsp[-1].block)->m_statements.push_back((yyvsp[0].node)); } #line 1843 "yyparser.cpp" /* yacc.c:1646 */ break; case 6: #line 186 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = (yyvsp[0].node); } #line 1849 "yyparser.cpp" /* yacc.c:1646 */ break; case 7: #line 187 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = (yyvsp[0].node); } #line 1855 "yyparser.cpp" /* yacc.c:1646 */ break; case 8: #line 188 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = (yyvsp[0].node); } #line 1861 "yyparser.cpp" /* yacc.c:1646 */ break; case 9: #line 189 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = (yyvsp[0].node); } #line 1867 "yyparser.cpp" /* yacc.c:1646 */ break; case 10: #line 190 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = (yyvsp[0].node); } #line 1873 "yyparser.cpp" /* yacc.c:1646 */ break; case 11: #line 191 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = (yyvsp[0].node); } #line 1879 "yyparser.cpp" /* yacc.c:1646 */ break; case 12: #line 195 "yyparser.y" /* yacc.c:1646 */ { (yyval.block) = (yyvsp[-1].block); } #line 1885 "yyparser.cpp" /* yacc.c:1646 */ break; case 13: #line 196 "yyparser.y" /* yacc.c:1646 */ { (yyval.block) = new BlockAST(); PARSER->addNodeAST((yyval.block)); } #line 1891 "yyparser.cpp" /* yacc.c:1646 */ break; case 14: #line 200 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = NULL; } #line 1897 "yyparser.cpp" /* yacc.c:1646 */ break; case 15: #line 201 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = (yyvsp[-1].node); } #line 1903 "yyparser.cpp" /* yacc.c:1646 */ break; case 16: #line 202 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = (yyvsp[-1].node); } #line 1909 "yyparser.cpp" /* yacc.c:1646 */ break; case 17: #line 203 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = (yyvsp[0].block); } #line 1915 "yyparser.cpp" /* yacc.c:1646 */ break; case 18: #line 207 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = new NullAST(); PARSER->addNodeAST((yyval.node)); (yyval.node)->setLine((yyvsp[0].token).m_beginLine); } #line 1921 "yyparser.cpp" /* yacc.c:1646 */ break; case 19: #line 208 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = (yyvsp[0].node); } #line 1927 "yyparser.cpp" /* yacc.c:1646 */ break; case 20: #line 209 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = (yyvsp[0].node); } #line 1933 "yyparser.cpp" /* yacc.c:1646 */ break; case 21: #line 210 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = (yyvsp[0].node); } #line 1939 "yyparser.cpp" /* yacc.c:1646 */ break; case 22: #line 212 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = (yyvsp[0].node); } #line 1945 "yyparser.cpp" /* yacc.c:1646 */ break; case 23: #line 213 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = (yyvsp[0].getvar); } #line 1951 "yyparser.cpp" /* yacc.c:1646 */ break; case 24: #line 215 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = (yyvsp[-1].node); } #line 1957 "yyparser.cpp" /* yacc.c:1646 */ break; case 25: #line 216 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = new GetVarAST(NULL, "this"); PARSER->addNodeAST((yyval.node)); (yyval.node)->setLine((yyvsp[0].token).m_beginLine); } #line 1963 "yyparser.cpp" /* yacc.c:1646 */ break; case 26: #line 217 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = (yyvsp[0].node); } #line 1969 "yyparser.cpp" /* yacc.c:1646 */ break; case 27: #line 221 "yyparser.y" /* yacc.c:1646 */ { (yyval.nodelist) = new NodeASTList(); PARSER->addNodeAST((yyval.nodelist)); (yyval.nodelist)->push_back((yyvsp[0].node)); } #line 1975 "yyparser.cpp" /* yacc.c:1646 */ break; case 28: #line 222 "yyparser.y" /* yacc.c:1646 */ { (yyval.nodelist) = new NodeASTList(); PARSER->addNodeAST((yyval.nodelist)); (yyval.nodelist)->push_back((yyvsp[0].node)); } #line 1981 "yyparser.cpp" /* yacc.c:1646 */ break; case 29: #line 223 "yyparser.y" /* yacc.c:1646 */ { (yyval.nodelist) = new NodeASTList(); PARSER->addNodeAST((yyval.nodelist)); (yyval.nodelist)->push_back((yyvsp[0].func)); } #line 1987 "yyparser.cpp" /* yacc.c:1646 */ break; case 30: #line 224 "yyparser.y" /* yacc.c:1646 */ { (yyvsp[-2].nodelist)->push_back((yyvsp[0].node)); } #line 1993 "yyparser.cpp" /* yacc.c:1646 */ break; case 31: #line 225 "yyparser.y" /* yacc.c:1646 */ { (yyvsp[-2].nodelist)->push_back((yyvsp[0].node)); } #line 1999 "yyparser.cpp" /* yacc.c:1646 */ break; case 32: #line 226 "yyparser.y" /* yacc.c:1646 */ { (yyvsp[-2].nodelist)->push_back((yyvsp[0].func)); } #line 2005 "yyparser.cpp" /* yacc.c:1646 */ break; case 33: #line 230 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = (yyvsp[0].node); } #line 2011 "yyparser.cpp" /* yacc.c:1646 */ break; case 34: #line 231 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = new GetVarAST((yyvsp[-2].node), (yyvsp[0].token).getRawString()); PARSER->addNodeAST((yyval.node)); (yyval.node)->setLine((yyvsp[-1].token).m_beginLine); } #line 2017 "yyparser.cpp" /* yacc.c:1646 */ break; case 35: #line 232 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = new GetVarAST((yyvsp[-3].node), (yyvsp[-1].node)); PARSER->addNodeAST((yyval.node)); (yyval.node)->setLine((yyvsp[-2].token).m_beginLine); } #line 2023 "yyparser.cpp" /* yacc.c:1646 */ break; case 36: #line 233 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = new CallAST((yyvsp[-2].node), NULL); PARSER->addNodeAST((yyval.node)); (yyval.node)->setLine((yyvsp[0].token).m_beginLine); } #line 2029 "yyparser.cpp" /* yacc.c:1646 */ break; case 37: #line 234 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = new CallAST((yyvsp[-3].node), (yyvsp[-1].nodelist)); PARSER->addNodeAST((yyval.node)); (yyval.node)->setLine((yyvsp[0].token).m_beginLine); } #line 2035 "yyparser.cpp" /* yacc.c:1646 */ break; case 38: #line 235 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = new PostfixIncrementAST((yyvsp[-1].node), TOK_PLUSPLUS); PARSER->addNodeAST((yyval.node)); (yyval.node)->setLine((yyvsp[0].token).m_beginLine); } #line 2041 "yyparser.cpp" /* yacc.c:1646 */ break; case 39: #line 236 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = new PostfixIncrementAST((yyvsp[-1].node), TOK_MINUSMINUS); PARSER->addNodeAST((yyval.node)); (yyval.node)->setLine((yyvsp[0].token).m_beginLine); } #line 2047 "yyparser.cpp" /* yacc.c:1646 */ break; case 44: #line 247 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = (yyvsp[0].node); } #line 2053 "yyparser.cpp" /* yacc.c:1646 */ break; case 45: #line 248 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = new UnaryAST((yyvsp[0].node), TOK_PLUSPLUS); PARSER->addNodeAST((yyval.node)); (yyval.node)->setLine((yyvsp[-1].token).m_beginLine); } #line 2059 "yyparser.cpp" /* yacc.c:1646 */ break; case 46: #line 249 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = new UnaryAST((yyvsp[0].node), TOK_MINUSMINUS); PARSER->addNodeAST((yyval.node)); (yyval.node)->setLine((yyvsp[-1].token).m_beginLine); } #line 2065 "yyparser.cpp" /* yacc.c:1646 */ break; case 47: #line 250 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = new UnaryAST((yyvsp[0].node), (yyvsp[-1].token).m_type); PARSER->addNodeAST((yyval.node)); (yyval.node)->setLine((yyvsp[-1].token).m_beginLine); } #line 2071 "yyparser.cpp" /* yacc.c:1646 */ break; case 48: #line 254 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = (yyvsp[0].node); } #line 2077 "yyparser.cpp" /* yacc.c:1646 */ break; case 49: #line 255 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = new MultiplicativeAST((yyvsp[-2].node), TOK_MUL, (yyvsp[0].node)); PARSER->addNodeAST((yyval.node)); (yyval.node)->setLine((yyvsp[-1].token).m_beginLine); } #line 2083 "yyparser.cpp" /* yacc.c:1646 */ break; case 50: #line 256 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = new MultiplicativeAST((yyvsp[-2].node), TOK_DIV, (yyvsp[0].node)); PARSER->addNodeAST((yyval.node)); (yyval.node)->setLine((yyvsp[-1].token).m_beginLine); } #line 2089 "yyparser.cpp" /* yacc.c:1646 */ break; case 51: #line 257 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = new MultiplicativeAST((yyvsp[-2].node), TOK_MOD, (yyvsp[0].node)); PARSER->addNodeAST((yyval.node)); (yyval.node)->setLine((yyvsp[-1].token).m_beginLine); } #line 2095 "yyparser.cpp" /* yacc.c:1646 */ break; case 52: #line 261 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = (yyvsp[0].node); } #line 2101 "yyparser.cpp" /* yacc.c:1646 */ break; case 53: #line 262 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = new AdditiveAST((yyvsp[-2].node), TOK_PLUS, (yyvsp[0].node)); PARSER->addNodeAST((yyval.node)); (yyval.node)->setLine((yyvsp[-1].token).m_beginLine); } #line 2107 "yyparser.cpp" /* yacc.c:1646 */ break; case 54: #line 263 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = new AdditiveAST((yyvsp[-2].node), TOK_MINUS, (yyvsp[0].node)); PARSER->addNodeAST((yyval.node)); (yyval.node)->setLine((yyvsp[-1].token).m_beginLine); } #line 2113 "yyparser.cpp" /* yacc.c:1646 */ break; case 55: #line 267 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = (yyvsp[0].node); } #line 2119 "yyparser.cpp" /* yacc.c:1646 */ break; case 56: #line 268 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = new ShiftAST((yyvsp[-2].node), TOK_SHL, (yyvsp[0].node)); PARSER->addNodeAST((yyval.node)); (yyval.node)->setLine((yyvsp[-1].token).m_beginLine); } #line 2125 "yyparser.cpp" /* yacc.c:1646 */ break; case 57: #line 269 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = new ShiftAST((yyvsp[-2].node), TOK_SHR, (yyvsp[0].node)); PARSER->addNodeAST((yyval.node)); (yyval.node)->setLine((yyvsp[-1].token).m_beginLine); } #line 2131 "yyparser.cpp" /* yacc.c:1646 */ break; case 58: #line 273 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = (yyvsp[0].node); } #line 2137 "yyparser.cpp" /* yacc.c:1646 */ break; case 59: #line 274 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = new RelationalAST((yyvsp[-2].node), TOK_LT, (yyvsp[0].node)); PARSER->addNodeAST((yyval.node)); (yyval.node)->setLine((yyvsp[-1].token).m_beginLine); } #line 2143 "yyparser.cpp" /* yacc.c:1646 */ break; case 60: #line 275 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = new RelationalAST((yyvsp[-2].node), TOK_GT, (yyvsp[0].node)); PARSER->addNodeAST((yyval.node)); (yyval.node)->setLine((yyvsp[-1].token).m_beginLine); } #line 2149 "yyparser.cpp" /* yacc.c:1646 */ break; case 61: #line 276 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = new RelationalAST((yyvsp[-2].node), TOK_LE, (yyvsp[0].node)); PARSER->addNodeAST((yyval.node)); (yyval.node)->setLine((yyvsp[-1].token).m_beginLine); } #line 2155 "yyparser.cpp" /* yacc.c:1646 */ break; case 62: #line 277 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = new RelationalAST((yyvsp[-2].node), TOK_GE, (yyvsp[0].node)); PARSER->addNodeAST((yyval.node)); (yyval.node)->setLine((yyvsp[-1].token).m_beginLine); } #line 2161 "yyparser.cpp" /* yacc.c:1646 */ break; case 63: #line 281 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = (yyvsp[0].node); } #line 2167 "yyparser.cpp" /* yacc.c:1646 */ break; case 64: #line 282 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = new EqualityAST((yyvsp[-2].node), TOK_EQUAL, (yyvsp[0].node)); PARSER->addNodeAST((yyval.node)); (yyval.node)->setLine((yyvsp[-1].token).m_beginLine); } #line 2173 "yyparser.cpp" /* yacc.c:1646 */ break; case 65: #line 283 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = new EqualityAST((yyvsp[-2].node), TOK_NOTEQUAL, (yyvsp[0].node)); PARSER->addNodeAST((yyval.node)); (yyval.node)->setLine((yyvsp[-1].token).m_beginLine); } #line 2179 "yyparser.cpp" /* yacc.c:1646 */ break; case 66: #line 287 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = (yyvsp[0].node); } #line 2185 "yyparser.cpp" /* yacc.c:1646 */ break; case 67: #line 288 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = new AndAST((yyvsp[-2].node), (yyvsp[0].node)); PARSER->addNodeAST((yyval.node)); (yyval.node)->setLine((yyvsp[-1].token).m_beginLine); } #line 2191 "yyparser.cpp" /* yacc.c:1646 */ break; case 68: #line 292 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = (yyvsp[0].node); } #line 2197 "yyparser.cpp" /* yacc.c:1646 */ break; case 69: #line 293 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = new ExclusiveOrAST((yyvsp[-2].node), (yyvsp[0].node)); PARSER->addNodeAST((yyval.node)); (yyval.node)->setLine((yyvsp[-1].token).m_beginLine); } #line 2203 "yyparser.cpp" /* yacc.c:1646 */ break; case 70: #line 297 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = (yyvsp[0].node); } #line 2209 "yyparser.cpp" /* yacc.c:1646 */ break; case 71: #line 298 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = new InclusiveOrAST((yyvsp[-2].node), (yyvsp[0].node)); PARSER->addNodeAST((yyval.node)); (yyval.node)->setLine((yyvsp[-1].token).m_beginLine); } #line 2215 "yyparser.cpp" /* yacc.c:1646 */ break; case 72: #line 302 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = (yyvsp[0].node); } #line 2221 "yyparser.cpp" /* yacc.c:1646 */ break; case 73: #line 303 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = new LogicalAndAST((yyvsp[-2].node), (yyvsp[0].node)); PARSER->addNodeAST((yyval.node)); (yyval.node)->setLine((yyvsp[-1].token).m_beginLine); } #line 2227 "yyparser.cpp" /* yacc.c:1646 */ break; case 74: #line 307 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = (yyvsp[0].node); } #line 2233 "yyparser.cpp" /* yacc.c:1646 */ break; case 75: #line 308 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = new LogicalOrAST((yyvsp[-2].node), (yyvsp[0].node)); PARSER->addNodeAST((yyval.node)); (yyval.node)->setLine((yyvsp[-1].token).m_beginLine); } #line 2239 "yyparser.cpp" /* yacc.c:1646 */ break; case 76: #line 312 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = (yyvsp[0].node); } #line 2245 "yyparser.cpp" /* yacc.c:1646 */ break; case 77: #line 313 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = new ConditionalAST((yyvsp[-4].node), (yyvsp[-2].node), (yyvsp[0].node)); PARSER->addNodeAST((yyval.node)); (yyval.node)->setLine((yyvsp[-3].token).m_beginLine); } #line 2251 "yyparser.cpp" /* yacc.c:1646 */ break; case 91: #line 333 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = (yyvsp[0].node); } #line 2257 "yyparser.cpp" /* yacc.c:1646 */ break; case 92: #line 334 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = new AssignmentAST((yyvsp[-2].node), (yyvsp[-1].token).m_type, (yyvsp[0].node)); PARSER->addNodeAST((yyval.node)); (yyval.node)->setLine((yyvsp[-1].token).m_beginLine); } #line 2263 "yyparser.cpp" /* yacc.c:1646 */ break; case 93: #line 335 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = new AssignmentAST((yyvsp[-2].node), (yyvsp[-1].token).m_type, (yyvsp[0].node)); PARSER->addNodeAST((yyval.node)); (yyval.node)->setLine((yyvsp[-1].token).m_beginLine); } #line 2269 "yyparser.cpp" /* yacc.c:1646 */ break; case 94: #line 336 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = new AssignmentAST((yyvsp[-2].node), (yyvsp[-1].token).m_type, (yyvsp[0].func)); PARSER->addNodeAST((yyval.node)); (yyval.node)->setLine((yyvsp[-1].token).m_beginLine); } #line 2275 "yyparser.cpp" /* yacc.c:1646 */ break; case 95: #line 340 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = (yyvsp[0].node); } #line 2281 "yyparser.cpp" /* yacc.c:1646 */ break; case 96: #line 344 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = (yyvsp[0].node); } #line 2287 "yyparser.cpp" /* yacc.c:1646 */ break; case 97: #line 345 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = (yyvsp[0].node); } #line 2293 "yyparser.cpp" /* yacc.c:1646 */ break; case 98: #line 346 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = (yyvsp[0].func); } #line 2299 "yyparser.cpp" /* yacc.c:1646 */ break; case 99: #line 350 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = new BooleanAST(1); PARSER->addNodeAST((yyval.node)); (yyval.node)->setLine((yyvsp[0].token).m_beginLine); } #line 2305 "yyparser.cpp" /* yacc.c:1646 */ break; case 100: #line 351 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = new BooleanAST(0); PARSER->addNodeAST((yyval.node)); (yyval.node)->setLine((yyvsp[0].token).m_beginLine); } #line 2311 "yyparser.cpp" /* yacc.c:1646 */ break; case 101: #line 355 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = new Int32AST((yyvsp[0].token).m_integerValue); PARSER->addNodeAST((yyval.node)); (yyval.node)->setLine((yyvsp[0].token).m_beginLine); } #line 2317 "yyparser.cpp" /* yacc.c:1646 */ break; case 102: #line 356 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = new Int64AST((yyvsp[0].token).m_integerValue); PARSER->addNodeAST((yyval.node)); (yyval.node)->setLine((yyvsp[0].token).m_beginLine); } #line 2323 "yyparser.cpp" /* yacc.c:1646 */ break; case 103: #line 357 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = new FloatAST((yyvsp[0].token).m_doubleValue); PARSER->addNodeAST((yyval.node)); (yyval.node)->setLine((yyvsp[0].token).m_beginLine); } #line 2329 "yyparser.cpp" /* yacc.c:1646 */ break; case 104: #line 358 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = new DoubleAST((yyvsp[0].token).m_doubleValue); PARSER->addNodeAST((yyval.node)); (yyval.node)->setLine((yyvsp[0].token).m_beginLine); } #line 2335 "yyparser.cpp" /* yacc.c:1646 */ break; case 105: #line 362 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = new StringAST((yyvsp[0].token).toUTF8String(), (yyvsp[0].token).m_postfix); PARSER->addNodeAST((yyval.node)); (yyval.node)->setLine((yyvsp[0].token).m_beginLine); } #line 2341 "yyparser.cpp" /* yacc.c:1646 */ break; case 106: #line 367 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = new KeyValueAST((yyvsp[0].token).getRawString(), NULL); PARSER->addNodeAST((yyval.node)); (yyval.node)->setLine((yyvsp[0].token).m_beginLine); } #line 2351 "yyparser.cpp" /* yacc.c:1646 */ break; case 107: #line 373 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = new KeyValueAST((yyvsp[-2].token).getRawString(), (yyvsp[0].node)); PARSER->addNodeAST((yyval.node)); (yyval.node)->setLine((yyvsp[-2].token).m_beginLine); } #line 2361 "yyparser.cpp" /* yacc.c:1646 */ break; case 108: #line 379 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = new KeyValueAST((yyvsp[-3].node), (yyvsp[0].node)); PARSER->addNodeAST((yyval.node)); (yyval.node)->setLine((yyvsp[-4].token).m_beginLine); } #line 2371 "yyparser.cpp" /* yacc.c:1646 */ break; case 109: #line 385 "yyparser.y" /* yacc.c:1646 */ { GetVarAST* gv = (yyvsp[0].func)->m_nameExpr; if(gv->m_keyIdentifier.empty() || gv->m_parentExpr != 0 || gv->m_keyExpr != 0) { yyerror(parser, "invalid function name in table, must be a string"); YYABORT; } (yyval.node) = new KeyValueAST(gv->m_keyIdentifier, (yyvsp[0].func)); PARSER->addNodeAST((yyval.node)); (yyval.node)->setLine((yyvsp[0].func)->m_line); } #line 2387 "yyparser.cpp" /* yacc.c:1646 */ break; case 110: #line 398 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = new KeyValueAST(((StringAST*)(yyvsp[-2].node))->m_val, (yyvsp[0].node)); PARSER->addNodeAST((yyval.node)); } #line 2396 "yyparser.cpp" /* yacc.c:1646 */ break; case 111: #line 405 "yyparser.y" /* yacc.c:1646 */ { (yyval.nodelist) = new NodeASTList(); PARSER->addNodeAST((yyval.nodelist)); (yyval.nodelist)->push_back((yyvsp[0].node)); } #line 2402 "yyparser.cpp" /* yacc.c:1646 */ break; case 112: #line 406 "yyparser.y" /* yacc.c:1646 */ { (yyvsp[-2].nodelist)->push_back((yyvsp[0].node)); } #line 2408 "yyparser.cpp" /* yacc.c:1646 */ break; case 113: #line 410 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = new TableAST(NULL); PARSER->addNodeAST((yyval.node)); (yyval.node)->setLine((yyvsp[0].token).m_beginLine); } #line 2414 "yyparser.cpp" /* yacc.c:1646 */ break; case 114: #line 411 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = new TableAST((yyvsp[-1].nodelist)); PARSER->addNodeAST((yyval.node)); (yyval.node)->setLine((yyvsp[0].token).m_beginLine); } #line 2420 "yyparser.cpp" /* yacc.c:1646 */ break; case 115: #line 412 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = new TableAST((yyvsp[-2].nodelist)); PARSER->addNodeAST((yyval.node)); (yyval.node)->setLine((yyvsp[0].token).m_beginLine); } #line 2426 "yyparser.cpp" /* yacc.c:1646 */ break; case 116: #line 416 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = (yyvsp[0].node); } #line 2432 "yyparser.cpp" /* yacc.c:1646 */ break; case 117: #line 420 "yyparser.y" /* yacc.c:1646 */ { (yyval.nodelist) = new NodeASTList(); PARSER->addNodeAST((yyval.nodelist)); (yyval.nodelist)->push_back((yyvsp[0].node)); } #line 2438 "yyparser.cpp" /* yacc.c:1646 */ break; case 118: #line 421 "yyparser.y" /* yacc.c:1646 */ { (yyvsp[-2].nodelist)->push_back((yyvsp[0].node)); } #line 2444 "yyparser.cpp" /* yacc.c:1646 */ break; case 119: #line 425 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = new ArrayAST(NULL); PARSER->addNodeAST((yyval.node)); (yyval.node)->setLine((yyvsp[0].token).m_beginLine); } #line 2450 "yyparser.cpp" /* yacc.c:1646 */ break; case 120: #line 426 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = new ArrayAST((yyvsp[-1].nodelist)); PARSER->addNodeAST((yyval.node)); (yyval.node)->setLine((yyvsp[0].token).m_beginLine); } #line 2456 "yyparser.cpp" /* yacc.c:1646 */ break; case 121: #line 427 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = new ArrayAST((yyvsp[-2].nodelist)); PARSER->addNodeAST((yyval.node)); (yyval.node)->setLine((yyvsp[0].token).m_beginLine); } #line 2462 "yyparser.cpp" /* yacc.c:1646 */ break; case 124: #line 438 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = (yyvsp[0].node); } #line 2468 "yyparser.cpp" /* yacc.c:1646 */ break; case 125: #line 439 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = (yyvsp[0].func); } #line 2474 "yyparser.cpp" /* yacc.c:1646 */ break; case 126: #line 440 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = (yyvsp[0].func); } #line 2480 "yyparser.cpp" /* yacc.c:1646 */ break; case 127: #line 444 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = new VariableDeclarationListAST((yyvsp[-1].nodelist)); PARSER->addNodeAST((yyval.node)); (yyval.node)->setLine((yyvsp[0].token).m_beginLine); } #line 2486 "yyparser.cpp" /* yacc.c:1646 */ break; case 128: #line 448 "yyparser.y" /* yacc.c:1646 */ { (yyval.getvar) = new GetVarAST(NULL, (yyvsp[0].token).getRawString(), GetVarAST::NONE); PARSER->addNodeAST((yyval.getvar)); (yyval.getvar)->setLine((yyvsp[0].token).m_beginLine); } #line 2492 "yyparser.cpp" /* yacc.c:1646 */ break; case 129: #line 449 "yyparser.y" /* yacc.c:1646 */ { (yyval.getvar) = new GetVarAST(NULL, (yyvsp[0].token).getRawString(), GetVarAST::GLOBAL); PARSER->addNodeAST((yyval.getvar)); (yyval.getvar)->setLine((yyvsp[0].token).m_beginLine); } #line 2498 "yyparser.cpp" /* yacc.c:1646 */ break; case 130: #line 450 "yyparser.y" /* yacc.c:1646 */ { (yyval.getvar) = new GetVarAST(NULL, (yyvsp[0].token).getRawString(), GetVarAST::THIS); PARSER->addNodeAST((yyval.getvar)); (yyval.getvar)->setLine((yyvsp[0].token).m_beginLine); } #line 2504 "yyparser.cpp" /* yacc.c:1646 */ break; case 131: #line 451 "yyparser.y" /* yacc.c:1646 */ { (yyval.getvar) = new GetVarAST(NULL, (yyvsp[-1].node), GetVarAST::THIS); PARSER->addNodeAST((yyval.getvar)); (yyval.getvar)->setLine((yyvsp[0].token).m_beginLine); } #line 2510 "yyparser.cpp" /* yacc.c:1646 */ break; case 132: #line 457 "yyparser.y" /* yacc.c:1646 */ { (yyval.getvar) = (yyvsp[0].getvar); } #line 2516 "yyparser.cpp" /* yacc.c:1646 */ break; case 133: #line 458 "yyparser.y" /* yacc.c:1646 */ { (yyval.getvar) = new GetVarAST((yyvsp[-2].getvar), (yyvsp[0].token).getRawString()); PARSER->addNodeAST((yyval.getvar)); (yyval.getvar)->setLine((yyvsp[0].token).m_beginLine); } #line 2522 "yyparser.cpp" /* yacc.c:1646 */ break; case 134: #line 459 "yyparser.y" /* yacc.c:1646 */ { (yyval.getvar) = new GetVarAST((yyvsp[-3].getvar), (yyvsp[-1].node)); PARSER->addNodeAST((yyval.getvar)); (yyval.getvar)->setLine((yyvsp[0].token).m_beginLine); } #line 2528 "yyparser.cpp" /* yacc.c:1646 */ break; case 135: #line 464 "yyparser.y" /* yacc.c:1646 */ { (yyval.nodelist) = new NodeASTList(); PARSER->addNodeAST((yyval.nodelist)); VariableDeclarationAST* node = new VariableDeclarationAST((yyvsp[0].getvar), NULL, ((yyvsp[-1].token).m_type == TOK_LOCAL)); PARSER->addNodeAST(node); (yyval.nodelist)->push_back(node); } #line 2540 "yyparser.cpp" /* yacc.c:1646 */ break; case 136: #line 472 "yyparser.y" /* yacc.c:1646 */ { (yyval.nodelist) = new NodeASTList(); PARSER->addNodeAST((yyval.nodelist)); VariableDeclarationAST* node = new VariableDeclarationAST((yyvsp[-2].getvar), (yyvsp[0].node), ((yyvsp[-3].token).m_type == TOK_LOCAL)); PARSER->addNodeAST(node); (yyval.nodelist)->push_back(node); } #line 2552 "yyparser.cpp" /* yacc.c:1646 */ break; case 137: #line 480 "yyparser.y" /* yacc.c:1646 */ { VariableDeclarationAST* node0 = (VariableDeclarationAST*)(yyval.nodelist)->m_nodeASTVec[0]; VariableDeclarationAST* node = new VariableDeclarationAST((yyvsp[0].getvar), NULL, node0->m_isLocal); PARSER->addNodeAST(node); (yyval.nodelist)->push_back(node); } #line 2563 "yyparser.cpp" /* yacc.c:1646 */ break; case 138: #line 487 "yyparser.y" /* yacc.c:1646 */ { VariableDeclarationAST* node0 = (VariableDeclarationAST*)(yyval.nodelist)->m_nodeASTVec[0]; VariableDeclarationAST* node = new VariableDeclarationAST((yyvsp[-2].getvar), (yyvsp[0].node), node0->m_isLocal); PARSER->addNodeAST(node); (yyval.nodelist)->push_back(node); } #line 2574 "yyparser.cpp" /* yacc.c:1646 */ break; case 139: #line 497 "yyparser.y" /* yacc.c:1646 */ { (yyval.arglist) = new StringList(); PARSER->addNodeAST((yyval.arglist)); (yyval.arglist)->push_back((yyvsp[0].token).getRawString()); } #line 2584 "yyparser.cpp" /* yacc.c:1646 */ break; case 140: #line 503 "yyparser.y" /* yacc.c:1646 */ { (yyval.arglist) = new StringList(); PARSER->addNodeAST((yyval.arglist)); (yyval.arglist)->push_back((yyvsp[0].token).getRawString()); } #line 2594 "yyparser.cpp" /* yacc.c:1646 */ break; case 141: #line 509 "yyparser.y" /* yacc.c:1646 */ { (yyvsp[-2].arglist)->push_back((yyvsp[0].token).getRawString()); if((yyvsp[-2].arglist)->m_hasDuplicateStr) { yyerror(parser, "argument name is duplicate"); YYABORT; } } #line 2607 "yyparser.cpp" /* yacc.c:1646 */ break; case 142: #line 518 "yyparser.y" /* yacc.c:1646 */ { (yyvsp[-3].arglist)->push_back((yyvsp[0].token).getRawString()); if((yyvsp[-3].arglist)->m_hasDuplicateStr) { yyerror(parser, "argument name is duplicate"); YYABORT; } } #line 2620 "yyparser.cpp" /* yacc.c:1646 */ break; case 143: #line 530 "yyparser.y" /* yacc.c:1646 */ { (yyval.func) = new FunctionAST((yyvsp[-3].getvar), NULL, (yyvsp[0].block)); PARSER->addNodeAST((yyval.func)); (yyval.func)->setLine((yyvsp[-4].token).m_beginLine); } #line 2630 "yyparser.cpp" /* yacc.c:1646 */ break; case 144: #line 536 "yyparser.y" /* yacc.c:1646 */ { (yyval.func) = new FunctionAST((yyvsp[-4].getvar), (yyvsp[-2].arglist), (yyvsp[0].block)); PARSER->addNodeAST((yyval.func)); (yyval.func)->setLine((yyvsp[-5].token).m_beginLine); } #line 2640 "yyparser.cpp" /* yacc.c:1646 */ break; case 145: #line 544 "yyparser.y" /* yacc.c:1646 */ { (yyvsp[0].func)->m_isLocal = true; (yyval.func) = (yyvsp[0].func); } #line 2646 "yyparser.cpp" /* yacc.c:1646 */ break; case 146: #line 549 "yyparser.y" /* yacc.c:1646 */ { (yyval.func) = new FunctionAST(NULL, NULL, (yyvsp[0].block)); PARSER->addNodeAST((yyval.func)); (yyval.func)->setLine((yyvsp[-3].token).m_beginLine); } #line 2656 "yyparser.cpp" /* yacc.c:1646 */ break; case 147: #line 555 "yyparser.y" /* yacc.c:1646 */ { (yyval.func) = new FunctionAST(NULL, (yyvsp[-2].arglist), (yyvsp[0].block)); PARSER->addNodeAST((yyval.func)); (yyval.func)->setLine((yyvsp[-4].token).m_beginLine); } #line 2666 "yyparser.cpp" /* yacc.c:1646 */ break; case 148: #line 564 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = new IfElseAST((yyvsp[-4].node), (yyvsp[-2].node), (yyvsp[0].node)); PARSER->addNodeAST((yyval.node)); } #line 2672 "yyparser.cpp" /* yacc.c:1646 */ break; case 149: #line 566 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = new IfElseAST((yyvsp[-2].node), (yyvsp[0].node), NULL); PARSER->addNodeAST((yyval.node)); } #line 2678 "yyparser.cpp" /* yacc.c:1646 */ break; case 150: #line 568 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = new SwitchAST((yyvsp[-4].node), (yyvsp[-1].nodelist)); PARSER->addNodeAST((yyval.node)); } #line 2684 "yyparser.cpp" /* yacc.c:1646 */ break; case 151: #line 573 "yyparser.y" /* yacc.c:1646 */ { (yyval.nodelist) = new NodeASTList(); PARSER->addNodeAST((yyval.nodelist)); (yyval.nodelist)->add_case_ast((CaseAST*)((yyvsp[0].node))); } #line 2694 "yyparser.cpp" /* yacc.c:1646 */ break; case 152: #line 579 "yyparser.y" /* yacc.c:1646 */ { (yyvsp[-1].nodelist)->add_case_ast((CaseAST*)((yyvsp[0].node))); if((yyvsp[-1].nodelist)->m_hasMultipleDefaultStmt) { yyerror(parser, "multiple default labels in one switch"); YYABORT; } } #line 2707 "yyparser.cpp" /* yacc.c:1646 */ break; case 153: #line 590 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = new CaseAST((yyvsp[-2].node), (yyvsp[0].block)); PARSER->addNodeAST((yyval.node)); (yyval.node)->setLine((yyvsp[-3].token).m_beginLine); } #line 2713 "yyparser.cpp" /* yacc.c:1646 */ break; case 154: #line 591 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = new CaseAST((yyvsp[-1].node), NULL); PARSER->addNodeAST((yyval.node)); (yyval.node)->setLine((yyvsp[-2].token).m_beginLine); } #line 2719 "yyparser.cpp" /* yacc.c:1646 */ break; case 155: #line 592 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = new CaseAST(NULL, (yyvsp[0].block)); PARSER->addNodeAST((yyval.node)); (yyval.node)->setLine((yyvsp[-2].token).m_beginLine); } #line 2725 "yyparser.cpp" /* yacc.c:1646 */ break; case 156: #line 593 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = new CaseAST(NULL, NULL); PARSER->addNodeAST((yyval.node)); (yyval.node)->setLine((yyvsp[-1].token).m_beginLine); } #line 2731 "yyparser.cpp" /* yacc.c:1646 */ break; case 157: #line 597 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = new ContinueAST(); PARSER->addNodeAST((yyval.node)); (yyval.node)->setLine((yyvsp[-1].token).m_beginLine); } #line 2737 "yyparser.cpp" /* yacc.c:1646 */ break; case 158: #line 598 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = new BreakAST(); PARSER->addNodeAST((yyval.node)); (yyval.node)->setLine((yyvsp[-1].token).m_beginLine); } #line 2743 "yyparser.cpp" /* yacc.c:1646 */ break; case 159: #line 599 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = new ReturnAST(NULL); PARSER->addNodeAST((yyval.node)); (yyval.node)->setLine((yyvsp[-1].token).m_beginLine); } #line 2749 "yyparser.cpp" /* yacc.c:1646 */ break; case 160: #line 600 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = new ReturnAST((yyvsp[-1].node)); PARSER->addNodeAST((yyval.node)); (yyval.node)->setLine((yyvsp[-2].token).m_beginLine); } #line 2755 "yyparser.cpp" /* yacc.c:1646 */ break; case 161: #line 601 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = new ReturnAST((yyvsp[0].node)); PARSER->addNodeAST((yyval.node)); (yyval.node)->setLine((yyvsp[-1].token).m_beginLine); } #line 2761 "yyparser.cpp" /* yacc.c:1646 */ break; case 162: #line 602 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = new ReturnAST((yyvsp[0].func)); PARSER->addNodeAST((yyval.node)); (yyval.node)->setLine((yyvsp[-1].token).m_beginLine); } #line 2767 "yyparser.cpp" /* yacc.c:1646 */ break; case 163: #line 606 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = new WhileAST((yyvsp[-2].node), (yyvsp[0].node)); PARSER->addNodeAST((yyval.node)); (yyval.node)->setLine((yyvsp[-1].token).m_beginLine); } #line 2773 "yyparser.cpp" /* yacc.c:1646 */ break; case 164: #line 607 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = new DoWhileAST((yyvsp[-2].node), (yyvsp[-5].node)); PARSER->addNodeAST((yyval.node)); (yyval.node)->setLine((yyvsp[-1].token).m_beginLine); } #line 2779 "yyparser.cpp" /* yacc.c:1646 */ break; case 165: #line 608 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = new ForAST((yyvsp[-3].node), (yyvsp[-2].node), NULL, (yyvsp[0].node)); PARSER->addNodeAST((yyval.node)); (yyval.node)->setLine((yyvsp[-1].token).m_beginLine); } #line 2785 "yyparser.cpp" /* yacc.c:1646 */ break; case 166: #line 609 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = new ForAST((yyvsp[-4].node), (yyvsp[-3].node), (yyvsp[-2].node), (yyvsp[0].node)); PARSER->addNodeAST((yyval.node)); (yyval.node)->setLine((yyvsp[-1].token).m_beginLine); } #line 2791 "yyparser.cpp" /* yacc.c:1646 */ break; case 167: #line 610 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = new ForAST((yyvsp[-3].node), (yyvsp[-2].node), NULL, (yyvsp[0].node)); PARSER->addNodeAST((yyval.node)); (yyval.node)->setLine((yyvsp[-1].token).m_beginLine); } #line 2797 "yyparser.cpp" /* yacc.c:1646 */ break; case 168: #line 611 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = new ForAST((yyvsp[-4].node), (yyvsp[-3].node), (yyvsp[-2].node), (yyvsp[0].node)); PARSER->addNodeAST((yyval.node)); (yyval.node)->setLine((yyvsp[-1].token).m_beginLine); } #line 2803 "yyparser.cpp" /* yacc.c:1646 */ break; case 169: #line 612 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = (yyvsp[0].node); } #line 2809 "yyparser.cpp" /* yacc.c:1646 */ break; case 170: #line 617 "yyparser.y" /* yacc.c:1646 */ { if((yyvsp[-4].node)->m_type != NodeAST::tGetVarAST) { yyerror(parser, "for-each expression is illegal"); YYABORT; } (yyval.node) = new ForeachAST(0, NULL, (GetVarAST*)(yyvsp[-4].node), (yyvsp[-2].node), (yyvsp[0].node)); PARSER->addNodeAST((yyval.node)); (yyval.node)->setLine((yyvsp[-1].token).m_beginLine); } #line 2824 "yyparser.cpp" /* yacc.c:1646 */ break; case 171: #line 628 "yyparser.y" /* yacc.c:1646 */ { if((yyvsp[-6].node)->m_type != NodeAST::tGetVarAST) { yyerror(parser, "for-each expression is illegal"); YYABORT; } (yyval.node) = new ForeachAST(0, (GetVarAST*)(yyvsp[-6].node), (yyvsp[-4].getvar), (yyvsp[-2].node), (yyvsp[0].node)); PARSER->addNodeAST((yyval.node)); (yyval.node)->setLine((yyvsp[-1].token).m_beginLine); } #line 2839 "yyparser.cpp" /* yacc.c:1646 */ break; case 172: #line 639 "yyparser.y" /* yacc.c:1646 */ { VariableDeclarationAST* node0 = (VariableDeclarationAST*)(yyvsp[-4].nodelist)->m_nodeASTVec[0]; if(node0->m_assignmentExpr != NULL) { yyerror(parser, "for-each expression is illegal"); YYABORT; } GetVarAST* getvar0 = node0->m_varExpr; VariableDeclarationAST* node1 = NULL; GetVarAST* getvar1 = NULL; if((yyvsp[-4].nodelist)->m_nodeASTVec.size() >= 2) { node1 = (VariableDeclarationAST*)(yyvsp[-4].nodelist)->m_nodeASTVec[1]; if(node1->m_assignmentExpr != NULL) { yyerror(parser, "for-each expression is illegal"); YYABORT; } getvar1 = node1->m_varExpr; } if(getvar1 == 0) { (yyval.node) = new ForeachAST(node0->m_isLocal? TOK_LOCAL : TOK_VAR, NULL, getvar0, (yyvsp[-2].node), (yyvsp[0].node)); } else { (yyval.node) = new ForeachAST(node0->m_isLocal? TOK_LOCAL : TOK_VAR, getvar0, getvar1, (yyvsp[-2].node), (yyvsp[0].node)); } PARSER->addNodeAST((yyval.node)); (yyval.node)->setLine((yyvsp[-1].token).m_beginLine); } #line 2877 "yyparser.cpp" /* yacc.c:1646 */ break; case 173: #line 675 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = new NamespaceAST((yyvsp[-3].getvar), (yyvsp[-1].block)); PARSER->addNodeAST((yyval.node)); (yyval.node)->setLine((yyvsp[-4].token).m_beginLine); } #line 2883 "yyparser.cpp" /* yacc.c:1646 */ break; case 174: #line 676 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = new NamespaceAST((yyvsp[-2].getvar), NULL); PARSER->addNodeAST((yyval.node)); (yyval.node)->setLine((yyvsp[-3].token).m_beginLine); } #line 2889 "yyparser.cpp" /* yacc.c:1646 */ break; case 175: #line 680 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = new NewAST((yyvsp[-2].getvar), NULL); PARSER->addNodeAST((yyval.node)); (yyval.node)->setLine((yyvsp[-3].token).m_beginLine); } #line 2895 "yyparser.cpp" /* yacc.c:1646 */ break; case 176: #line 681 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = new NewAST((yyvsp[-3].getvar), (yyvsp[-1].nodelist)); PARSER->addNodeAST((yyval.node)); (yyval.node)->setLine((yyvsp[-4].token).m_beginLine); } #line 2901 "yyparser.cpp" /* yacc.c:1646 */ break; case 177: #line 685 "yyparser.y" /* yacc.c:1646 */ { (yyval.node) = new DeleteAST((yyvsp[0].getvar)); PARSER->addNodeAST((yyval.node)); (yyval.node)->setLine((yyvsp[-1].token).m_beginLine); } #line 2907 "yyparser.cpp" /* yacc.c:1646 */ break; #line 2911 "yyparser.cpp" /* yacc.c:1646 */ default: break; } /* User semantic actions sometimes alter yychar, and that requires that yytoken be updated with the new translation. We take the approach of translating immediately before every use of yytoken. One alternative is translating here after every semantic action, but that translation would be missed if the semantic action invokes YYABORT, YYACCEPT, or YYERROR immediately after altering yychar or if it invokes YYBACKUP. In the case of YYABORT or YYACCEPT, an incorrect destructor might then be invoked immediately. In the case of YYERROR or YYBACKUP, subsequent parser actions might lead to an incorrect destructor call or verbose syntax error message before the lookahead is translated. */ YY_SYMBOL_PRINT ("-> $$ =", yyr1[yyn], &yyval, &yyloc); YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); *++yyvsp = yyval; /* Now 'shift' the result of the reduction. Determine what state that goes to, based on the state we popped back to and the rule number reduced by. */ yyn = yyr1[yyn]; yystate = yypgoto[yyn - YYNTOKENS] + *yyssp; if (0 <= yystate && yystate <= YYLAST && yycheck[yystate] == *yyssp) yystate = yytable[yystate]; else yystate = yydefgoto[yyn - YYNTOKENS]; goto yynewstate; /*--------------------------------------. | yyerrlab -- here on detecting error. | `--------------------------------------*/ yyerrlab: /* Make sure we have latest lookahead translation. See comments at user semantic actions for why this is necessary. */ yytoken = yychar == YYEMPTY ? YYEMPTY : YYTRANSLATE (yychar); /* If not already recovering from an error, report this error. */ if (!yyerrstatus) { ++yynerrs; #if ! YYERROR_VERBOSE yyerror (parser, YY_("syntax error")); #else # define YYSYNTAX_ERROR yysyntax_error (&yymsg_alloc, &yymsg, \ yyssp, yytoken) { char const *yymsgp = YY_("syntax error"); int yysyntax_error_status; yysyntax_error_status = YYSYNTAX_ERROR; if (yysyntax_error_status == 0) yymsgp = yymsg; else if (yysyntax_error_status == 1) { if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); yymsg = (char *) YYSTACK_ALLOC (yymsg_alloc); if (!yymsg) { yymsg = yymsgbuf; yymsg_alloc = sizeof yymsgbuf; yysyntax_error_status = 2; } else { yysyntax_error_status = YYSYNTAX_ERROR; yymsgp = yymsg; } } yyerror (parser, yymsgp); if (yysyntax_error_status == 2) goto yyexhaustedlab; } # undef YYSYNTAX_ERROR #endif } if (yyerrstatus == 3) { /* If just tried and failed to reuse lookahead token after an error, discard it. */ if (yychar <= YYEOF) { /* Return failure if at end of input. */ if (yychar == YYEOF) YYABORT; } else { yydestruct ("Error: discarding", yytoken, &yylval, parser); yychar = YYEMPTY; } } /* Else will try to reuse lookahead token after shifting the error token. */ goto yyerrlab1; /*---------------------------------------------------. | yyerrorlab -- error raised explicitly by YYERROR. | `---------------------------------------------------*/ yyerrorlab: /* Pacify compilers like GCC when the user code never invokes YYERROR and the label yyerrorlab therefore never appears in user code. */ if (/*CONSTCOND*/ 0) goto yyerrorlab; /* Do not reclaim the symbols of the rule whose action triggered this YYERROR. */ YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); yystate = *yyssp; goto yyerrlab1; /*-------------------------------------------------------------. | yyerrlab1 -- common code for both syntax error and YYERROR. | `-------------------------------------------------------------*/ yyerrlab1: yyerrstatus = 3; /* Each real token shifted decrements this. */ for (;;) { yyn = yypact[yystate]; if (!yypact_value_is_default (yyn)) { yyn += YYTERROR; if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYTERROR) { yyn = yytable[yyn]; if (0 < yyn) break; } } /* Pop the current state because it cannot handle the error token. */ if (yyssp == yyss) YYABORT; yydestruct ("Error: popping", yystos[yystate], yyvsp, parser); YYPOPSTACK (1); yystate = *yyssp; YY_STACK_PRINT (yyss, yyssp); } YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN *++yyvsp = yylval; YY_IGNORE_MAYBE_UNINITIALIZED_END /* Shift the error token. */ YY_SYMBOL_PRINT ("Shifting", yystos[yyn], yyvsp, yylsp); yystate = yyn; goto yynewstate; /*-------------------------------------. | yyacceptlab -- YYACCEPT comes here. | `-------------------------------------*/ yyacceptlab: yyresult = 0; goto yyreturn; /*-----------------------------------. | yyabortlab -- YYABORT comes here. | `-----------------------------------*/ yyabortlab: yyresult = 1; goto yyreturn; #if !defined yyoverflow || YYERROR_VERBOSE /*-------------------------------------------------. | yyexhaustedlab -- memory exhaustion comes here. | `-------------------------------------------------*/ yyexhaustedlab: yyerror (parser, YY_("memory exhausted")); yyresult = 2; /* Fall through. */ #endif yyreturn: if (yychar != YYEMPTY) { /* Make sure we have latest lookahead translation. See comments at user semantic actions for why this is necessary. */ yytoken = YYTRANSLATE (yychar); yydestruct ("Cleanup: discarding lookahead", yytoken, &yylval, parser); } /* Do not reclaim the symbols of the rule whose action triggered this YYABORT or YYACCEPT. */ YYPOPSTACK (yylen); YY_STACK_PRINT (yyss, yyssp); while (yyssp != yyss) { yydestruct ("Cleanup: popping", yystos[*yyssp], yyvsp, parser); YYPOPSTACK (1); } #ifndef yyoverflow if (yyss != yyssa) YYSTACK_FREE (yyss); #endif #if YYERROR_VERBOSE if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); #endif return yyresult; } #line 688 "yyparser.y" /* yacc.c:1906 */
20,082
https://github.com/alexander-pimenov/lessons-job4j/blob/master/chapter_tutorial/src/main/java/ru/job4j/tutorial/yandex_tasks/test_april/CipherCode.java
Github Open Source
Open Source
Apache-2.0
null
lessons-job4j
alexander-pimenov
Java
Code
465
1,440
package ru.job4j.tutorial.yandex_tasks.test_april; import java.util.Scanner; /** * Здесь рассмотрены некоторые варианты кодировки или просто сдвига посимвольно в строке */ public class CipherCode { static String alfa = "абвгдежзиклмнопрстуфхцчшщъыьэюяАБВГДЕЖЗИКЛМНОПРСТУФХЦЧШЩЪЫьЭЮЯ !?.,"; public static void main(String[] args) { String ret; Scanner sc = new Scanner(System.in); System.out.print("Введите строку:"); //String str = "просто пример строки"; //sc.nextLine(); String str = "я ваша тетя"; //sc.nextLine(); System.out.print("Введите строку:"); String key = "ключ"; //sc.nextLine(); System.out.println(""); System.out.println(str); System.out.println(key); ret = cryptStr(str, key); System.out.println("туда"); System.out.println(ret); ret = cryptStr(ret, key); System.out.println("обратно"); System.out.println(ret); String row = "yandex"; String row2 = "a"; String row3 = "y"; String row4 = "z"; String row5 = "bcc"; String row6 = "def"; // String s1 = "abcdef"; // char[] str = s1.toCharArray(); // StringBuilder s2 = new StringBuilder(); // s2.append(str[str.length-1]); // for (int i=0; i<s1.length()-1; i++) { // s2.append(str[i]); // } // System.out.println(s2); System.out.println(cycle(row)); System.out.println(substring(row)); System.out.println(encode(row, 2)); System.out.println(encode(row2, 2)); System.out.println(encode(row3, 2)); System.out.println(encode(row4, 2)); System.out.println(row5 + " -> " + encode(row5, 2)); System.out.println(row5 + " -> " + code(row5, 2)); System.out.println(row6 + " -> " + encode(row6, 2)); System.out.println(row6 + " -> " + code(row6, 2)); } private static String cryptStr(String str, String key) { StringBuilder res = new StringBuilder(); char[] codeKey = key.toCharArray(); // разложили ключ в байты for (int i = 0; i < codeKey.length; i++) codeKey[i] = (char) alfa.indexOf(codeKey[i]); // привели символы к номерам символов в alfa char[] codeStr = str.toCharArray(); // разложили строку в байты for (int i = 0; i < codeStr.length; i++) { codeStr[i] = (char) alfa.indexOf(codeStr[i]); // привели символ к номеру из alfa res.append(alfa.charAt(codeStr[i] ^ codeKey[i % codeKey.length])); // сохранили символ alfa с номером XOR кодов } return res.toString(); } public static String cycle(String row) { // сдвиг вправо на 1 элемент char[] m = row.toCharArray(); int n = 1; char[] result = new char[m.length]; for (int i = 0; i < m.length - n; i++) { result[i + n] = m[i]; } for (int i = 0; i < n; i++) { result[i] = m[m.length - n + i]; } return new String(result); } public static String substring(String row) { // сдвиг вправо на 2 элемента int move = 2; int cursor = row.length() - move; return row.substring(cursor) + row.substring(0, cursor); } public static String encode(String text, int move) { char[] chars = text.toCharArray(); char[] result = new char[chars.length]; for (int i = 0; i < chars.length; i++) { int i1 = chars[i] + move; System.out.print(i1); System.out.println((char) i1); result[i] = (char) (chars[i] + move); } return new String(result) + " - такой ответ"; } public static String code(String text, int move) { char[] chars = text.toCharArray(); char[] result = new char[chars.length]; for (int i = 0; i < chars.length; i++) { int i1 = chars[i] - move; System.out.print(i1); System.out.println((char) i1); result[i] = (char) (chars[i] - move); } return new String(result) + " - такой ответ"; } }
14,474
https://github.com/prashanthkk/imx-atf/blob/master/lib/libc/memset.c
Github Open Source
Open Source
BSD-3-Clause
2,019
imx-atf
prashanthkk
C
Code
39
107
/* * Copyright (c) 2013-2018, ARM Limited and Contributors. All rights reserved. * * SPDX-License-Identifier: BSD-3-Clause */ #include <stddef.h> void *memset(void *dst, int val, size_t count) { char *ptr = dst; while (count--) *ptr++ = val; return dst; }
27,487
https://github.com/dotnetkits/Mapster/blob/master/src/Mapster/Models/KeyValuePairModel.cs
Github Open Source
Open Source
MIT
2,022
Mapster
dotnetkits
C#
Code
119
368
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; namespace Mapster.Models { public class KeyValuePairModel : IMemberModelEx { readonly Func<Expression, Expression, Expression> _getFn; readonly Func<Expression, Expression, Expression, Expression> _setFn; public KeyValuePairModel(string name, Type type, Func<Expression, Expression, Expression> getFn, Func<Expression, Expression, Expression, Expression> setFn) { Name = name; Type = type; _getFn = getFn; _setFn = setFn; } public Type Type { get; } public string Name { get; } public object? Info => null; public AccessModifier SetterModifier => AccessModifier.Public; public AccessModifier AccessModifier => AccessModifier.Public; public IEnumerable<object> GetCustomAttributes(bool inherit) => Enumerable.Empty<object>(); public IEnumerable<CustomAttributeData> GetCustomAttributesData() => Enumerable.Empty<CustomAttributeData>(); public Expression GetExpression(Expression source) { return _getFn(source, Expression.Constant(this.Name)); } public Expression SetExpression(Expression source, Expression value) { return _setFn(source, Expression.Constant(this.Name), value); } } }
12,380
https://github.com/cpehle/SciLean/blob/master/SciLean/Mechanics.lean
Github Open Source
Open Source
Apache-2.0
2,022
SciLean
cpehle
Lean
Code
2
11
import SciLean.Mechanics.Basic
18,296
https://github.com/marco-c/gecko-dev-wordified/blob/master/gfx/harfbuzz/src/hb-ot-var-avar-table.hh
Github Open Source
Open Source
LicenseRef-scancode-unknown-license-reference, MIT-Modern-Variant, LicenseRef-scancode-other-permissive
2,023
gecko-dev-wordified
marco-c
C++
Code
1,547
3,703
/ * * Copyright 2017 Google Inc . * * This is part of HarfBuzz a text shaping library . * * Permission is hereby granted without written agreement and without * license or royalty fees to use copy modify and distribute this * software and its documentation for any purpose provided that the * above copyright notice and the following two paragraphs appear in * all copies of this software . * * IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR * DIRECT INDIRECT SPECIAL INCIDENTAL OR CONSEQUENTIAL DAMAGES * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION EVEN * IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE . * * THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES INCLUDING * BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE . THE SOFTWARE PROVIDED HEREUNDER IS * ON AN " AS IS " BASIS AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO * PROVIDE MAINTENANCE SUPPORT UPDATES ENHANCEMENTS OR MODIFICATIONS . * * Google Author ( s ) : Behdad Esfahbod * / # ifndef HB_OT_VAR_AVAR_TABLE_HH # define HB_OT_VAR_AVAR_TABLE_HH # include " hb - open - type . hh " # include " hb - ot - var - common . hh " / * * avar - - Axis Variations * https : / / docs . microsoft . com / en - us / typography / opentype / spec / avar * / # define HB_OT_TAG_avar HB_TAG ( ' a ' ' v ' ' a ' ' r ' ) namespace OT { / * " Spec " : https : / / github . com / be - fonts / boring - expansion - spec / issues / 14 * / struct avarV2Tail { friend struct avar ; bool sanitize ( hb_sanitize_context_t * c const void * base ) const { TRACE_SANITIZE ( this ) ; return_trace ( varIdxMap . sanitize ( c base ) & & varStore . sanitize ( c base ) ) ; } protected : Offset32To < DeltaSetIndexMap > varIdxMap ; / * Offset from the beginning of ' avar ' table . * / Offset32To < VariationStore > varStore ; / * Offset from the beginning of ' avar ' table . * / public : DEFINE_SIZE_STATIC ( 8 ) ; } ; struct AxisValueMap { bool sanitize ( hb_sanitize_context_t * c ) const { TRACE_SANITIZE ( this ) ; return_trace ( c - > check_struct ( this ) ) ; } public : F2DOT14 coords [ 2 ] ; / / F2DOT14 fromCoord ; / * A normalized coordinate value obtained using / / * default normalization . * / / / F2DOT14 toCoord ; / * The modified normalized coordinate value . * / public : DEFINE_SIZE_STATIC ( 4 ) ; } ; struct SegmentMaps : Array16Of < AxisValueMap > { int map ( int value unsigned int from_offset = 0 unsigned int to_offset = 1 ) const { # define fromCoord coords [ from_offset ] . to_int ( ) # define toCoord coords [ to_offset ] . to_int ( ) / * The following special - cases are not part of OpenType which requires * that at least - 1 0 and + 1 must be mapped . But we include these as * part of a better error recovery scheme . * / if ( len < 2 ) { if ( ! len ) return value ; else / * len = = 1 * / return value - arrayZ [ 0 ] . fromCoord + arrayZ [ 0 ] . toCoord ; } if ( value < = arrayZ [ 0 ] . fromCoord ) return value - arrayZ [ 0 ] . fromCoord + arrayZ [ 0 ] . toCoord ; unsigned int i ; unsigned int count = len - 1 ; for ( i = 1 ; i < count & & value > arrayZ [ i ] . fromCoord ; i + + ) ; if ( value > = arrayZ [ i ] . fromCoord ) return value - arrayZ [ i ] . fromCoord + arrayZ [ i ] . toCoord ; if ( unlikely ( arrayZ [ i - 1 ] . fromCoord = = arrayZ [ i ] . fromCoord ) ) return arrayZ [ i - 1 ] . toCoord ; int denom = arrayZ [ i ] . fromCoord - arrayZ [ i - 1 ] . fromCoord ; return roundf ( arrayZ [ i - 1 ] . toCoord + ( ( float ) ( arrayZ [ i ] . toCoord - arrayZ [ i - 1 ] . toCoord ) * ( value - arrayZ [ i - 1 ] . fromCoord ) ) / denom ) ; # undef toCoord # undef fromCoord } int unmap ( int value ) const { return map ( value 1 0 ) ; } public : DEFINE_SIZE_ARRAY ( 2 * this ) ; } ; struct avar { static constexpr hb_tag_t tableTag = HB_OT_TAG_avar ; bool has_data ( ) const { return version . to_int ( ) ; } const SegmentMaps * get_segment_maps ( ) const { return & firstAxisSegmentMaps ; } unsigned get_axis_count ( ) const { return axisCount ; } bool sanitize ( hb_sanitize_context_t * c ) const { TRACE_SANITIZE ( this ) ; if ( ! ( version . sanitize ( c ) & & ( version . major = = 1 # ifndef HB_NO_AVAR2 | | version . major = = 2 # endif ) & & c - > check_struct ( this ) ) ) return_trace ( false ) ; const SegmentMaps * map = & firstAxisSegmentMaps ; unsigned int count = axisCount ; for ( unsigned int i = 0 ; i < count ; i + + ) { if ( unlikely ( ! map - > sanitize ( c ) ) ) return_trace ( false ) ; map = & StructAfter < SegmentMaps > ( * map ) ; } # ifndef HB_NO_AVAR2 if ( version . major < 2 ) return_trace ( true ) ; const auto & v2 = * ( const avarV2Tail * ) map ; if ( unlikely ( ! v2 . sanitize ( c this ) ) ) return_trace ( false ) ; # endif return_trace ( true ) ; } void map_coords ( int * coords unsigned int coords_length ) const { unsigned int count = hb_min ( coords_length axisCount ) ; const SegmentMaps * map = & firstAxisSegmentMaps ; for ( unsigned int i = 0 ; i < count ; i + + ) { coords [ i ] = map - > map ( coords [ i ] ) ; map = & StructAfter < SegmentMaps > ( * map ) ; } # ifndef HB_NO_AVAR2 if ( version . major < 2 ) return ; for ( ; count < axisCount ; count + + ) map = & StructAfter < SegmentMaps > ( * map ) ; const auto & v2 = * ( const avarV2Tail * ) map ; const auto & varidx_map = this + v2 . varIdxMap ; const auto & var_store = this + v2 . varStore ; auto * var_store_cache = var_store . create_cache ( ) ; hb_vector_t < int > out ; out . alloc ( coords_length ) ; for ( unsigned i = 0 ; i < coords_length ; i + + ) { int v = coords [ i ] ; uint32_t varidx = varidx_map . map ( i ) ; float delta = var_store . get_delta ( varidx coords coords_length var_store_cache ) ; v + = roundf ( delta ) ; v = hb_clamp ( v - ( 1 < < 14 ) + ( 1 < < 14 ) ) ; out . push ( v ) ; } for ( unsigned i = 0 ; i < coords_length ; i + + ) coords [ i ] = out [ i ] ; OT : : VariationStore : : destroy_cache ( var_store_cache ) ; # endif } void unmap_coords ( int * coords unsigned int coords_length ) const { unsigned int count = hb_min ( coords_length axisCount ) ; const SegmentMaps * map = & firstAxisSegmentMaps ; for ( unsigned int i = 0 ; i < count ; i + + ) { coords [ i ] = map - > unmap ( coords [ i ] ) ; map = & StructAfter < SegmentMaps > ( * map ) ; } } protected : FixedVersion < > version ; / * Version of the avar table * initially set to 0x00010000u * / HBUINT16 reserved ; / * This field is permanently reserved . Set to 0 . * / HBUINT16 axisCount ; / * The number of variation axes in the font . This * must be the same number as axisCount in the * ' fvar ' table . * / SegmentMaps firstAxisSegmentMaps ; public : DEFINE_SIZE_MIN ( 8 ) ; } ; } / * namespace OT * / # endif / * HB_OT_VAR_AVAR_TABLE_HH * /
45,783
https://github.com/sendevman/rctvertex/blob/master/packages/material-hooks/src/phong/attenuation.glsl
Github Open Source
Open Source
MIT
2,022
rctvertex
sendevman
GLSL
Code
53
163
// attenuation by Tom Madams // Simple: // https://imdoingitwrong.wordpress.com/2011/01/31/light-attenuation/ // // Improved // https://imdoingitwrong.wordpress.com/2011/02/10/improved-light-attenuation/ float attenuation(float r, float f, float d) { float denom = d / r + 1.0; float attenuation = 1.0 / (denom*denom); float t = (attenuation - f) / (1.0 - f); return max(t, 0.0); } #pragma glslify: export(attenuation)
24,310
https://github.com/own-character-in-pocket/client-desktop/blob/master/app/request/schema/AudioType/AudioWavType/index.ts
Github Open Source
Open Source
MIT
2,020
client-desktop
own-character-in-pocket
TypeScript
Code
48
136
import { GraphQLID, GraphQLNonNull, GraphQLObjectType, GraphQLString } from 'graphql'; import { NodeInterface } from '../../NodeInterface'; import { AudioInterface } from '../AudioInterface'; export const AudioWavType = new GraphQLObjectType({ name: 'AudioWavType', interfaces: [NodeInterface, AudioInterface], fields: { id: { type: new GraphQLNonNull(GraphQLID) }, quality: { type: new GraphQLNonNull(GraphQLString) } } });
22,238
https://github.com/Ical852/Mechanical-Engineering-System---OEE/blob/master/application/views/sql.sql
Github Open Source
Open Source
MIT
null
Mechanical-Engineering-System---OEE
Ical852
SQL
Code
131
452
SELECT t.nama_mesin, t.date, t.OEE FROM oee_data t INNER JOIN (SELECT nama_mesin, MAX(date) AS MaxDate FROM oee_data GROUP BY nama_mesin) tm ON t.nama_mesin = tm.nama_mesin AND t.date = tm.MaxDate SELECT t.nama_mesin, t.date, t.OEE FROM oee_data_daily t INNER JOIN (SELECT nama_mesin, MAX(date) AS MaxDate FROM oee_data_daily GROUP BY nama_mesin) tm ON t.nama_mesin = tm.nama_mesin AND t.date = tm.MaxDate SELECT t.date, t.kode_barang, t.nama_barang, t.merek, t.tipe, t.jumlah_masuk, t.keterangan FROM spmasuk t INNER JOIN (SELECT nama_barang, MAX(date) AS MaxDate FROM spmasuk GROUP BY nama_barang) tm ON t.nama_barang = tm.nama_barang AND t.date = tm.MaxDate SELECT nama_barang, date FROM sparepart WHERE date=(SELECT MAX(date) FROM sparepart); SELECT kode_barang, nama_barang, merek, tipe, stok, date, keterangan FROM sparepart WHERE date=(SELECT MAX(date) FROM sparepart); SELECT supplier, date, nama_barang, pengiriman, kualitas, pelayanan_pumajual, pelayanan_keluhan, total_nilai, rata2, keterangan FROM evaluasisup WHERE date=(SELECT MAX(date) FROM evaluasisup);
45,281
https://github.com/mmrath/Highlander.Net/blob/master/Tests/FpML.V5r3.Analytics.Tests/SABRModel/SABRCalibrationSettingsUnitTests.cs
Github Open Source
Open Source
BSD-3-Clause
null
Highlander.Net
mmrath
C#
Code
134
428
using Orion.Analytics.Stochastics.SABR; using Orion.Analytics.Utilities; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Orion.Analytics.Tests.SABRModel { /// <summary> /// Unit Tests for the class SABRCalibrationSettings. /// </summary> [TestClass] public class SABRCalibrationSettingsUnitTests { #region Private Fields private string _handle; // name of the SABR calibration settings object private decimal _beta; // SABR parameter beta private InstrumentType.Instrument _instrument; // instrument type private string _currency; // currency type #endregion Private Fields #region SetUp /// <summary> /// Set up method. /// </summary> [TestInitialize] public void Initialisation() { _handle = "SABR Calibration Settings Unit Test"; _instrument = InstrumentType.Instrument.Swaption; _currency = "AUD"; _beta = 0.85m; } #endregion SetUp #region Tests: Constructor /// <summary> /// Tests the class constructor. /// </summary> [TestMethod] public void TestConstructor() { var settingsObj = new SABRCalibrationSettings(_handle, _instrument,_currency, _beta); Assert.IsNotNull(settingsObj); Assert.AreEqual(_beta, settingsObj.Beta); Assert.AreEqual(_handle, settingsObj.Handle); Assert.AreEqual(_instrument, settingsObj.Instrument); Assert.AreEqual(_currency, settingsObj.Currency); } #endregion Tests: Constructor } }
18,278
https://github.com/amoudgl/leetcode-solutions/blob/master/src/substring-with-concatenation-of-all-words.cpp
Github Open Source
Open Source
MIT
null
leetcode-solutions
amoudgl
C++
Code
181
624
// Author: Abhinav Moudgil [ https://leetcode.com/amoudgl/ ] class Solution { public: vector<int> findSubstring(string s, vector<string>& words) { unordered_map<char, int> m; unordered_set<string> st; int count = 0, l = s.length(); sort(words.begin(), words.end()); for (int i = 0; i < words.size(); i++) { st.insert(words[i]); for (int j = 0; j < words[i].length(); j++) { if (m.find(words[i][j]) == m.end()) m[words[i][j]] = 1; else m[words[i][j]]++; count++; } } unordered_map<char, int> m_temp; vector<int> ans; for (int i = 0; i < (l-count+1); i++) { if (i == 0) { for (int j = 0; j < count; j++) { if (m_temp.find(s[j]) == m_temp.end()) m_temp[s[j]] = 1; else m_temp[s[j]]++; } } else { m_temp[s[i-1]]--; if (m_temp[s[i-1]] == 0) m_temp.erase(s[i-1]); if (m_temp.find(s[i+count-1]) == m_temp.end()) m_temp[s[i+count-1]] = 1; else m_temp[s[i+count-1]]++; } if (m_temp == m && check(s.substr(i, count), st, words)) ans.push_back(i); } return ans; } bool check(string x, unordered_set<string> st, vector<string> &words) { string word; vector<string> s; for (char c : x) { word += c; if (st.find(word) != st.end()) { s.push_back(word); word = ""; } } sort(s.begin(), s.end()); if (s == words) return true; return false; } };
50,950
https://github.com/eserozvataf/BasketForm/blob/master/BasketForm/frmMain.cs
Github Open Source
Open Source
Apache-2.0
2,021
BasketForm
eserozvataf
C#
Code
577
1,719
// ----------------------------------------------------------------------- // <copyright file="frmMain.cs" company="-"> // Copyright (c) 2013 larukedi (eser@sent.com). All rights reserved. // </copyright> // <author>larukedi (http://github.com/larukedi/)</author> // ----------------------------------------------------------------------- //// This program is free software: you can redistribute it and/or modify //// it under the terms of the GNU General Public License as published by //// the Free Software Foundation, either version 3 of the License, or //// (at your option) any later version. //// //// This program is distributed in the hope that it will be useful, //// but WITHOUT ANY WARRANTY; without even the implied warranty of //// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //// GNU General Public License for more details. //// //// You should have received a copy of the GNU General Public License //// along with this program. If not, see <http://www.gnu.org/licenses/>. namespace BasketForm { using System; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using System.IO; using System.Windows.Forms; using BasketForm.Abstraction; public partial class frmMain : Form { public List<Folder> Folders { get; set; } private string[] contextMenuFiles; private string contextTargetDirectory; private bool allowQuit = false; public frmMain() { this.InitializeComponent(); this.Folders = new List<Folder>(); if (ProgramLogic.Instance.Config.Folders != null) { this.Folders.AddRange(ProgramLogic.Instance.Config.Folders); } int finalX = this.FoldersCreate(); Rectangle x = Screen.GetWorkingArea(this); this.Width = finalX; this.SetDesktopLocation(x.Right - this.Width - 5, x.Top + 5); } public void FoldersClear() { foreach (Folder folder in this.Folders) { if (folder.FormButton != null) { this.Controls.Remove(folder.FormButton); } } } public int FoldersCreate() { const int spacing = 12; int x = spacing; foreach (Folder folder in this.Folders) { int width = 90 * folder.TileSize; folder.FormButton = new Button() { AllowDrop = true, Text = folder.Title, Tag = folder, Size = new Size(width, 78), Location = new Point(x, 28), Image = global::BasketForm.Properties.Resources.Folder.ToBitmap(), ImageAlign = ContentAlignment.MiddleCenter, TextImageRelation = TextImageRelation.ImageAboveText, Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left // | AnchorStyles.Right }; x += width + spacing; folder.FormButton.DragEnter += this.button_DragEnter; folder.FormButton.DragDrop += this.button_DragDrop; folder.FormButton.Click += this.button_Click; this.Controls.Add(folder.FormButton); } return x + spacing; } public void FoldersReset() { this.FoldersClear(); this.FoldersCreate(); } public Folder GetFolderFromControl(object sender) { Control control = sender as Control; if (control == null) { return null; } return control.Tag as Folder; } private void button_Click(object sender, EventArgs e) { Folder folder = this.GetFolderFromControl(sender); if (folder == null) { return; } Process.Start(folder.PhysicalPath); } private void button_DragEnter(object sender, DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.FileDrop)) { e.Effect = DragDropEffects.Move; } } private void button_DragDrop(object sender, DragEventArgs e) { Folder folder = this.GetFolderFromControl(sender); if (folder == null) { return; } this.contextMenuFiles = (string[])e.Data.GetData(DataFormats.FileDrop); this.contextTargetDirectory = folder.PhysicalPath; if (folder.DisplaySubfolderTree) { contextMenuStrip1.Items.Clear(); foreach (string directory in Directory.EnumerateDirectories(folder.PhysicalPath, "*.*", SearchOption.TopDirectoryOnly)) { ToolStripMenuItem item = new ToolStripMenuItem() { Text = Path.GetFileName(directory), Tag = directory }; item.Click += this.item_Click; contextMenuStrip1.Items.Add(item); } if (contextMenuStrip1.Items.Count > 0) { Control senderControl = sender as Control; contextMenuStrip1.Show(senderControl, 0, senderControl.Height); return; } } this.MoveFiles(this.contextMenuFiles, this.contextTargetDirectory); } private void item_Click(object sender, EventArgs e) { ToolStripMenuItem item = sender as ToolStripMenuItem; if (item == null) { return; } this.MoveFiles(this.contextMenuFiles, (string)item.Tag); } private void MoveFiles(string[] files, string targetPath) { foreach (string file in files) { retryPoint: try { File.Move(file, Path.Combine(targetPath, Path.GetFileName(file))); } catch (Exception ex) { DialogResult response = MessageBox.Show(ex.GetType().Name + ": " + ex.Message, this.Text, MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Stop); if (response == DialogResult.Abort) { return; } else if (response == DialogResult.Retry) { goto retryPoint; } // else is ignore, so ignore it. } } } private void toolStripQuit_Click(object sender, EventArgs e) { Application.Exit(); } private void frmMain_FormClosing(object sender, FormClosingEventArgs e) { if (!this.allowQuit && e.CloseReason == CloseReason.UserClosing) { e.Cancel = true; this.WindowState = FormWindowState.Minimized; } } } }
2,198
https://github.com/irebollo/stomach_brain_Scripts/blob/master/review_controlPower.m
Github Open Source
Open Source
MIT
2,018
stomach_brain_Scripts
irebollo
MATLAB
Code
332
1,542
% review_controlPower insideBrain= tools_getIndexBrain('inside'); subjects = global_subjectList cfgMain = global_getcfgmain; peak = global_getEGGpeaks SpectrumXSignalXSubject=zeros(30,2,93); % subjects, cominations freqsbins SpectrumXSignalXSubjectPeak = zeros (30,2,61); %% DMNcenter_tal = [-5 -49 40];% tal Fox 2005 PNAS DMNcenter = tal2mni(DMNcenter_tal'); % transform to MNI DMN_center_vox = tools_mni2vox(DMNcenter,1); % transform to voxel coordinates emptyBrain = zeros (53,63,46); % empty 3d Volume for storing empirical PLV % take cube of 3 voxels centered at coodinates emptyBrain(DMN_center_vox(1)-1:DMN_center_vox(1)+1,DMN_center_vox(2)-1:DMN_center_vox(2)+1,DMN_center_vox(3)-1:DMN_center_vox(3)+1 ) = 1; DMNCoreMask = emptyBrain(insideBrain); DMNCoreMask = find(DMNCoreMask); % tools_writeMri(emptyBrain,'DMN_seed') S1_center_MNI = [45 -28 46]; S1_center_vox = tools_mni2vox(S1_center_MNI',1); % transform to voxel coordinates emptyBrain = zeros (53,63,46); % empty 3d Volume for storing empirical PLV emptyBrain(S1_center_vox(1)-1:S1_center_vox(1)+1,S1_center_vox(2)-1:S1_center_vox(2)+1,S1_center_vox(3)-1:S1_center_vox(3)+1 ) = 1; SICoreMask = emptyBrain(insideBrain); SICoreMask = find(SICoreMask); % tools_writeMri(emptyBrain,'SI_seed') for iSubj = 1:length(subjects) subj_idx = subjects(iSubj) %% Load BOLD boldname = global_filename(subj_idx,cfgMain,'BOLD_filtered_fullbandFilename'); load(boldname) BOLD_filtered_zscored_cutted_inside = BOLD_filtered_zscored(insideBrain,cfgMain.beginCut:cfgMain.endCut); mean_precuneus_timeseries = mean(BOLD_filtered_zscored_cutted_inside(DMNCoreMask,:)); mean_ssi_timeseries = mean(BOLD_filtered_zscored_cutted_inside(SICoreMask,:)); figure plot(mean_precuneus_timeseries) hold on plot(mean_ssi_timeseries,'r') %% get fourier timeseries2Coherence(1,:) = mean_ssi_timeseries; timeseries2Coherence(2,:) = mean_precuneus_timeseries; nVoxels = size(timeseries2Coherence,1); %load base fieldtrip data structure load(strcat(global_path2root,'\scripts4paper\files\sampleFieldtripStruc.mat')) labelsChannelsMAIN = {'S1','DMN'}; labelsChannels = labelsChannelsMAIN; clusterRegionsComparisons = timeseries2Coherence; dataStructure.hdr = EGG_downsampled.hdr; dataStructure.fsample = 0.5; dataStructure.time{1,1} = [0:2:(size(clusterRegionsComparisons,2)*2)-1];dataStructure.label = labelsChannels;%channelStr; dataStructure.cfg = EGG_downsampled.cfg; dataStructure.trial{1,1} = clusterRegionsComparisons; %computing fourier cfgWelch = []; cfgWelch.lengthWindow = 120; %seconds cfgWelch.overlap = 6;% propotion i.e 1/6 len = dataStructure.fsample*cfgWelch.lengthWindow; % length of subtrials cfg.length s in samples dataStructure.sampleinfo=[1 max(dataStructure.time{1,1})*dataStructure.fsample]; % Cut data into trials cfg = []; cfg.trl(:,1) = dataStructure.sampleinfo(1):(len/cfgWelch.overlap):dataStructure.sampleinfo(2)-len+1;%trial start in samples from begining of raw data cfg.trl(:,2) = dataStructure.sampleinfo(1)+len-1:(len/cfgWelch.overlap):dataStructure.sampleinfo(2);%trial ends in samples from begining of raw data cfg.trl(:,3) = 0; %offset of the trigger with respect to the trial data_trials = ft_redefinetrial(cfg,dataStructure); % Perform frequency analysis cfg = []; cfg.method = 'mtmfft'; cfg.taper = 'hanning'; cfg.output = 'powandcsd'; cfg.pad = 1000; cfg.foilim = [1/cfgWelch.lengthWindow 0.1]; % 0 - 6 cpm cfg.keeptrials = 'no'; frequencyWelch = ft_freqanalysis(cfg,data_trials); figure plot(frequencyWelch.freq,frequencyWelch.powspctrm) % labels('si','dmn') indPeaks(iSubj) = find(frequencyWelch.freq == peak(iSubj,3)); SpectrumXSignalXSubject(iSubj,:,:) = frequencyWelch.powspctrm ; % subjects, cominations freqsbins SpectrumXSignalXSubjectPeak(iSubj,:,:) = frequencyWelch.powspctrm(:,indPeaks(iSubj)-30:indPeaks(iSubj)+30); %% Get power in BOLD end figure plot(squeeze(mean(SpectrumXSignalXSubjectPeak))') legend('s1','Prec') % check cube is inside the brain
12,152
https://github.com/fineanmol/30-Days-of-Python/blob/master/tutorial-reference/Day 23/cli_sys.py
Github Open Source
Open Source
MIT
2,022
30-Days-of-Python
fineanmol
Python
Code
26
82
import sys if __name__== "__main__": try: name = sys.argv[1] except: name = input("What's your name?\n") from getpass import getpass pw = getpass("What's your password?\n") print(name, pw)
44,192
https://github.com/deimspb/TSParser/blob/master/TSParser/Descriptors/Dvb/TerrestrialDeliverySystemDescriptor_0x5A.cs
Github Open Source
Open Source
Apache-2.0
null
TSParser
deimspb
C#
Code
582
1,667
// Copyright 2021 Eldar Nizamutdinov deim.mobile<at>gmail.com // // Licensed under the Apache License, Version 2.0 (the "License") // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System.Buffers.Binary; using TSParser.Service; namespace TSParser.Descriptors.Dvb { public record TerrestrialDeliverySystemDescriptor_0x5A : Descriptor { public uint CentreFrequency { get; } public byte Bandwidth { get; } public bool Priority { get; } public bool TimeSlicingIndicator { get; } public bool MpeFecIndicator { get; } public byte Constellation { get; } public byte HierarchyInformation { get; } public byte CodeRateHpStream { get; } public byte CodeRateLpStream { get; } public byte GuardInterval { get; } public byte TransmissionMode { get; } public bool OtherFrequencyFlag { get; } public TerrestrialDeliverySystemDescriptor_0x5A(ReadOnlySpan<byte> bytes) : base(bytes) { var pointer = 2; CentreFrequency = BinaryPrimitives.ReadUInt32BigEndian(bytes[pointer..])*10; pointer += 4; Bandwidth = (byte)(bytes[pointer]>>5); Priority = (bytes[pointer] & 0x10) != 0; TimeSlicingIndicator = (bytes[pointer] & 0x08) != 0; MpeFecIndicator = (bytes[pointer++] & 0x04) != 0; //reserved 2 bits Constellation = (byte)(bytes[pointer] >> 6); HierarchyInformation = (byte)((bytes[pointer]&0x38)>>3); CodeRateHpStream = (byte)(bytes[pointer++] & 0x07); CodeRateLpStream = (byte)(bytes[pointer] >> 5); GuardInterval = (byte)((bytes[pointer] &0x18)>>3); TransmissionMode = (byte)((bytes[pointer] & 0x06)>>1); OtherFrequencyFlag = (bytes[pointer] & 0x01) != 0; //reserved 32 bit } public override string Print(int prefixLen) { string header = Utils.HeaderPrefix(prefixLen); string prefix = Utils.Prefix(prefixLen); string str = $"{header}Descriptor tag: 0x{DescriptorTag:X2}, {DescriptorName}\n"; str += $"{prefix}Centre Frequency:{CentreFrequency} Hz\n"; str += $"{prefix}Bandwidth: {GetBw(Bandwidth)}\n"; str += $"{prefix}Priority: {Priority}\n"; str += $"{prefix}TimeSlicing Indicator: {TimeSlicingIndicator}\n"; str += $"{prefix}MpeFec Indicator: {MpeFecIndicator}\n"; str += $"{prefix}Constellation: {GetConstellation(Constellation)}\n"; str += $"{prefix}Hierarchy Information: {GetConstellation(Constellation)}\n"; str += $"{prefix}Code Rate HpStream: {GetCodeRateHpStream(CodeRateHpStream)}\n"; str += $"{prefix}Code Rate LpStream: {GetCodeRateHpStream(CodeRateLpStream)}\n"; str += $"{prefix}Guard Interval: {GetGuardInterval(GuardInterval)}\n"; str += $"{prefix}Transmission Mode: {GetTransmissionMode(TransmissionMode)}\n"; str += $"{prefix}Other Frequency Flag: {OtherFrequencyFlag}\n"; return str; } private string GetBw(byte bt) { switch (bt) { case 0b000: return "8 MHz"; case 0b001: return "7 MHz"; case 0b010: return "6 MHz"; case 0b011: return "5 MHz"; default: return "Reserved for future use"; } } private string GetConstellation(byte bt) { switch (bt) { case 0b00: return "QPSK"; case 0b01: return "16-QAM"; case 0b10: return "64-QAM"; default: return "reserved for future use"; } } private string GetHierarchyInformation(byte bt) { switch (bt) { case 0b000: return "non-hierarchical, native interleaver"; case 0b001: return "α = 1, native interleaver"; case 0b010: return "α = 2, native interleaver"; case 0b011: return "α = 4, native interleaver"; case 0b100: return "non-hierarchical, in-depth interleaver"; case 0b101: return "α = 1, in-depth interleaver"; case 0b110: return "α = 2, in-depth interleaver"; case 0b111: return "α = 4, in-depth interleaver"; default : return "unknown"; } } private string GetCodeRateHpStream(byte bt) { switch (bt) { case 0b000: return "1/2"; case 0b001: return "2/3"; case 0b010: return "3/4"; case 0b011: return "5/6"; case 0b100: return "7/8"; default: return "reserved for future use"; } } private string GetGuardInterval(byte bt) { switch (bt) { case 0b00: return "1/32"; case 0b01: return "1/16"; case 0b10: return "1/8"; case 0b11: return "1/4"; default: return "unknown"; } } private string GetTransmissionMode(byte bt) { switch (bt) { case 0b00: return "2k mode"; case 0b01: return "8k mode"; case 0b10: return "4k mode"; default: return "reserved for future use"; } } } }
5,477
https://github.com/yurimelo96/MantisBt/blob/master/Mantis/src/test/java/page/LoginPage.java
Github Open Source
Open Source
Apache-2.0
2,021
MantisBt
yurimelo96
Java
Code
422
1,984
package page; import static util.EvidenceManager.GerarEvidencia; import org.openqa.selenium.By; import core.BasePage; import core.Elemento; import io.cucumber.java.pt.Dado; import io.cucumber.java.pt.E; import io.cucumber.java.pt.Entao; import io.cucumber.java.pt.Quando; public class LoginPage extends BasePage { private Elemento inputLogin = new Elemento(getDriver(), "xpath", "//input[@type='text']"); private Elemento inputPass = new Elemento(getDriver(), "xpath", "//input[@type='password']"); private Elemento buttonLogin = new Elemento(getDriver(), "xpath", "//input[@type='submit']"); private Elemento buttonReport = new Elemento(getDriver(), "xpath", "//a[contains(text(),'Report Issue')]"); private Elemento optionProject = new Elemento(getDriver(), "xpath", "//td[@width='60%']//select[@name='project_id']"); private Elemento selectProjectJm = new Elemento(getDriver(), "xpath", "//td[@width='60%']//select[@name='project_id']//option[@value='24'][contains(text(),'Desafio jMeter Project 1')]"); private Elemento buttonSelect = new Elemento(getDriver(), "xpath", "//td[@class='center']//input[@type='submit']"); private Elemento optionCategory = new Elemento(getDriver(), "xpath", "//select[@name='category_id']"); private Elemento optionGeneral = new Elemento(getDriver(), "xpath", "//option[contains(text(),'[All Projects] General')]"); private Elemento optionReproducibility = new Elemento(getDriver(), "xpath", "//select[@tabindex='2']"); private Elemento optionSometimes = new Elemento(getDriver(), "xpath", "//option[contains(text(),'sometimes')]"); private Elemento optionSeverity = new Elemento(getDriver(), "xpath", "//select[@tabindex='2']"); private Elemento optionText = new Elemento(getDriver(), "xpath", "//option[contains(text(),'text')]"); private Elemento optionPriority = new Elemento(getDriver(), "xpath", "//select[@tabindex='4']"); private Elemento optionNormal = new Elemento(getDriver(), "xpath", "//option[contains(text(),'normal')]"); private Elemento optionProfile = new Elemento(getDriver(), "xpath", "//select[@tabindex='5']"); private Elemento optionWindows10 = new Elemento(getDriver(), "xpath", "//option[@value='74']"); private Elemento inputPlataform = new Elemento(getDriver(), "xpath", "//input[@id='platform']"); private Elemento inputOs = new Elemento(getDriver(), "xpath", "//input[@id='os']"); private Elemento inputVersion = new Elemento(getDriver(), "xpath", "//input[@id='os_build']"); private Elemento inputSumary = new Elemento(getDriver(), "xpath", "//body/div[@align='center']/form[@name='report_bug_form']/table[@class='width90']/tbody/tr[8]/td[2]/input[1]"); private Elemento inputDescription = new Elemento(getDriver(), "xpath", "//textarea[@name='description']"); private Elemento inputStep = new Elemento(getDriver(), "xpath", "//textarea[@name='steps_to_reproduce']"); private Elemento inputAdditional = new Elemento(getDriver(), "xpath", "//textarea[@tabindex='12']"); private Elemento fileUpload = new Elemento(getDriver(), "xpath", "//input[@id='ufile[]']"); private Elemento radioStatus = new Elemento(getDriver(), "xpath", "//label[contains(text(),'public')]//input[@type='radio']"); private Elemento buttonSubmit = new Elemento(getDriver(), "xpath", "//td[@class='center']//input[@type='submit']"); @Dado("que preencho o login e senha no sistema MantisBT com as credenciais {string} e {string}") public void acessarMantis(String user, String pass) throws Exception { navegar("https://mantis-prova.base2.com.br"); esperarElemento(buttonLogin, SMALL); GerarEvidencia("Tela inicial do mantis"); escrever(inputLogin, user); escrever(inputPass, pass); } @Quando("clico no botao Login") public void clicarLogin() throws Exception { clicar(buttonLogin); GerarEvidencia("botão clicado"); } @Entao("valido a mensagem de erro") public void validarMensagem() throws Exception { Elemento labelError = new Elemento(getDriver(), "xpath", "/html[1]/body[1]/div[2]/font[1]"); validarElemento(labelError); GerarEvidencia("Mensagem de falha"); } @Entao("valido a mensagem de sucesso") public void validarMensagemSucesso() throws Exception { Elemento labelSucesso = new Elemento(getDriver(), "xpath", "/html[1]/body[1]/table[1]/tbody[1]/tr[1]/td[1]"); validarElemento(labelSucesso); GerarEvidencia("Mensagem de sucesso"); } @Quando("clico na aba Report Issue") public void clicarReportIssue() throws Exception { esperarElemento(buttonReport, BIG); clicar(buttonReport); GerarEvidencia("botão clicado"); } @E("seleciono o projeto") public void selecionoProjeto() throws Exception { clicar(optionProject); clicar(selectProjectJm); clicar(buttonSelect); GerarEvidencia("botão clicado"); } @Entao("preencho o formulario com o upload") public void preenchoFormulario() throws Exception { clicar(optionCategory); clicar(optionGeneral); clicar(optionReproducibility); clicar(optionSometimes); clicar(optionSeverity); clicar(optionText); clicar(optionPriority); clicar(optionNormal); clicar(optionProfile); clicar(optionWindows10); escrever(inputPlataform, "Windows10"); escrever(inputOs, "Windows"); escrever(inputVersion, "Ultimate"); escrever(inputSumary, "testY"); escrever(inputDescription, "ola"); esperarElemento(inputStep, SMALL); escrever(inputStep, "etccte"); escrever(inputAdditional, "Nothing"); driver.findElement(By.xpath("//input[@id='ufile[]']")).sendKeys("C:/Users/ymelorei/Documents/yuri/Mantis/Data/teste.txt"); escrever(fileUpload, "C:/Users/ymelorei/Documents/yuri/Mantis/Data/teste.txt"); clicar(radioStatus); clicar(buttonSubmit); GerarEvidencia("Formulario preenchido"); } }
48,719
https://github.com/abdul-kader138/exambooking/blob/master/application/models/admin/Exam_attribute_model.php
Github Open Source
Open Source
MIT
null
exambooking
abdul-kader138
PHP
Code
381
1,672
<?php class Exam_attribute_model extends CI_Model { public function add_exam_attribute($data) { $this->db->insert('ci_exam_instrument_product', $data); return true; } //--------------------------------------------------- public function get_all_exam_attribute() { $wh = array(); $SQL = 'SELECT ci_exam_instrument_product.id,ci_exam_instrument_product.instrument_name as attribute_name, ci_exam_type.name as type_name, ci_exam_type_types.name as type_types_name, ci_exam_instrument_product.created_date FROM ci_exam_instrument_product inner join ci_exam_type on ci_exam_instrument_product.exam_type_id=ci_exam_type.id INNER join ci_exam_type_types on ci_exam_instrument_product.type_types_id=ci_exam_type_types.id'; if (count($wh) > 0) { $WHERE = implode(' and ', $wh); return $this->datatable->LoadJson($SQL, $WHERE); } else { return $this->datatable->LoadJson($SQL); } } //--------------------------------------------------- public function get_all_simple_exam_attribute() { $this->db->order_by('created_date', 'desc'); $query = $this->db->get('ci_exam_instrument_product'); return $result = $query->result_array(); } //--------------------------------------------------- public function count_all_exam_attribute() { return $this->db->count_all('ci_exam_instrument_product'); } //--------------------------------------------------- public function get_all_exam_attribute_for_pagination($limit, $offset) { $wh = array(); $this->db->order_by('created_date', 'desc'); $this->db->limit($limit, $offset); if (count($wh) > 0) { $WHERE = implode(' and ', $wh); $query = $this->db->get_where('ci_exam_instrument_product', $WHERE); } else { $query = $this->db->get('ci_exam_instrument_product'); } return $query->result_array(); //echo $this->db->last_query(); } //--------------------------------------------------- public function get_all_exam_attribute_by_advance_search() { $wh = array(); $SQL = 'SELECT * FROM ci_exam_suite'; if ($this->session->userdata('exam_attribute_search_from') != '') $wh[] = " `created_date` >= '" . date('Y-m-d', strtotime($this->session->userdata('exam_attribute_search_from'))) . "'"; if ($this->session->userdata('exam_attribute_search_to') != '') $wh[] = " `created_date` <= '" . date('Y-m-d', strtotime($this->session->userdata('exam_attribute_search_to'))) . "'"; if (count($wh) > 0) { $WHERE = implode(' and ', $wh); return $this->datatable->LoadJson($SQL, $WHERE); } else { return $this->datatable->LoadJson($SQL); } } //--------------------------------------------------- public function get_exam_attribute_by_id($id) { $query = $this->db->get_where('ci_exam_instrument_product', array('md5(id)' => $id)); return $result = $query->row_array(); } //--------------------------------------------------- public function get_attribute_by_type_id($exam_type,$type_id,$name) { $test=strtolower($name); $query = $this->db->get_where('ci_exam_instrument_product', array('exam_type_id' => $exam_type,'type_types_id' => $type_id,'LOWER(instrument_name)' => strtolower($name))); return $result = $query->row_array(); } //--------------------------------------------------- public function edit_exam_attribute($data, $id) { $this->db->where('md5(id)', $id); $this->db->update('ci_exam_instrument_product', $data); return true; } //--------------------------------------------------- public function get_types_by_exam_type_id($id = null) { $query = $this->db->get_where('ci_exam_type_types', array('exam_type_id' => $id)); if ($query->num_rows() > 0) { foreach (($query->result()) as $row) { $data[] = $row; } return $data; } return false; } //--------------------------------------------------- public function get_exam_types() { $query = $this->db->get('ci_exam_type'); if ($query->num_rows() > 0) { foreach (($query->result()) as $row) { $data[] = $row; } return $data; } return false; } //--------------------------------------------------- public function get_type_types($id) { $this->db->where('exam_type_id',$id); $query = $this->db->get('ci_exam_type_types'); if ($query->num_rows() > 0) { foreach (($query->result()) as $row) { $data[] = $row; } return $data; } return false; } public function get_attribute_from_grade_by_id($id){ $query = $this->db->get_where('ci_exam_grade_diploma', array('instrument_id' => $id)); return $result = $query->row_array(); } public function get_exam_details_by_instrument_id($id){ $query = $this->db->get_where('ci_user_exam_details', array('md5(instrument)' => $id)); return $result = $query->row_array(); } public function get_attribute_details_by_grade_id($id){ $query = $this->db->get_where('ci_exam_grade_diploma', array('md5(instrument_id)' => $id)); return $result = $query->row_array(); } } ?>
5,045
https://github.com/nylas/nylas-python/blob/master/tests/test_scheduler.py
Github Open Source
Open Source
MIT
2,023
nylas-python
nylas
Python
Code
767
4,146
import json from datetime import datetime import pytest import responses from nylas.client.restful_models import Scheduler, Calendar from nylas.client.scheduler_models import SchedulerTimeSlot, SchedulerBookingRequest def blank_scheduler_page(api_client): scheduler = api_client.scheduler.create() scheduler.access_tokens = ["test-access-token"] scheduler.name = "Python SDK Example" scheduler.slug = "py_example_1" return scheduler def test_scheduler_endpoint(api_client): scheduler = api_client.scheduler assert scheduler.api.api_server == "https://api.schedule.nylas.com" @pytest.mark.usefixtures("mock_schedulers") def test_scheduler(api_client): scheduler = api_client.scheduler.first() assert isinstance(scheduler, Scheduler) assert scheduler.id == 90210 assert scheduler.app_client_id == "test-client-id" assert scheduler.app_organization_id == 12345 assert len(scheduler.config) == 4 assert isinstance(scheduler.config, dict) assert scheduler.config["locale"] == "en" assert len(scheduler.config["reminders"]) == 0 assert scheduler.config["timezone"] == "America/Los_Angeles" assert scheduler.edit_token == "test-edit-token-1" assert scheduler.name == "test-1" assert scheduler.slug == "test1" assert scheduler.created_at == datetime.strptime("2021-10-22", "%Y-%m-%d").date() assert scheduler.modified_at == datetime.strptime("2021-10-22", "%Y-%m-%d").date() @pytest.mark.usefixtures("mock_scheduler_create_response") def test_create_scheduler(api_client): scheduler = blank_scheduler_page(api_client) scheduler.save() assert scheduler.id == "cv4ei7syx10uvsxbs21ccsezf" @pytest.mark.usefixtures("mock_scheduler_create_response") def test_modify_scheduler(api_client): scheduler = blank_scheduler_page(api_client) scheduler.id = "cv4ei7syx10uvsxbs21ccsezf" scheduler.name = "Updated Name" scheduler.save() assert scheduler.name == "Updated Name" @pytest.mark.usefixtures("mock_scheduler_get_available_calendars") def test_scheduler_get_available_calendars(api_client): scheduler = blank_scheduler_page(api_client) scheduler.id = "cv4ei7syx10uvsxbs21ccsezf" calendars = scheduler.get_available_calendars() assert len(calendars) == 1 calendar = calendars[0] assert len(calendar["calendars"]) == 1 assert isinstance(calendar["calendars"][0], Calendar) assert calendar["calendars"][0].id == "calendar-id" assert calendar["calendars"][0].name == "Emailed events" assert calendar["calendars"][0].read_only assert calendar["email"] == "swag@nylas.com" assert calendar["id"] == "scheduler-id" assert calendar["name"] == "Python Tester" @pytest.mark.usefixtures("mock_scheduler_get_available_calendars") def test_scheduler_get_available_calendars_no_id_throws_error(api_client): scheduler = blank_scheduler_page(api_client) with pytest.raises(ValueError): scheduler.get_available_calendars() @pytest.mark.usefixtures("mock_scheduler_upload_image") def test_scheduler_upload_image(api_client): scheduler = blank_scheduler_page(api_client) scheduler.id = "cv4ei7syx10uvsxbs21ccsezf" upload = scheduler.upload_image("image/png", "test.png") assert upload["filename"] == "test.png" assert upload["originalFilename"] == "test.png" assert upload["publicUrl"] == "https://public.nylas.com/test.png" assert upload["signedUrl"] == "https://signed.nylas.com/test.png" @pytest.mark.usefixtures("mock_scheduler_get_available_calendars") def test_scheduler_get_available_calendars_no_id_throws_error(api_client): scheduler = blank_scheduler_page(api_client) with pytest.raises(ValueError): scheduler.upload_image("image/png", "test.png") @pytest.mark.usefixtures("mock_scheduler_provider_availability") def test_scheduler_get_google_availability(mocked_responses, api_client): api_client.scheduler.get_google_availability() request = mocked_responses.calls[0].request assert request.url == "https://api.schedule.nylas.com/schedule/availability/google" assert request.method == responses.GET @pytest.mark.usefixtures("mock_scheduler_provider_availability") def test_scheduler_get_o365_availability(mocked_responses, api_client): api_client.scheduler.get_office_365_availability() request = mocked_responses.calls[0].request assert request.url == "https://api.schedule.nylas.com/schedule/availability/o365" assert request.method == responses.GET @pytest.mark.usefixtures("mock_schedulers") def test_scheduler_get_page_slug(mocked_responses, api_client): scheduler = api_client.scheduler.get_page_slug("test1") request = mocked_responses.calls[0].request assert request.url == "https://api.schedule.nylas.com/schedule/test1/info" assert request.method == responses.GET assert isinstance(scheduler, Scheduler) assert scheduler.id == 90210 assert scheduler.app_client_id == "test-client-id" assert scheduler.app_organization_id == 12345 assert len(scheduler.config) == 4 assert isinstance(scheduler.config, dict) assert scheduler.config["locale"] == "en" assert len(scheduler.config["reminders"]) == 0 assert scheduler.config["timezone"] == "America/Los_Angeles" assert scheduler.edit_token == "test-edit-token-1" assert scheduler.name == "test-1" assert scheduler.slug == "test1" assert scheduler.created_at == datetime.strptime("2021-10-22", "%Y-%m-%d").date() assert scheduler.modified_at == datetime.strptime("2021-10-22", "%Y-%m-%d").date() @pytest.mark.usefixtures("mock_scheduler_timeslots") def test_scheduler_get_available_time_slots(mocked_responses, api_client): scheduler = blank_scheduler_page(api_client) timeslots = api_client.scheduler.get_available_time_slots(scheduler.slug) request = mocked_responses.calls[0].request assert ( request.url == "https://api.schedule.nylas.com/schedule/py_example_1/timeslots" ) assert request.method == responses.GET assert len(timeslots) == 1 assert timeslots[0] assert timeslots[0].account_id == "test-account-id" assert timeslots[0].calendar_id == "test-calendar-id" assert timeslots[0].emails[0] == "test@example.com" assert timeslots[0].host_name == "www.hostname.com" assert timeslots[0].end == datetime.utcfromtimestamp(1636731958) assert timeslots[0].start == datetime.utcfromtimestamp(1636728347) @pytest.mark.usefixtures("mock_scheduler_timeslots") def test_scheduler_get_available_time_slots(mocked_responses, api_client): scheduler = blank_scheduler_page(api_client) timeslots = api_client.scheduler.get_available_time_slots(scheduler.slug) request = mocked_responses.calls[0].request assert ( request.url == "https://api.schedule.nylas.com/schedule/py_example_1/timeslots" ) assert request.method == responses.GET assert len(timeslots) == 1 assert timeslots[0] assert timeslots[0].account_id == "test-account-id" assert timeslots[0].calendar_id == "test-calendar-id" assert timeslots[0].emails[0] == "test@example.com" assert timeslots[0].host_name == "www.hostname.com" assert timeslots[0].end == datetime.utcfromtimestamp(1636731958) assert timeslots[0].start == datetime.utcfromtimestamp(1636728347) @pytest.mark.usefixtures("mock_scheduler_timeslots") def test_scheduler_book_time_slot(mocked_responses, api_client): scheduler = blank_scheduler_page(api_client) slot = SchedulerTimeSlot.create(api_client) slot.account_id = "test-account-id" slot.calendar_id = "test-calendar-id" slot.emails = ["recipient@example.com"] slot.host_name = "www.nylas.com" slot.start = datetime.utcfromtimestamp(1636728347) slot.end = datetime.utcfromtimestamp(1636731958) timeslot_to_book = SchedulerBookingRequest.create(api_client) timeslot_to_book.additional_values = { "test": "yes", } timeslot_to_book.email = "recipient@example.com" timeslot_to_book.locale = "en_US" timeslot_to_book.name = "Recipient Doe" timeslot_to_book.timezone = "America/New_York" timeslot_to_book.slot = slot booking_response = api_client.scheduler.book_time_slot( scheduler.slug, timeslot_to_book ) request = mocked_responses.calls[0].request assert ( request.url == "https://api.schedule.nylas.com/schedule/py_example_1/timeslots" ) assert request.method == responses.POST assert json.loads(request.body) == { "additional_emails": [], "additional_values": { "test": "yes", }, "email": "recipient@example.com", "locale": "en_US", "name": "Recipient Doe", "timezone": "America/New_York", "slot": { "account_id": "test-account-id", "calendar_id": "test-calendar-id", "emails": ["recipient@example.com"], "host_name": "www.nylas.com", "start": 1636728347, "end": 1636731958, }, } assert booking_response.account_id == "test-account-id" assert booking_response.calendar_id == "test-calendar-id" assert booking_response.additional_field_values == { "test": "yes", } assert booking_response.calendar_event_id == "test-event-id" assert booking_response.calendar_id == "test-calendar-id" assert booking_response.calendar_event_id == "test-event-id" assert booking_response.edit_hash == "test-edit-hash" assert booking_response.id == 123 assert booking_response.is_confirmed is False assert booking_response.location == "Earth" assert booking_response.title == "Test Booking" assert booking_response.recipient_email == "recipient@example.com" assert booking_response.recipient_locale == "en_US" assert booking_response.recipient_name == "Recipient Doe" assert booking_response.recipient_tz == "America/New_York" assert booking_response.end_time == datetime.utcfromtimestamp(1636731958) assert booking_response.start_time == datetime.utcfromtimestamp(1636728347) @pytest.mark.usefixtures("mock_scheduler_timeslots") def test_scheduler_confirm_booking(mocked_responses, api_client): scheduler = blank_scheduler_page(api_client) booking_confirmation = api_client.scheduler.confirm_booking( scheduler.slug, "test-edit-hash" ) request = mocked_responses.calls[0].request assert ( request.url == "https://api.schedule.nylas.com/schedule/py_example_1/test-edit-hash/confirm" ) assert request.method == responses.POST assert booking_confirmation.account_id == "test-account-id" assert booking_confirmation.calendar_id == "test-calendar-id" assert booking_confirmation.additional_field_values == { "test": "yes", } assert booking_confirmation.calendar_event_id == "test-event-id" assert booking_confirmation.calendar_id == "test-calendar-id" assert booking_confirmation.calendar_event_id == "test-event-id" assert booking_confirmation.edit_hash == "test-edit-hash" assert booking_confirmation.id == 123 assert booking_confirmation.is_confirmed is True assert booking_confirmation.location == "Earth" assert booking_confirmation.title == "Test Booking" assert booking_confirmation.recipient_email == "recipient@example.com" assert booking_confirmation.recipient_locale == "en_US" assert booking_confirmation.recipient_name == "Recipient Doe" assert booking_confirmation.recipient_tz == "America/New_York" assert booking_confirmation.end_time == datetime.utcfromtimestamp(1636731958) assert booking_confirmation.start_time == datetime.utcfromtimestamp(1636728347) @pytest.mark.usefixtures("mock_scheduler_timeslots") def test_scheduler_cancel_booking(mocked_responses, api_client): scheduler = blank_scheduler_page(api_client) timeslots = api_client.scheduler.cancel_booking( scheduler.slug, "test-edit-hash", "It was a test." ) request = mocked_responses.calls[0].request assert ( request.url == "https://api.schedule.nylas.com/schedule/py_example_1/test-edit-hash/cancel" ) assert request.method == responses.POST assert json.loads(request.body) == {"reason": "It was a test."}
38,164
https://github.com/kiransabne/calmecac/blob/master/app/policies/my_classroom_policy.rb
Github Open Source
Open Source
MIT
2,018
calmecac
kiransabne
Ruby
Code
11
40
class MyClassroomPolicy < Struct.new(:user, :my_classroom) def index? user.has_role? :student end end
50,362
https://github.com/Missouri-BMI/popmednet/blob/master/Plugins/Lpp.Dns.General.Metadata/Views/DisplayRequest.cshtml
Github Open Source
Open Source
Apache-2.0
2,021
popmednet
Missouri-BMI
C#
Code
736
3,647
@using Lpp.Mvc @using Lpp.Dns.Portal @model Lpp.Dns.General.Metadata.Models.MetadataSearchModel @{ this.Stylesheet("MetadataSearch.css"); var id = Html.UniqueId(); } <script type="text/javascript"> var KOViewModel = true; // indicates this page is built with KO templates </script> <div id="AgeRangeTerm" style="display: none"> <span>Age Range</span> <div class="ui-form"> <div class="Field"> <label>Minimum Age</label> <input type="text" data-bind="value: MinAge" style="width: 25px; margin-right: 10px;" disabled="disabled" /> </div> <div class="Field"> <label>Maximum Age</label> <input type="text" data-bind="value: MaxAge" style="width: 25px;" disabled="disabled" /> </div> </div> </div> <div id="AgeStratifierTerm" style="display: none"> <label>Age Stratifier</label> <select data-bind="options: RequestCriteriaViewModels.AgeStratifierTerm.AgeStratifiersList, optionsText: 'Key', optionsValue: 'Value', value: AgeStratifier" disabled="disabled"> </select> </div> <div id="ClinicalSettingTerm" style="display: none"> <label>Clinical Setting</label> <select data-bind="options: RequestCriteriaViewModels.ClinicalSettingTerm.ClinicalSettingsList, optionsText: 'Key', optionsValue: 'Value', value: ClinicalSetting" disabled="disabled"> </select> </div> <div id="CodesTerm" style="display: none;"> <input type="hidden" id="CodesTerm_Codes" name="CodesTerm_Codes" data-bind="value: Codes" /> <label>Code Set</label> <select data-bind="options: MetadataQuery.Create.ViewModel.MDQCodeSetList, optionsText: 'Key', optionsValue: 'Value', value: CodesTermType" disabled="disabled"> </select > <label>Codes</label> <span data-bind="text: Codes"> </span> </div> <div id="DateRangeTerm" style="display: none"> <div style="width: 240px;"> <label data-bind="text: Title"></label> <input type="text" data-bind="value: StartDate() != null ? moment.utc(StartDate()).local().format('MM/DD/YYYY') : ''" style="width: 100px;" disabled="disabled" />&nbsp;-&nbsp; <input type="text" data-bind="value: EndDate() != null ? moment.utc(EndDate()).local().format('MM/DD/YYYY') : ''" style="width: 100px;" disabled="disabled" /> </div> </div> <div id="ProjectTerm" style="display: none"> <label>Project</label> <select data-bind="options: $.parseJSON('@(Json.Encode(Model.Projects))'), optionsText: 'Key', optionsValue: 'Value', value: Project" disabled="disabled"> </select> </div> <div id="RequestStatusTerm" style="display: none"> <label>Request Status</label> <select style="width:270px; " data-bind="options: MetadataQuery.Create.ViewModel.RequestStatusList, optionsText: 'text', optionsValue: 'value', value: RequestStatus" disabled="disabled"> </select> </div> <div id="SexTerm" style="display: none"> <label>Sex</label> <select data-bind="options: RequestCriteriaViewModels.SexTerm.SexesList, optionsText: 'Key', optionsValue: 'Value', value: Sex" disabled="disabled"> </select> </div> <div id="RequesterCenterTerm" style="display: none"> <label>Requester Center</label> <select data-bind="options: RequestCriteriaViewModels.RequestCriteria.RequesterCenterList, optionsText: 'Value', optionsValue: 'Key', value: RequesterCenter" disabled="disabled"></select> </div> <div id="WorkplanTypeTerm" style="display: none"> <label>Workplan Type</label> <select style="width:270px; " data-bind="options: RequestCriteriaViewModels.RequestCriteria.WorkplanTypeList, optionsText: 'Value', optionsValue: 'Key', value: WorkplanType" disabled="disabled"></select> </div> <div id="ReportAggregationLevelTerm" style="display: none"> <label>Level of Report Aggregation</label> <select data-bind="options: RequestCriteriaViewModels.RequestCriteria.ReportAggregationLevelList, optionsText: 'Value', optionsValue: 'Key', value: ReportAggregationLevel" disabled="disabled"></select> </div> <div class="MetadataSearch ui-form"> <div class="ui-form"> <fieldset id="fsCriteria" style="padding: 0px; margin: 0px;"> <legend style="display: none;"></legend> @*@Html.HiddenFor(m => m.CriteriaGroupsJSON)*@ <div id='errorLocation' style="font-size: small; color: Gray;"></div> <div class="ui-groupbox"> <div class="ui-groupbox-header"> <span>Search Criteria</span> </div> <ol data-bind="foreach: RequestCriteria.Criterias"> <li> <ul data-bind="foreach: HeaderTerms"> <li class="col-xs-3"> <div data-bind="template: { name: TemplateName }"></div> </li> </ul> </li> </ol> <br style="clear: both;" /> <ol> <li> <br style="clear: both;" /> <ul> <li class="col-xs-3" id="SourceTaskOrderSearchTerm"> <label>Source Task Order</label> <input id="cboSearchSourceTask" data-bind="kendoDropDownList: { value:SearchSourceTaskOrderID, data:SourceTaskActivities.dsTaskOrders, dataTextField:'ActivityName', dataValueField:'ActivityID', optionLabel:{ ActivityName:'Not Selected', ActivityID:'' }, autoBind:true}" style="width:100%;" disabled="disabled" /> </li> <li class="col-xs-3" id="SourceActivitySearchTerm"> <label>Source Activity</label> <input id="cboSearchSourceActivity" data-bind="enable: false, kendoDropDownList: { enable: false, data:SourceTaskActivities.dsActivities, dataTextField:'ActivityName', dataValueField:'ActivityID', cascadeFrom: 'cboSearchSourceTask', cascadeFromField: 'ParentID', optionLabel: { ActivityName: 'Not Selected', ActivityID: ''}, autoBind: false}, value: SearchSourceActivityID" style="width:100%;" disabled="disabled" /> </li> <li class="col-xs-3" id="SourceActivityProjectSearchTerm"> <label>Source Activity Project</label> <input id="cboSearchSourceActivityProject" data-bind="enable: false, kendoDropDownList: {enable: false, data:SourceTaskActivities.dsActivityProjects, dataTextField:'ActivityName', dataValueField:'ActivityID', cascadeFrom: 'cboSearchSourceActivity', cascadeFromField: 'ParentID', optionLabel: { ActivityName: 'Not Selected', ActivityID: ''}, autoBind: false}, value: SearchSourceActivityProjectID" style="width:100%;" disabled="disabled" /> </li> </ul> </li> </ol> <br style="clear: both;" /> <ol> <li> <ul> <li class="col-xs-3" id="TaskOrderSearchTerm"> <label>Budget Task Order</label> <input id="cboSearchTask" data-bind="kendoDropDownList: { value:SearchTaskOrderID, data:TaskActivities.dsTaskOrders, dataTextField:'ActivityName', dataValueField:'ActivityID', optionLabel:{ ActivityName:'Not Selected', ActivityID:'' }, autoBind:true}" style="width:100%;" disabled="disabled" /> </li> <li class="col-xs-3" id="ActivitySearchTerm"> <label>Budget Activity</label> <input id="cboSearchActivity" data-bind=" enable: false, kendoDropDownList: { enable: false, data:TaskActivities.dsActivities, dataTextField:'ActivityName', dataValueField:'ActivityID', cascadeFrom: 'cboSearchTask', cascadeFromField: 'ParentID', optionLabel: { ActivityName: 'Not Selected', ActivityID: ''}, autoBind: false}, value: SearchActivityID" style="width:100%;" disabled="disabled" /> </li> <li class="col-xs-3" id="ActivityProjectSearchTerm"> <label>Budget Activity Project</label> <input id="cboSearchActivityProject" data-bind="enable: false, kendoDropDownList: { enable: false, data:TaskActivities.dsActivityProjects, dataTextField:'ActivityName', dataValueField:'ActivityID', cascadeFrom: 'cboSearchActivity', cascadeFromField: 'ParentID', optionLabel: { ActivityName: 'Not Selected', ActivityID: ''}, autoBind: false}, value: SearchActivityProjectID" style="width:100%;" disabled="disabled" /> </li> </ul> </li> </ol> <br style="clear: both;" /> <hr style="color: #FFFFFF; background-color: #FFFFFF;"> <ol data-bind="foreach: RequestCriteria.Criterias"> <li> <ul data-bind="foreach: RequestTerms"> <li class="col3"> <div data-bind="template: { name: TemplateName }"></div> </li> </ul> </li> </ol> <br style="clear: both;" /> </div> </fieldset> </div> </div> @*bootstrap the RequestCriteria support*@ <script src="@this.Resource("Models/RequestCriteria.js")"></script> <script src="@this.Resource("ViewModels/RequestCriteria.js")"></script> <script src="@this.Resource("Models/Criteria.js")"></script> <script src="@this.Resource("ViewModels/Criteria.js")"></script> <script src="@this.Resource("Models/Terms.js")"></script> <script src="@this.Resource("ViewModels/Terms.js")"></script> @*bootstrap the terms*@ <script src="@this.Resource("Models/Terms/AgeRange.js")"></script> <script src="@this.Resource("ViewModels/Terms/AgeRange.js")"></script> <script src="@this.Resource("Models/Terms/AgeStratifier.js")"></script> <script src="@this.Resource("ViewModels/Terms/AgeStratifier.js")"></script> <script src="@this.Resource("Models/Terms/ClinicalSetting.js")"></script> <script src="@this.Resource("ViewModels/Terms/ClinicalSetting.js")"></script> <script src="@this.Resource("ViewModels/Terms/CodesTerm.js")"></script> <script src="@this.Resource("ViewModels/Terms/DateRange.js")"></script> <script src="@this.Resource("Models/Terms/Project.js")"></script> <script src="@this.Resource("ViewModels/Terms/Project.js")"></script> <script src="@this.Resource("Models/Terms/RequestStatus.js")"></script> <script src="@this.Resource("ViewModels/Terms/RequestStatus.js")"></script> <script src="@this.Resource("Models/Terms/Sex.js")"></script> <script src="@this.Resource("ViewModels/Terms/Sex.js")"></script> <script src="@this.Resource("Models/Terms/WorkplanType.js")"></script> <script src="@this.Resource("ViewModels/Terms/WorkplanType.js")"></script> <script src="@this.Resource("Models/Terms/RequesterCenter.js")"></script> <script src="@this.Resource("ViewModels/Terms/RequesterCenter.js")"></script> <script src="@this.Resource("Models/Terms/ReportAggregationLevel.js")"></script> <script src="@this.Resource("ViewModels/Terms.ReportAggregationLevel.js")"></script> @*bootstrap the page*@ <script src="@this.Resource("Create.js")"></script> <script type="text/javascript"> jQuery(document).ready(function () { // initialize the viewmodel var json = '@(Html.Raw(Model.CriteriaGroupsJSON))' || '{}'; var activityjson = '@Html.Raw(Json.Encode(Model.AllActivities))' || '{}'; var workplanTypeJson = '@Html.Raw(Json.Encode(Model.WorkplanTypeList))' || '{}'; var requesterCenterJson = '@Html.Raw(Json.Encode(Model.RequesterCenterList))' || '{}'; var reportAggregationLevelJson = '@Html.Raw(Json.Encode(Model.ReportAggregationLevelList))' || '{}'; var taskOrder = '@Model.TaskOrder'; var activity = '@Model.Activity'; var activityProject = '@Model.ActivityProject'; var sourceTaskOrder = '@Model.SourceTaskOrder'; var sourceActivity = '@Model.SourceActivity'; var sourceActivityProject = '@Model.SourceActivityProject'; MetadataQuery.Create.init($.parseJSON(json), $("#fsCriteria"), $("#CriteriaGroupsJSON"), $.parseJSON(activityjson), $.parseJSON(workplanTypeJson), $.parseJSON(requesterCenterJson), $.parseJSON(reportAggregationLevelJson), taskOrder, activity, activityProject, sourceTaskOrder, sourceActivity, sourceActivityProject); var dropdownlist = $("#cboSearchActivity").data("kendoDropDownList"); dropdownlist.open(); dropdownlist.close(); var sourcedropdownlist = $('#cboSearchSourceActivity').data("kendoDropDownList"); sourcedropdownlist.open(); sourcedropdownlist.close(); }); </script>
33,650
https://github.com/anniyanvr/gravitee-gateway/blob/master/gravitee-apim-rest-api/gravitee-apim-rest-api-management/gravitee-apim-rest-api-management-rest/src/main/java/io/gravitee/rest/api/management/rest/resource/param/AuditType.java
Github Open Source
Open Source
Apache-2.0
2,023
gravitee-gateway
anniyanvr
Java
Code
149
438
/** * Copyright (C) 2015 The Gravitee team (http://gravitee.io) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.gravitee.rest.api.management.rest.resource.param; import static java.util.Map.entry; import io.gravitee.rest.api.model.audit.AuditReferenceType; import io.swagger.v3.oas.annotations.media.Schema; import java.util.Map; @Schema(enumAsRef = true) public enum AuditType { ORGANIZATION, ENVIRONMENT, APPLICATION, API; private static final Map<AuditType, AuditReferenceType> AUDIT_TYPE_AUDIT_REFERENCE_TYPE_MAP = Map.ofEntries( entry(AuditType.ORGANIZATION, AuditReferenceType.ORGANIZATION), entry(AuditType.ENVIRONMENT, AuditReferenceType.ENVIRONMENT), entry(AuditType.APPLICATION, AuditReferenceType.APPLICATION), entry(AuditType.API, AuditReferenceType.API) ); public static AuditReferenceType fromAuditType(AuditType auditType) { return AUDIT_TYPE_AUDIT_REFERENCE_TYPE_MAP.get(auditType); } }
22,577
https://github.com/joseacevedo9698/prueba-tecnica-slab-code/blob/master/src/Models/index.ts
Github Open Source
Open Source
MIT
null
prueba-tecnica-slab-code
joseacevedo9698
TypeScript
Code
12
25
export * from './Interfaces' export * from './Structures' export * from './Schemas'
44,579
https://github.com/onpointtech/agency-portal-v2/blob/master/ClaimantServiceNew/src/main/java/com/opt/optimum/ui/benefits/claimant/business/ClaimantBusinessServiceImpl.java
Github Open Source
Open Source
Unlicense
null
agency-portal-v2
onpointtech
Java
Code
132
697
package com.opt.optimum.ui.benefits.claimant.business; import java.time.OffsetDateTime; import java.util.List; import org.modelmapper.ModelMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.opt.optimum.ui.benefits.claimant.domain.ClaimantDomainService; import com.opt.optimum.ui.benefits.claimant.domain.ClaimantDomainServiceImpl; import com.opt.optimum.ui.benefits.claimant.entity.Address; import com.opt.optimum.ui.benefits.claimant.entity.ClaimantProfile; import com.opt.optimum.ui.benefits.claimant.so.ClaimantProfileSO; import com.opt.optimum.ui.benefits.claimant.so.UpdateClaimantProfileSO; @Service public class ClaimantBusinessServiceImpl implements ClaimantBusinessService{ private ModelMapper modelMapper; private ClaimantDomainService claimantDomainService; private static final Logger logger = LoggerFactory.getLogger(ClaimantBusinessServiceImpl.class); @Autowired public ClaimantBusinessServiceImpl(ModelMapper modelMapper, ClaimantDomainService claimantDomainService) { this.modelMapper = modelMapper; this.claimantDomainService = claimantDomainService; } public long registerClaimant(ClaimantProfileSO claimantProfileSO) { ModelMapper modelMapper = new ModelMapper(); ClaimantProfile claimantProfile = modelMapper.map(claimantProfileSO, ClaimantProfile.class); return claimantDomainService.registerClaimant(claimantProfile); } public ClaimantProfile getClaimantById(long claimantId) { return claimantDomainService.getClaimantById(claimantId); } public List<ClaimantProfile> getAllClaimants() { return claimantDomainService.getAllClaimants(); } public ClaimantProfile updateClaimant(UpdateClaimantProfileSO updateClaimantProfileSO, long claimantId) { ModelMapper modelMapper = new ModelMapper(); ClaimantProfile claimantProfile = modelMapper.map(updateClaimantProfileSO, ClaimantProfile.class); return claimantDomainService.updateClaimant(claimantProfile, claimantId); } public List<ClaimantProfile> searchClaimant(String claimantInfo) { return claimantDomainService.searchClaimant(claimantInfo); } public ClaimantProfile getClaimantBySsn(String ssn) { return claimantDomainService.getClaimantBySsn(ssn); } }
48,481
https://github.com/9d77v/leetcode/blob/master/internal/lcof/32.cong-shang-dao-xia-da-yin-er-cha-shu/main.go
Github Open Source
Open Source
BSD-3-Clause
null
leetcode
9d77v
Go
Code
85
374
package main import ( . "github.com/9d77v/leetcode/pkg/algorithm/binarytree" ) /* 题目:从上到下打印二叉树 从上到下打印出二叉树的每个节点,同一层的节点按照从左到右的顺序打印。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-lcof/ */ /* 方法一:bfs 时间复杂度:О(n) 空间复杂度:О(n) 运行时间:0 ms 内存消耗:2.7 MB */ func levelOrder(root *TreeNode) (ans []int) { if root == nil { return } q := []*TreeNode{root} for len(q) > 0 { tmp := []*TreeNode{} for _, p := range q { ans = append(ans, p.Val) if p.Left != nil { tmp = append(tmp, p.Left) } if p.Right != nil { tmp = append(tmp, p.Right) } } q = tmp } return ans }
4,066
https://github.com/pattayatus/Nextjs-Car-Market/blob/master/pages/HomePage.js
Github Open Source
Open Source
MIT
null
Nextjs-Car-Market
pattayatus
JavaScript
Code
456
1,881
import React from "react"; import Link from "next/link"; // plugin that creates slider import Slider from "nouislider"; // @material-ui/core components import { makeStyles } from "@material-ui/core/styles"; import InputAdornment from "@material-ui/core/InputAdornment"; import FormControlLabel from "@material-ui/core/FormControlLabel"; import Checkbox from "@material-ui/core/Checkbox"; import Radio from "@material-ui/core/Radio"; import Switch from "@material-ui/core/Switch"; // @material-ui/icons import Favorite from "@material-ui/icons/Favorite"; import People from "@material-ui/icons/People"; import Check from "@material-ui/icons/Check"; import FiberManualRecord from "@material-ui/icons/FiberManualRecord"; // core components import GridContainer from "components/Grid/GridContainer.js"; import GridItem from "components/Grid/GridItem.js"; // import Button from "components/CustomButtons/Button.js"; import CustomInput from "components/CustomInput/CustomInput.js"; import CustomLinearProgress from "components/CustomLinearProgress/CustomLinearProgress.js"; import Paginations from "components/Pagination/Pagination.js"; import Badge from "components/Badge/Badge.js"; import Card from "@material-ui/core/Card"; import CardActionArea from "@material-ui/core/CardActionArea"; import CardActions from "@material-ui/core/CardActions"; import CardContent from "@material-ui/core/CardContent"; import CardMedia from "@material-ui/core/CardMedia"; import GridListTileBar from "@material-ui/core/GridListTileBar"; import ButtonGroup from "@material-ui/core/ButtonGroup"; import Button from "@material-ui/core/Button"; import StarIcon from "@material-ui/icons/Star"; import IconButton from "@material-ui/core/IconButton"; import { hexToRGBAlpha, defaultFont, primaryColor, infoColor, successColor, warningColor, dangerColor, roseColor, transition, boxShadow, drawerWidth, } from "styles/jss/nextjs-material-kit.js"; import Grid from "@material-ui/core/Grid"; import Typography from "@material-ui/core/Typography"; import styles from "styles/jss/nextjs-material-kit/pages/homepageStyle.js"; const useStylesone = makeStyles((theme) => ({ btGroup: { display: "flex", flexDirection: "column", alignItems: "center", marginLeft: "1000px", "& > *": { margin: theme.spacing(1), }, }, icon: { color: "rgba(255, 255, 255, 0.54)", }, })); const useStyles = makeStyles(styles); export default function HomePage() { const classes = useStyles(); const classone = useStylesone(); return ( <div className={classes.sections}> <div className={classes.container}> <div className={classes.title}> <h2>Handy picked</h2> </div> <div> <div className={classes.title}> <h1>Featured Listings</h1> <div className={classone.btGroup}> <ButtonGroup color="primary" aria-label="outlined primary button group" > <Button>New</Button> <Button>Used</Button> </ButtonGroup> </div> </div> <div></div> <GridContainer className="containermain"> <GridContainer className="container-one"> <Grid> <Link href="/carsPage"> <Card className={classes.rootmain}> <CardActionArea> <div className="hovereffect"> <img src="/img/car_vector.jpg" alt width={600} height={600} /> </div> <GridListTileBar title="Name of the car1.1" subtitle="Heloo" // actionIcon={ // <IconButton className={classone.icon}> // <StarIcon /> // </IconButton> // } /> </CardActionArea> </Card> </Link> </Grid> </GridContainer> <GridContainer className="container-two"> <Grid> <Link href="/carsPage"> <Card className={classes.root}> <CardActionArea> <div className="hovereffect"> <img src="/img/car_vector.jpg" alt width={280} height={280} /> </div> <GridListTileBar title="Name of the car2.1" subtitle="Heloo" // actionIcon={ // <IconButton className={classone.icon}> // <StarIcon /> // </IconButton> // } /> </CardActionArea> </Card> </Link> </Grid> <Grid style={{ marginTop: "20px" }}> <Link href="/carsPage"> <Card className={classes.root}> <CardActionArea> <div className="hovereffect"> <img src="/img/car_vector.jpg" alt width={280} height={280} /> </div> <GridListTileBar title="Name of the car2.2" subtitle="Heloo" // actionIcon={ // <IconButton className={classone.icon}> // <StarIcon /> // </IconButton> // } /> </CardActionArea> </Card> </Link> </Grid> </GridContainer> <GridContainer className="container-two"> <Grid> <Link href="/carsPage"> <Card className={classes.root}> <CardActionArea> <div className="hovereffect"> <img src="/img/car_vector.jpg" alt width={280} height={280} /> </div> <GridListTileBar title="Name of the car3.1" subtitle="Heloo" // actionIcon={ // <IconButton className={classone.icon}> // <StarIcon /> // </IconButton> // } /> </CardActionArea> </Card> </Link> </Grid> <Grid> <Link href="/carsPage"> <Card className={classes.root}> <CardActionArea> <div className="hovereffect"> <img src="/img/car_vector.jpg" alt width={280} height={280} /> </div> <GridListTileBar title="Name of the car3.2" subtitle="Heloo" // actionIcon={ // <IconButton className={classone.icon}> // <StarIcon /> // </IconButton> // } /> </CardActionArea> </Card> </Link> </Grid> </GridContainer> </GridContainer> </div> </div> </div> ); }
33,931
https://github.com/Robotron-GmbH/splunk-youtube-material/blob/master/Saegewerk/bin/Saegewerk.py
Github Open Source
Open Source
MIT
2,021
splunk-youtube-material
Robotron-GmbH
Python
Code
624
6,020
# -*- coding: utf-8 -*- """ Created on Wed Mar 18 11:09:31 2020 @author: stephan.fuchs """ import sys import os sys.path.insert(0, "..") import datetime import time import random from random import randrange import math Erstelle_Lookup=False kunden=int(sys.argv[1]) #Anzahl der Sekunden wie lange das Skript laufen soll def zufalls_ip(): #return str(np.random.randint(255, size=1)[0])+"."+str(np.random.randint(255, size=1)[0])+"."+str(np.random.randint(255, size=1)[0])+"."+str(np.random.randint(255, size=1)[0]) return str(randrange(1,255,1))+"."+str(randrange(1,255,1))+"."+str(randrange(1,255,1))+"."+str(randrange(1,255,1)) def write_logs(file,line): # Input ist hier dictonary #write out the event, open and close the file each time for proper tailing #Time= datetime.datetime.fromtimestamp(int(Zeitpunkt)).strftime('%Y-%m-%d %H:%M:%S') output_file = open(file, 'a') for column in line.values(): output_file.write(str(column)+",") output_file.write(str("\n")) output_file.close() def write_logs_array(file,array): # Input ist hier Array #write out the event, open and close the file each time for proper tailing #Time= datetime.datetime.fromtimestamp(int(Zeitpunkt)).strftime('%Y-%m-%d %H:%M:%S') output_file = open(file, 'a') for value in array: output_file.write(str(value)+",") output_file.write(str("\n")) output_file.close() def aufaddieren(arr): zwi=[] a=0 for i in arr: a=i+a zwi.append(a) ##print("zwi",zwi) return zwi def erstelle_lookup(erste_spalte,dictionary,dateiname): # erstellt lookups aus dictionarys output_file = open(dateiname, 'w') a=next(iter(dictionary.values())) #beispiel Values header=erste_spalte+"," for spalte in a.keys(): header=header+spalte+"," #print(header) output_file.write(header+"\n") for keys in dictionary.keys(): output_file.write(str(keys)+",") for werte in dictionary[keys].values(): output_file.write(str(werte)+",") output_file.write("\n") output_file.close() def statistik_funktion(wahrscheinlichkeiten,auswahl): zufalls_zahl=random.random() wahr_arr=wahrscheinlichkeiten[:] #.copy() #fuer Version 2.7 wahr_arr.insert(0,0) wahr_arr_zwi=aufaddieren(wahr_arr) wahr_arr_zwi[-1]=1.0 ausgabe_i=0 ##print("Wahr_arr",wahr_arr,"Wahr_arr_zwi",wahr_arr_zwi,"Auswahl",auswahl) for i in range(len(wahr_arr)-1): ##print(i,zufalls_zahl,wahr_arr_zwi[i]) if (zufalls_zahl>wahr_arr_zwi[i]) and (zufalls_zahl<wahr_arr_zwi[i+1]): ##print("Bin drin",auswahl[i]) ausgabe_i=auswahl[i] return ausgabe_i def wichtigkeit(arr): Prio=[i["Prio"] for i in arr] #print("Prio",Prio) laenge=sum(Prio) ausgabe=[i/laenge for i in Prio] #print("Ausgabe",ausgabe) return ausgabe def auftrag(kunden_arr,verhaltnis_auftrage): Eintrag=statistik_funktion(verhaltnis_auftrage,kunden_arr) ##print("Eintrag",Eintrag) kunde=Eintrag["Kunde"] Produkt=statistik_funktion(Eintrag["P_Produkt"],Eintrag["Produkte"]) Holz= statistik_funktion(Eintrag["P_Holzart"],Eintrag["Holzart"]) return [kunde,Produkt,Holz] def Zufallszahlen(start,abweichung): #ausgabe=start+num_ra.normal(0,abweichung) ausgabe=start+random.gauss(0,abweichung) return round(ausgabe,2) # Um den Wasserdruck der Hauptpumpe zu simulieren, inklusive Störungen def temperatur_ausreisser(x): #x=x/30. # hoehere Zeitauflösung periode=random.randrange(20,50,1) #print(x,x%periode,periode) laenge_ausbrauch=3 if (x%periode<laenge_ausbrauch): Temp=random.gauss(30,10) #print("Wasserausreißer") else: Temp=random.gauss(30,1) return Temp def maschinen_daten_schreiben(Zeitstempel,Mitarbeiter,Halle,Maschine,i): Temp= round(2*math.sin(0.4*i)+random.gauss(40,1),2) Strom= round(math.sin(0.2*i)+random.gauss(10,1),3) # einmal in der Minute steigt die Temperatur auf über 100 Grad. if Zeitstempel%60<2: Temp=Temp+61 #maschinendaten={"Zeitstempel":Zeitstempel,"Halle":Halle,"Messwert":Halle+"."+Maschine+".Temperatur","Temperatur":str(Temp)} write_logs_array(file_metrics,[Zeitstempel,Mitarbeiter,Halle+"."+Maschine+".Temperatur",str(Temp)]) #maschinendaten={"Zeitstempel":Zeitstempel,"Halle":Halle,"Messwert":Halle+"."+Maschine+".Strom","Strom":str(Strom)} write_logs_array(file_metrics,[Zeitstempel,Mitarbeiter,Halle+"."+Maschine+".Strom",str(Strom)]) #print("Temperatur",Temp,"Strom",Strom,"Halle",Halle,"Maschine",Maschine) return Temp,Strom def maschinen_daten_schreiben_aussen(Zeitstempel,i,Wasserdruck,Sensehat_Vorhanden): Luftdruck= round(random.gauss(1012,0.8),2) Aussentemp= round(math.sin(0.02*i)+random.gauss(17.4,0.3),1) Feuchtigkeit= round(random.gauss(51,0.6),1) Wasserdruck=round(temperatur_ausreisser(i),3) # maschinendaten={"Zeitstempel":Zeitstempel,"Halle":"Aussenbereich","Messwert":"Aussenbereich.Aussentemperatur","Temperatur":str(Aussentemp)} #write_logs(file_metrics,maschinendaten) write_logs_array(file_metrics,[Zeitstempel,"Emilia","Aussenbereich.Aussentemperatur",str(Aussentemp)]) # maschinendaten={"Zeitstempel":Zeitstempel,"Halle":"Aussenbereich","Messwert":"Aussenbereich.Luftfeuchtigkeit","Luftfeuchtigkeit":str(Feuchtigkeit)} write_logs_array(file_metrics,[Zeitstempel,"Emilia","Aussenbereich.Luftfeuchtigkeit",str(Feuchtigkeit)]) #maschinendaten={"Zeitstempel":Zeitstempel,"Halle":"Aussenbereich","Messwert":"Aussenbereich.Luftdruck","Luftdruck":str(Luftdruck)} write_logs_array(file_metrics,[Zeitstempel,"Emilia","Aussenbereich.Luftdruck",str(Luftdruck)]) #maschinendaten={"Zeitstempel":Zeitstempel,"Halle":"Aussenbereich","Messwert":"Aussenbereich.Wasserdruck","Wasserdruck":str(Wasserdruck)} write_logs_array(file_metrics,[Zeitstempel,"Emilia","Aussenbereich.Wasserdruck",str(Wasserdruck)]) #print("Aussentemp,Feuchtigkeit,Luftdruck,Wasserdruck",Aussentemp,Feuchtigkeit,Luftdruck,Wasserdruck) return Aussentemp,Feuchtigkeit,Luftdruck,Wasserdruck def zufalls_ID(): ABC=['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] Buchstaben=random.sample(ABC, 5) Buchstaben="".join(Buchstaben) Zahl= random.choice([1,10,100,1000]) ID=str(int(random.random()*100000))+"-"+str(int(random.random()*Zahl))+Buchstaben+"-"+str(int(random.random()*10000)) return ID ################# Header schreiben falls datei nicht exisitiert####################### file_index="Holzfabrik.csv" ##print("Datei wird hier gespeichert: ",file_index) if os.path.isfile(file_index): #print("Datei Holzfabrik vorhanden") pass else: output_file = open(file_index, 'w') output_file.write("Kunde,Produkt,Holz,AuftragsID,Maschine,Dauer,_time,Umsatz,Gewicht\n") output_file.close() file_metrics="Holzfabrik_Maschinen.csv" if os.path.isfile(file_metrics): #print("Datei File Metrics vorhanden") pass else: output_file = open(file_metrics, 'w') output_file.write("metric_timestamp,Verantwortlicher,metric_name,_value\n") output_file.close() ################## Datengrundlage ############################# kunden_arr=[] kunden_arr.append({"Kunde":"IDEA" ,"Prio":6,"Produkte":["Schrank","Stuhl","Tisch","Regal","Tablethalter"],"P_Produkt":[0.4,0.2,0.15,0.2,0.05],"Holzart":["Fichte","Kiefer","Buche","Birke"],"P_Holzart":[0.1,0.3,0.2,0.4]}) kunden_arr.append({"Kunde":"Fuchsbau","Prio":5,"Produkte":["Tisch","Stuhl","Regal"],"P_Produkt":[0.7,0.1,0.2],"Holzart":["Fichte","Tanne"],"P_Holzart":[0.4,0.6]}) kunden_arr.append({"Kunde":"Porathholz" ,"Prio":4,"Produkte":["Tisch","Stuhl"],"P_Produkt":[0.9,0.1],"Holzart":["Buche","Kiefer"],"P_Holzart":[0.5,0.5]}) kunden_arr.append({"Kunde":"Schmidt Bretter","Prio":3,"Produkte":["Tisch","Regal","Stuhl"],"P_Produkt":[0.8,0.1,0.1],"Holzart":["Fichte","Tanne"],"P_Holzart":[0.3,0.7]}) kunden_arr.append({"Kunde":"Weser Baumschule" ,"Prio":2,"Produkte":["Schrank","Hocker"],"P_Produkt":[0.5,0.5],"Holzart":["Fichte","Buche"],"P_Holzart":[0.4,0.6]}) kunden_arr.append({"Kunde":"Walter Baumhaus" ,"Prio":0.5,"Produkte":["Regal"],"P_Produkt":[1],"Holzart":["Fichte","Birke"],"P_Holzart":[0.7,0.3]}) kunden_arr.append({"Kunde":"Pinoccio" ,"Prio":1 ,"Produkte":["Tisch","Hocker"],"P_Produkt":[0.3,0.7],"Holzart":["Kiefer","Buche"],"P_Holzart":[0.5,0.5]}) kunden_arr.append({"Kunde":"Herrmann Bretter","Prio":1,"Produkte":["Bank"],"P_Produkt":[1],"Holzart":["Birke","Buche"],"P_Holzart":[0.1,0.9]}) kunden_arr.append({"Kunde":"Ecke" ,"Prio":1,"Produkte":["Schrank","Stuhl"],"P_Produkt":[0.3,0.7],"Holzart":["Fichte","Kiefer"],"P_Holzart":[0.2,0.8]}) kunden_arr.append({"Kunde":"Immanuel Kantholz" ,"Prio":1,"Produkte":["Stuhl","Bank"],"P_Produkt":[0.5,0.5],"Holzart":["Fichte","Kiefer"],"P_Holzart":[0.4,0.6]}) kunden_arr.append({"Kunde":"BlumenExpress" ,"Prio":1.5,"Produkte":["Tablethalter","Truhe"],"P_Produkt":[0.8,0.2],"Holzart":["Fichte","Kiefer"],"P_Holzart":[0.4,0.6]}) kunden_arr.append({"Kunde":"Blocksberg Besen" ,"Prio":0.3,"Produkte":["Truhe","Tablethalter"],"P_Produkt":[0.8,0.2],"Holzart":["Buche","Eiche"],"P_Holzart":[0.4,0.6]}) kunden_arr.append({"Kunde":"Fynn" ,"Prio":0.05,"Produkte":["Zaunlatten"],"P_Produkt":[1],"Holzart":["Birke"],"P_Holzart":[1.]}) kunden_info={} kunden_info.update({"IDEA":{"Adresse":"Orangenstrasse 30","IP":zufalls_ip()}}) kunden_info.update({"Fuchsbau":{"Adresse":"Himbeerstrasse 18","IP":zufalls_ip()}}) kunden_info.update({"Porathholz":{"Adresse":"Baumweg 3","IP":zufalls_ip()}}) kunden_info.update({"Schmidt Bretter":{"Adresse":"Zitronengasse 32","IP":zufalls_ip()}}) kunden_info.update({"Weser Baumschule":{"Adresse":"Erdbeer Rue 32","IP":zufalls_ip()}}) kunden_info.update({"Walter Baumhaus":{"Adresse":"Marmeladenplatz 642","IP":zufalls_ip()}}) kunden_info.update({"Pinoccio":{"Adresse":"Keksstrasse 22","IP":zufalls_ip()}}) kunden_info.update({"Herrmann Bretter":{"Adresse":"Hariboweg 98","IP":zufalls_ip()}}) kunden_info.update({"Ecke":{"Adresse":"An der Ecke 54","IP":zufalls_ip()}}) kunden_info.update({"Immanuel Kantholz":{"Adresse":"Fotogasse 766","IP":zufalls_ip()}}) kunden_info.update({"Blocksberg Besen":{"Adresse":"Hexenweg 666","IP":zufalls_ip()}}) kunden_info.update({"Blümchen":{"Adresse":"Sonnenblumnenallee 10","IP":zufalls_ip()}}) verhaltnis_auftrage=wichtigkeit(kunden_arr) # erstellt array aus den Prioritäten und normiert die Summe auf 1. produkt_info={} produkt_info.update({"Stuhl":{"Kosten":100,"Dauer":15,"Gewicht":5}}) produkt_info.update({"Schrank":{"Kosten":200,"Dauer":30,"Gewicht":50}}) produkt_info.update({"Tisch":{"Kosten":150,"Dauer":20,"Gewicht":20}}) produkt_info.update({"Regal":{"Kosten":50,"Dauer":10,"Gewicht":2}}) produkt_info.update({"Hocker":{"Kosten":40,"Dauer":7,"Gewicht":1}}) produkt_info.update({"Bank":{"Kosten":60,"Dauer":12,"Gewicht":15}}) produkt_info.update({"Tablethalter":{"Kosten":5,"Dauer":1,"Gewicht":0.3}}) produkt_info.update({"Truhe":{"Kosten":30,"Dauer":25,"Gewicht":40}}) produkt_info.update({"Zaunlatten":{"Kosten":15,"Dauer":8,"Gewicht":10}}) holz_info={} holz_info.update({"Eiche":{"Kosten":1.1,"Dauer":1.0,"Farbe":"Sehr Dunkel"}}) holz_info.update({"Buche":{"Kosten":1.2,"Dauer":1.02,"Farbe":"Leicht Dunkel"}}) holz_info.update({"Fichte":{"Kosten":1.3,"Dauer":1.15,"Farbe":"Mittel Dunkel"}}) holz_info.update({"Tanne":{"Kosten":0.9,"Dauer":1.05,"Farbe":"Sehr Hell"}}) holz_info.update({"Kiefer":{"Kosten":0.95,"Dauer":1.07,"Farbe":"Mittel Hell"}}) holz_info.update({"Birke":{"Kosten":1.0,"Dauer":1.04,"Farbe":"Dunkel"}}) Mitarbeiter=["Albert","Richard","Thomas"] # Lookups generiert aus simulierten Daten. Für den Fall das sich was ändert, ausklammern und in Lookup Ordner verschieben. if Erstelle_Lookup: erstelle_lookup("Holz",holz_info,"holzinfo_lookup.csv") erstelle_lookup("Produkt",produkt_info,"produktinfo_lookup.csv") erstelle_lookup("Kunde",kunden_info,"kundeninfo_lookup.csv") ######################## hallen={"Halle":{"Bieberbau":{"alpha":{"Messwerte":["Temperatur","Strom"]}},"Spechtnest":{"beta":{"Messwerte":["Temperatur","Strom"]},"gamma":{"Messwerte":["Temperatur","Strom"]}}}} aussenwerte={"Aussenwerte":{"Messwerte":["Wasserdruck","Aussentemp","Feuchtigkeit","Luftdruck"]}} auftrags_wert={"Letzter_Auftrag":["Maschine","Kunde","Produkt","Holz","ID","Dauer","Umsatz","Gewicht","Zeit"]} #Startparameter Wasserdruck=20 Temp_a,Strom_a=10,30 Temp_b,Strom_b=10,30 Temp_c,Strom_c=10,40 letzter_Kunde="IDEA" ID=int(random.random()*10000000) #Start ID neuer_auftrag=True alpha,beta,gamma=0,0,0 Maschine="Alpha" for i in range(kunden): time.sleep(1) Zeitstempel=round(time.time(),1) Time= datetime.datetime.fromtimestamp(int(Zeitstempel)).strftime('%Y-%m-%d %H:%M:%S') if (neuer_auftrag): kunde_aus=auftrag(kunden_arr,verhaltnis_auftrage) ##print("kundeaus",kunde_aus) if letzter_Kunde==kunde_aus[0]: #print("Sammelauftrag:", ID, "aktueller Kunde:",kunde_aus[0]," Letzter Kunde:",letzter_Kunde) pass else: ID=zufalls_ID() letzter_Kunde=kunde_aus[0] gewicht =produkt_info[kunde_aus[1]]["Gewicht"]+round(random.gauss(1,0.2),3) auftragsdauer=round(produkt_info[kunde_aus[1]]["Dauer"] *holz_info[kunde_aus[2]]["Dauer"],2) umsatz =round(produkt_info[kunde_aus[1]]["Kosten"]+holz_info[kunde_aus[2]]["Kosten"]*gewicht,2) #Arbeitskosten + Materialkosten #Auftrag der als Event an Splunk geht aktueller_auftrag={"Kunde":kunde_aus[0],"Produkt":kunde_aus[1],"Holz":kunde_aus[2],"AuftragsID":ID,"Maschine":Maschine,"Dauer":auftragsdauer,"_time":Time,"Umsatz":umsatz,"Gewicht":gewicht} #print("Alpha:",alpha,"Beta:",beta,"Gamma:",gamma) #print(aktueller_auftrag) #write_logs(file_index,aktueller_auftrag) write_logs_array(file_index,[kunde_aus[0],kunde_aus[1],kunde_aus[2],ID, Maschine,auftragsdauer,Time,umsatz,gewicht]) #Welche Maschine als nächstes Ausgewählt wird neuer_auftrag=False if alpha<=0: alpha=auftragsdauer+alpha*0 Maschine="Alpha" neuer_auftrag=True elif beta <=0: beta=auftragsdauer+beta*0 Maschine="Beta" neuer_auftrag=True elif gamma <=0: gamma=auftragsdauer+gamma*0 Maschine="Gamma" neuer_auftrag=True if i%120==0: #Schichtwechsel Benutzer=["Michael","Karl","Emilia","Tim","Sarah","Wilhelm","Emmy"] Benutzer_a=random.choice(Benutzer) Benutzer.remove(Benutzer_a) Benutzer_b=random.choice(Benutzer) Benutzer.remove(Benutzer_b) Benutzer_c=random.choice(Benutzer) Benutzer.remove(Benutzer_c) Temp_a,Strom_a=maschinen_daten_schreiben(Zeitstempel,Benutzer_a,"Bieberbau","alpha",i) Temp_b,Strom_b=maschinen_daten_schreiben(Zeitstempel,Benutzer_b,"Spechtnest","beta", i) Temp_c,Strom_c=maschinen_daten_schreiben(Zeitstempel,Benutzer_c,"Spechtnest","gamma",i) Aussentemp,Feuchtigkeit,Luftdruck,Wasserdruck=maschinen_daten_schreiben_aussen(Zeitstempel,i,Wasserdruck,False) # Abarbeiten der Maschine alpha=alpha-1 beta=beta-1 gamma=gamma-1
42,085
https://github.com/lmachens/aeternum-map/blob/master/src/app/utils/useReadLivePosition.ts
Github Open Source
Open Source
MIT
2,022
aeternum-map
lmachens
TypeScript
Code
481
1,487
import { useEffect, useState } from 'react'; import { io } from 'socket.io-client'; import { useAccount } from '../contexts/UserContext'; import { getJSONItem } from './storage'; import { toast } from 'react-toastify'; import useGroupPositions from '../components/WorldMap/useGroupPositions'; import { usePlayer } from '../contexts/PlayerContext'; import Peer from 'peerjs'; export type Position = { location: [number, number]; rotation: number }; export type Player = { steamId: string; steamName: string; username: string | null; position: Position | null; location: string | null; region: string | null; worldName: string | null; map: string | null; }; export type Group = { [playerToken: string]: Player; }; let latestPlayer: Player | null = null; let latestGroup: Group | null = null; function useReadLivePosition() { const { setPlayer, isSyncing, setIsSyncing } = usePlayer(); const [group, setGroup] = useState<Group>({}); const { account } = useAccount(); useGroupPositions(group); useEffect(() => { if (!isSyncing) { return; } const token = account?.liveShareToken || getJSONItem<string | null>('live-share-token', null); const serverUrl = account?.liveShareServerUrl || getJSONItem<string | null>('live-share-server-url', null); if (!token || !serverUrl) { setIsSyncing(false); return; } const socket = io(serverUrl, { query: { token, }, upgrade: false, transports: ['websocket'], }); const updateStatus = (group: Group) => { const sessionIds = Object.keys(group); const playerSessionId = sessionIds.find((sessionId) => { if (account) { const player = group[sessionId]; return player.steamId === account.steamId; } return true; }) || sessionIds[0]; latestPlayer = group[playerSessionId]; setPlayer(latestPlayer); delete group[playerSessionId]; latestGroup = group; setGroup(group); }; socket.emit('status', updateStatus); socket.on('status', updateStatus); const peerConnectedSteamIds: string[] = []; const updateData = (data: Partial<Player>) => { const { steamId, ...partialPlayer } = data; if (!steamId) { return; } if (latestPlayer && latestPlayer.steamId === steamId) { Object.assign(latestPlayer, partialPlayer); setPlayer({ ...latestPlayer }); } else if (latestGroup) { const player = Object.values(latestGroup).find( (player) => player.steamId === steamId ); if (player) { Object.assign(player, partialPlayer); setGroup({ ...latestGroup }); } } }; socket.on('data', (data: Partial<Player>) => { if (!data.steamId || peerConnectedSteamIds.includes(data.steamId)) { return; } updateData(data); }); const handleHotkey = (steamId: string, hotkey: string) => { if (steamId !== account?.steamId) { return; } const event = new CustomEvent(`hotkey-${hotkey}`); window.dispatchEvent(event); }; socket.on('hotkey', handleHotkey); let peer: Peer | null = null; socket.on('connect', () => { toast.success('Sharing live status 👌'); peer = new Peer(socket.id.replace(/[^a-zA-Z ]/g, ''), { debug: 2, }); peer.on('error', (error) => { console.error('Peer error', error); }); peer.on('open', (id) => { console.log('My peer ID is: ' + id); }); peer.on('connection', (conn) => { let connSteamId: string | null = null; conn.on('open', () => { console.log('Peer opened'); socket.emit('status', updateStatus); }); conn.on('error', (error) => { console.log('Peer error', error); }); conn.on('close', () => { console.log('Peer closed'); if (connSteamId) { const index = peerConnectedSteamIds.indexOf(connSteamId); if (index !== -1) { peerConnectedSteamIds.splice(index, 1); } } }); conn.on('data', (data) => { if (data.group) { updateStatus(data.group); return; } if (data.steamId && !peerConnectedSteamIds.includes(data.steamId)) { peerConnectedSteamIds.push(data.steamId); connSteamId = data.steamId; } updateData(data); }); }); }); return () => { socket.off('connect'); socket.off('update'); socket.off('hotkey'); peer?.destroy(); socket.close(); setGroup({}); toast.info('Stop sharing live status 🛑'); }; }, [ account?.liveShareToken, account?.liveShareServerUrl, isSyncing, account?.steamId, ]); } export default useReadLivePosition;
23,773
https://github.com/tmancal74/quantarhei/blob/master/quantarhei/wizard/benchmarks/bm_001.py
Github Open Source
Open Source
MIT
2,023
quantarhei
tmancal74
Python
Code
44
222
# -*- coding: utf-8 -*- import quantarhei as qr def main(): with qr.energy_units("1/cm"): mol1 = qr.Molecule([0.0, 12000.0]) mol2 = qr.Molecule([0.0, 12100.0]) mol3 = qr.Molecule([0.0, 12100.0]) agg = qr.Aggregate([mol1, mol2, mol3]) m1 = qr.Mode(100) mol1.add_Mode(m1) m2 = qr.Mode(100) mol2.add_Mode(m2) m3 = qr.Mode(100) mol3.add_Mode(m3) agg.build(mult=1) print(agg.Ntot)
1,255
https://github.com/WuSantaFe/YiShaAdmin/blob/master/YiSha.Web/YiSha.Admin.Web/Areas/OrganizationManage/Views/Department/DepartmentForm.cshtml
Github Open Source
Open Source
MIT
2,021
YiShaAdmin
WuSantaFe
C#
Code
284
1,284
@{ Layout = "~/Views/Shared/_FormWhite.cshtml"; } <div class="wrapper animated fadeInRight"> <form id="form" class="form-horizontal m"> <div class="form-group"> <label class="col-sm-3 control-label ">上级部门</label> <div class="col-sm-8"> <div id="parentId" col="ParentId"></div> </div> </div> <div class="form-group"> <label class="col-sm-3 control-label ">部门名称<font class="red"> *</font></label> <div class="col-sm-8"> <input id="departmentName" col="DepartmentName" type="text" class="form-control" /> </div> </div> <div class="form-group"> <label class="col-sm-3 control-label ">负责人</label> <div class="col-sm-8"> <div id="principalId" col="PrincipalId"></div> </div> </div> <div class="form-group"> <label class="col-sm-3 control-label ">电话号码</label> <div class="col-sm-8"> <input id="telephone" col="Telephone" type="text" class="form-control" /> </div> </div> <div class="form-group"> <label class="col-sm-3 control-label ">传真</label> <div class="col-sm-8"> <input id="fax" col="Fax" type="text" class="form-control" /> </div> </div> <div class="form-group"> <label class="col-sm-3 control-label ">Email</label> <div class="col-sm-8"> <input id="email" col="Email" type="text" class="form-control" /> </div> </div> <div class="form-group"> <label class="col-sm-3 control-label ">显示顺序</label> <div class="col-sm-8"> <input id="departmentSort" col="DepartmentSort" type="text" class="form-control" /> </div> </div> <div class="form-group"> <label class="col-sm-3 control-label ">备注</label> <div class="col-sm-8"> <textarea id="remark" col="Remark" class="form-control"></textarea> </div> </div> </form> </div> <script type="text/javascript"> var id = ys.request("id"); $(function () { $('#parentId').ysComboBoxTree({ url: '@Url.Content("~/OrganizationManage/Department/GetDepartmentTreeListJson")', async: false }); $('#principalId').ysComboBoxTree({ url: '@Url.Content("~/OrganizationManage/Department/GetUserTreeListJson")', async: false }); getForm(); $("#form").validate({ rules: { departmentName: { required: true }, parentIdInput: { required: true } } }); }); function getForm() { if (id > 0) { ys.ajax({ url: '@Url.Content("~/OrganizationManage/Department/GetFormJson")' + '?id=' + id, type: "get", success: function (obj) { if (obj.Tag == 1) { var result = obj.Result; $("#form").setWebControls(result); $('#parentId').ysComboBoxTree("setValue", result.ParentId); $('#principalId').ysComboBoxTree("setValue", result.PrincipalId); } } }); } else { ys.ajax({ url: '@Url.Content("~/OrganizationManage/Department/GetMaxSortJson")', type: "get", success: function (obj) { if (obj.Tag == 1) { $("#departmentSort").val(obj.Result); } } }); } } function saveForm(index) { if ($("#form").validate().form()) { var postData = $("#form").getWebControls({ Id: id }); postData.ParentId = ys.getLastValue(postData.ParentId); postData.PrincipalId = ys.getLastValue(postData.PrincipalId); ys.ajax({ url: '@Url.Content("~/OrganizationManage/Department/SaveFormJson")', type: "post", data: postData, success: function (obj) { if (obj.Tag == 1) { ys.msgSuccess(obj.Message); parent.searchTreeGrid(); parent.layer.close(index); } else { ys.msgError(obj.Message); } } }); } } </script>
19,675
https://github.com/Clay-Ferguson/quantizr/blob/master/src/main/java/quanta/service/LuceneService.java
Github Open Source
Open Source
MIT
2,023
quantizr
Clay-Ferguson
Java
Code
221
561
package quanta.service; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import quanta.config.ServiceBase; import quanta.mongo.MongoSession; import quanta.mongo.model.SubNode; import quanta.response.LuceneIndexResponse; import quanta.response.LuceneSearchResponse; /** * Service for processing Lucene-related functions. */ @Component public class LuceneService extends ServiceBase { private static Logger log = LoggerFactory.getLogger(LuceneService.class); public LuceneIndexResponse reindex(MongoSession ms, String nodeId, String searchFolder) { LuceneIndexResponse res = new LuceneIndexResponse(); String ret = null; SubNode node = read.getNode(ms, nodeId, true, null); if (node != null) { /* * Remember 'searchFolder' will have to be visible to the VM and therefore this might require adding * a new mapping parameter to the startup shell script for docker. Docker can't see the entire * folder structure on the host machine, but can only see what has specifically been shared to it. * * NOTE: We're using the nodeId as the subdirectory in the lucene data folder to keep the index of * this node garanteed to be separate but determined by this node (i.e. unique to this node) */ fileIndexer.index(searchFolder/* "/tmp/search" */, nodeId, "sh,md,txt,pdf,zip,tar,json,gz,tgz,xz", true); ret = fileIndexer.getSummaryReport(); fileIndexer.close(); } res.setMessage(ret); return res; } public LuceneSearchResponse search(MongoSession ms, String nodeId, String searchText) { LuceneSearchResponse res = new LuceneSearchResponse(); String ret = null; // disabled for now. // SubNode node = read.getNode(session, nodeId, true); // if (ok(node )) { // ret = searcher.search(nodeId, searchText); // } res.setMessage(ret); return res; } }
35,822
https://github.com/stephenstengel/361-lab5/blob/master/ShortThrower.cpp
Github Open Source
Open Source
MIT
null
361-lab5
stephenstengel
C++
Code
90
308
/* * Stephen Stengel <stephen.stengel@cwu.edu> 40819903 * * ShortThrower.cpp * * ShortThrower ant. Inherits from Ant * */ #include "ShortThrower.h" #include "GameBoard.h" ShortThrower::ShortThrower() { setType("ShortThrower"); setHealthRemaining(SHORT_THROWER_STARTING_HEALTH); } ShortThrower::~ShortThrower() { } //Damage to bee closest, but no more than 2 squares away. void ShortThrower::attack(GameBoard& gb, int thisIndex) { //NOTE: Converting from int to size_t is fine here, because thisIndex will always be positive or 0! for (size_t i = thisIndex; i < gb.gameSquares.size() && i <= (size_t)(thisIndex + 2); i++) { if ( gb.gameSquares[i]->isThereABeeHere() ) { gb.gameSquares[i]->damageFirstBee(SHORT_THROWER_DAMAGE); break; } } }
12,882
https://github.com/binh-lashic/lashic-care-web/blob/master/fuel/app/com/gmo_pg/client/output/SearchRecurringResultOutput.php
Github Open Source
Open Source
MIT
null
lashic-care-web
binh-lashic
PHP
Code
1,034
4,227
<?php require_once ('com/gmo_pg/client/output/BaseOutput.php'); /** * <b>自動売上自動売上結果照会 出力パラメータクラス</b> * * @package com.gmo_pg.client * @subpackage output * @see outputPackageInfo.php * @author GMO PaymentGateway */ class SearchRecurringResultOutput extends BaseOutput { /** * @var string 課金手段 */ var $method; /** * @var string ショップID */ var $shopID; /** * @var string 自動売上ID */ var $recurringID; /** * @var string オーダーID */ var $orderID; /** * @var string 課金日 */ var $chargeDate; /** * @var string 取引状態 または 振替依頼レコード状態 */ var $status; /** * @var integer 利用金額 */ var $amount; /** * @var integer 税送料 */ var $tax; /** * @var string 次回課金日 */ var $nextChargeDate; /** * @var string アクセスID */ var $accessID; /** * @var string アクセスパスワード */ var $accessPass; /** * @var string 仕向先 */ var $forward; /** * @var string 承認番号 */ var $approvalNo; /** * @var string サイトID */ var $siteID; /** * @var string メンバーID */ var $memberID; /** * @var string 通帳記載内容 */ var $printStr; /** * @var string 振替結果詳細コード */ var $result; /** * @var string 自動売上エラーコード */ var $chargeErrCode; /** * @var string 自動売上エラー詳細コード */ var $chargeErrInfo; /** * @var string 処理日時 */ var $processDate; /** * コンストラクタ * * @param IgnoreCaseMap $params 出力パラメータ */ function SearchRecurringResultOutput($params = null) { $this->__construct($params); } /** * コンストラクタ * * @param IgnoreCaseMap $params 出力パラメータ */ function __construct($params = null) { parent::__construct($params); // 引数が無い場合は戻る if (is_null($params)) { return; } // マップの展開 $this->setMethod($params->get('Method')); $this->setShopID($params->get('ShopID')); $this->setRecurringID($params->get('RecurringID')); $this->setOrderID($params->get('OrderID')); $this->setChargeDate($params->get('ChargeDate')); $this->setStatus($params->get('Status')); $this->setAmount($params->get('Amount')); $this->setTax($params->get('Tax')); $this->setNextChargeDate($params->get('NextChargeDate')); $this->setAccessID($params->get('AccessID')); $this->setAccessPass($params->get('AccessPass')); $this->setForward($params->get('Forward')); $this->setApprovalNo($params->get('ApprovalNo')); $this->setSiteID($params->get('SiteID')); $this->setMemberID($params->get('MemberID')); $this->setPrintStr($params->get('PrintStr')); $this->setResult($params->get('Result')); $this->setChargeErrCode($params->get('ChargeErrCode')); $this->setChargeErrInfo($params->get('ChargeErrInfo')); $this->setProcessDate($params->get('ProcessDate')); } /** * 課金手段取得 * @return string 課金手段 */ function getMethod() { return $this->method; } /** * ショップID取得 * @return string ショップID */ function getShopID() { return $this->shopID; } /** * 自動売上ID取得 * @return string 自動売上ID */ function getRecurringID() { return $this->recurringID; } /** * オーダーID取得 * @return string オーダーID */ function getOrderID() { return $this->orderID; } /** * 課金日取得 * @return string 課金日 */ function getChargeDate() { return $this->chargeDate; } /** * 取引状態 または 振替依頼レコード状態取得 * @return string 取引状態 または 振替依頼レコード状態 */ function getStatus() { return $this->status; } /** * 利用金額取得 * @return integer 利用金額 */ function getAmount() { return $this->amount; } /** * 税送料取得 * @return integer 税送料 */ function getTax() { return $this->tax; } /** * 次回課金日取得 * @return string 次回課金日 */ function getNextChargeDate() { return $this->nextChargeDate; } /** * アクセスID取得 * @return string アクセスID */ function getAccessID() { return $this->accessID; } /** * アクセスパスワード取得 * @return string アクセスパスワード */ function getAccessPass() { return $this->accessPass; } /** * 仕向先取得 * @return string 仕向先 */ function getForward() { return $this->forward; } /** * 承認番号取得 * @return string 承認番号 */ function getApprovalNo() { return $this->approvalNo; } /** * サイトID取得 * @return string サイトID */ function getSiteID() { return $this->siteID; } /** * メンバーID取得 * @return string メンバーID */ function getMemberID() { return $this->memberID; } /** * 通帳記載内容取得 * @return string 通帳記載内容 */ function getPrintStr() { return $this->printStr; } /** * 振替結果詳細コード取得 * @return string 振替結果詳細コード */ function getResult() { return $this->result; } /** * 自動売上エラーコード取得 * @return string 自動売上エラーコード */ function getChargeErrCode() { return $this->chargeErrCode; } /** * 自動売上エラー詳細コード取得 * @return string 自動売上エラー詳細コード */ function getChargeErrInfo() { return $this->chargeErrInfo; } /** * 処理日時取得 * @return string 処理日時 */ function getProcessDate() { return $this->processDate; } /** * 課金手段設定 * * @param string $method */ function setMethod($method) { $this->method = $method; } /** * ショップID設定 * * @param string $shopID */ function setShopID($shopID) { $this->shopID = $shopID; } /** * 自動売上ID設定 * * @param string $recurringID */ function setRecurringID($recurringID) { $this->recurringID = $recurringID; } /** * オーダーID設定 * * @param string $orderID */ function setOrderID($orderID) { $this->orderID = $orderID; } /** * 課金日設定 * * @param string $chargeDate */ function setChargeDate($chargeDate) { $this->chargeDate = $chargeDate; } /** * 取引状態 または 振替依頼レコード状態設定 * * @param string $status */ function setStatus($status) { $this->status = $status; } /** * 利用金額設定 * * @param integer $amount */ function setAmount($amount) { $this->amount = $amount; } /** * 税送料設定 * * @param integer $tax */ function setTax($tax) { $this->tax = $tax; } /** * 次回課金日設定 * * @param string $nextChargeDate */ function setNextChargeDate($nextChargeDate) { $this->nextChargeDate = $nextChargeDate; } /** * アクセスID設定 * * @param string $accessID */ function setAccessID($accessID) { $this->accessID = $accessID; } /** * アクセスパスワード設定 * * @param string $accessPass */ function setAccessPass($accessPass) { $this->accessPass = $accessPass; } /** * 仕向先設定 * * @param string $forward */ function setForward($forward) { $this->forward = $forward; } /** * 承認番号設定 * * @param string $approvalNo */ function setApprovalNo($approvalNo) { $this->approvalNo = $approvalNo; } /** * サイトID設定 * * @param string $siteID */ function setSiteID($siteID) { $this->siteID = $siteID; } /** * メンバーID設定 * * @param string $memberID */ function setMemberID($memberID) { $this->memberID = $memberID; } /** * 通帳記載内容設定 * * @param string $printStr */ function setPrintStr($printStr) { $this->printStr = $printStr; } /** * 振替結果詳細コード設定 * * @param string $result */ function setResult($result) { $this->result = $result; } /** * 自動売上エラーコード設定 * * @param string $chargeErrCode */ function setChargeErrCode($chargeErrCode) { $this->chargeErrCode = $chargeErrCode; } /** * 自動売上エラー詳細コード設定 * * @param string $chargeErrInfo */ function setChargeErrInfo($chargeErrInfo) { $this->chargeErrInfo = $chargeErrInfo; } /** * 処理日時設定 * * @param string $processDate */ function setProcessDate($processDate) { $this->processDate = $processDate; } /** * 文字列表現 * <p> * 現在の各パラメータを、パラメータ名=値&パラメータ名=値の形式で取得します。 * </p> * @return string 出力パラメータの文字列表現 */ function toString() { $str =''; $str .= 'Method=' . $this->encodeStr($this->getMethod()); $str .='&'; $str .= 'ShopID=' . $this->encodeStr($this->getShopID()); $str .='&'; $str .= 'RecurringID=' . $this->encodeStr($this->getRecurringID()); $str .='&'; $str .= 'OrderID=' . $this->encodeStr($this->getOrderID()); $str .='&'; $str .= 'ChargeDate=' . $this->encodeStr($this->getChargeDate()); $str .='&'; $str .= 'Status=' . $this->encodeStr($this->getStatus()); $str .='&'; $str .= 'Amount=' . $this->encodeStr($this->getAmount()); $str .='&'; $str .= 'Tax=' . $this->encodeStr($this->getTax()); $str .='&'; $str .= 'NextChargeDate=' . $this->encodeStr($this->getNextChargeDate()); $str .='&'; $str .= 'AccessID=' . $this->encodeStr($this->getAccessID()); $str .='&'; $str .= 'AccessPass=' . $this->encodeStr($this->getAccessPass()); $str .='&'; $str .= 'Forward=' . $this->encodeStr($this->getForward()); $str .='&'; $str .= 'ApprovalNo=' . $this->encodeStr($this->getApprovalNo()); $str .='&'; $str .= 'SiteID=' . $this->encodeStr($this->getSiteID()); $str .='&'; $str .= 'MemberID=' . $this->encodeStr($this->getMemberID()); $str .='&'; $str .= 'PrintStr=' . $this->encodeStr($this->getPrintStr()); $str .='&'; $str .= 'Result=' . $this->encodeStr($this->getResult()); $str .='&'; $str .= 'ChargeErrCode=' . $this->encodeStr($this->getChargeErrCode()); $str .='&'; $str .= 'ChargeErrInfo=' . $this->encodeStr($this->getChargeErrInfo()); $str .='&'; $str .= 'ProcessDate=' . $this->encodeStr($this->getProcessDate()); if ($this->isErrorOccurred()) { // エラー文字列を連結して返す $errString = parent::toString(); $str .= '&' . $errString; } return $str; } } ?>
22,021
https://github.com/nethkenn/ultraproactive/blob/master/app/Http/Controllers/AdminFaqController.php
Github Open Source
Open Source
MIT
null
ultraproactive
nethkenn
PHP
Code
193
1,048
<?php namespace App\Http\Controllers; use DB; use Redirect; use Request; use App\Classes\Image; use App\Classes\Admin; use App\Classes\Log; class AdminFaqController extends AdminController { public function index() { $data["category"] = Request::input("type"); $data["_product"] = DB::table("tbl_faq")->where("faq_type", "product")->where("archived", 0)->get(); $data["_mindsync"] = DB::table("tbl_faq")->where("faq_type", "mindsync")->where("archived", 0)->get(); $data["_opportunity"] = DB::table("tbl_faq")->where("faq_type", "opportunity")->where("archived", 0)->get(); $data["_glossary"] = DB::table("tbl_faq")->where("faq_type", "glossary")->where("archived", 0)->get(); Log::Admin(Admin::info()->account_id,Admin::info()->account_username." visits the FAQ ".Request::input("type")); return view('admin.content.faq', $data); } public function add() { $data["category"] = Request::input("type"); $title = Request::input("title"); $content = Request::input("content"); if (isset($title) && isset($content)) { $id = DB::table("tbl_faq")->insertGetId(['faq_title' => $title, 'faq_content' => $content, 'faq_type' => $data["category"]]); $new = DB::table('tbl_faq')->where('faq_id',$id)->first(); Log::Admin(Admin::info()->account_id,Admin::info()->account_username." Add an FAQ to the ".$data['category'],null,serialize($new)); return Redirect::to("/admin/content/faq?type=".$data["category"]); } else { return view('admin.content.faq_add', $data); } } public function edit() { $data["category"] = Request::input("type"); $id = Request::input("id"); $data["edit"] = DB::table("tbl_faq")->where("faq_id", $id)->first(); $title = Request::input("title"); $content = Request::input("content"); if (isset($title) && isset($content)) { $old = DB::table('tbl_faq')->where('faq_id',$id)->first(); DB::table("tbl_faq")->where("faq_id", $id)->update(['faq_title' => $title, 'faq_content' => $content]); $new = DB::table('tbl_faq')->where('faq_id',$id)->first(); Log::Admin(Admin::info()->account_id,Admin::info()->account_username." Add an FAQ to the ".$data['category'],serialize($old),serialize($new)); return Redirect::to("/admin/content/faq?type=".$data["category"]); } else { Log::Admin(Admin::info()->account_id,Admin::info()->account_username." visits the Edit FAQ ".Request::input("type")." id #".$id); return view('admin.content.faq_edit', $data); } } public function delete() { $id = Request::input("id"); $type = Request::input("type"); Log::Admin(Admin::info()->account_id,Admin::info()->account_username." archive the FAQ ".Request::input("type")." id #".$id); DB::table("tbl_faq")->where("faq_id", $id)->update(['archived' => 1]); return Redirect::to("/admin/content/faq?type=".$type); } }
27,596
https://github.com/Dhruv-Sachdev1313/macports-webapp/blob/master/app/port/migrations/0006_port_subscribers.py
Github Open Source
Open Source
BSD-2-Clause
2,022
macports-webapp
Dhruv-Sachdev1313
Python
Code
40
174
# Generated by Django 2.2.10 on 2020-07-10 12:49 from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('port', '0005_auto_20200625_1819'), ] operations = [ migrations.AddField( model_name='port', name='subscribers', field=models.ManyToManyField(related_name='ports', to=settings.AUTH_USER_MODEL, verbose_name='Subscribers of the port'), ), ]
2,189
https://github.com/LaudateCorpus1/smart-test-framework/blob/master/stf-desktop-automation-lib/src/main/java/com/github/jeansantos38/stf/framework/ui/UiAutomationHelper.java
Github Open Source
Open Source
MIT
2,020
smart-test-framework
LaudateCorpus1
Java
Code
1,381
4,559
package com.github.jeansantos38.stf.framework.ui; import com.github.jeansantos38.stf.enums.UiMouseButton; import com.github.jeansantos38.stf.framework.io.InputOutputHelper; import com.github.jeansantos38.stf.framework.misc.CalendarHelper; import com.github.jeansantos38.stf.framework.misc.RandomValuesHelper; import com.google.common.base.Stopwatch; import org.sikuli.basics.Settings; import org.sikuli.script.*; import java.io.IOException; import java.util.concurrent.TimeUnit; /************************************************************ * © Copyright 2019 HP Development Company, L.P. * SPDX-License-Identifier: MIT * * Smart Test Framework ************************************************************/ public class UiAutomationHelper { private final String SINGLE_DOUBLE_CLICK_LOG = "[#action: %1$s],[#on: %2$s],[#at: %3$s],[#similatiry: %4$s]"; private final String WAIT_EXISTS_LOG = "[#action: %1$s],[#on: %2$s],[#similatiry: %3$s],[#will wait: %4$s seconds]"; private final String FIND_LOG = "[#action: %1$s],[#on: %2$s],[#similatiry: %3$s]"; private final String DRAG_AND_DROP_LOG = "[#action: %1$s],[#Source: %2$s],[#Destination: %3$s]"; protected void click(UiElement uiElement) throws Exception { click(uiElement, UiMouseButton.LEFT); } protected void rightClick(UiElement uiElement) throws Exception { click(uiElement, UiMouseButton.RIGHT); } protected void middleClick(UiElement uiElement) throws Exception { actionClick(uiElement, UiMouseButton.MIDDLE, 1); } protected void paste(UiElement uiElement, String content) { UiAutomationUtils.paste(!uiElement.isVncScreen() ? uiElement.getScreen() : uiElement.getVncScreen(), content); } protected void dragAndDrop(UiElement target, UiElement destination) throws FindFailed { if (!target.isVncScreen()) { target.getScreen().dragDrop(target.getMatch(), destination.getMatch()); } else { target.getVncScreen().dragDrop(target.getMatch(), destination.getMatch()); } } protected void type(UiElement uiElement, String content) throws InterruptedException, FindFailed { UiAutomationUtils.type(!uiElement.isVncScreen() ? uiElement.getScreen() : uiElement.getVncScreen(), content); } protected void performKeyCombination(UiElement uiElement, String key, int... modifiers) throws InterruptedException { UiAutomationUtils.performKeyCombination(!uiElement.isVncScreen() ? uiElement.getScreen() : uiElement.getVncScreen(), key, modifiers); } protected void moveCursorOver(UiElement uiElement) throws Exception { find(uiElement); if (!uiElement.isVncScreen()) { uiElement.getScreen().hover(uiElement.getMatch()); } else { uiElement.getVncScreen().hover(uiElement.getMatch()); } } protected void doubleClickRegion(UiElement uiElement, Region region) throws FindFailed { region.doubleClick(createPattern(uiElement)); } protected void doubleClick(UiElement uiElement) throws Exception { find(uiElement); if (!uiElement.isVncScreen()) { uiElement.getScreen().doubleClick(uiElement.getMatch()); } else { uiElement.getVncScreen().doubleClick(uiElement.getMatch()); } uiElement.getWaitHelper().waitMilliseconds(uiElement.getMsDelayBetweenClicks()); } protected boolean exists(UiElement uiElement) throws Exception { return exists(uiElement, 0); } /*** * Helper that checks if an image does exist. * @param timeoutMs: How long will keep trying before given up from this operation. * @return */ protected boolean exists(UiElement uiElement, int timeoutMs, boolean screenCaptureIfFound) throws IOException, FindFailed { return superExists(false, null, uiElement, screenCaptureIfFound, timeoutMs); } protected boolean exists(UiElement uiElement, int timeoutMs) throws IOException, FindFailed { return superExists(false, null, uiElement, false, timeoutMs); } /*** * Helper that takes a screenshot from a given region. * @param region: A screen region. * @return * @throws IOException */ protected String saveScreenshotFromRegion(UiElement uiElement, Region region) throws IOException { return saveScreenshotFromRegion(region, uiElement.getFolderPathToSaveScreenshots(), String.format("%s_%s", RandomValuesHelper.generateAlphabetic(10), CalendarHelper.getCurrentTimeAndDate())); } /*** * Helper that takes a screenshot from a given region. * @param region: A screen region. * @param path: Folder where it should be save. * @param filename: The screenshot filename. * @return * @throws IOException */ protected String saveScreenshotFromRegion(Region region, String path, String filename) throws IOException { InputOutputHelper.createDirectory(path); region.getImage().save(filename + ".png", path); return String.format("%s/%s", path, filename); } protected void waitVanishes(UiElement uiElement, double timeoutSec, boolean abortOnAssertionFailure) throws Exception { Pattern pattern = createPattern(uiElement); boolean vanished = !uiElement.isVncScreen() ? uiElement.getScreen().waitVanish(pattern, timeoutSec) : uiElement.getVncScreen().waitVanish(pattern, timeoutSec); if (abortOnAssertionFailure && !vanished) { highlight(uiElement, pattern); throw new Exception("The pattern did not vanished!"); } } protected void waitExists(UiElement uiElement, double timeoutSec, boolean abortOnAssertionFailure) throws Exception { Pattern pattern = createPattern(uiElement); try { if (!uiElement.isVncScreen()) { uiElement.getScreen().wait(pattern, timeoutSec); } else { uiElement.getVncScreen().wait(pattern, timeoutSec); } highlight(uiElement, pattern); } catch (Exception e) { if (abortOnAssertionFailure) throw e; } } protected Region createRegionFromReferencePattern(UiElement uiElement) throws Exception { Match patternMatch = find(uiElement); int recH = uiElement.getDetails().regionBottomRightY - uiElement.getDetails().regionTopLeftY; int recW = uiElement.getDetails().regionBottomRightX - uiElement.getDetails().regionTopLeftX; int finalX = patternMatch.x + ((patternMatch.w / 2) + uiElement.getDetails().regionTopLeftX); int finalY = patternMatch.y + ((patternMatch.h / 2) + uiElement.getDetails().regionTopLeftY); Region region = new Region(finalX, finalY, recW, recH); highlight(uiElement, region); return region; } protected String extractTextFromRegionViaOCR(UiElement uiElement) throws Exception { Settings.OcrTextRead = true; Settings.OcrTextSearch = true; Region region = createRegionFromReferencePattern(uiElement); return region.text(); } protected boolean referenceAreaHasPattern(UiElement reference, UiElement expectedPattern) throws Exception { Region region = createRegionFromReferencePattern(reference); return superExists(true, region, expectedPattern, reference.takeScreenshotWhenFail(), 0); } protected Match find(UiElement uiElement) throws Exception { return find(uiElement, null); } protected Match find(UiElement uiElement, Pattern pattern) throws Exception { Pattern tempPattern = pattern == null ? createPattern(uiElement) : pattern; try { if (uiElement.getMatch() == null) { uiElement.setMatch(!uiElement.isVncScreen() ? uiElement.getScreen().find(tempPattern) : uiElement.getVncScreen().find(tempPattern)); } highlight(uiElement, uiElement.getMatch()); return uiElement.getMatch(); } catch (Exception e) { if (uiElement.takeScreenshotWhenFail()) { uiElement.getTestLog().logIt(String.format("The pattern was not found! ###The expected master is:[%1$s] ### It was not found at: [%2$s]", tempPattern.getFilename(), UiAutomationUtils.saveDesktopScreenshot(!uiElement.isVncScreen() ? uiElement.getScreen() : uiElement.getVncScreen(), uiElement.getFolderPathToSaveScreenshots()))); } throw new Exception(e); } } protected void scrollUp(UiElement uiElement, int steps) throws FindFailed { scroll(uiElement, true, steps, 0); } protected void scrollUp(UiElement uiElement, int steps, int msDelay) throws FindFailed { scroll(uiElement, true, steps, msDelay); } protected void scrollDown(UiElement uiElement, int steps) throws FindFailed { scroll(uiElement, false, steps, 0); } protected void scrollDown(UiElement uiElement, int steps, int msDelay) throws FindFailed { scroll(uiElement, false, steps, msDelay); } protected void actionClick(UiElement uiElement, UiMouseButton uiMouseButton, int howManyClicks) throws Exception { int tempBtn; switch (uiMouseButton) { case RIGHT: tempBtn = Button.RIGHT; break; case LEFT: tempBtn = Button.LEFT; break; case MIDDLE: tempBtn = Button.MIDDLE; break; default: throw new Exception("This method only support clickable mouse buttons!"); } for (int i = 0; i < howManyClicks; i++) { if (!uiElement.isVncScreen()) { uiElement.getScreen().mouseDown(tempBtn); uiElement.getWaitHelper().waitMilliseconds(uiElement.getMsDelayBetweenActions()); uiElement.getScreen().mouseUp(tempBtn); } else { uiElement.getVncScreen().mouseDown(tempBtn); uiElement.getWaitHelper().waitMilliseconds(uiElement.getMsDelayBetweenActions()); uiElement.getVncScreen().mouseUp(tempBtn); } uiElement.getWaitHelper().waitMilliseconds(uiElement.getMsDelayBetweenClicks()); } } private void scroll(UiElement uiElement, boolean upDirection, int steps, int msDelay) throws FindFailed { if (!uiElement.isVncScreen()) { uiElement.getScreen().wheel(upDirection ? Button.WHEEL_UP : Button.WHEEL_DOWN, steps, msDelay); } else { uiElement.getVncScreen().wheel(upDirection ? Button.WHEEL_UP : Button.WHEEL_DOWN, steps, msDelay); } } private void click(UiElement uiElement, UiMouseButton uiMouseButton) throws Exception { find(uiElement); if (!uiElement.isVncScreen()) { switch (uiMouseButton) { case LEFT: uiElement.getScreen().click(uiElement.getMatch()); break; case RIGHT: uiElement.getScreen().rightClick(uiElement.getMatch()); break; default: throw new Exception("This method only supports Left and Right buttons"); } } else { switch (uiMouseButton) { case LEFT: uiElement.getVncScreen().click(uiElement.getMatch()); break; case RIGHT: uiElement.getVncScreen().rightClick(uiElement.getMatch()); break; default: throw new Exception("This method only supports Left and Right buttons"); } } uiElement.getWaitHelper().waitMilliseconds(uiElement.getMsDelayBetweenClicks()); } private void highlight(UiElement uiElement, Pattern pattern) throws Exception { highlight(uiElement, find(uiElement, pattern)); } private void highlight(UiElement uiElement, Region region) { UiVisualFeedback visualFeedback = uiElement.getUiVisualFeedback(); if (visualFeedback != null && visualFeedback.enableHighlight && !uiElement.isVncScreen()) { region.highlight(visualFeedback.highlightTimeSec, visualFeedback.areaHighlightColor); } else { uiElement.getTestLog().logIt("Nothing to highlight here!"); } } private void highlight(UiElement uiElement, Match match) { UiVisualFeedback visualFeedback = uiElement.getUiVisualFeedback(); if (visualFeedback != null && visualFeedback.enableHighlight && !uiElement.isVncScreen()) { match.highlight(visualFeedback.highlightTimeSec, visualFeedback.masterHighlightColor); if (uiElement.getDetails().xCoordinate != 0 || uiElement.getDetails().yCoordinate != 0) { new Region(match.getCenter().x + uiElement.getDetails().xCoordinate, match.getCenter().y + uiElement.getDetails().yCoordinate, visualFeedback.relHighlightW, visualFeedback.relHighlightH) .highlight(visualFeedback.highlightTimeSec, visualFeedback.coordinateHighlightColor); } } else { uiElement.getTestLog().logIt("Nothing to highlight here!"); } } private boolean superExists(boolean isForRegion, Region region, UiElement uiElement, boolean screenCaptureIfFound, double timeoutSec) throws IOException { Pattern pattern = createPattern(uiElement); Match match = null; Stopwatch stopwatch = Stopwatch.createStarted(); while (stopwatch.elapsed(TimeUnit.MILLISECONDS) <= timeoutSec) { try { /* If you're thinking "Why the heck we're using find here instead exists?!" Well - I've some bad news for you - or not. The exists method is not reliable. It fails often on MAC and Windows. After some research I've found that there's a defect for that in the LIB repo (at the date of this sentence first commit). So as workaround I'm using the FIND, but making it behave as Exists. It might not be the right thing to do, but the world is cruel sometimes. This way it simple works - it's reliable. That's it. */ if (isForRegion) { match = region.find(pattern); } else { match = find(uiElement); } break; } catch (Exception e) { uiElement.getTestLog().logIt(e.getMessage()); } } boolean wasFound = false; /* You might be asking why we've this insanity here. The truth is quite simple. Sometimes this lib is capable of evaluating the given pattern inside a region and return a percentage below 1, meaning that we don't have a match. In other occasions it simply returns null because was not able to find it at all. Both results have the same meaning - THERE'S NO MATCH. Any complains about it please go ask for MIT that has developed it. Thanks! */ if (match != null) { double current = match.getScore(); wasFound = evaluateScore(uiElement, current); } if (uiElement.takeScreenshotWhenFail() && !wasFound) { uiElement.getTestLog().logIt( String.format("The expected image [%s] was not found, instead found [%s]", pattern.getFilename(), isForRegion ? saveScreenshotFromRegion(uiElement, region) : UiAutomationUtils.saveDesktopScreenshot( uiElement.isVncScreen() ? uiElement.getVncScreen() : uiElement.getScreen(), uiElement.getFolderPathToSaveScreenshots()))); } else if (screenCaptureIfFound && wasFound) { uiElement.getTestLog().logIt( String.format("The expected image [%s] was found, see it on captured screenshot [%s]", pattern.getFilename(), isForRegion ? saveScreenshotFromRegion(uiElement, region) : UiAutomationUtils.saveDesktopScreenshot( uiElement.isVncScreen() ? uiElement.getVncScreen() : uiElement.getScreen(), uiElement.getFolderPathToSaveScreenshots()))); } return wasFound; } /*** * Simple helper that evaluates the min score required to consider a match successful. * @param currentScore: The score found on a match pattern. * @return */ private boolean evaluateScore(UiElement uiElement, double currentScore) { uiElement.getTestLog().logIt(String.format("###Image Recognition match evaluation:[#Found pattern score:%1$s][#Minimum acceptance score:%2$s]", String.valueOf(currentScore), String.valueOf(uiElement.getDetails().similarity))); return (currentScore >= uiElement.getDetails().similarity); } private Pattern createPattern(UiElement uiElement) { Pattern pattern = new Pattern(uiElement.getDetails().imagePath); pattern.similar(uiElement.getDetails().similarity); pattern.targetOffset(uiElement.getDetails().xCoordinate, uiElement.getDetails().yCoordinate); return pattern; } }
41,306
https://github.com/alisw/AliPhysics/blob/master/PWGDQ/dielectron/macrosLMEE/ConfigRemiLMEEPbPb2011AOD.C
Github Open Source
Open Source
2,023
AliPhysics
alisw
C
Code
1,980
14,833
//#include "PWGDQ/dielectron/macrosLMEE/LMEECutLib.C" void InitHistograms(AliDielectron *die, Int_t cutDefinition); void InitCF(AliDielectron* die, Int_t cutDefinition); void EnableMC(); TString names=("noPairing;ITSTPCTOFCentnoRej;ITSTPCTOFSemiCent1noRej;ITSTPCTOFSemiCent2noRej;ITSTPCTOFPerinoRej;ITSTPCTOFCentInvMLowRP;ITSTPCTOFSemiCent1InvMLowRP;ITSTPCTOFSemiCent2InvMLowRP;ITSTPCTOFPeriInvMLowRP;ITSTPCTOFCentInvMMiddleRP;ITSTPCTOFSemiCent1InvMMiddleRP;ITSTPCTOFSemiCent2InvMMiddleRP;ITSTPCTOFPeriInvMMiddleRP;ITSTPCTOFCentInvMHighRP;ITSTPCTOFSemiCent1InvMHighRP;ITSTPCTOFSemiCent2InvMHighRP;ITSTPCTOFPeriInvMHighRP;ITSTPCTOFCentInvMLowMag;ITSTPCTOFSemiCent1InvMLowMag;ITSTPCTOFSemiCent2InvMLowMag;ITSTPCTOFPeriInvMLowMag;ITSTPCTOFCentInvMMiddleMag;ITSTPCTOFSemiCent1InvMMiddleMag;ITSTPCTOFSemiCent2InvMMiddleMag;ITSTPCTOFPeriInvMMiddleMag;ITSTPCTOFCentInvMHighMag;ITSTPCTOFSemiCent1InvMHighMag;ITSTPCTOFSemiCent2InvMHighMag;ITSTPCTOFPeriInvMHighMag"); TObjArray *arrNames=names.Tokenize(";"); const Int_t nDie=arrNames->GetEntries(); Bool_t MCenabled=kFALSE; AliDielectron* ConfigRemiLMEEPbPb2011AOD(Int_t cutDefinition, Bool_t hasMC=kFALSE, Bool_t ESDanalysis=kFALSE) { Int_t selectedPID=-1; Int_t selectedCentrality=-1; Int_t selectedPairInvMassCut=-1; Int_t selectedPairInOutCut = -1; Bool_t rejectionStep=kFALSE; Bool_t PairInvMassCut=kFALSE; Bool_t PairInOutCut=kFALSE; LMEECutLibRemi* LMCL = new LMEECutLibRemi(); // // Setup the instance of AliDielectron // MCenabled=hasMC; // create the actual framework object TString name=Form("%02d",cutDefinition); if ((cutDefinition)<arrNames->GetEntriesFast()){ name=arrNames->At((cutDefinition))->GetName(); } //thisCut only relevant for MC: AliDielectron *die = new AliDielectron(Form ("%s",name.Data()), Form("Track cuts: %s",name.Data())); // TString ZDCRecenteringfile = "alien:///alice/cern.ch/user/r/rtanizak/ZDCrpH1/ZDCRecentProf/ZDCRecenteringProfile.root"; TString ZDCRecenteringfile = "/home/tanizaki/nfs/ZDCrpH1Recentering/ZDCRecenteringProfile.root"; die->SetZDCRecenteringFilename(ZDCRecenteringfile); //Setup AnalysisSelection: if (cutDefinition==0) { //not yet implemented } else if (cutDefinition==1) { selectedPID = LMEECutLibRemi::kPbPb2011pidITSTPCTOF; selectedCentrality = LMEECutLibRemi::kPbPb2011Central; rejectionStep = kFALSE; PairInvMassCut = kFALSE; } else if (cutDefinition==2) { selectedPID = LMEECutLibRemi::kPbPb2011pidITSTPCTOF; selectedCentrality = LMEECutLibRemi::kPbPb2011SemiCentral1; rejectionStep = kFALSE; PairInvMassCut = kFALSE; } else if (cutDefinition==3) { selectedPID = LMEECutLibRemi::kPbPb2011pidITSTPCTOF; selectedCentrality = LMEECutLibRemi::kPbPb2011SemiCentral2; rejectionStep = kFALSE; PairInvMassCut = kFALSE; } else if (cutDefinition==4) { selectedPID = LMEECutLibRemi::kPbPb2011pidITSTPCTOF; selectedCentrality = LMEECutLibRemi::kPbPb2011Peripheral; rejectionStep = kFALSE; PairInvMassCut = kFALSE; } ////////////////////////////////////////////////////////// else if (cutDefinition==5) { selectedPID = LMEECutLibRemi::kPbPb2011pidITSTPCTOF; selectedCentrality = LMEECutLibRemi::kPbPb2011Central; selectedPairInvMassCut = LMEECutLibRemi::kPbPb2011MassLow; selectedPairInOutCut = LMEECutLibRemi::kPbPb2011RP; rejectionStep = kFALSE; PairInvMassCut = kTRUE; PairInOutCut = kTRUE; } else if (cutDefinition==6) { selectedPID = LMEECutLibRemi::kPbPb2011pidITSTPCTOF; selectedCentrality = LMEECutLibRemi::kPbPb2011SemiCentral1; selectedPairInvMassCut = LMEECutLibRemi::kPbPb2011MassLow; selectedPairInOutCut = LMEECutLibRemi::kPbPb2011RP; rejectionStep = kFALSE; PairInvMassCut = kTRUE; PairInOutCut = kTRUE; } else if (cutDefinition==7) { selectedPID = LMEECutLibRemi::kPbPb2011pidITSTPCTOF; selectedCentrality = LMEECutLibRemi::kPbPb2011SemiCentral2; selectedPairInvMassCut = LMEECutLibRemi::kPbPb2011MassLow; selectedPairInOutCut = LMEECutLibRemi::kPbPb2011RP; rejectionStep = kFALSE; PairInvMassCut = kTRUE; PairInOutCut = kTRUE; } else if (cutDefinition==8) { selectedPID = LMEECutLibRemi::kPbPb2011pidITSTPCTOF; selectedCentrality = LMEECutLibRemi::kPbPb2011Peripheral; selectedPairInvMassCut = LMEECutLibRemi::kPbPb2011MassLow; selectedPairInOutCut = LMEECutLibRemi::kPbPb2011RP; rejectionStep = kFALSE; PairInvMassCut = kTRUE; PairInOutCut = kTRUE; } else if (cutDefinition==9) { selectedPID = LMEECutLibRemi::kPbPb2011pidITSTPCTOF; selectedCentrality = LMEECutLibRemi::kPbPb2011Central; selectedPairInvMassCut = LMEECutLibRemi::kPbPb2011MassMiddle; selectedPairInOutCut = LMEECutLibRemi::kPbPb2011RP; rejectionStep = kFALSE; PairInvMassCut = kTRUE; PairInOutCut = kTRUE; } else if (cutDefinition==10) { selectedPID = LMEECutLibRemi::kPbPb2011pidITSTPCTOF; selectedCentrality = LMEECutLibRemi::kPbPb2011SemiCentral1; selectedPairInvMassCut = LMEECutLibRemi::kPbPb2011MassMiddle; selectedPairInOutCut = LMEECutLibRemi::kPbPb2011RP; rejectionStep = kFALSE; PairInvMassCut = kTRUE; PairInOutCut = kTRUE; } else if (cutDefinition==11) { selectedPID = LMEECutLibRemi::kPbPb2011pidITSTPCTOF; selectedCentrality = LMEECutLibRemi::kPbPb2011SemiCentral2; selectedPairInvMassCut = LMEECutLibRemi::kPbPb2011MassMiddle; selectedPairInOutCut = LMEECutLibRemi::kPbPb2011RP; rejectionStep = kFALSE; PairInvMassCut = kTRUE; PairInOutCut = kTRUE; } else if (cutDefinition==12) { selectedPID = LMEECutLibRemi::kPbPb2011pidITSTPCTOF; selectedCentrality = LMEECutLibRemi::kPbPb2011Peripheral; selectedPairInvMassCut = LMEECutLibRemi::kPbPb2011MassMiddle; selectedPairInOutCut = LMEECutLibRemi::kPbPb2011RP; rejectionStep = kFALSE; PairInvMassCut = kTRUE; PairInOutCut = kTRUE; } else if (cutDefinition==13) { selectedPID = LMEECutLibRemi::kPbPb2011pidITSTPCTOF; selectedCentrality = LMEECutLibRemi::kPbPb2011Central; selectedPairInvMassCut = LMEECutLibRemi::kPbPb2011MassHigh; selectedPairInOutCut = LMEECutLibRemi::kPbPb2011RP; rejectionStep = kFALSE; PairInvMassCut = kTRUE; PairInOutCut = kTRUE; } else if (cutDefinition==14) { selectedPID = LMEECutLibRemi::kPbPb2011pidITSTPCTOF; selectedCentrality = LMEECutLibRemi::kPbPb2011SemiCentral1; selectedPairInvMassCut = LMEECutLibRemi::kPbPb2011MassHigh; selectedPairInOutCut = LMEECutLibRemi::kPbPb2011RP; rejectionStep = kFALSE; PairInvMassCut = kTRUE; PairInOutCut = kTRUE; } else if (cutDefinition==15) { selectedPID = LMEECutLibRemi::kPbPb2011pidITSTPCTOF; selectedCentrality = LMEECutLibRemi::kPbPb2011SemiCentral2; selectedPairInvMassCut = LMEECutLibRemi::kPbPb2011MassHigh; selectedPairInOutCut = LMEECutLibRemi::kPbPb2011RP; rejectionStep = kFALSE; PairInvMassCut = kTRUE; PairInOutCut = kTRUE; } else if (cutDefinition==16) { selectedPID = LMEECutLibRemi::kPbPb2011pidITSTPCTOF; selectedCentrality = LMEECutLibRemi::kPbPb2011Peripheral; selectedPairInvMassCut = LMEECutLibRemi::kPbPb2011MassHigh; selectedPairInOutCut = LMEECutLibRemi::kPbPb2011RP; rejectionStep = kFALSE; PairInvMassCut = kTRUE; PairInOutCut = kTRUE; } ////////////////////////////////////////////////////////// else if (cutDefinition==17) { selectedPID = LMEECutLibRemi::kPbPb2011pidITSTPCTOF; selectedCentrality = LMEECutLibRemi::kPbPb2011Central; selectedPairInvMassCut = LMEECutLibRemi::kPbPb2011MassLow; selectedPairInOutCut = LMEECutLibRemi::kPbPb2011Mag; rejectionStep = kFALSE; PairInvMassCut = kTRUE; PairInOutCut = kTRUE; } else if (cutDefinition==18) { selectedPID = LMEECutLibRemi::kPbPb2011pidITSTPCTOF; selectedCentrality = LMEECutLibRemi::kPbPb2011SemiCentral1; selectedPairInvMassCut = LMEECutLibRemi::kPbPb2011MassLow; selectedPairInOutCut = LMEECutLibRemi::kPbPb2011Mag; rejectionStep = kFALSE; PairInvMassCut = kTRUE; PairInOutCut = kTRUE; } else if (cutDefinition==19) { selectedPID = LMEECutLibRemi::kPbPb2011pidITSTPCTOF; selectedCentrality = LMEECutLibRemi::kPbPb2011SemiCentral2; selectedPairInvMassCut = LMEECutLibRemi::kPbPb2011MassLow; selectedPairInOutCut = LMEECutLibRemi::kPbPb2011Mag; rejectionStep = kFALSE; PairInvMassCut = kTRUE; PairInOutCut = kTRUE; } else if (cutDefinition==20) { selectedPID = LMEECutLibRemi::kPbPb2011pidITSTPCTOF; selectedCentrality = LMEECutLibRemi::kPbPb2011Peripheral; selectedPairInvMassCut = LMEECutLibRemi::kPbPb2011MassLow; selectedPairInOutCut = LMEECutLibRemi::kPbPb2011Mag; rejectionStep = kFALSE; PairInvMassCut = kTRUE; PairInOutCut = kTRUE; } else if (cutDefinition==21) { selectedPID = LMEECutLibRemi::kPbPb2011pidITSTPCTOF; selectedCentrality = LMEECutLibRemi::kPbPb2011Central; selectedPairInvMassCut = LMEECutLibRemi::kPbPb2011MassMiddle; selectedPairInOutCut = LMEECutLibRemi::kPbPb2011Mag; rejectionStep = kFALSE; PairInvMassCut = kTRUE; PairInOutCut = kTRUE; } else if (cutDefinition==22) { selectedPID = LMEECutLibRemi::kPbPb2011pidITSTPCTOF; selectedCentrality = LMEECutLibRemi::kPbPb2011SemiCentral1; selectedPairInvMassCut = LMEECutLibRemi::kPbPb2011MassMiddle; selectedPairInOutCut = LMEECutLibRemi::kPbPb2011Mag; rejectionStep = kFALSE; PairInvMassCut = kTRUE; PairInOutCut = kTRUE; } else if (cutDefinition==23) { selectedPID = LMEECutLibRemi::kPbPb2011pidITSTPCTOF; selectedCentrality = LMEECutLibRemi::kPbPb2011SemiCentral2; selectedPairInvMassCut = LMEECutLibRemi::kPbPb2011MassMiddle; selectedPairInOutCut = LMEECutLibRemi::kPbPb2011Mag; rejectionStep = kFALSE; PairInvMassCut = kTRUE; PairInOutCut = kTRUE; } else if (cutDefinition==24) { selectedPID = LMEECutLibRemi::kPbPb2011pidITSTPCTOF; selectedCentrality = LMEECutLibRemi::kPbPb2011Peripheral; selectedPairInvMassCut = LMEECutLibRemi::kPbPb2011MassMiddle; selectedPairInOutCut = LMEECutLibRemi::kPbPb2011Mag; rejectionStep = kFALSE; PairInvMassCut = kTRUE; PairInOutCut = kTRUE; } else if (cutDefinition==25) { selectedPID = LMEECutLibRemi::kPbPb2011pidITSTPCTOF; selectedCentrality = LMEECutLibRemi::kPbPb2011Central; selectedPairInvMassCut = LMEECutLibRemi::kPbPb2011MassHigh; selectedPairInOutCut = LMEECutLibRemi::kPbPb2011Mag; rejectionStep = kFALSE; PairInvMassCut = kTRUE; PairInOutCut = kTRUE; } else if (cutDefinition==26) { selectedPID = LMEECutLibRemi::kPbPb2011pidITSTPCTOF; selectedCentrality = LMEECutLibRemi::kPbPb2011SemiCentral1; selectedPairInvMassCut = LMEECutLibRemi::kPbPb2011MassHigh; selectedPairInOutCut = LMEECutLibRemi::kPbPb2011Mag; rejectionStep = kFALSE; PairInvMassCut = kTRUE; PairInOutCut = kTRUE; } else if (cutDefinition==27) { selectedPID = LMEECutLibRemi::kPbPb2011pidITSTPCTOF; selectedCentrality = LMEECutLibRemi::kPbPb2011SemiCentral2; selectedPairInvMassCut = LMEECutLibRemi::kPbPb2011MassHigh; selectedPairInOutCut = LMEECutLibRemi::kPbPb2011Mag; rejectionStep = kFALSE; PairInvMassCut = kTRUE; PairInOutCut = kTRUE; } else if (cutDefinition==28) { selectedPID = LMEECutLibRemi::kPbPb2011pidITSTPCTOF; selectedCentrality = LMEECutLibRemi::kPbPb2011Peripheral; selectedPairInvMassCut = LMEECutLibRemi::kPbPb2011MassHigh; selectedPairInOutCut = LMEECutLibRemi::kPbPb2011Mag; rejectionStep = kFALSE; PairInvMassCut = kTRUE; PairInOutCut = kTRUE; } /* /////////////////////////////////////////////////////////// else if (cutDefinition==21) { selectedPID = LMEECutLibRemi::kPbPb2011TPCandTOFwide selectedCentrality = LMEECutLibRemi::kPbPb2011Central; selectedPairInvMassCut = LMEECutLibRemi::kPbPb2011RP; //selectedPairMCut = LMEECutLibRemi::kPbPb2011MassAll; rejectionStep = kFALSE; PairCut=kTRUE; PolaCut=kTRUE; } else if (cutDefinition==22) { selectedPID = LMEECutLibRemi::kPbPb2011TPCandTOFwide; selectedCentrality = LMEECutLibRemi::kPbPb2011SemiCentral1; selectedPairInvMassCut = LMEECutLibRemi::kPbPb2011RP; // selectedPairMCut = LMEECutLibRemi::kPbPb2011MassMiddle; rejectionStep = kFALSE; PairCut=kTRUE; PolaCut=kTRUE; } else if (cutDefinition==23) { selectedPID = LMEECutLibRemi::kPbPb2011TPCandTOFwide; selectedCentrality = LMEECutLibRemi::kPbPb2011SemiCentral2; // selectedPairMCut = LMEECutLibRemi::kPbPb2011MassMiddle; selectedPairInvMassCut = LMEECutLibRemi::kPbPb2011RP; rejectionStep = kFALSE; PairCut=kTRUE; PolaCut=kTRUE; } else if (cutDefinition==24) { selectedPID = LMEECutLibRemi::kPbPb2011TPCandTOFwide; selectedCentrality = LMEECutLibRemi::kPbPb2011Peripheral; selectedPairInvMassCut = LMEECutLibRemi::kPbPb2011RP; // selectedPairMCut = LMEECutLibRemi::kPbPb2011MassMiddle; rejectionStep = kFALSE; PairCut=kTRUE; PolaCut=kTRUE; } ///////////////////////////////////////////////////////// else if (cutDefinition==25) { selectedPID = LMEECutLibRemi::kPbPb2011TPCandTOFwide; selectedCentrality = LMEECutLibRemi::kPbPb2011Central; selectedPairInvMassCut = LMEECutLibRemi::kPbPb2011Mag; // selectedPairMCut = LMEECutLibRemi::kPbPb2011MassAll; rejectionStep = kFALSE; PairCut=kTRUE; PolaCut=kTRUE; } else if (cutDefinition==26) { selectedPID = LMEECutLibRemi::kPbPb2011TPCandTOFwide; selectedCentrality = LMEECutLibRemi::kPbPb2011SemiCentral1; selectedPairInvMassCut = LMEECutLibRemi::kPbPb2011Mag; // selectedPairMCut = LMEECutLibRemi::kPbPb2011MassMiddle; rejectionStep = kFALSE; PairCut=kTRUE; PolaCut=kTRUE; } else if (cutDefinition==27) { selectedPID = LMEECutLibRemi::kPbPb2011TPCandTOFwide; selectedCentrality = LMEECutLibRemi::kPbPb2011SemiCentral2; // selectedPairMCut = LMEECutLibRemi::kPbPb2011MassMiddle; selectedPairInvMassCut = LMEECutLibRemi::kPbPb2011Mag; rejectionStep = kFALSE; PairCut=kTRUE; PolaCut=kTRUE; } else if (cutDefinition==28) { selectedPID = LMEECutLibRemi::kPbPb2011TPCandTOFwide; selectedCentrality = LMEECutLibRemi::kPbPb2011Peripheral; selectedPairInvMassCut = LMEECutLibRemi::kPbPb2011Mag; // selectedPairMCut = LMEECutLibRemi::kPbPb2011MassMiddle; rejectionStep = kFALSE; PairCut=kTRUE; PolaCut=kTRUE; } */ else { cout << " =============================== " << endl; cout << " ==== INVALID CONFIGURATION ==== " << endl; cout << " =============================== " << endl; } //Now configure task //Apply correct Pre-Filter Scheme, if necessary die->SetPreFilterAllSigns(); //switch off KF PArticle: die->SetUseKF(kFALSE); /* if (selectedPID == LMEECutLibRemi::kPbPb2011NoPID) { die->SetNoPairing(); } */ die->GetEventFilter().AddCuts( LMCL->GetCentralityCuts(selectedCentrality)); // die->GetTrackFilter().AddCuts( LMCL->GetTrackCutsAna(selectedPID) ); die->GetTrackFilter().AddCuts( LMCL->GetPIDCutsAna(selectedPID) ); // die->GetPairFilter().AddCuts( LMCL->GetPairCutsAna(selectedPID,kFALSE) ); if (PairInvMassCut) die->GetPairFilter().AddCuts( LMCL->GetPairCutsInvMass(selectedPairInvMassCut)); if(PairInOutCut) die->GetPairFilter().AddCuts( LMCL->GetPairCutsInOut(selectedPairInOutCut)); /* if(PairCut){ if (rejectionStep) { die->GetPairPreFilterLegs().AddCuts(LMCL->GetPIDCutsAna(selectedPID) ); die->GetPairPreFilter().AddCuts( LMCL->GetPairPreFilterCuts(selectedPairCut)); die->GetPairFilter().AddCuts( LMCL->GetPairCuts(selectedPairCut)); } else { // die->GetPairFilter().AddCuts( LMCL->GetPairCutsInvMass(selectedPairCut)); die->GetPairFilter().AddCuts( LMCL->GetPairCuts(selectedPID)); // die->GetPairFilter().AddCuts( LMCL->GetPairCuts4(selectedPairMCut)); } } */ /* if (rejectionStep) { if (ESDanalysis) { die->GetTrackFilter().AddCuts( LMCL->GetESDTrackCutsAna(selectedPID) ); die->GetPairPreFilterLegs().AddCuts( LMCL->GetESDTrackCutsAna(selectedPID) ); } //die->GetTrackFilter().AddCuts(LMCL->GetPIDCutsPre(selectedPID) ); die->GetTrackFilter().AddCuts(LMCL->GetPIDCutsAna(selectedPID) ); die->GetPairPreFilterLegs().AddCuts(LMCL->GetPIDCutsAna(selectedPID) ); die->GetPairPreFilter().AddCuts(LMCL->GetPairCuts(selectedPID) ); // if(PairCut){ // die->GetPairFilter().AddCuts( LMCL->GetPairCutsInvMass(selectedPairCut)); // } } else { //No Prefilter, no Pairfilter if (ESDanalysis) { die->GetTrackFilter().AddCuts( LMCL->GetESDTrackCutsAna(selectedPID) ); } die->GetTrackFilter().AddCuts( LMCL->GetTrackCutsAna(selectedPID) ); die->GetTrackFilter().AddCuts( LMCL->GetPIDCutsAna(selectedPID) ); die->GetEventFilter().AddCuts(LMCL->GetCentralityCuts(selectedCentrality)); // if(PairCut){ // die->GetPairFilter().AddCuts( LMCL->GetPairCutsInvMass(selectedPairCut)); // } die->GetPairFilter().AddCuts(LMCL->GetPairCuts2(selectedPID,kFALSE)); } //Introduce NULL-check for pp? die->GetEventFilter().AddCuts(LMCL->GetCentralityCuts(selectedCentrality)); */ AliDielectronTrackRotator *rot= 0x0; /*AliDielectronTrackRotator *rot= LMCL->GetTrackRotator(selectedPID); die->SetTrackRotator(rot); */ AliDielectronMixingHandler *mix=LMCL->GetMixingHandler(selectedPID); die->SetMixingHandler(mix); // histogram setup // only if an AliDielectronHistos object is attached to the // dielectron framework histograms will be filled // InitHistograms(die,cutDefinition); // the last definition uses no cuts and only the QA histograms should be filled! // InitCF(die,cutDefinition); return die; } //______________________________________________________________________________________ void InitHistograms(AliDielectron *die, Int_t cutDefinition) { // // Initialise the histograms // //Setup histogram Manager AliDielectronHistos *histos= new AliDielectronHistos(die->GetName(), die->GetTitle()); //Initialise histogram classes histos->SetReservedWords("Track;Pair;Pre;RejTrack;RejPair"); //Event class // if (cutDefinition==nDie-1) histos->AddClass("Event"); //Track classes //to fill also track info from 2nd event loop until 2 for (Int_t i=0; i<2; ++i){ histos->AddClass(Form("Track_%s",AliDielectron::TrackClassName(i))); } //Pair classes // to fill also mixed event histograms loop until 10 for (Int_t i=0; i<3; ++i){ histos->AddClass(Form("Pair_%s",AliDielectron::PairClassName(i))); } //ME and track rot if (die->GetMixingHandler()) { histos->AddClass(Form("Pair_%s",AliDielectron::PairClassName(3))); histos->AddClass(Form("Pair_%s",AliDielectron::PairClassName(4))); histos->AddClass(Form("Pair_%s",AliDielectron::PairClassName(6))); histos->AddClass(Form("Pair_%s",AliDielectron::PairClassName(7))); } if (die->GetTrackRotator()) { histos->AddClass(Form("Pair_%s",AliDielectron::PairClassName(10))); } //PreFilter Classes //to fill also track info from 2nd event loop until 2 for (Int_t i=0; i<2; ++i){ histos->AddClass(Form("Pre_%s",AliDielectron::TrackClassName(i))); } //Create Classes for Rejected Tracks/Pairs: for (Int_t i=0; i<2; ++i){ histos->AddClass(Form("RejTrack_%s",AliDielectron::TrackClassName(i))); } for (Int_t i=0; i<3; ++i){ histos->AddClass(Form("RejPair_%s",AliDielectron::PairClassName(i))); } /* //track rotation histos->AddClass(Form("Pair_%s",AliDielectron::PairClassName(AliDielectron::kEv1PMRot))); histos->AddClass(Form("Track_Legs_%s",AliDielectron::PairClassName(AliDielectron::kEv1PMRot))); */ //add histograms to event class histos->UserHistogram("Event","nEvents","Number of processed events after cuts;Number events", 1,0.,1.,AliDielectronVarManager::kNevents); histos->UserHistogram("Event","Centrality","Centrality;Centrality [%]","0,10,20,40,80,100,101", AliDielectronVarManager::kCentrality); histos->UserHistogram("Event","v0ACrpH2","VZERO-AC;v0ACrpH2", 100,-2.0,2.0, AliDielectronVarManager::kv0ACrpH2); histos->UserHistogram("Event","v0ArpH2","VZERO-A;v0ArpH2", 100,-2.0,2.0, AliDielectronVarManager::kv0ArpH2); histos->UserHistogram("Event","v0CrpH2","VZERO-C;v0CrpH2", 100,-2.0,2.0, AliDielectronVarManager::kv0CrpH2); histos->UserHistogram("Event","RadomRP","RandomRP;RandomRP", 100,-2.0,2.0, AliDielectronVarManager::kRandomRP); histos->UserHistogram("Event","ZDCArpH1","ZDC-ZN-A;ZDCrpH1", 100,-3.5,3.5, AliDielectronVarManager::kZDCACrpH1); histos->UserProfile("Event","ZDCrpResH1Prof","ZDC;ZDCrpResH1", AliDielectronVarManager::kZDCrpResH1, 10, 0, 100, AliDielectronVarManager::kCentrality); histos->UserProfile("Event","v0ZDCrpResProf","ZDC;v0ZDCrpRes", AliDielectronVarManager::kv0ZDCrpRes, 10, 0, 100, AliDielectronVarManager::kCentrality); histos->UserHistogram("Event","RefMult","RefMultiplicity;Multiplixity", 100,-3.5,3.5, AliDielectronVarManager::kRefMult); histos->UserHistogram("Event","kXvPrim","VertexX;vertex_x", 100,0.03,0.1, AliDielectronVarManager::kXvPrim); histos->UserHistogram("Event","kYvPrim","VartexY;vertex_y", 100,0.2,0.3, AliDielectronVarManager::kYvPrim); //add histograms to Track classes histos->UserHistogram("Track","Pt","Pt;Pt [GeV];#tracks",200,0,20.,AliDielectronVarManager::kPt); histos->UserHistogram("Track","Px","Px;Px [GeV];#tracks",200,0,20.,AliDielectronVarManager::kPx); histos->UserHistogram("Track","Py","Py;Py [GeV];#tracks",200,0,20.,AliDielectronVarManager::kPy); histos->UserHistogram("Track","Pz","Pz;Pz [GeV];#tracks",200,0,20.,AliDielectronVarManager::kPz); histos->UserHistogram("Track","Eta","Eta; Eta;#tracks", 200,-2,2,AliDielectronVarManager::kEta); histos->UserHistogram("Track","Phi","Phi; Phi;#tracks", 200,0.,3.15,AliDielectronVarManager::kPhi); /* histos->UserHistogram("Track","NclsSFracTPC","NclsSFracTPC; NclsSFracTPC;#tracks",200,0,10.,AliDielectronVarManager::kNclsSFracTPC); histos->UserHistogram("Track","TPCclsDiff","TPCclsDiff; TPCclsDiff;#tracks",200,0,10.,AliDielectronVarManager::kTPCclsDiff); histos->UserHistogram("Track","ITS_dEdx_P","ITS_dEdx;P [GeV];ITS signal (arb units);#tracks", 400,0.0,20.,1000,0.,1000.,AliDielectronVarManager::kPIn,AliDielectronVarManager::kITSsignal,kTRUE); histos->UserHistogram("Track","dEdx_P","dEdx;P [GeV];TPC signal (arb units);#tracks", 400,0.0,20.,200,0.,200.,AliDielectronVarManager::kPIn,AliDielectronVarManager::kTPCsignal,kTRUE); histos->UserHistogram("Track","TPCnSigmaEle_P","TPC number of sigmas Electrons;P [GeV];TPC number of sigmas Electrons;#tracks", 400,0.0,20.,100,-5.,5.,AliDielectronVarManager::kPIn,AliDielectronVarManager::kTPCnSigmaEle,kTRUE); histos->UserHistogram("Track","TPCnSigmaKao_P","TPC number of sigmas Kaons;P [GeV];TPC number of sigmas Kaons;#tracks", 400,0.0,20.,100,-5.,5.,AliDielectronVarManager::kPIn,AliDielectronVarManager::kTPCnSigmaKao,kTRUE); histos->UserHistogram("Track","TPCnSigmaPio_P","TPC number of sigmas Pions;P [GeV];TPC number of sigmas Pions;#tracks", 400,0.0,20.,100,-5.,5.,AliDielectronVarManager::kPIn,AliDielectronVarManager::kTPCnSigmaPio,kTRUE); histos->UserHistogram("Track","TRDpidPobEle_P","TRD PID probability Electrons;P [GeV];TRD prob Electrons;#tracks", 400,0.0,20.,100,0.,1.,AliDielectronVarManager::kPIn,AliDielectronVarManager::kTRDprobEle,kTRUE); histos->UserHistogram("Track","TRDpidPobPio_P","TRD PID probability Pions;P [GeV];TRD prob Pions;#tracks", 400,0.0,20.,100,0.,1.,AliDielectronVarManager::kPIn,AliDielectronVarManager::kTRDprobPio,kTRUE); histos->UserHistogram("Track","TOFnSigmaKao_P","TOF number of sigmas Kaons;P [GeV];TOF number of sigmas Kaons;#tracks", 400,0.0,20.,100,-5.,5.,AliDielectronVarManager::kPIn,AliDielectronVarManager::kTOFnSigmaKao,kTRUE); histos->UserHistogram("Track","TOFnSigmaPro_P","TOF number of sigmas Protons;P [GeV];TOF number of sigmas Protons;#tracks", 400,0.0,20.,100,-5.,5.,AliDielectronVarManager::kPIn,AliDielectronVarManager::kTOFnSigmaPro,kTRUE); histos->UserHistogram("Track","TOFbeta","TOF beta;P [GeV];TOF beta;#tracks", 400,0.0,20.,100,0.,1.,AliDielectronVarManager::kPIn,AliDielectronVarManager::kTOFbeta,kTRUE); histos->UserHistogram("Track","Eta","Eta; Eta;#tracks", 200,-2,2,AliDielectronVarManager::kEta); histos->UserHistogram("Track","Phi","Phi; Phi;#tracks", 200,0.,3.15,AliDielectronVarManager::kPhi); histos->UserHistogram("Track","Eta_Phi","Eta Phi Map; Eta; Phi;#tracks", 200,-2,2,200,0,3.15,AliDielectronVarManager::kEta,AliDielectronVarManager::kPhi); histos->UserHistogram("Track","dXY_dZ","dXY dZ Map; dXY; dZ;#tracks", 200,-2,2,200,-2,2.,AliDielectronVarManager::kImpactParXY,AliDielectronVarManager::kImpactParZ); histos->UserHistogram("Track","dXY","dXY;dXY [cm];#tracks",200,-2.,2.,AliDielectronVarManager::kImpactParXY); histos->UserHistogram("Track","dZ","dZ;dZ [cm];#tracks",200,-2.,2.,AliDielectronVarManager::kImpactParZ); histos->UserHistogram("Track","TPCcrossedRowsOverFindable","Number of Crossed Rows TPC over Findable;TPC crossed rows over findable;#tracks",100,0.,1.,AliDielectronVarManager::kNFclsTPCfCross); histos->UserHistogram("Track","TPCcrossedRows","Number of Crossed Rows TPC;TPC crossed rows;#tracks",159,0.,159.,AliDielectronVarManager::kNFclsTPCr); histos->UserHistogram("Track","TPCnCls","Number of Clusters TPC;TPC number clusteres;#tracks",159,0.,159.,AliDielectronVarManager::kNclsTPC); histos->UserHistogram("Track","ITSnCls","Number of Clusters ITS;ITS number clusteres;#tracks",159,0.,159.,AliDielectronVarManager::kNclsITS); histos->UserHistogram("Track","TPCchi2","TPC Chi2 value;TPC chi2;#tracks",100,0.,10.,AliDielectronVarManager::kTPCchi2Cl); histos->UserHistogram("Track","ITSchi2","ITS Chi2 value;ITS chi2;#tracks",100,0.,10.,AliDielectronVarManager::kITSchi2Cl); histos->UserHistogram("Track","TPCnCls_kNFclsTPCr","nTPC vs nTPCr;nTPC vs nTPCr;#tracks",159,0.,159.,159,0.,159.,AliDielectronVarManager::kNclsTPC,AliDielectronVarManager::kNFclsTPCr); histos->UserHistogram("Track","kNFclsTPCr_pT","nTPCr vs pt;nTPCr vs pt;#tracks",159,0.,159.,200,0.,20.,AliDielectronVarManager::kNFclsTPCr,AliDielectronVarManager::kPt); */ //add histograms to Pair classes histos->UserHistogram("Pair","InvMass","Inv.Mass;Inv. Mass [GeV];#pairs", 500,0.0,5.00,AliDielectronVarManager::kM); histos->UserHistogram("Pair","Rapidity","Rapidity;Rapidity;#pairs", 100,-2.,2.,AliDielectronVarManager::kY); histos->UserHistogram("Pair","OpeningAngle","Opening angle;angle", 100,0.,3.15,AliDielectronVarManager::kOpeningAngle); //2D Histo Plot histos->UserHistogram("Pair","InvMassPairPt","Inv.Mass vs PairPt;Inv. Mass [GeV], pT [GeV];#pairs", 500,0.0,5.0,500,0.,50.,AliDielectronVarManager::kM,AliDielectronVarManager::kPt); histos->UserHistogram("Pair","InvMassOpeningAngle","Opening Angle vs Inv.Mass;Inv. Mass [GeV];#pairs", 500,0.0,5.0,200,0.,6.3,AliDielectronVarManager::kM,AliDielectronVarManager::kOpeningAngle); histos->UserHistogram("Pair","Pt","Pt;Pt [GeV];#tracks",300,0,30.,AliDielectronVarManager::kPt); histos->UserHistogram("Pair","Px","Px;Px [GeV];#tracks",300,0,30.,AliDielectronVarManager::kPx); histos->UserHistogram("Pair","Py","Py;Py [GeV];#tracks",300,0,30.,AliDielectronVarManager::kPy); histos->UserHistogram("Pair","Pz","Pz;Pz [GeV];#tracks",300,0,30.,AliDielectronVarManager::kPz); histos->UserHistogram("Pair","Phi","Phi;Phi[rad];#counts",100,-3.15,3.15,AliDielectronVarManager::kPhi ); histos->UserHistogram("Pair","DeltaPhiv0ArpH2","Phi;Phi[rad];#counts", 100,-3.15,3.15,AliDielectronVarManager::kDeltaPhiv0ArpH2); histos->UserHistogram("Pair","DeltaPhiv0CrpH2","Phi;Phi[rad];#counts", 100,-3.15,3.15,AliDielectronVarManager::kDeltaPhiv0CrpH2); histos->UserHistogram("Pair","DeltaPhiv0ACrpH2","Phi;Phi[rad];#counts", 100,-3.15,3.15,AliDielectronVarManager::kDeltaPhiv0ACrpH2); histos->UserHistogram("Pair","DeltaPhiRandomRP","Phi;Phi[rad];#counts", 100,-3.15,3.15,AliDielectronVarManager::kDeltaPhiRandomRP); histos->UserHistogram("Pair","PairPlaneAngle2C","Phi;Phi[rad];#counts", 100,0,1.6,AliDielectronVarManager::kPairPlaneAngle2C); histos->UserHistogram("Pair","PairPlaneAngle3C","Phi;Phi[rad];#counts", 100,0,1.6,AliDielectronVarManager::kPairPlaneAngle3C); histos->UserHistogram("Pair","PairPlaneAngle4C","Phi;Phi[rad];#counts", 100,0,1.6,AliDielectronVarManager::kPairPlaneAngle4C); histos->UserHistogram("Pair","PairPlaneAngleRan","Phi;Phi[rad];#counts", 100,0,1.6,AliDielectronVarManager::kPairPlaneAngle3Ran); //2D Histo Plot histos->UserHistogram("Pair","InvMAllPP1C","Inv.Mass vs PairPlaneAngle;Inv. Mass [GeV];Phi [rad]",500,0.0,0.50,100,0.,3.15,AliDielectronVarManager::kM,AliDielectronVarManager::kPairPlaneAngle1C); histos->UserHistogram("Pair","InvMAllPP2C","Inv.Mass vs PairPlaneAngle;Inv. Mass [GeV];Phi [rad]",500,0.0,0.50,100,0.,3.15,AliDielectronVarManager::kM,AliDielectronVarManager::kPairPlaneAngle2C); histos->UserHistogram("Pair","InvMAllPP3C","Inv.Mass vs PairPlaneAngle;Inv. Mass [GeV];Phi [rad]",500,0.0,0.50,100,0.,3.15,AliDielectronVarManager::kM,AliDielectronVarManager::kPairPlaneAngle3C); histos->UserHistogram("Pair","InvMAllPP4C","Inv.Mass vs PairPlaneAngle;Inv. Mass [GeV];Phi [rad]",500,0.0,0.50,100,0.,3.15,AliDielectronVarManager::kM,AliDielectronVarManager::kPairPlaneAngle4C); histos->UserHistogram("Pair","PtAllPP1C","Pair Pt vs PairPlaneAngle;Pt [GeV];Phi [rad]", 500,0.,10.0,100,0.,3.15,AliDielectronVarManager::kPt, AliDielectronVarManager::kPairPlaneAngle1C); histos->UserHistogram("Pair","PtAllPP2C","Pair Pt vs PairPlaneAngle;Pt [GeV];Phi [rad]", 500,0.,10.0,100,0.,3.15,AliDielectronVarManager::kPt, AliDielectronVarManager::kPairPlaneAngle2C); histos->UserHistogram("Pair","PtAllPP3C","Pair Pt vs PairPlaneAngle;Pt [GeV];Phi [rad]", 500,0.,10.0,100,0.,3.15,AliDielectronVarManager::kPt, AliDielectronVarManager::kPairPlaneAngle3C); histos->UserHistogram("Pair","PtAllPP4C","Pair Pt vs PairPlaneAngle;Pt [GeV];Phi [rad]", 500,0.,10.0,100,0.,3.15,AliDielectronVarManager::kPt, AliDielectronVarManager::kPairPlaneAngle4C); /* histos->UserHistogram("Pair","InvMassAllPairplaneMagInPro","Inner Product of Mag and ee plane vs Inv.Mass;Inv. Mass [GeV];Phi [rad]", 1000, 0.0,1.0,100,-2.0,2.0,AliDielectronVarManager::kM,AliDielectronVarManager::kPairPlaneMagInPro); histos->UserHistogram("Pair","InvMassLowPairplaneMagInPro","ee plane Mag component vs Inv.Mass;Inv. Mass [GeV];Phi [rad]", 300, 0.0,0.03,100,-2.0,2.0,AliDielectronVarManager::kM,AliDielectronVarManager::kPairPlaneMagInPro); histos->UserHistogram("Pair","InvMassMiddlePairplaneMagInPro","ee plane Mag component vs Inv.Mass;Inv. Mass [GeV];Phi [rad]", 180,0.12, 0.3,100,-2.0,2.0,AliDielectronVarManager::kM,AliDielectronVarManager::kPairPlaneMagInPro); histos->UserHistogram("Pair","InvMassHighPairplaneMagInPro","ee plane Mag component vs Inv.Mass;Inv. Mass [GeV];Phi [rad]", 200, 0.3, 0.5,100,-2.0,2.0,AliDielectronVarManager::kM,AliDielectronVarManager::kPairPlaneMagInPro); */ histos->UserHistogram("Pair","DeltaPhiv0CrpH2","Phi;Phi[rad];#counts", 100,-3.15,3.15,AliDielectronVarManager::kDeltaPhiv0CrpH2); histos->UserHistogram("Pair","PtAllPairplaneMagInPro","ee plane Mag component vs Pt;Pt [GeV];Phi [rad]", 500,0.0,10.0,100,-2.0,2.0,AliDielectronVarManager::kPt,AliDielectronVarManager::kPairPlaneMagInPro); histos->UserHistogram("Pair","PtLowPairplaneMagInPro","ee plane Mag component vs Pt;Pt [GeV];Phi [rad]", 100,0.0,1.0,100,-2.0,2.0,AliDielectronVarManager::kPt,AliDielectronVarManager::kPairPlaneMagInPro); histos->UserHistogram("Pair","PtMiddlePairplaneMagInPro","ee plane Mag component vs Pt;Pt [GeV];Phi [rad]", 100,1.0,2.0,100,-2.0,2.0,AliDielectronVarManager::kPt,AliDielectronVarManager::kPairPlaneMagInPro); histos->UserHistogram("Pair","PtHighPairplaneMagInPro","ee plane Mag component vs Pt;Pt [GeV];Phi [rad]", 200,2.0,10.0,100,-2.0,2.0,AliDielectronVarManager::kPt,AliDielectronVarManager::kPairPlaneMagInPro); /* histos->UserHistogram("Pair","AllInvMassPtPairplaneMagInPro","ee plane Mag component;Inv.Mass[GeV];Pt[GeV];Phi[red]", 1000,0.0 ,0.5,500,0.0,10.0,100,-2.0,2.0, AliDielectronVarManager::kM,AliDielectronVarManager::kPt,AliDielectronVarManager::kPairPlaneMagInPro); */ // histos->UserHistogram("Pair","AllInvMassPtPairplaneMagInPro","ee plane Mag component vs Pt;Inv.Mass[GeV];Pt [GeV];Phi [rad]", // 1000,0.0,0.5,500,0.0,10.0,100,-2.0,2.0, // AliDielectronVarManager::kM,AliDielectronVarManager::kPt,AliDielectronVarManager::kPairPlaneMagInPro); /* //add histograms to Track classes histos->UserHistogram("Pre","Pt","Pt;Pt [GeV];#tracks",200,0,20.,AliDielectronVarManager::kPt); histos->UserHistogram("Pre","ITS_dEdx_P","ITS_dEdx;P [GeV];ITS signal (arb units);#tracks", 400,0.0,20.,1000,0.,1000.,AliDielectronVarManager::kPIn,AliDielectronVarManager::kITSsignal,kTRUE); histos->UserHistogram("Pre","dEdx_P","dEdx;P [GeV];TPC signal (arb units);#tracks", 400,0.0,20.,200,0.,200.,AliDielectronVarManager::kPIn,AliDielectronVarManager::kTPCsignal,kTRUE); histos->UserHistogram("Pre","TPCnSigmaEle_P","TPC number of sigmas Electrons;P [GeV];TPC number of sigmas Electrons;#tracks", 400,0.0,20.,100,-5.,5.,AliDielectronVarManager::kPIn,AliDielectronVarManager::kTPCnSigmaEle,kTRUE); histos->UserHistogram("Pre","TPCnSigmaKao_P","TPC number of sigmas Kaons;P [GeV];TPC number of sigmas Kaons;#tracks", 400,0.0,20.,100,-5.,5.,AliDielectronVarManager::kPIn,AliDielectronVarManager::kTPCnSigmaKao,kTRUE); histos->UserHistogram("Pre","TPCnSigmaPio_P","TPC number of sigmas Pions;P [GeV];TPC number of sigmas Pions;#tracks", 400,0.0,20.,100,-5.,5.,AliDielectronVarManager::kPIn,AliDielectronVarManager::kTPCnSigmaPio,kTRUE); histos->UserHistogram("Pre","TRDpidPobEle_P","TRD PID probability Electrons;P [GeV];TRD prob Electrons;#tracks", 400,0.0,20.,100,0.,1.,AliDielectronVarManager::kPIn,AliDielectronVarManager::kTRDprobEle,kTRUE); histos->UserHistogram("Pre","TRDpidPobPio_P","TRD PID probability Pions;P [GeV];TRD prob Pions;#tracks", 400,0.0,20.,100,0.,1.,AliDielectronVarManager::kPIn,AliDielectronVarManager::kTRDprobPio,kTRUE); histos->UserHistogram("Pre","TOFnSigmaKao_P","TOF number of sigmas Kaons;P [GeV];TOF number of sigmas Kaons;#tracks", 400,0.0,20.,100,-5.,5.,AliDielectronVarManager::kPIn,AliDielectronVarManager::kTOFnSigmaKao,kTRUE); histos->UserHistogram("Pre","TOFnSigmaPro_P","TOF number of sigmas Protons;P [GeV];TOF number of sigmas Protons;#tracks", 400,0.0,20.,100,-5.,5.,AliDielectronVarManager::kPIn,AliDielectronVarManager::kTOFnSigmaPro,kTRUE); histos->UserHistogram("Pre","Eta_Phi","Eta Phi Map; Eta; Phi;#tracks", 200,-2,2,200,0,3.15,AliDielectronVarManager::kEta,AliDielectronVarManager::kPhi); histos->UserHistogram("Pre","dXY","dXY;dXY [cm];#tracks",200,-2.,2.,AliDielectronVarManager::kImpactParXY); histos->UserHistogram("Pre","ZVertex ","ZVertex ;ZVertex[cm];#tracks",20,-20,20,AliDielectronVarManager::kZv); histos->UserHistogram("Pre","XVertex ","XVertex ;XVertex[cm];#tracks",20,-20,20,AliDielectronVarManager::kXv); histos->UserHistogram("Pre","YVertex ","YVertex ;YVertex[cm];#tracks",20,-20,20,AliDielectronVarManager::kYv); histos->UserHistogram("Pre","TPCnCls","Number of Clusters TPC;TPC number clusteres;#tracks",159,0.,159.,AliDielectronVarManager::kNclsTPC); */ //add histograms to Pair classes For Rejected Pairs: die->SetHistogramManager(histos); } void InitCF(AliDielectron* die, Int_t cutDefinition) { // // Setupd the CF Manager if needed // AliDielectronCF *cf=new AliDielectronCF(die->GetName(),die->GetTitle()); //pair variables cf->AddVariable(AliDielectronVarManager::kP,200,0,20); cf->AddVariable(AliDielectronVarManager::kM,201,-0.01,4.01); //20Mev Steps cf->AddVariable(AliDielectronVarManager::kPairType,10,0,10); cf->AddVariable(AliDielectronVarManager::kCentrality,"0.,10.0,30.0,40.0,60.,80.,100."); //leg variables cf->AddVariable(AliDielectronVarManager::kP,200,0.,20.,kTRUE); cf->AddVariable(AliDielectronVarManager::kITSsignal,1000,0.0.,1000.,kTRUE); cf->AddVariable(AliDielectronVarManager::kTPCsignal,500,0.0.,500.,kTRUE); cf->AddVariable(AliDielectronVarManager::kHaveSameMother,21,-10,10,kTRUE); //only in this case write MC truth info if (MCenabled) { cf->SetStepForMCtruth(); cf->SetStepsForMCtruthOnly(); cf->AddVariable(AliDielectronVarManager::kPdgCode,10000,-5000.5,4999.5,kTRUE); cf->AddVariable(AliDielectronVarManager::kPdgCodeMother,10000,-5000.5,4999.5,kTRUE); } cf->SetStepsForSignal(); die->SetCFManagerPair(cf); } //-------------------------------------- void EnableMC() { MCenabled=kTRUE; } // LocalWords: cutDefinition
9,740
https://github.com/sylarsykes/java-spring-boot-meal-builder/blob/master/common/common-util/src/main/java/org/sylrsykssoft/springboot/common/util/mapper/ModelMapperFunction.java
Github Open Source
Open Source
Apache-2.0
null
java-spring-boot-meal-builder
sylarsykes
Java
Code
121
391
/** * ModelMapperFunction.java 31 ene. 2021 * */ package org.sylrsykssoft.springboot.common.util.mapper; import java.util.function.Function; import org.modelmapper.ModelMapper; import org.springframework.beans.factory.annotation.Autowired; import lombok.extern.slf4j.Slf4j; /** * Mapper entity to resource or resource to entity. * * @author juan.gonzalez.fernandez.jgf * @param <T> the generic type * @param <R> the generic type * */ @Slf4j public class ModelMapperFunction<T, R> implements Function<T, R> { private static final String LOG_CLASS_NAME = ModelMapperFunction.class.getSimpleName() + "."; private static final String LOG_CLASS_APPLY_METHOD_NAME = LOG_CLASS_NAME + "apply - Map input object to result object - "; @Autowired ModelMapper modelMapper; ModelMapperDTO<R> result; /** * {@inheritDoc} */ @Override public R apply(final T source) { LOGGER.info("{} Mapper a soruce {}", LOG_CLASS_APPLY_METHOD_NAME, source); final R target = modelMapper.map(source, result.getTargetClass()); LOGGER.info("{} Result -> {}", LOG_CLASS_APPLY_METHOD_NAME, target); return target; } }
1,794
https://github.com/ray-ruisun/FedML/blob/master/app/fedcv/object_detection/model/__init__.py
Github Open Source
Open Source
Apache-2.0
null
FedML
ray-ruisun
Python
Code
6
16
from .yolo.models.yolo import Model as YOLO
31,967
https://github.com/ravamo/hop/blob/master/plugins/transforms/http/src/test/java/org/apache/hop/pipeline/transforms/http/HttpTest.java
Github Open Source
Open Source
Apache-2.0
null
hop
ravamo
Java
Code
480
1,376
/*! ****************************************************************************** * * Hop : The Hop Orchestration Platform * * http://www.project-hop.org * ******************************************************************************* * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************************/ package org.apache.hop.pipeline.transforms.http; import org.apache.hop.core.logging.ILogChannel; import org.apache.hop.core.row.IRowMeta; import org.apache.hop.core.util.HttpClientManager; import org.apache.http.Header; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.entity.BasicHttpEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import java.io.ByteArrayInputStream; import java.net.HttpURLConnection; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.mockito.Matchers.any; import static org.mockito.Mockito.doCallRealMethod; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.powermock.api.mockito.PowerMockito.mockStatic; import static org.powermock.reflect.Whitebox.setInternalState; /** * @author Luis Martins * @since 14-Aug-2018 */ @RunWith( PowerMockRunner.class ) @PrepareForTest( HttpClientManager.class ) public class HttpTest { private ILogChannel log = mock( ILogChannel.class ); private IRowMeta rmi = mock( IRowMeta.class ); private HttpData data = mock( HttpData.class ); private HttpMeta meta = mock( HttpMeta.class ); private Http http = mock( Http.class ); private final String DATA = "This is the description, there's some HTML here, like &lt;strong&gt;this&lt;/strong&gt;. " + "Sometimes this text is another language that might contain these characters:\n" + "&lt;p&gt;é, è, ô, ç, à, ê, â.&lt;/p&gt; They can, of course, come in uppercase as well: &lt;p&gt;É, È Ô, Ç, À," + " Ê, Â&lt;/p&gt;. UTF-8 handles this well."; @Before public void setup() throws Exception { HttpClientManager.HttpClientBuilderFacade builder = mock( HttpClientManager.HttpClientBuilderFacade.class ); HttpClientManager manager = mock( HttpClientManager.class ); doReturn( builder ).when( manager ).createBuilder(); CloseableHttpClient client = mock( CloseableHttpClient.class ); doReturn( client ).when( builder ).build(); CloseableHttpResponse response = mock( CloseableHttpResponse.class ); doReturn( response ).when( client ).execute( any( HttpGet.class ) ); BasicHttpEntity entity = new BasicHttpEntity(); entity.setContent( new ByteArrayInputStream( DATA.getBytes() ) ); doReturn( entity ).when( response ).getEntity(); mockStatic( HttpClientManager.class ); when( HttpClientManager.getInstance() ).thenReturn( manager ); setInternalState( data, "realUrl", "http://pentaho.com" ); setInternalState( data, "argnrs", new int[ 0 ] ); doReturn( false ).when( meta ).isUrlInField(); doReturn( "body" ).when( meta ).getFieldName(); doReturn( false ).when( log ).isDetailed(); doCallRealMethod().when( http ).callHttpService( any( IRowMeta.class ), any( Object[].class ) ); doReturn( HttpURLConnection.HTTP_OK ).when( http ).requestStatusCode( any( CloseableHttpResponse.class ) ); doReturn( new Header[ 0 ] ).when( http ).searchForHeaders( any( CloseableHttpResponse.class ) ); setInternalState( http, "log", log ); setInternalState( http, "data", data ); setInternalState( http, "meta", meta ); } @Test public void callHttpServiceWithUTF8Encoding() throws Exception { doReturn( "UTF-8" ).when( meta ).getEncoding(); assertEquals( DATA, http.callHttpService( rmi, new Object[] { 0 } )[ 0 ] ); } @Test public void callHttpServiceWithoutEncoding() throws Exception { doReturn( null ).when( meta ).getEncoding(); assertNotEquals( DATA, http.callHttpService( rmi, new Object[] { 0 } )[ 0 ] ); } }
39,368
https://github.com/ErnstThalmann/2019-fall-polytech-cs/blob/master/Rosch-exs-1-2-2.py
Github Open Source
Open Source
MIT
null
2019-fall-polytech-cs
ErnstThalmann
Python
Code
47
163
def factorial(Number): factorial_value = 1 for i in range(1, Number+1): factorial_value *= i return factorial_value def distribution_options_top3(func): print(abs(func(Number)//(func(Number-3)))) def distribution_options_all(func): print(abs(func(Number))) print("Enter number of attendees: ") Number = int(input()) print('value of combinations at top three positions: ') distribution_options_top3(factorial) print('value of combinations at all positions : ') distribution_options_all(factorial)
33,740
https://github.com/Stratus3D/dotfiles/blob/master/vim/UltiSnips/sh.snippets
Github Open Source
Open Source
MIT
2,023
dotfiles
Stratus3D
Vim Snippet
Code
187
492
# Many of these snippets were taken from my own Bash scripts, or from places # like: # * https://betterdev.blog/minimal-safe-bash-script-template/ # * https://dougrichardson.us/2018/08/03/fail-fast-bash-scripting.html # * https://github.com/ralish/bash-script-template snippet shebang "The Bash shebang line I typically use" #!/usr/bin/env bash endsnippet snippet strict "My own Bash strict mode variation" # Unofficial Bash "strict mode" # http://redsymbol.net/articles/unofficial-bash-strict-mode/ set -euo pipefail #ORIGINAL_IFS=$IFS IFS=$'\t\n' # Stricter IFS settings endsnippet snippet tempdir "My own temp directory creating code" TEMP_DIR=$(mktemp -dt "$(basename \$0).XXXXXX") echo "Created temp directory $TEMP_DIR" cd $TEMP_DIR endsnippet snippet debugflag "Code to turn on tracing when the DEBUG env var is set" # Enable xtrace if the DEBUG environment variable is set if [[ ${DEBUG-} =~ ^1|yes|true$ ]]; then # Trace the execution of the script (debug) set -o xtrace fi endsnippet snippet errorexit "My own error exit function" error_exit() { printf "%s\\n" "\$1" 1>&2 exit "\${2:-1}" # default exit status 1 } endsnippet snippet usage "Usage function template" usage() { cat <<EOF Usage: $(basename "\$0") [-h] [-v] arg1 [arg2...] Script description here. Available options: -h, --help Print this help and exit -v, --verbose Print script debug info EOF exit } endsnippet
30,824
https://github.com/Philippe-Morin/azure-powershell/blob/master/src/ResourceManager/PolicyInsights/Commands.PolicyInsights/Cmdlets/GetAzureRmPolicyState.cs
Github Open Source
Open Source
MIT
null
azure-powershell
Philippe-Morin
C#
Code
1,188
4,168
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- namespace Microsoft.Azure.Commands.PolicyInsights.Cmdlets { using System; using System.Collections.Generic; using System.Linq; using System.Management.Automation; using Microsoft.Azure.Commands.PolicyInsights.Common; using Microsoft.Azure.Commands.PolicyInsights.Models; using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters; using Microsoft.Azure.Management.PolicyInsights; using RestApiModels = Microsoft.Azure.Management.PolicyInsights.Models; /// <summary> /// Gets policy states /// </summary> [Cmdlet(VerbsCommon.Get, "AzureRmPolicyState", DefaultParameterSetName = ParameterSetNames.SubscriptionScope), OutputType(typeof(PolicyState))] public class GetAzureRmPolicyState : PolicyInsightsCmdletBase { [Parameter(ParameterSetName = ParameterSetNames.ManagementGroupScope, Mandatory = false, HelpMessage = ParameterHelpMessages.All)] [Parameter(ParameterSetName = ParameterSetNames.SubscriptionScope, Mandatory = false, HelpMessage = ParameterHelpMessages.All)] [Parameter(ParameterSetName = ParameterSetNames.ResourceGroupScope, Mandatory = false, HelpMessage = ParameterHelpMessages.All)] [Parameter(ParameterSetName = ParameterSetNames.ResourceScope, Mandatory = false, HelpMessage = ParameterHelpMessages.All)] [Parameter(ParameterSetName = ParameterSetNames.PolicySetDefinitionScope, Mandatory = false, HelpMessage = ParameterHelpMessages.All)] [Parameter(ParameterSetName = ParameterSetNames.PolicyDefinitionScope, Mandatory = false, HelpMessage = ParameterHelpMessages.All)] [Parameter(ParameterSetName = ParameterSetNames.SubscriptionLevelPolicyAssignmentScope, Mandatory = false, HelpMessage = ParameterHelpMessages.All)] [Parameter(ParameterSetName = ParameterSetNames.ResourceGroupLevelPolicyAssignmentScope, Mandatory = false, HelpMessage = ParameterHelpMessages.All)] public SwitchParameter All { get; set; } [Parameter(ParameterSetName = ParameterSetNames.ManagementGroupScope, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = ParameterHelpMessages.ManagementGroupName)] [ValidateNotNullOrEmpty] public string ManagementGroupName { get; set; } [Parameter(ParameterSetName = ParameterSetNames.SubscriptionScope, Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = ParameterHelpMessages.SubscriptionId)] [Parameter(ParameterSetName = ParameterSetNames.ResourceGroupScope, Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = ParameterHelpMessages.SubscriptionId)] [Parameter(ParameterSetName = ParameterSetNames.PolicySetDefinitionScope, Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = ParameterHelpMessages.SubscriptionId)] [Parameter(ParameterSetName = ParameterSetNames.PolicyDefinitionScope, Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = ParameterHelpMessages.SubscriptionId)] [Parameter(ParameterSetName = ParameterSetNames.SubscriptionLevelPolicyAssignmentScope, Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = ParameterHelpMessages.SubscriptionId)] [Parameter(ParameterSetName = ParameterSetNames.ResourceGroupLevelPolicyAssignmentScope, Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = ParameterHelpMessages.SubscriptionId)] [ValidateNotNullOrEmpty] public string SubscriptionId { get; set; } [Parameter(ParameterSetName = ParameterSetNames.ResourceGroupScope, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = ParameterHelpMessages.ResourceGroupName)] [Parameter(ParameterSetName = ParameterSetNames.ResourceGroupLevelPolicyAssignmentScope, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = ParameterHelpMessages.ResourceGroupName)] [ResourceGroupCompleter] [ValidateNotNullOrEmpty] public string ResourceGroupName { get; set; } [Parameter(ParameterSetName = ParameterSetNames.ResourceScope, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = ParameterHelpMessages.ResourceId)] [ValidateNotNullOrEmpty] public string ResourceId { get; set; } [Parameter(ParameterSetName = ParameterSetNames.PolicySetDefinitionScope, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = ParameterHelpMessages.PolicySetDefinitionName)] [ValidateNotNullOrEmpty] public string PolicySetDefinitionName { get; set; } [Parameter(ParameterSetName = ParameterSetNames.PolicyDefinitionScope, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = ParameterHelpMessages.PolicyDefinitionName)] [ValidateNotNullOrEmpty] public string PolicyDefinitionName { get; set; } [Parameter(ParameterSetName = ParameterSetNames.SubscriptionLevelPolicyAssignmentScope, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = ParameterHelpMessages.PolicyAssignmentName)] [Parameter(ParameterSetName = ParameterSetNames.ResourceGroupLevelPolicyAssignmentScope, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = ParameterHelpMessages.PolicyAssignmentName)] [ValidateNotNullOrEmpty] public string PolicyAssignmentName { get; set; } [Parameter(ParameterSetName = ParameterSetNames.ManagementGroupScope, Mandatory = false, HelpMessage = ParameterHelpMessages.Top)] [Parameter(ParameterSetName = ParameterSetNames.SubscriptionScope, Mandatory = false, HelpMessage = ParameterHelpMessages.Top)] [Parameter(ParameterSetName = ParameterSetNames.ResourceGroupScope, Mandatory = false, HelpMessage = ParameterHelpMessages.Top)] [Parameter(ParameterSetName = ParameterSetNames.ResourceScope, Mandatory = false, HelpMessage = ParameterHelpMessages.Top)] [Parameter(ParameterSetName = ParameterSetNames.PolicySetDefinitionScope, Mandatory = false, HelpMessage = ParameterHelpMessages.Top)] [Parameter(ParameterSetName = ParameterSetNames.PolicyDefinitionScope, Mandatory = false, HelpMessage = ParameterHelpMessages.Top)] [Parameter(ParameterSetName = ParameterSetNames.SubscriptionLevelPolicyAssignmentScope, Mandatory = false, HelpMessage = ParameterHelpMessages.Top)] [Parameter(ParameterSetName = ParameterSetNames.ResourceGroupLevelPolicyAssignmentScope, Mandatory = false, HelpMessage = ParameterHelpMessages.Top)] public int Top { get; set; } [Parameter(ParameterSetName = ParameterSetNames.ManagementGroupScope, Mandatory = false, HelpMessage = ParameterHelpMessages.OrderBy)] [Parameter(ParameterSetName = ParameterSetNames.SubscriptionScope, Mandatory = false, HelpMessage = ParameterHelpMessages.OrderBy)] [Parameter(ParameterSetName = ParameterSetNames.ResourceGroupScope, Mandatory = false, HelpMessage = ParameterHelpMessages.OrderBy)] [Parameter(ParameterSetName = ParameterSetNames.ResourceScope, Mandatory = false, HelpMessage = ParameterHelpMessages.OrderBy)] [Parameter(ParameterSetName = ParameterSetNames.PolicySetDefinitionScope, Mandatory = false, HelpMessage = ParameterHelpMessages.OrderBy)] [Parameter(ParameterSetName = ParameterSetNames.PolicyDefinitionScope, Mandatory = false, HelpMessage = ParameterHelpMessages.OrderBy)] [Parameter(ParameterSetName = ParameterSetNames.SubscriptionLevelPolicyAssignmentScope, Mandatory = false, HelpMessage = ParameterHelpMessages.OrderBy)] [Parameter(ParameterSetName = ParameterSetNames.ResourceGroupLevelPolicyAssignmentScope, Mandatory = false, HelpMessage = ParameterHelpMessages.OrderBy)] [ValidateNotNullOrEmpty] public string OrderBy { get; set; } [Parameter(ParameterSetName = ParameterSetNames.ManagementGroupScope, Mandatory = false, HelpMessage = ParameterHelpMessages.Select)] [Parameter(ParameterSetName = ParameterSetNames.SubscriptionScope, Mandatory = false, HelpMessage = ParameterHelpMessages.Select)] [Parameter(ParameterSetName = ParameterSetNames.ResourceGroupScope, Mandatory = false, HelpMessage = ParameterHelpMessages.Select)] [Parameter(ParameterSetName = ParameterSetNames.ResourceScope, Mandatory = false, HelpMessage = ParameterHelpMessages.Select)] [Parameter(ParameterSetName = ParameterSetNames.PolicySetDefinitionScope, Mandatory = false, HelpMessage = ParameterHelpMessages.Select)] [Parameter(ParameterSetName = ParameterSetNames.PolicyDefinitionScope, Mandatory = false, HelpMessage = ParameterHelpMessages.Select)] [Parameter(ParameterSetName = ParameterSetNames.SubscriptionLevelPolicyAssignmentScope, Mandatory = false, HelpMessage = ParameterHelpMessages.Select)] [Parameter(ParameterSetName = ParameterSetNames.ResourceGroupLevelPolicyAssignmentScope, Mandatory = false, HelpMessage = ParameterHelpMessages.Select)] [ValidateNotNullOrEmpty] public string Select { get; set; } [Parameter(ParameterSetName = ParameterSetNames.ManagementGroupScope, Mandatory = false, HelpMessage = ParameterHelpMessages.From)] [Parameter(ParameterSetName = ParameterSetNames.SubscriptionScope, Mandatory = false, HelpMessage = ParameterHelpMessages.From)] [Parameter(ParameterSetName = ParameterSetNames.ResourceGroupScope, Mandatory = false, HelpMessage = ParameterHelpMessages.From)] [Parameter(ParameterSetName = ParameterSetNames.ResourceScope, Mandatory = false, HelpMessage = ParameterHelpMessages.From)] [Parameter(ParameterSetName = ParameterSetNames.PolicySetDefinitionScope, Mandatory = false, HelpMessage = ParameterHelpMessages.From)] [Parameter(ParameterSetName = ParameterSetNames.PolicyDefinitionScope, Mandatory = false, HelpMessage = ParameterHelpMessages.From)] [Parameter(ParameterSetName = ParameterSetNames.SubscriptionLevelPolicyAssignmentScope, Mandatory = false, HelpMessage = ParameterHelpMessages.From)] [Parameter(ParameterSetName = ParameterSetNames.ResourceGroupLevelPolicyAssignmentScope, Mandatory = false, HelpMessage = ParameterHelpMessages.From)] public DateTime From { get; set; } [Parameter(ParameterSetName = ParameterSetNames.ManagementGroupScope, Mandatory = false, HelpMessage = ParameterHelpMessages.To)] [Parameter(ParameterSetName = ParameterSetNames.SubscriptionScope, Mandatory = false, HelpMessage = ParameterHelpMessages.To)] [Parameter(ParameterSetName = ParameterSetNames.ResourceGroupScope, Mandatory = false, HelpMessage = ParameterHelpMessages.To)] [Parameter(ParameterSetName = ParameterSetNames.ResourceScope, Mandatory = false, HelpMessage = ParameterHelpMessages.To)] [Parameter(ParameterSetName = ParameterSetNames.PolicySetDefinitionScope, Mandatory = false, HelpMessage = ParameterHelpMessages.To)] [Parameter(ParameterSetName = ParameterSetNames.PolicyDefinitionScope, Mandatory = false, HelpMessage = ParameterHelpMessages.To)] [Parameter(ParameterSetName = ParameterSetNames.SubscriptionLevelPolicyAssignmentScope, Mandatory = false, HelpMessage = ParameterHelpMessages.To)] [Parameter(ParameterSetName = ParameterSetNames.ResourceGroupLevelPolicyAssignmentScope, Mandatory = false, HelpMessage = ParameterHelpMessages.To)] public DateTime To { get; set; } [Parameter(ParameterSetName = ParameterSetNames.ManagementGroupScope, Mandatory = false, HelpMessage = ParameterHelpMessages.Filter)] [Parameter(ParameterSetName = ParameterSetNames.SubscriptionScope, Mandatory = false, HelpMessage = ParameterHelpMessages.Filter)] [Parameter(ParameterSetName = ParameterSetNames.ResourceGroupScope, Mandatory = false, HelpMessage = ParameterHelpMessages.Filter)] [Parameter(ParameterSetName = ParameterSetNames.ResourceScope, Mandatory = false, HelpMessage = ParameterHelpMessages.Filter)] [Parameter(ParameterSetName = ParameterSetNames.PolicySetDefinitionScope, Mandatory = false, HelpMessage = ParameterHelpMessages.Filter)] [Parameter(ParameterSetName = ParameterSetNames.PolicyDefinitionScope, Mandatory = false, HelpMessage = ParameterHelpMessages.Filter)] [Parameter(ParameterSetName = ParameterSetNames.SubscriptionLevelPolicyAssignmentScope, Mandatory = false, HelpMessage = ParameterHelpMessages.Filter)] [Parameter(ParameterSetName = ParameterSetNames.ResourceGroupLevelPolicyAssignmentScope, Mandatory = false, HelpMessage = ParameterHelpMessages.Filter)] [ValidateNotNullOrEmpty] public string Filter { get; set; } [Parameter(ParameterSetName = ParameterSetNames.ManagementGroupScope, Mandatory = false, HelpMessage = ParameterHelpMessages.Apply)] [Parameter(ParameterSetName = ParameterSetNames.SubscriptionScope, Mandatory = false, HelpMessage = ParameterHelpMessages.Apply)] [Parameter(ParameterSetName = ParameterSetNames.ResourceGroupScope, Mandatory = false, HelpMessage = ParameterHelpMessages.Apply)] [Parameter(ParameterSetName = ParameterSetNames.ResourceScope, Mandatory = false, HelpMessage = ParameterHelpMessages.Apply)] [Parameter(ParameterSetName = ParameterSetNames.PolicySetDefinitionScope, Mandatory = false, HelpMessage = ParameterHelpMessages.Apply)] [Parameter(ParameterSetName = ParameterSetNames.PolicyDefinitionScope, Mandatory = false, HelpMessage = ParameterHelpMessages.Apply)] [Parameter(ParameterSetName = ParameterSetNames.SubscriptionLevelPolicyAssignmentScope, Mandatory = false, HelpMessage = ParameterHelpMessages.Apply)] [Parameter(ParameterSetName = ParameterSetNames.ResourceGroupLevelPolicyAssignmentScope, Mandatory = false, HelpMessage = ParameterHelpMessages.Apply)] [ValidateNotNullOrEmpty] public string Apply { get; set; } /// <summary> /// Executes the cmdlet /// </summary> public override void ExecuteCmdlet() { var queryOptions = new RestApiModels.QueryOptions { Top = MyInvocation.BoundParameters.ContainsKey("Top") ? (int?)Top : null, OrderBy = OrderBy, Select = Select, FromProperty = MyInvocation.BoundParameters.ContainsKey("From") ? (DateTime?)From : null, To = MyInvocation.BoundParameters.ContainsKey("To") ? (DateTime?)To : null, Filter = Filter, Apply = Apply }; RestApiModels.PolicyStatesQueryResults policyStatesQueryResults; var policyStatesResource = !All.IsPresent ? RestApiModels.PolicyStatesResource.Latest : RestApiModels.PolicyStatesResource.Default; try { switch (ParameterSetName) { case ParameterSetNames.ManagementGroupScope: policyStatesQueryResults = PolicyInsightsClient.PolicyStates.ListQueryResultsForManagementGroup( policyStatesResource, ManagementGroupName, queryOptions); break; case ParameterSetNames.SubscriptionScope: policyStatesQueryResults = PolicyInsightsClient.PolicyStates.ListQueryResultsForSubscription( policyStatesResource, SubscriptionId ?? DefaultContext.Subscription.Id, queryOptions); break; case ParameterSetNames.ResourceGroupScope: policyStatesQueryResults = PolicyInsightsClient.PolicyStates.ListQueryResultsForResourceGroup( policyStatesResource, SubscriptionId ?? DefaultContext.Subscription.Id, ResourceGroupName, queryOptions); break; case ParameterSetNames.ResourceScope: policyStatesQueryResults = PolicyInsightsClient.PolicyStates.ListQueryResultsForResource( policyStatesResource, ResourceId, queryOptions); break; case ParameterSetNames.PolicySetDefinitionScope: policyStatesQueryResults = PolicyInsightsClient.PolicyStates.ListQueryResultsForPolicySetDefinition( policyStatesResource, SubscriptionId ?? DefaultContext.Subscription.Id, PolicySetDefinitionName, queryOptions); break; case ParameterSetNames.PolicyDefinitionScope: policyStatesQueryResults = PolicyInsightsClient.PolicyStates.ListQueryResultsForPolicyDefinition( policyStatesResource, SubscriptionId ?? DefaultContext.Subscription.Id, PolicyDefinitionName, queryOptions); break; case ParameterSetNames.SubscriptionLevelPolicyAssignmentScope: policyStatesQueryResults = PolicyInsightsClient.PolicyStates.ListQueryResultsForSubscriptionLevelPolicyAssignment( policyStatesResource, SubscriptionId ?? DefaultContext.Subscription.Id, PolicyAssignmentName, queryOptions); break; case ParameterSetNames.ResourceGroupLevelPolicyAssignmentScope: policyStatesQueryResults = PolicyInsightsClient.PolicyStates.ListQueryResultsForResourceGroupLevelPolicyAssignment( policyStatesResource, SubscriptionId ?? DefaultContext.Subscription.Id, ResourceGroupName, PolicyAssignmentName, queryOptions); break; default: throw new PSInvalidOperationException(); } } catch (RestApiModels.QueryFailureException e) { WriteExceptionError(e.Body?.Error != null ? new Exception($"{e.Message} ({e.Body.Error.Code}: {e.Body.Error.Message})") : e); return; } WriteObject(policyStatesQueryResults.Value.Select(policyState => new PolicyState(policyState)), true); } } }
49,459
https://github.com/dewpey/GlobalHealth/blob/master/.gitignore
Github Open Source
Open Source
MIT
2,018
GlobalHealth
dewpey
Ignore List
Code
12
125
Server/vaccine_checker.py Server/Tierion_check.py Server/raw_data.csv Server/medicaid.pyc Server/medicaid.py Server/BetterDoctor.py Server/BetterDoctor.js Server/__pycache__/medicaid.cpython-36.pyc Server/__pycache__/insuranceinfo.cpython-37.pyc Server/.DS_Store .DS_Store Xcode/GlobalHealth/Pods/
33,410
https://github.com/arielhenryson/Socotra/blob/master/src/public/app/app.component.spec.ts
Github Open Source
Open Source
MIT
2,016
Socotra
arielhenryson
TypeScript
Code
87
233
import { TestBed } from '@angular/core/testing' import { App } from './app.component' import { BrowserDynamicTestingModule, platformBrowserDynamicTesting } from '@angular/platform-browser-dynamic/testing' import { RouterTestingModule } from '@angular/router/testing' let fixture let comp describe('1st tests', () => { beforeEach(() => { TestBed.initTestEnvironment( BrowserDynamicTestingModule, platformBrowserDynamicTesting() ) // refine the test module by declaring the test component TestBed.configureTestingModule({ declarations: [ App ], imports: [ RouterTestingModule ] }) // create component and test fixture fixture = TestBed.createComponent(App) // get test component from the fixture comp = fixture.componentInstance }) it('test value', () => expect(comp.testValue).toBe('test')) })
50,203
https://github.com/majk1/netbeans-mmd-plugin/blob/master/mind-map/nb-mind-map/src/main/java/com/igormaznitsa/nbmindmap/nb/refactoring/MindMapLink.java
Github Open Source
Open Source
Apache-2.0
2,022
netbeans-mmd-plugin
majk1
Java
Code
455
1,279
/* * Copyright 2015-2018 Igor Maznitsa. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.igormaznitsa.nbmindmap.nb.refactoring; import com.igormaznitsa.mindmap.model.MindMap; import com.igormaznitsa.mindmap.model.logger.Logger; import com.igormaznitsa.mindmap.model.logger.LoggerFactory; import com.igormaznitsa.nbmindmap.nb.editor.MMDDataObject; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.io.StringReader; import org.apache.commons.io.IOUtils; import org.openide.filesystems.FileAlreadyLockedException; import org.openide.filesystems.FileLock; import org.openide.filesystems.FileObject; import org.openide.filesystems.FileUtil; import org.openide.loaders.DataObject; import org.openide.loaders.DataObjectNotFoundException; public class MindMapLink { private static final Logger LOGGER = LoggerFactory.getLogger(MindMapLink.class); private final DataObject dataObject; private volatile FileObject theFile; private volatile MindMap model; public MindMapLink(final FileObject file) { this.theFile = file; this.dataObject = findDataObject(file); } private static DataObject findDataObject(final FileObject fileObj) { DataObject doj = null; if (fileObj != null) { try { doj = DataObject.find(fileObj); } catch (DataObjectNotFoundException ex) { LOGGER.warn("Can't find data object for file " + fileObj); } } return doj; } public FileObject getFile() { DataObject doj = this.dataObject == null ? findDataObject(this.theFile) : this.dataObject; return doj == null ? this.theFile : doj.getPrimaryFile(); } public File asFile() { File result = null; final FileObject fo = getFile(); if (fo != null) { result = FileUtil.toFile(fo); } else { LOGGER.warn("Can't find file object [" + this.dataObject + "; " + this.theFile + ']'); } return result; } private void delay(final long time) { try { Thread.sleep(time); } catch (InterruptedException ex) { LOGGER.warn("Delay has been interrupted"); Thread.currentThread().interrupt(); } } private FileLock lock(final FileObject fo) throws IOException { if (fo != null) { FileLock lock = null; while (!Thread.currentThread().isInterrupted()) { try { lock = fo.lock(); break; } catch (FileAlreadyLockedException ex) { delay(500L); } } return lock; } else { return null; } } public void writeUTF8Text(final String text) throws IOException { final FileObject foj = getFile(); final FileLock flock = lock(foj); try { final OutputStream out = foj.getOutputStream(flock); try { IOUtils.write(text, out, "UTF-8"); } finally { IOUtils.closeQuietly(out); } } finally { flock.releaseLock(); } final DataObject doj = DataObject.find(foj); if (doj instanceof MMDDataObject) { LOGGER.info("Notify about change primary file"); ((MMDDataObject) doj).firePrimaryFileChanged(); } } public String readUTF8Text() throws IOException { final FileObject foj = getFile(); final FileLock flock = lock(foj); try { return foj.asText("UTF-8"); } finally { flock.releaseLock(); } } public synchronized MindMap asMindMap() throws IOException { if (this.model == null) { this.model = new MindMap(new StringReader(readUTF8Text())); } return this.model; } public synchronized void writeMindMap() throws IOException { if (this.model != null) { writeUTF8Text(this.model.packToString()); } } }
30,637
https://github.com/openopt/copt/blob/master/ci/test.sh
Github Open Source
Open Source
BSD-3-Clause
2,023
copt
openopt
Shell
Code
56
165
#!/bin/sh # pip install -r requirements.txt pip install pytest-parallel # run tests in parallel python setup.py install # py.test --workers auto # pylint pip install pylint anybadge pylint --rcfile=ci/pylintrc --output-format=text copt tests/*.py examples/*.py examples/*/*.py | tee pylint.txt score=$(sed -n 's/^Your code has been rated at \([-0-9.]*\)\/.*/\1/p' pylint.txt) echo "Pylint score was $score" anybadge --value=$score --file=pylint.svg pylint
26,225
https://github.com/vandermerwewaj/RED4ext.SDK/blob/master/include/RED4ext/Scripting/Natives/Generated/anim/CurvePathBakerAdvancedUserInput.hpp
Github Open Source
Open Source
MIT
2,021
RED4ext.SDK
vandermerwewaj
C++
Code
60
201
#pragma once // This file is generated from the Game's Reflection data #include <cstdint> #include <RED4ext/Common.hpp> #include <RED4ext/NativeTypes.hpp> #include <RED4ext/Scripting/Natives/Generated/anim/CurvePathPartInput.hpp> namespace RED4ext { namespace anim { struct CurvePathBakerAdvancedUserInput { static constexpr const char* NAME = "animCurvePathBakerAdvancedUserInput"; static constexpr const char* ALIAS = NAME; alignas(8) StaticArray<anim::CurvePathPartInput, 3> partsInputs; // 00 }; RED4EXT_ASSERT_SIZE(CurvePathBakerAdvancedUserInput, 0x80); } // namespace anim } // namespace RED4ext
179
https://github.com/WhitingHuo/apollo/blob/master/modules/v2x/fusion/libs/fusion/test_tools.h
Github Open Source
Open Source
Apache-2.0
null
apollo
WhitingHuo
C
Code
312
892
/****************************************************************************** * Copyright 2020 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include <fstream> #include <iostream> #include <string> #include <vector> #include "modules/v2x/fusion/libs/common/base/v2x_object.h" namespace apollo { namespace v2x { namespace ft { bool LoadData(const std::string& file, std::vector<base::Object>* objects, const std::string& frame_id) { std::fstream fin; fin.open(file.c_str(), std::ios::in); if (!fin) { return false; } std::string line; while (getline(fin, line)) { std::istringstream iss(line); float sub_type_probs, x, y, z, xx, xy, xz, yx, yy, yz, zx, zy, zz; Eigen::Vector3d pos; Eigen::Matrix3d var; int type, sub_type; iss >> type >> sub_type >> sub_type_probs >> x >> y >> z >> xx >> xy >> xz >> yx >> yy >> yz >> zx >> zy >> zz; pos << x, y, z; var << xx, xy, xz, yx, yy, yz, zx, zy, zz; base::Object obj; obj.type = base::ObjectType::VEHICLE; Eigen::Vector3d car_size, bus_size, van_size; Eigen::Matrix3d id_var; car_size << 4.2, 2.0, 1.8; bus_size << 12, 2.2, 3; van_size << 4.5, 2.1, 2; id_var << 1, 0, 0, 0, 1, 0, 0, 0, 1; switch (sub_type) { case 3: obj.sub_type = base::ObjectSubType::CAR; obj.size.Set(car_size, id_var); break; case 4: obj.sub_type = base::ObjectSubType::VAN; obj.size.Set(van_size, id_var); break; case 5: obj.sub_type = base::ObjectSubType::BUS; obj.size.Set(bus_size, id_var); break; default: break; } obj.sensor_type = base::SensorType::MONOCULAR_CAMERA; obj.frame_id = frame_id; obj.position.Set(pos, var); obj.theta.Set(0, 1); obj.type_probs.push_back(0.9f); obj.sub_type_probs.push_back(sub_type_probs); objects->push_back(obj); } return true; } } // namespace ft } // namespace v2x } // namespace apollo
19,531