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/serghalak/otus_java_2020_03/blob/master/L22-noSQL/cassandra-demo/src/main/java/ru/otus/cassandrademo/db/PhoneRepository.java
Github Open Source
Open Source
MIT
2,021
otus_java_2020_03
serghalak
Java
Code
29
109
package ru.otus.cassandrademo.db; import java.util.List; import java.util.Optional; import java.util.UUID; public interface PhoneRepository { <T> void insert(T phone, Class<T> tClass); <T> Optional<T> findOne(UUID id, Class<T> tClass); <T> List<T> findAll(Class<T> tClass); }
15,845
https://github.com/chenjiaxing6/pocket-shop/blob/master/pocket-shop-web-ui/src/main/java/cn/ishangit/shop/web/ui/dto/UserDto.java
Github Open Source
Open Source
Apache-2.0
2,020
pocket-shop
chenjiaxing6
Java
Code
31
88
package cn.ishangit.shop.web.ui.dto; import lombok.Data; /** * @description: * @author: Chen * @create: 2019-05-31 22:23 **/ @Data public class UserDto { private String username; private String phone ; private String email; }
48,858
https://github.com/ANONYMOUS609/Competitive-Programming/blob/master/practice/Algorithms/Divide and Conquer/mergeSort.cpp
Github Open Source
Open Source
MIT
2,021
Competitive-Programming
ANONYMOUS609
C++
Code
77
461
#include<bits/stdc++.h> using namespace std; void merge(int A[],int p,int q,int r) { int i,j,n1,n2; n1=q-p+1; n2=r-q; int L[n1+1],R[n2+1]; for(i=1;i<=n1;i++) L[i]=A[p+i-1]; for(j=1;j<=n2;j++) R[j]=A[q+j]; L[n1+1]=100000000; R[n2+1]=100000000; i=1;j=1; for(int k=p;k<=r;k++) { if(L[i]<=R[j]) { A[k]=L[i]; i=i+1; } else { A[k]=R[j]; j=j+1; } } } void merge_sort(int A[],int p,int r) { int q=(p+r)/2; if(p<r) { merge_sort(A,p,q); merge_sort(A,q+1,r); merge(A,p,q,r); } } int main() { int n; printf("enter size of array:\n"); cin>>n; int A[n]; for(int i=1;i<=n;i++) cin>>A[i]; merge_sort(A,1,n); for(int j=1;j<=n;j++) cout<<A[j]<<" "; return 0; }
14,050
https://github.com/NikitaKemarskiy/online-file-repository/blob/master/api/functions/logging.js
Github Open Source
Open Source
MIT
null
online-file-repository
NikitaKemarskiy
JavaScript
Code
123
394
// Modules const path = require('path'); const fs = require('fs'); // Constants const LOGS_PATH = path.join(process.cwd(), 'logs'); // Constant value for storage folder const LOGS_FILE = 'logs.txt'; const ERROR_FILE = 'error.txt'; let log_stream = null; let error_stream = null; const start_logging = function() { let log_path = path.join(LOGS_PATH, LOGS_FILE); let error_path = path.join(LOGS_PATH, ERROR_FILE); log_stream = fs.createWriteStream(log_path); error_stream = fs.createWriteStream(error_path); } const end_logging = function() { log_stream.end(); error_stream.end(); } const log = function(str) { console.log(str); str = str.toString(); str = str.concat('\n'); log_stream.write(str, 'utf8'); } const dir = function(str) { console.dir(str); str = str.toString(); str = str.concat('\n'); log_stream.write(str, 'utf8'); } const error = function(str) { console.error(str); str = str.toString(); str = str.concat('\n'); error_stream.write(str, 'utf8'); } module.exports = { start_logging, end_logging, log, dir, error };
3,203
https://github.com/pawanakhil/fractional-nft/blob/master/packages/react-app/src/supabaseConfig.js
Github Open Source
Open Source
MIT
2,022
fractional-nft
pawanakhil
JavaScript
Code
15
23
export const imageBaseUrl = ""; export const projectUrl = ""; export const projectKey = "";
24,764
https://github.com/ratebkefi/site_deal/blob/master/src/Back/DealBundle/Resources/views/Deal/coupon.html.twig
Github Open Source
Open Source
MIT
null
site_deal
ratebkefi
Twig
Code
481
1,430
{% set commFix = 0 %} {% set commVar = 0 %} {% set CA = 0 %} {% set PrixCoupon = 0 %} {% set CVariable = 0 %} <!-- ==================== DEFAULT TABLE FLOATING BOX ==================== --> <div class="floatingBox table"> <div class="container-fluid"> <table class="table"> <thead> <tr> <th class="hidden"><label><input type="checkbox" checked ="checked" name="all" id="all"/> Sélectionner tout</label></th> <th>N° Coupon</th> <th>Prix</th> <th>Etat de vente</th> <th>Etat de reception</th> </tr> </thead> <tbody> {% set nbr = entities | length %} {% for item in entities %} <!-- <input id="{{ item.id }}" type="checkbox" class="" checked="checked" name="coupon[]" value="{{ item.id }}" onclick="modifFacture({{ item.id }} , {{ item.price }})" > <label class="css-label" for="{{ item.id }}">{{ item.code }} Prix : {{ item.price }} TND Etat de vente : {{ item.vendu|getVenduCoupon }} Etat de reception : {{ item.recu|getRecuCoupon }} </label> --> <tr id="tr{{ item.id }}"> <td class="hidden"><input id="{{ item.id }}" class="itemcheck" type="checkbox" checked="checked" name="coupon[]" value="{{ item.id }}" onclick="modifFacture({{ item.id }} , {{ item.price }})" ></td> <td>{{ item.code }}</td> <td>{{ item.price }} TND</td> <td>{{ item.vendu|getVenduCoupon }}</td> <td>{{ item.recu|getRecuCoupon }}</td> </tr> {% if facture==0 %} {% set commFix = item.fixedCommission %} {% endif %} {% set commVar = item.variableCommission %} {% if item.vendu ==3 %} {% set PrixCoupon = PrixCoupon + item.price %} {% endif %} {% endfor %} </tbody> </table> </div> </div> {% set CA = PrixCoupon %} {% set CVariable = (CA - minprice*nbrgratuit) * commVar/100 %} <span class="label badge" >Recette : {{ PrixCoupon }} TND</span> <span class="label badge-important" id="span_ca">Chiffre d'affaire : {{ CA - minprice*nbrgratuit }} TND</span> <span class="label badge-primary" >Gratuité : {{ minprice*nbrgratuit }} TND</span> <span class="label badge-warning" id="com_fixe">Commission Fixe : {{ commFix }} TND</span> <span class="label badge-success" id="span_com_variable">Commission Variable : {{ CVariable }} TND</span> <span class="label badge-info" >Commission TTC : {{ CVariable + commFix }} TND</span> <input type="hidden" value="{{ CA }}" name="ca" id="ca" > <input type="hidden" value="{{ CVariable }}" name="com_variable" id="com_variable" > <input type="hidden" value="{{ commFix }}" name="com_fixe" id="com_fixe"> {% block javascripts %} <script> var price =new Array(); {% for item in entities %} price[{{ item.id }}]={{ item.price }}; {% endfor %} function modifFacture(idCoupon,prixCoupon) { var CA = $("#ca").val(); var NewCA = 0; var ComVariable = 0; if( $('#' + idCoupon).is(':checked') ){ //add NewCA = parseFloat( CA ) + prixCoupon; $("#ca").val(NewCA); $('#span_ca').html("Chiffre d'affaire : " + NewCA + " TND"); } else { //moins NewCA = parseFloat( CA ) - prixCoupon; $("#ca").val(NewCA) ; $('#span_ca').html("Chiffre d'affaire : " + NewCA + " TND"); } ComVariable = parseFloat(NewCA * {{ commVar }}/100) ; $("#com_variable").val(ComVariable); $('#span_com_variable').html("Commission Variable : " + ComVariable + " TND"); } $(document).ready(function () { $('#all').click(function (event) { //on click if (this.checked) { // check select status $('.itemcheck').each(function () { //loop through each checkbox this.checked = true; //select all checkboxes with class "checkbox1" modifFacture($(this).val() , price[$(this).val()]) ///console.log(price) }); } else { $('.itemcheck').each(function () { //loop through each checkbox this.checked = false; //deselect all checkboxes with class "checkbox1" modifFacture($(this).val() , price[$(this).val()]) }); } }); }); </script> {% endblock %}
51,189
https://github.com/Laul0/generator-spfx/blob/master/generators/handlebars/templates/gulpfile.js
Github Open Source
Open Source
MIT
2,022
generator-spfx
Laul0
JavaScript
Code
66
199
// definition of Handlebars loader const loaderConfig = { test: /\.hbs/, loader: 'handlebars-loader' }; // Merge custom loader to web pack configuration build.configureWebpack.mergeConfig({ additionalConfiguration: (generatedConfiguration) => { generatedConfiguration.module.rules.push(loaderConfig); return generatedConfiguration; } }); // register custom watch for hbbs.JS files // copy of '.hba' files will be handled by 'copy-static-assets.json' gulp.watch('./src/**/*.hbs', event => { // copy empty index.ts onto itself to launch build procees gulp.src('./src/index.ts') .pipe(gulp.dest('./src/')); });
33,672
https://github.com/caponetto/kogito-editors-java/blob/master/errai-ioc/src/main/java/org/jboss/errai/ioc/rebind/ioc/bootstrapper/FactoryGenerator.java
Github Open Source
Open Source
Apache-2.0
2,021
kogito-editors-java
caponetto
Java
Code
801
2,687
/* * Copyright (C) 2015 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.errai.ioc.rebind.ioc.bootstrapper; import static org.jboss.errai.codegen.builder.impl.ClassBuilder.define; import static org.jboss.errai.codegen.meta.MetaClassFactory.parameterizedAs; import static org.jboss.errai.codegen.meta.MetaClassFactory.typeParametersOf; import java.io.PrintWriter; import java.util.HashMap; import java.util.Map; import org.jboss.errai.codegen.builder.ClassStructureBuilder; import org.jboss.errai.codegen.meta.MetaClassMember; import org.jboss.errai.codegen.meta.MetaParameter; import org.jboss.errai.common.metadata.RebindUtils; import org.jboss.errai.ioc.client.container.Factory; import org.jboss.errai.ioc.rebind.ioc.graph.api.CustomFactoryInjectable; import org.jboss.errai.ioc.rebind.ioc.graph.api.DependencyGraph; import org.jboss.errai.ioc.rebind.ioc.graph.api.DependencyGraphBuilder.Dependency; import org.jboss.errai.ioc.rebind.ioc.graph.api.DependencyGraphBuilder.InjectableType; import org.jboss.errai.ioc.rebind.ioc.graph.api.Injectable; import org.jboss.errai.ioc.rebind.ioc.injector.api.InjectionContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.gwt.core.ext.GeneratorContext; import com.google.gwt.core.ext.IncrementalGenerator; import com.google.gwt.core.ext.RebindMode; import com.google.gwt.core.ext.RebindResult; import com.google.gwt.core.ext.TreeLogger; import com.google.gwt.core.ext.UnableToCompleteException; /** * Generates {@link Factory} subclasses by dispatching to the appropriate * {@link FactoryBodyGenerator} and writing the output. * * @author Max Barkley <mbarkley@redhat.com> */ public class FactoryGenerator extends IncrementalGenerator { private static final Logger log = LoggerFactory.getLogger(FactoryGenerator.class); private static final String GENERATED_PACKAGE = "org.jboss.errai.ioc.client"; private static DependencyGraph graph; private static InjectionContext injectionContext; private static Map<String, String> generatedSourceByFactoryTypeName = new HashMap<String, String>(); private static Map<String, Injectable> injectablesByFactoryTypeName = new HashMap<String, Injectable>(); private static long totalTime; public static void resetTotalTime() { totalTime = 0; } public static void setDependencyGraph(final DependencyGraph graph) { log.debug("Dependency graph set."); FactoryGenerator.graph = graph; } public static DependencyGraph getDependencyGraph() { return graph; } public static void setInjectionContext(final InjectionContext injectionContext) { log.debug("Injection context set."); FactoryGenerator.injectionContext = injectionContext; } public static String getLocalVariableName(final MetaParameter param) { final MetaClassMember member = param.getDeclaringMember(); return member.getName() + "_" + param.getName() + "_" + param.getIndex(); } private static DependencyGraph assertGraphSet() { if (graph == null) { throw new RuntimeException("Dependency graph must be generated and set before " + FactoryGenerator.class.getSimpleName() + " runs."); } return graph; } private static InjectionContext assertInjectionContextSet() { if (injectionContext == null) { throw new RuntimeException("Injection context must be set before " + FactoryGenerator.class.getSimpleName() + " runs."); } return injectionContext; } @Override public RebindResult generateIncrementally(final TreeLogger logger, final GeneratorContext generatorContext, final String typeName) throws UnableToCompleteException { final long start = System.currentTimeMillis(); final DependencyGraph graph = assertGraphSet(); final InjectionContext injectionContext = assertInjectionContextSet(); final Injectable injectable = graph.getConcreteInjectable(typeName.substring(typeName.lastIndexOf('.')+1)); final InjectableType factoryType = injectable.getInjectableType(); final ClassStructureBuilder<?> factoryBuilder = define(getFactorySubTypeName(typeName), parameterizedAs(Factory.class, typeParametersOf(injectable.getInjectedType()))).publicScope().body(); final FactoryBodyGenerator generator = selectBodyGenerator(factoryType, typeName, injectable); final String factorySimpleClassName = getFactorySubTypeSimpleName(typeName); final PrintWriter pw = generatorContext.tryCreate(logger, GENERATED_PACKAGE, factorySimpleClassName); final RebindResult retVal; if (pw != null) { final String factorySource; if (isCacheUsable(typeName, injectable)) { log.debug("Reusing cached factory for " + typeName); factorySource = generatedSourceByFactoryTypeName.get(typeName); } else { log.debug("Generating factory for " + typeName); generator.generate(factoryBuilder, injectable, graph, injectionContext, logger, generatorContext); factorySource = factoryBuilder.toJavaString(); generatedSourceByFactoryTypeName.put(typeName, factorySource); injectablesByFactoryTypeName.put(typeName, injectable); writeToDotErraiFolder(factorySimpleClassName, factorySource); } pw.write(factorySource); generatorContext.commit(logger, pw); retVal = new RebindResult(RebindMode.USE_ALL_NEW, factoryBuilder.getClassDefinition().getFullyQualifiedName()); } else { log.debug("Reusing factory for " + typeName); retVal = new RebindResult(RebindMode.USE_EXISTING, getFactorySubTypeName(typeName)); } final long ellapsed = System.currentTimeMillis() - start; totalTime += ellapsed; log.debug("Factory for {} completed in {}ms. Total factory generation time: {}ms", typeName, ellapsed, totalTime); return retVal; } private void writeToDotErraiFolder(final String factorySimpleClassName, final String factorySource) { RebindUtils.writeStringToJavaSourceFileInErraiCacheDir(GENERATED_PACKAGE, factorySimpleClassName, factorySource); } private boolean isCacheUsable(final String typeName, final Injectable givenInjectable) { if (RebindUtils.NO_CACHE) { return false; } final Injectable cachedInjectable = injectablesByFactoryTypeName.get(typeName); if (cachedInjectable != null) { final boolean sameContent = cachedInjectable.hashContent() == givenInjectable.hashContent(); if (log.isTraceEnabled() && !sameContent) { log.trace("Different hashContent for cached " + typeName); traceConstituentHashContents(cachedInjectable, "cached " + typeName); traceConstituentHashContents(givenInjectable, "new " + typeName); } return sameContent; } else { log.trace("No cached injectable was found for {}", typeName); return false; } } private static void traceConstituentHashContents(final Injectable injectable, final String name) { log.trace("Begin trace of hashContent for {}", name); log.trace("Combined content: {}", injectable.hashContent()); log.trace("HashContent for injectable type: {}", injectable.getInjectedType().hashContent()); for (final Dependency dep : injectable.getDependencies()) { log.trace("HashContent for {} dep of type {}: {}", dep.getDependencyType().toString(), dep.getInjectable().getInjectedType(), dep.getInjectable().getInjectedType().hashContent()); } log.trace("End trace of hashContent for {}", name); } private FactoryBodyGenerator selectBodyGenerator(final InjectableType factoryType, final String typeName, final Injectable injectable) { final FactoryBodyGenerator generator; switch (factoryType) { case Type: generator = new TypeFactoryBodyGenerator(); break; case Provider: generator = new ProviderFactoryBodyGenerator(); break; case JsType: generator = new JsTypeFactoryBodyGenerator(); break; case Producer: generator = new ProducerFactoryBodyGenerator(); break; case ContextualProvider: generator = new ContextualFactoryBodyGenerator(); break; case ExtensionProvided: if (!(injectable instanceof CustomFactoryInjectable)) { throw new RuntimeException(String.format("The injectable, %s, for %s is extension provided but is not a %s", injectable.toString(), typeName, CustomFactoryInjectable.class.getSimpleName())); } generator = ((CustomFactoryInjectable) injectable).getGenerator(); break; default: throw new RuntimeException(factoryType + " not yet implemented!"); } return generator; } public static String getFactorySubTypeName(final String typeName) { return GENERATED_PACKAGE + "." + getFactorySubTypeSimpleName(typeName); } public static String getFactorySubTypeSimpleName(final String typeName) { final int simpleNameStart = Math.max(typeName.lastIndexOf('.'), typeName.lastIndexOf('$')) + 1; return typeName.substring(simpleNameStart); } @Override public long getVersionId() { return 1; } }
5,480
https://github.com/a2x1/factorio_a2x1_military_kit/blob/master/resources/data_raw_projectile.lua
Github Open Source
Open Source
MIT
null
factorio_a2x1_military_kit
a2x1
Lua
Code
244
813
require "shared" local settings_key_prefix = "a2x1_config_bits" .. "-" .. "data_raw_projectile" .. "-" function __settings_startup__data_raw_projectile(data, order) return data:extend( { { type = "int-setting", name = settings_key_prefix .. "damage", setting_type = "startup", default_value = 1000, maximum_value = 100000, minimum_value = 1, localised_name = "Projectile Damage", localised_description = "1% Smaller - 100% Default - 100000% Larger", order = tonumber(order .. "1") } } ) end function __data__data_raw_projectile(data, settings) for k, v in pairs(data.raw["projectile"]) do -- if type(v) == "table" and type(v.action) == "table" then __shared__parse_data_action(v.action, (settings.startup[settings_key_prefix .. "damage"].value or 100)) end if type(v) == "table" and type(v.final_action) == "table" then __shared__parse_data_action(v.final_action, (settings.startup[settings_key_prefix .. "damage"].value or 100)) end if type(v) == "table" and v.piercing_damage then v.piercing_damage = (piercing_damage or 1) / 100 * (settings.startup[settings_key_prefix .. "damage"].value or 100) end if settings.startup["a2x1_config_bits" .. "-" .. "dual_damage"].value then if v.action then if v.action.action_delivery and v.action.action_delivery.target_effects then update_target_effects(v.action.action_delivery.target_effects) else for k1, v1 in pairs(v.action) do if type(v1) == "table" and v1.action_delivery and v1.action_delivery.target_effects then update_target_effects(v1.action_delivery.target_effects) end end end end end -- end end function update_target_effects(target_effects) local damage_amount, damage_type local count = 0 for k, v in pairs(target_effects) do if type(v) == "table" and v.damage then damage_amount = v.damage.amount damage_type = v.damage.type count = count + 1 end end if count == 1 then if damage_type == "explosion" then table.insert(target_effects, {type = "damage", damage = {amount = damage_amount, type = "physical"}}) end if damage_type == "physical" then table.insert(target_effects, {type = "damage", damage = {amount = damage_amount, type = "impact"}}) end end end
41,715
https://github.com/maxkao/dotfiles-22/blob/master/scripts/git-change-author.sh
Github Open Source
Open Source
BSD-3-Clause
2,020
dotfiles-22
maxkao
Shell
Code
122
435
#!/usr/bin/env bash function git_change_author { FROM_EMAIL="${1:-${FROM_EMAIL:-"email@example.org"}}" FROM_NAME="${2:-${FROM_NAME:-"User Name"}}" TO_EMAIL="${3:-${GIT_AUTHOR_EMAIL}}" TO_NAME="${4:-${GIT_AUTHOR_NAME}}" shift; shift; shift; shift test -n "${FROM_EMAIL}" || (echo '$1 - FROM_EMAIL - email@example.org' && return 2) test -n "${FROM_NAME}" || (echo '$2 - FROM_NAME - "User Name"' && return 3) test -n "${TO_EMAIL}" || (echo '$3 - TO_EMAIL - ${GIT_AUTHOR_EMAIL}' && return 4) test -n "${TO_NAME}" || (echo '$4 - TO_NAME - ${GIT_AUTHOR_NAME}' && return 5) git filter-branch --commit-filter " if [ \"\$GIT_AUTHOR_EMAIL\" = '${FROM_EMAIL}' ] \ || [ \"\$GIT_AUTHOR_NAME\" = '${FROM_NAME}' ]; then GIT_AUTHOR_NAME='${TO_NAME}'; GIT_AUTHOR_EMAIL='${TO_EMAIL}'; git commit-tree "\$@"; else git commit-tree "\$@"; fi" "${@}" HEAD # 1ebcf80 # HEAD } function main { (set -v -e -x; git_change_author "${@}") } if [[ "${BASH_SOURCE}" == "${0}" ]]; then main "${@}" fi
31,554
https://github.com/KaraAliAbdElbasset/zh/blob/master/resources/views/funerals/show.blade.php
Github Open Source
Open Source
MIT
null
zh
KaraAliAbdElbasset
PHP
Code
272
1,567
@extends('layouts.app') @section('content') <div class="row"> <div class="col-md-6"> <div class="card"> <div class="card-header"> <h4 class="card-title">{{__('names.details')}}</h4> <button class="btn btn-danger btn-sm" onclick="deleteForm({{$f->id}})" rel="tooltip" title="{{__('actions.delete')}}" data-original-title="{{__('actions.delete')}}"> <i class="material-icons">close</i> </button> <a class="btn btn-warning btn-sm" href="{{route('funerals.edit',$f->id)}}" rel="tooltip" title="{{__('actions.edit')}}" data-original-title="{{__('actions.edit')}}"> <i class="material-icons">edit</i> </a> </div> <div class="card-body "> <div class="row " > <div class="col-md-6 border">{{__('names.f_name')}}</div> <div class="col-md-6 border">{{$f->first_name}}</div> </div> <div class="row " > <div class="col-md-6 border">{{__('names.l_name')}}</div> <div class="col-md-6 border">{{$f->last_name}}</div> </div> <div class="row " > <div class="col-md-6 border">{{__('names.gender')}}</div> <div class="col-md-6 border">{{__('names.'.$f->gender)}}</div> </div> <div class="row " > <div class="col-md-6 border">{{__('names.birth_date')}}</div> <div class="col-md-6 border">{{$f->birth_date->format('d/m/Y')}}</div> </div> <div class="row " > <div class="col-md-6 border">{{__('names.birth_place')}}</div> <div class="col-md-6 border">{{$f->birth_place}}</div> </div> <div class="row " > <div class="col-md-6 border">{{__('names.death_date')}}</div> <div class="col-md-6 border">{{$f->death_date->format('d/m/Y')}}</div> </div> <div class="row " > <div class="col-md-6 border">{{__('names.death_place')}}</div> <div class="col-md-6 border">{{$f->death_place}}</div> </div> <div class="row " > <div class="col-md-6 border">{{__('names.father_name')}}</div> <div class="col-md-6 border">{{$f->father_name}}</div> </div> <div class="row " > <div class="col-md-6 border">{{__('names.mother_full_name')}}</div> <div class="col-md-6 border">{{$f->mother_full_name}}</div> </div> <div class="row " > <div class="col-md-6 border">{{__('names.expenses')}}</div> <div class="col-md-6 border">{{$f->expenses}}</div> </div> <div class="row " > <div class="col-md-6 border">{{__('names.n_meals')}}</div> <div class="col-md-6 border">{{$f->meals_number}}</div> </div> <div class="row " > <div class="col-md-6 border">{{__('names.moderators')}}</div> <div class="col-md-6 border">{{$f->moderators}}</div> </div> <div class="row " > <div class="col-md-6 border">{{__('names.contributors')}}</div> <div class="col-md-6 border">{{$f->contributors}}</div> </div> <div class="row " > <div class="col-md-6 border">{{__('names.note')}}</div> <div class="col-md-6 border">{{$f->note}}</div> </div> </div> </div> </div> </div> @endsection @push('js') <script> const deleteForm = id => { Swal.fire({ title: '{{__('actions.delete_confirm_title')}}', text: "{{__('actions.delete_confirm_text')}}", icon: 'warning', showCancelButton: true, confirmButtonColor: '#3085d6', cancelButtonColor: '#d33', confirmButtonText: '{{__('actions.delete_btn_yes')}}', cancelButtonText: '{{__('actions.delete_btn_cancel')}}' }).then((result) => { if (result.value) { createForm(id).submit(); } }); } const createForm = id => { let f = document.createElement("form"); f.setAttribute('method',"post"); f.setAttribute('action',`/funerals/${id}`); let i1 = document.createElement("input"); //input element, text i1.setAttribute('type',"hidden"); i1.setAttribute('name','_token'); i1.setAttribute('value','{{csrf_token()}}'); let i2 = document.createElement("input"); //input element, text i2.setAttribute('type',"hidden"); i2.setAttribute('name','_method'); i2.setAttribute('value','DELETE'); f.appendChild(i1); f.appendChild(i2); document.body.appendChild(f); return f; } </script> @endpush
18,236
https://github.com/hnjm/GIS-Editor/blob/master/MapSuiteGisEditor/GisEditorInfrastructure/Plugins/Styles/StyleBuilder/HelpKeyToButtonConverter.cs
Github Open Source
Open Source
Apache-2.0
2,020
GIS-Editor
hnjm
C#
Code
262
611
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Diagnostics; using System.Reflection; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Media.Imaging; namespace ThinkGeo.MapSuite.GisEditor { [Obfuscation] internal class HelpKeyToButtonConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (value == null) return Binding.DoNothing; return GetHelpButton((Uri)value); } public object ConvertBack(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture) { return Binding.DoNothing; } private FrameworkElement GetHelpButton(Uri helpUri) { FrameworkElement frameworkElement = null; frameworkElement = new Image { Source = new BitmapImage(new Uri("/Images/help.png", UriKind.RelativeOrAbsolute)), Width = 16, Height = 16 }; frameworkElement.MouseLeftButtonUp += NavigateToHelpUri_Click; frameworkElement.ToolTip = "Help"; frameworkElement.Tag = helpUri; return frameworkElement; } private static void NavigateToHelpUri_Click(object sender, RoutedEventArgs e) { FrameworkElement image = sender as FrameworkElement; if (image != null) { if (image.Tag is Uri) { Uri uri = (Uri)image.Tag; if (!string.IsNullOrEmpty(uri.AbsoluteUri)) Process.Start(uri.AbsoluteUri); } } } } }
19,880
https://github.com/LogosCode/logoscode.github.io/blob/master/src/dataStore/DataStoreInvoker.js
Github Open Source
Open Source
Apache-2.0
null
logoscode.github.io
LogosCode
JavaScript
Code
195
725
import Utils from '../library/Utils.js'; var storeUpdateWatcher = { initialState:0, updatedState:0 } var dataStoreClone={}; var callbackFunctionsRegister = [ { callbackFunctionName:'productsCallback', executed:false }, { callbackFunctionName:'categoryCallback', executed:false }, { callbackFunctionName:'statusCallback', executed:false }, { callbackFunctionName:'statusCallback1', executed:false } ] function watchReducerUpdate(dataStoreObj){ dataStoreClone = Object.assign({},dataStoreObj); storeUpdateWatcher.updatedState +=1; for(var c =0; c< callbackFunctionsRegister.length; c++){ callbackFunctionsRegister[c].executed = false; } } const intervalInMilliseconds = 500; const notifyDataStoreState = function(property, callbackName, propertyCallback){ setInterval(function(){ //code goes here that will be run every 5 seconds. if(storeUpdateWatcher.initialState < storeUpdateWatcher.updatedState){ if(Utils.isValid(propertyCallback)){ propertyCallback(dataStoreClone[property]); } var allCallbacksExecuted = isCallbackRegisterExecuted(callbackName); if(allCallbacksExecuted){ storeUpdateWatcher.initialState = storeUpdateWatcher.updatedState; if(storeUpdateWatcher.initialState ==50){ storeUpdateWatcher.initialState = 0; storeUpdateWatcher.updatedState = 0; } } } }, intervalInMilliseconds); return dataStoreClone[property]; } const getDataStoreState = function(property){ var dataStorePropertyValue = dataStoreClone[property]; return dataStorePropertyValue; } const invoker = { watchReducerUpdate:watchReducerUpdate, notifyDataStoreState : notifyDataStoreState, getDataStoreState : getDataStoreState } export default invoker; //#region Private Methods function isCallbackRegisterExecuted(callbackName){ var totalCallbacks = callbackFunctionsRegister.length for(var a = 0; a<totalCallbacks; a++) { if(callbackFunctionsRegister[a].callbackFunctionName === callbackName) { callbackFunctionsRegister[a].executed = true; } } var result = countCallbackFunctionsExecuted(); var allExecuted = (result === totalCallbacks)? true: false; return allExecuted; } function countCallbackFunctionsExecuted(){ var counter = 0; for(var a = 0; a<callbackFunctionsRegister.length; a++) { if(callbackFunctionsRegister[a].executed == true) { counter++; } } return counter; } //#endregion Private Methods
8,270
https://github.com/GomezMimo/restaurante/blob/master/classes/database.php
Github Open Source
Open Source
Apache-2.0
2,016
restaurante
GomezMimo
PHP
Code
38
143
<?php class Database{ var $user_db = 'root'; var $pass_db = ''; var $host_db = 'localhost'; var $name_db = 'taller'; var $connection; function connect(){ $this->connection = new PDO("mysql:$this->host_db=;dbname=$this->name_db;charset=utf8", $this->user_db, $this->pass_db); } function close(){ $this->connection = null; } } ?>
16,795
https://github.com/stichting-cito/QuestifyBuilder/blob/master/Builder/UnitTests.VB/Cito.TestBuilder.Logic/Chain/Processing/AddNonExistingSectionsToAssessmentTest.vb
Github Open Source
Open Source
MS-PL
2,019
QuestifyBuilder
stichting-cito
Visual Basic
Code
276
1,068
 Imports Questify.Builder.Logic.Chain Imports Cito.Tester.ContentModel Imports Questify.Builder.Logic.TestConstruction.Requests Imports Questify.Builder.Logic.TestConstruction.ChainHandlers.Processing Imports Questify.Builder.UnitTests.Framework.Faketory <TestClass()> Public Class AddNonExistingSectionsToAssessmentTest <TestMethod(), TestCategory("Logic")> Public Sub NoOperationNeeded_NothingShouldHaveHappend() 'Arrange Dim targetSection As TestSection2 Dim assessment As AssessmentTest2 Dim req As TestConstructionRequest = TestConstructionFactory.Add("1001", "1002") 'Very basic Assessment assessment = FakeFactory.AssesmentTest.MakeAssessment("Test1", Function(tp) tp.MakeTestPart("tp1", Function(s) s.MakeSection("TargetSection", Sub(sTarget) targetSection = sTarget))) Dim handler As New AddNonExistingSectionsToAssessment(assessment, targetSection) 'Act Dim status As ChainHandlerResult status = handler.ProcessRequest(req) 'Assert Assert.AreEqual(ChainHandlerResult.RequestHandled, status) 'All went ok (nothing should have happened). Assert.AreEqual(1, assessment.GetAllSectionsInTest().Count) 'Since nothing happened, the number of sections should be 1 End Sub <TestMethod(), TestCategory("Logic")> Public Sub CreateSingleSection_SingleSectionShouldHaveBeenMadeUnderTargetSection() 'Arrange Dim targetSection As TestSection2 Dim assessment As AssessmentTest2 Dim req As TestConstructionRequest = TestConstructionFactory.Add("1001", "1002") 'Very basic Assessment assessment = FakeFactory.AssesmentTest.MakeAssessment("Test1", Function(tp) tp.MakeTestPart("tp1", Function(s) s.MakeSection("TargetSection", Sub(sTarget) targetSection = sTarget))) req.OverridenTarget.Add(ResourceRefFactory.Make("1001"), New TestSection2() With {.Title = "new", .Identifier = "new"}) 'Retarget an item. Dim handler As New AddNonExistingSectionsToAssessment(assessment, targetSection) Dim status As ChainHandlerResult 'Act status = handler.ProcessRequest(req) 'Assert Assert.AreEqual(2, assessment.GetAllSectionsInTest().Count) 'A single sections should have been created/ Assert.AreEqual(1, targetSection.GetAllSectionsInSection().Count) 'The sections should have been placed in the target section. Assert.AreEqual("new", targetSection.GetAllSectionsInSection()(0).Identifier) 'Name should be the same. Assert.AreEqual(ChainHandlerResult.RequestHandled, status) 'Chain was handled? End Sub <TestMethod(), TestCategory("Logic")> Public Sub NoOperationNeededRetargetToExistingSection_NothingShouldHaveHappend() 'Arrange Dim targetSection As TestSection2 Dim assessment As AssessmentTest2 Dim req As TestConstructionRequest = TestConstructionFactory.Add("1001", "1002") 'Construct assessment assessment = FakeFactory.AssesmentTest.MakeAssessment("Test1", Function(tp) tp.MakeTestPart("tp1", Function(s) s.MakeSection("TargetSection", Sub(sTarget) targetSection = sTarget), Function(s) s.MakeSection("Re-TargetSection"))) req.OverridenTarget.Add(ResourceRefFactory.Make("1001"), New TestSection2() With {.Identifier = "Re-TargetSection"}) 'Retarget an item. Dim handler As New AddNonExistingSectionsToAssessment(assessment, targetSection) Dim status As ChainHandlerResult 'Act status = handler.ProcessRequest(req) 'Assert Assert.AreEqual(2, assessment.GetAllSectionsInTest().Count) 'There are 2 sections in original assessment, none were created. Assert.AreEqual(0, targetSection.GetAllSectionsInSection().Count) 'Double check that nothing was moved. Assert.AreEqual(ChainHandlerResult.RequestHandled, status) 'Chain was handled? End Sub End Class
11,030
https://github.com/hq9000/py-headless-daw/blob/master/py_headless_daw/project/project_renderer.py
Github Open Source
Open Source
MIT
2,021
py-headless-daw
hq9000
Python
Code
192
811
from math import ceil from typing import List from scipy.io import wavfile from py_headless_daw.compiler.project_compiler import ProjectCompiler from py_headless_daw.project.project import Project from py_headless_daw.schema.dto.time_interval import TimeInterval from py_headless_daw.schema.wiring import StreamNode import numpy as np class ProjectRenderer: SAMPLE_RATE = 44100 def __init__(self, project_compiler: ProjectCompiler): self._compiler: ProjectCompiler = project_compiler def render_to_file(self, project: Project, start_time: float, end_time: float, out_file_path: str): buffer = self.render_to_array(project, start_time, end_time) self.render_array_to_file(buffer, self.SAMPLE_RATE, out_file_path) def render_array_to_file(self, data: np.ndarray, sample_rate: int, out_file_path: str): """ data: the array that render_to_array would have produced out_file_path: path to output wav data to """ rotated = np.rot90(data, k=-1) wavfile.write(out_file_path, sample_rate, rotated) def render_to_array(self, project: Project, start_time: float, end_time: float) -> np.ndarray: output_stream_nodes: List[StreamNode] = self._compiler.compile(project) left_node = output_stream_nodes[0] right_node = output_stream_nodes[1] buffer_length_samples = 4410 sample_rate = self.SAMPLE_RATE buffer_length_seconds = buffer_length_samples / sample_rate num_frames = ceil((end_time - start_time) / buffer_length_seconds) result_buffer = np.ndarray(shape=(2, num_frames * buffer_length_samples), dtype=np.float32) left_frame_buffer = np.ndarray(shape=(buffer_length_samples,), dtype=np.float32) right_frame_buffer = np.ndarray(shape=(buffer_length_samples,), dtype=np.float32) for i in range(num_frames): interval = TimeInterval() interval.num_samples = buffer_length_samples interval.start_in_seconds = start_time + i * buffer_length_seconds interval.end_in_seconds = interval.start_in_seconds + buffer_length_seconds left_node.render(interval, left_frame_buffer) right_node.render(interval, right_frame_buffer) start_sample_in_result = i * buffer_length_samples end_sample_in_result = start_sample_in_result + buffer_length_samples result_buffer[0][start_sample_in_result:end_sample_in_result] = left_frame_buffer result_buffer[1][start_sample_in_result:end_sample_in_result] = right_frame_buffer return result_buffer
12,111
https://github.com/OLIMEX/DIY-LAPTOP/blob/master/HARDWARE/A64-TERES/KiCad/Footprints.old/OLIMEX_LEDs-FP.pretty/LED_0603_KA.kicad_mod
Github Open Source
Open Source
LicenseRef-scancode-free-unknown, Apache-2.0, GPL-3.0-only, GPL-1.0-or-later
2,023
DIY-LAPTOP
OLIMEX
KiCad Layout
Code
384
1,324
(module LED_0603_KA (layer F.Cu) (tedit 57D252E1) (descr CCCCC) (tags "resistor 0603") (attr smd) (fp_text reference Led_Small (at 0 -1.905) (layer F.SilkS) (effects (font (size 1.27 1.27) (thickness 0.254))) ) (fp_text value Led_Small (at 0 2.54) (layer F.Fab) (effects (font (size 1.27 1.27) (thickness 0.254))) ) (fp_line (start -1.397 -0.4826) (end -1.397 0.5588) (layer F.SilkS) (width 0.254)) (fp_line (start -1.5621 0.4445) (end -1.5621 -0.381) (layer F.SilkS) (width 0.254)) (fp_line (start -1.4097 -0.5207) (end -1.5494 -0.3937) (layer F.SilkS) (width 0.254)) (fp_line (start -1.4097 0.5715) (end -1.5621 0.4445) (layer F.SilkS) (width 0.254)) (fp_line (start -0.2413 0.8636) (end -0.7874 1.4351) (layer F.SilkS) (width 0.15)) (fp_line (start -0.8001 1.4351) (end -0.381 1.3462) (layer F.SilkS) (width 0.15)) (fp_line (start -0.8001 1.4224) (end -0.7493 1.0287) (layer F.SilkS) (width 0.15)) (fp_line (start -0.0127 1.4224) (end 0.0381 1.0287) (layer F.SilkS) (width 0.15)) (fp_line (start -0.0127 1.4351) (end 0.4064 1.3462) (layer F.SilkS) (width 0.15)) (fp_line (start 0.5461 0.8636) (end 0 1.4351) (layer F.SilkS) (width 0.15)) (fp_line (start -0.08 0.25) (end -0.21 0.36) (layer F.SilkS) (width 0.05)) (fp_line (start -0.22 0.38) (end -0.14 0.37) (layer F.SilkS) (width 0.05)) (fp_line (start -0.22 0.38) (end -0.22 0.3) (layer F.SilkS) (width 0.05)) (fp_line (start -0.03 0.38) (end -0.03 0.3) (layer F.SilkS) (width 0.05)) (fp_line (start -0.03 0.38) (end 0.05 0.37) (layer F.SilkS) (width 0.05)) (fp_line (start 0.11 0.25) (end -0.02 0.36) (layer F.SilkS) (width 0.05)) (fp_line (start -0.1 0.11) (end -0.1 -0.11) (layer F.SilkS) (width 0.1)) (fp_line (start 0.09 -0.11) (end -0.01 -0.01) (layer F.SilkS) (width 0.1)) (fp_line (start 0.09 0.11) (end -0.02 0.01) (layer F.SilkS) (width 0.1)) (fp_line (start 0.09 0.11) (end 0.09 -0.11) (layer F.SilkS) (width 0.1)) (fp_line (start 0.26 0) (end -0.26 0) (layer F.SilkS) (width 0.1)) (fp_line (start -0.381 0.635) (end -1.397 0.635) (layer F.SilkS) (width 0.127)) (fp_line (start -1.397 -0.5842) (end -0.381 -0.5842) (layer F.SilkS) (width 0.127)) (fp_line (start 1.397 0.5842) (end 1.397 -0.5842) (layer F.SilkS) (width 0.127)) (fp_line (start 1.397 -0.5842) (end 0.381 -0.5842) (layer F.SilkS) (width 0.127)) (fp_line (start 1.397 0.5842) (end 0.381 0.5842) (layer F.SilkS) (width 0.127)) (pad 2 smd rect (at 0.762 0 180) (size 0.8 0.8) (layers F.Cu F.Paste F.Mask) (solder_mask_margin 0.0508)) (pad 1 smd rect (at -0.762 0 180) (size 0.8 0.8) (layers F.Cu F.Paste F.Mask) (solder_mask_margin 0.0508)) (model Resistors_SMD/R_0603.wrl (at (xyz 0 0 0)) (scale (xyz 1 1 1)) (rotate (xyz 0 0 0)) ) )
23,343
https://github.com/wmacevoy/testrng/blob/master/dieharder/d208/g026/d208_g026_S2419383274.sh
Github Open Source
Open Source
Apache-2.0
null
testrng
wmacevoy
Shell
Code
8
23
#!/bin/bash dieharder -d 208 -g 26 -S 2419383274
41,236
https://github.com/190103480/inf232-lab4/blob/master/routes/web.php
Github Open Source
Open Source
MIT
null
inf232-lab4
190103480
PHP
Code
74
195
<?php use Illuminate\Support\Facades\Route; /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('/', function () { return view('welcome'); }); Route::get('firstroute',function(){ return "Anelya Zharylkapova"; }); Route::get('secondroute', function () { return view('lab4'); }); Route::get('fourthroute/{fname}/{lname}',function($fname,$lname){ return "My full name is: ".$fname." ".$lname; });
44,493
https://github.com/swiftyspiffy/Twitch-Moderator-Logger/blob/master/Twitch Moderator Logger/UI.Designer.cs
Github Open Source
Open Source
WTFPL
2,022
Twitch-Moderator-Logger
swiftyspiffy
C#
Code
358
1,623
namespace Twitch_Moderator_Logger { partial class UI { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.listView1 = new System.Windows.Forms.ListView(); this.statusStrip1 = new System.Windows.Forms.StatusStrip(); this.toolStripStatusLabel1 = new System.Windows.Forms.ToolStripStatusLabel(); this.toolStripStatusLabel2 = new System.Windows.Forms.ToolStripStatusLabel(); this.button1 = new System.Windows.Forms.Button(); this.statusStrip1.SuspendLayout(); this.SuspendLayout(); // // listView1 // this.listView1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.listView1.Location = new System.Drawing.Point(12, 12); this.listView1.Name = "listView1"; this.listView1.Size = new System.Drawing.Size(823, 708); this.listView1.TabIndex = 0; this.listView1.UseCompatibleStateImageBehavior = false; this.listView1.View = System.Windows.Forms.View.Details; this.listView1.ColumnClick += new System.Windows.Forms.ColumnClickEventHandler(this.listView1_ColumnClicked); this.listView1.ColumnWidthChanged += new System.Windows.Forms.ColumnWidthChangedEventHandler(this.listView1_ColumnWidthChanged); // // statusStrip1 // this.statusStrip1.ImageScalingSize = new System.Drawing.Size(40, 40); this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripStatusLabel1, this.toolStripStatusLabel2}); this.statusStrip1.Location = new System.Drawing.Point(0, 726); this.statusStrip1.Name = "statusStrip1"; this.statusStrip1.RightToLeft = System.Windows.Forms.RightToLeft.Yes; this.statusStrip1.Size = new System.Drawing.Size(847, 51); this.statusStrip1.TabIndex = 1; this.statusStrip1.Text = "statusStrip1"; // // toolStripStatusLabel1 // this.toolStripStatusLabel1.Font = new System.Drawing.Font("Segoe UI", 9.900001F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.toolStripStatusLabel1.ForeColor = System.Drawing.Color.Red; this.toolStripStatusLabel1.Name = "toolStripStatusLabel1"; this.toolStripStatusLabel1.Size = new System.Drawing.Size(235, 46); this.toolStripStatusLabel1.Text = "Disconnected"; // // toolStripStatusLabel2 // this.toolStripStatusLabel2.Name = "toolStripStatusLabel2"; this.toolStripStatusLabel2.Size = new System.Drawing.Size(178, 46); this.toolStripStatusLabel2.Text = ":Connection"; // // button1 // this.button1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.button1.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.1F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.button1.Location = new System.Drawing.Point(-10, 726); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(344, 64); this.button1.TabIndex = 2; this.button1.Text = "Customize Columns"; this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(this.button1_Click); // // UI // this.AutoScaleDimensions = new System.Drawing.SizeF(16F, 31F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(847, 777); this.Controls.Add(this.button1); this.Controls.Add(this.statusStrip1); this.Controls.Add(this.listView1); this.MinimumSize = new System.Drawing.Size(879, 865); this.Name = "UI"; this.Text = "Twitch Moderator Logger"; this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.UI_Closing); this.Load += new System.EventHandler(this.UI_Load); this.ResizeBegin += new System.EventHandler(this.UI_ResizeBegin); this.ResizeEnd += new System.EventHandler(this.UI_ResizeEnd); this.Resize += new System.EventHandler(this.UI_Resize); this.statusStrip1.ResumeLayout(false); this.statusStrip1.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.ListView listView1; private System.Windows.Forms.StatusStrip statusStrip1; private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel1; private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel2; private System.Windows.Forms.Button button1; } }
48,003
https://github.com/Prastiwar/TPFrameworkUnity/blob/master/Runtime/CoreUnity/TPFadePackage/FadeLayout.cs
Github Open Source
Open Source
MIT
2,021
TPFrameworkUnity
Prastiwar
C#
Code
36
134
/** * Authored by Tomasz Piowczyk * MIT LICENSE: https://github.com/Prastiwar/TPFrameworkUnity/blob/master/LICENSE * Repository: https://github.com/Prastiwar/TPFrameworkUnity */ using System; using UnityEngine; using UnityEngine.UI; namespace TP.Framework.Unity { [Serializable] public class FadeLayout { public Image Image; public CanvasGroup CanvasGrouup; } }
11,780
https://github.com/Pzaaaz/myself/blob/master/11-24/AI/src/AI.java
Github Open Source
Open Source
MIT
2,020
myself
Pzaaaz
Java
Code
222
1,058
import javax.microedition.lcdui.*; import javax.microedition.midlet.*; import java.io.*; import java.util.*; public class AI extends MIDlet { Display display; MainCanvas mc; public AI(){ display=Display.getDisplay(this); mc=new MainCanvas(); display.setCurrent(mc); } public void startApp(){ } public void destroyApp(boolean unc){ } public void pauseApp(){ } } class MainCanvas extends Canvas implements Runnable { Thread thread; int heroX,heroY,bossX,bossY,counnt; Image bossImg; Image heroImg [][] = new Image[4][3]; Image currentImg; Random random = new Random(); public MainCanvas(){ try { for(int i = 0;i<heroImg.length;i++){//令0上方向,1为下方向,2为左方向,3为右方向 for (int j = 0;j<heroImg[i].length ;j++ ){ heroImg[i][j] = Image.createImage("/sayo"+i+j+".png"); } } bossImg = Image.createImage("/zuzu000.png"); currentImg = heroImg[1][1]; bossX = 0; bossY = 0; heroX = 120; heroY = 100; counnt=0; thread=new Thread(this); thread.start(); } catch (IOException e) { e.printStackTrace(); } } public void run(){ while(true) { int a = random.nextInt(10); System.out.println(a); try { Thread.sleep(200);//FPS:屏幕刷新率 } catch (InterruptedException e) { e.printStackTrace(); } if(a%2==0){ if (bossX<heroX) { bossX++; } else{ bossX--; } if (bossY<heroY) { bossY++; } else{ bossY--; } } repaint(); } } public void paint(Graphics g){ g.setColor(0,0,0); g.fillRect(0,0,getWidth(),getHeight()); g.drawImage(currentImg,heroX,heroY,0); g.drawImage(bossImg,bossX,bossY,0); } public void keyPressed(int keyCode){ int action = getGameAction(keyCode); if(action == LEFT){ changeImg(2); System.out.println("向左转"); heroX-=1; } else if(action ==UP){ changeImg(0); System.out.println("向上转"); heroY-=1; } else if(action == DOWN){ changeImg(1); System.out.println("向下转"); heroY+=1; } else if(action ==RIGHT){ changeImg(3); System.out.println("向右转"); heroX+=1; } } void changeImg(int direction){ if (counnt==0){ counnt=1; currentImg = heroImg[direction][0]; } else if(counnt==1){ counnt=0; currentImg = heroImg[direction][2]; } } }
3,103
https://github.com/Mas211/hwadee/blob/master/jxt/src/main/java/com/jxt/entity/Auth.java
Github Open Source
Open Source
MIT
2,019
hwadee
Mas211
Java
Code
46
129
package com.jxt.entity; //权限 public class Auth { private Integer authId; private String authPath; public Integer getAuthId() { return authId; } public void setAuthId(Integer authId) { this.authId = authId; } public String getAuthPath() { return authPath; } public void setAuthPath(String authPath) { this.authPath = authPath; } }
24,365
https://github.com/smcclure879/radioreceiver/blob/master/image-src/build-icons.sh
Github Open Source
Open Source
Apache-2.0
2,017
radioreceiver
smcclure879
Shell
Code
16
67
#!/bin/bash convert icon.svg -size 16x16 ../extension/icon-16.png convert icon.svg -size 48x48 ../extension/icon-48.png convert icon.svg -size 128x128 ../extension/icon-128.png
21,200
https://github.com/bagel-man/bagel-man.github.io/blob/master/eaglercraftx-1.8-main/gateway/PlaceholderServer/src/main/java/net/lax1dude/eaglercraft/v1_8/placeholder_server/PlaceholderServerConfig.java
Github Open Source
Open Source
LicenseRef-scancode-proprietary-license
2,023
bagel-man.github.io
bagel-man
Java
Code
678
2,152
package net.lax1dude.eaglercraft.v1_8.placeholder_server; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.Reader; import java.nio.charset.StandardCharsets; import java.util.UUID; import org.json.JSONArray; import org.json.JSONObject; /** * Copyright (c) 2022 LAX1DUDE. All Rights Reserved. * * WITH THE EXCEPTION OF PATCH FILES, MINIFIED JAVASCRIPT, AND ALL FILES * NORMALLY FOUND IN AN UNMODIFIED MINECRAFT RESOURCE PACK, YOU ARE NOT ALLOWED * TO SHARE, DISTRIBUTE, OR REPURPOSE ANY FILE USED BY OR PRODUCED BY THE * SOFTWARE IN THIS REPOSITORY WITHOUT PRIOR PERMISSION FROM THE PROJECT AUTHOR. * * NOT FOR COMMERCIAL OR MALICIOUS USE * * (please read the 'LICENSE' file this repo's root directory for more info) * */ public class PlaceholderServerConfig { public static final File configFile = new File("config.json"); public static String host = "0.0.0.0"; public static int port = 8081; public static String icon = null; public static String serverName = "EaglercraftX 1.8 Server"; public static String serverUUID = ""; public static int clientTimeout = 3000; public static String motd1 = "Coming Soon"; public static String motd2 = ""; public static String kick = "This server is still under construction"; public static String redirect = ""; public static byte[] cachedIconPacket = null; public static byte[] cachedLegacyKickRedirectPacket = null; public static byte[] cachedKickPacket = null; public static void load() throws IOException { if(!configFile.exists()) { System.out.println("Writing new config file to: " + configFile.getName()); int i; try(Reader is = new InputStreamReader(PlaceholderServerConfig.class.getResourceAsStream("/config_default.json")); OutputStream os = new FileOutputStream(configFile)) { char[] copyBuffer = new char[1024]; StringBuilder sb = new StringBuilder(); while((i = is.read(copyBuffer)) != -1) { sb.append(copyBuffer, 0, i); } String str = sb.toString(); str = str.replace("${random_uuid}", UUID.randomUUID().toString()); os.write(str.getBytes(StandardCharsets.UTF_8)); } try(InputStream is = PlaceholderServerConfig.class.getResourceAsStream("/server-icon_default.png"); OutputStream os = new FileOutputStream(new File("server-icon.png"))) { byte[] copyBuffer = new byte[1024]; while((i = is.read(copyBuffer)) != -1) { os.write(copyBuffer, 0, i); } } } System.out.println("Reading config file: " + configFile.getName()); byte[] fileBytes = new byte[(int)configFile.length()]; try(InputStream is = new FileInputStream(configFile)) { int i = 0, j; while(i < fileBytes.length && (j = is.read(fileBytes, i, fileBytes.length - i)) != -1) { i += j; } } try { JSONObject loaded = new JSONObject(new String(fileBytes, StandardCharsets.UTF_8)); host = loaded.getString("server_host"); port = loaded.getInt("server_port"); icon = loaded.getString("server_icon"); serverName = loaded.getString("server_name"); serverUUID = loaded.getString("server_uuid"); clientTimeout = loaded.getInt("client_timeout"); JSONArray motd = loaded.getJSONArray("server_motd"); motd1 = motd.getString(0); if(motd.length() > 1) { motd2 = motd.getString(1); } kick = loaded.getString("kick_message"); if(kick.length() > 255) { kick = kick.substring(0, 255); System.err.println("Warning: kick message was truncated to 255 characters"); } redirect = loaded.optString("redirect_legacy", null); }catch(Throwable t) { throw new IOException("Could not load config file \"" + configFile.getAbsolutePath() + "\"!", t); } cacheKickPacket(); cacheRedirectPacket(); if(icon != null && icon.length() > 0) { cacheIconPacket(); } } private static void cacheKickPacket() throws IOException { ByteArrayOutputStream bao = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(bao); dos.writeByte(0xFF); dos.writeByte(0x08); dos.writeByte(kick.length()); for(int i = 0, l = kick.length(); i < l; ++i) { dos.writeByte(kick.charAt(i) & 0xFF); } cachedKickPacket = bao.toByteArray(); } private static void cacheRedirectPacket() throws IOException { ByteArrayOutputStream bao = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(bao); if(redirect == null || redirect.length() == 0) { String message = "This is an EaglercraftX 1.8 server, it is not compatible with 1.5.2!"; dos.writeByte(0xFF); dos.writeShort(message.length()); for(int i = 0, l = message.length(), j; i < l; ++i) { j = message.charAt(i); dos.writeByte((j >> 8) & 0xFF); dos.writeByte(j & 0xFF); } }else { // Packet1Login dos.writeByte(0x01); dos.writeInt(0); dos.writeShort(0); dos.writeByte(0); dos.writeByte(0); dos.writeByte(0xFF); dos.writeByte(0); dos.writeByte(0); // Packet250CustomPayload dos.writeByte(0xFA); String channel = "EAG|Reconnect"; int cl = channel.length(); dos.writeShort(cl); for(int i = 0; i < cl; ++i) { dos.writeChar(channel.charAt(i)); } byte[] redirect_ = redirect.getBytes(StandardCharsets.UTF_8); dos.writeShort(redirect_.length); dos.write(redirect_); } cachedLegacyKickRedirectPacket = bao.toByteArray(); } private static void cacheIconPacket() throws IOException { File f = new File(icon); int[] iconPixels = ServerIconLoader.createServerIcon(f); if(iconPixels != null) { cachedIconPacket = new byte[16384]; for(int i = 0, j; i < 4096; ++i) { j = i << 2; cachedIconPacket[j] = (byte)((iconPixels[i] >> 16) & 0xFF); cachedIconPacket[j + 1] = (byte)((iconPixels[i] >> 8) & 0xFF); cachedIconPacket[j + 2] = (byte)(iconPixels[i] & 0xFF); cachedIconPacket[j + 3] = (byte)((iconPixels[i] >> 24) & 0xFF); } }else { System.err.println("Could not load server icon \"" + f.getAbsolutePath() + "\"!"); } } }
19,266
https://github.com/seznam/ima/blob/master/packages/create-ima-app/template/ts/app/page/home/HomeView.tsx
Github Open Source
Open Source
MIT
2,023
ima
seznam
TSX
Code
178
499
import { useSettings, useLocalize } from '@ima/react-page-renderer'; import { Card } from 'app/component/card/Card'; import { CardData } from 'app/page/home/HomeController'; import { useState, useEffect } from 'react'; import './homeView.less'; export interface HomeViewProps { message: string; name: string; cards: CardData; } /** * The `load` method in HomeController.js passes entries * in the returned object as props to this component view. The * data are passed all at once, as soon as all promises resolve * (in case of SSR) or one by one as the promises are being resolved. */ export function HomeView({ message, name, cards }: HomeViewProps) { const links = useSettings('links') as Record<string, string>; const localize = useLocalize(); const [mounted, setMounted] = useState(false); // This executes only on client side useEffect(() => { setMounted(true); }, []); return ( <div className='page-home'> <div className='content'> <h1> {message}{' '} <a target='_blank' href='https://imajs.io' title={name} rel='noopener noreferrer' > {name} </a> </h1> <p className='hero' dangerouslySetInnerHTML={{ __html: localize('home.intro') }} ></p> <div className='cards'> {cards?.map(card => ( <Card key={card.id} title={card.title} href={links[card.id] ?? ''}> {card.content} </Card> )) ?? null} </div> {mounted && <div className='mounted'>💡</div>} </div> </div> ); }
36,666
https://github.com/cflowe/ACE/blob/master/TAO/orbsvcs/tests/Notify/Persistent_Filter/supplier.cpp
Github Open Source
Open Source
DOC
2,022
ACE
cflowe
C++
Code
64
203
// -*- C++ -*- // $Id: supplier.cpp 84685 2009-03-02 22:49:17Z mesnier_p $ #include "Filter.h" int ACE_TMAIN (int argc, ACE_TCHAR *argv []) { FilterClient client; try { client.init_supplier (argc, argv); //Init the Client client.run_supplier (); } catch (const CORBA::UserException& ue) { ue._tao_print_exception ("TLS_Client user error: "); return 1; } catch (const CORBA::SystemException& se) { se._tao_print_exception ("Supplier system error: "); return 1; } return 0; }
8,941
https://github.com/ericrbg/lean/blob/master/tests/lean/run/1813.lean
Github Open Source
Open Source
Apache-2.0
2,022
lean
ericrbg
Lean
Code
149
258
open tactic example {A B : Type} (f : A -> B) (a b c) (h1 : f a = b) (h2 : f a = c) : false := begin rw h1 at *, guard_hyp h1 : f a = b, guard_hyp h2 : b = c, admit end example {A B : Type} (f : A -> B) (a b c) (h1 : f a = b) (h2 : f a = c) : false := begin rw [id h1] at *, guard_hyp h1 : f a = b, guard_hyp h2 : b = c, admit end example {A B : Type} (f : A -> B) (a b c) (h1 : f a = b) (h2 : f a = c) : false := begin rw [id id h1] at *, guard_hyp h1 : f a = b, guard_hyp h2 : b = c, admit end
39,807
https://github.com/nankasuisui/phaselimiter/blob/master/src/phase_limiter/auto_mastering2.cpp
Github Open Source
Open Source
MIT
2,022
phaselimiter
nankasuisui
C++
Code
793
3,240
#include "phase_limiter/auto_mastering.h" #include <cmath> #include <iostream> #include <vector> #include <unordered_map> #include <sstream> #include <chrono> #include <string> #include <random> #include <stdexcept> #include <algorithm> #include <fstream> #include <streambuf> #include <thread> #include <mutex> #include "gflags/gflags.h" #include "picojson.h" #include "audio_analyzer/reverb.h" #include "audio_analyzer/peak.h" #include "bakuage/loudness_ebu_r128.h" #include "audio_analyzer/multiband_histogram.h" #include "audio_analyzer/statistics.h" #include "bakuage/convolution.h" #include "bakuage/sndfile_wrapper.h" #include "bakuage/compressor_filter.h" #include "bakuage/channel_wise_compressor_filter.h" #include "bakuage/ms_compressor_filter.h" #include "bakuage/file_utils.h" #include "bakuage/utils.h" #include "bakuage/fir_design.h" #include "bakuage/fir_filter.h" #include "bakuage/ffmpeg.h" #include "bakuage/window_func.h" #include "bakuage/mfcc.h" #include "bakuage/dct.h" DECLARE_string(mastering2_config_file); typedef float Float; using namespace bakuage; namespace { void raise(const std::string &message) { throw std::logic_error("auto mastering2 error: " + message); } class Band { public: Band(const picojson::object &band) { using namespace picojson; gain = band.at("gain").get<double>(); mean = band.at("mean").get<double>(); ratio = band.at("ratio").get<double>(); threshold_relative_to_mean = band.at("threshold_relative_to_mean").get<double>(); } Float gain; Float mean; Float ratio; Float threshold_relative_to_mean; }; enum class Mastering2Mode { kBand = 1, kMfcc = 2, }; class Mastering2Config { public: /* kBandの場合 bandsの長さは40 kMfccの場合 40band -> 13coefで、bandsの長さは13 */ Mastering2Config(const std::string &reference_file_path) { using namespace picojson; value v; std::ifstream reference_file(reference_file_path.c_str()); std::string json_str((std::istreambuf_iterator<char>(reference_file)), std::istreambuf_iterator<char>()); std::string err = parse(v, json_str); if (!err.empty()) { raise(err); } object root = v.get<object>(); auto mode_str = root.at("mode").get<std::string>(); if (mode_str == "band") { mode = Mastering2Mode::kBand; } else if (mode_str == "mfcc") { mode = Mastering2Mode::kMfcc; } else { raise("unknown mode " + mode_str); } array bands_json = root.at("bands").get<array>(); for (const auto band_json : bands_json) { bands.push_back(Band(band_json.get<object>())); } } Mastering2Mode mode; std::vector<Band> bands; }; } namespace phase_limiter { void AutoMastering2(std::vector<float> *_wave, const int sample_rate, const std::function<void(float)> &progress_callback) { #ifdef PHASELIMITER_ENABLE_FFTW Mastering2Config mastering2_config(FLAGS_mastering2_config_file); const int frames = _wave->size() / 2; const int channels = 2; const float *wave_ptr = &(*_wave)[0]; std::mutex task_mtx; std::mutex result_mtx; std::mutex progression_mtx; std::vector<std::function<void()>> tasks; std::vector<Float> result(_wave->size()); /* 処理概要 1. STFT 2. calculate mel band or MFCC 3. calculate gain for each band or each MFCC 4. gainを1の結果に適用 5. overlap addで出力 */ int width = 2048; int shift = 1024; int num_filters = 40; int mfcc_len = 13; int pos = -width + shift; int spec_len = width / 2 + 1; std::vector<std::vector<std::complex<float>>> complex_spec(channels, std::vector<std::complex<float>>(spec_len)); std::vector<std::complex<float>> complex_spec_mono(spec_len); std::vector<float> mel_bands_mono(num_filters); std::vector<float> mfcc_mono(num_filters); std::vector<float> mfcc_gains_mono(num_filters); std::vector<float> band_gains_mono(num_filters); std::vector<float> spec_gains_mono(spec_len); std::vector<float> window(width); bakuage::CopyHanning(width, window.begin()); bakuage::MfccCalculator<float> mfcc_calculator(sample_rate, 0, 11000, num_filters); bakuage::Dct dct(num_filters); double *fft_input; fftw_complex * fft_output; fftw_plan plan; fftw_plan inv_plan; { std::lock_guard<std::recursive_mutex> lock(FFTW::mutex()); fft_input = (double *)fftw_malloc(sizeof(double) * width); std::fill_n(fft_input, width, 0); fft_output = (fftw_complex *)fftw_malloc(sizeof(fftw_complex) * spec_len); std::fill_n((double *)fft_output, 2 * spec_len, 0); plan = fftw_plan_dft_r2c_1d(width, fft_input, fft_output, FFTW_ESTIMATE); inv_plan = fftw_plan_dft_c2r_1d(width, fft_output, fft_input, FFTW_ESTIMATE); } while (pos < frames) { // window and fft std::fill_n(complex_spec_mono.data(), spec_len, 0); for (int i = 0; i < channels; i++) { for (int j = 0; j < width; j++) { int k = pos + j; fft_input[j] = (0 <= k && k < frames) ? wave_ptr[channels * k + i] * window[j] : 0; } fftw_execute(plan); for (int j = 0; j < spec_len; j++) { complex_spec[i][j] = std::complex<float>(fft_output[j][0], fft_output[j][1]); complex_spec_mono[j] += complex_spec[i][j]; } } // calculate mel band mfcc_calculator.calculateMelSpectrumFromDFT((float *)complex_spec_mono.data(), width, true, false, mel_bands_mono.data()); for (int j = 0; j < num_filters; j++) { mel_bands_mono[j] = 10 * std::log10(1e-10 + mel_bands_mono[j]); } // calculate gain if (mastering2_config.mode == Mastering2Mode::kBand) { for (int j = 0; j < num_filters; j++) { const double threshold = mastering2_config.bands[j].mean + mastering2_config.bands[j].threshold_relative_to_mean; if (mel_bands_mono[j] < threshold) { band_gains_mono[j] = (threshold - mastering2_config.bands[j].mean) / mastering2_config.bands[j].ratio + mastering2_config.bands[j].mean + mastering2_config.bands[j].gain - threshold; } else { band_gains_mono[j] = (mel_bands_mono[j] - mastering2_config.bands[j].mean) / mastering2_config.bands[j].ratio + mastering2_config.bands[j].mean + mastering2_config.bands[j].gain - mel_bands_mono[j]; } } } else if (mastering2_config.mode == Mastering2Mode::kMfcc) { // calculate mfcc dct.DctType2(mel_bands_mono.data(), mfcc_mono.data()); // calculate gain in mfcc for (int j = 0; j < mfcc_len; j++) { const double threshold = mastering2_config.bands[j].mean + mastering2_config.bands[j].threshold_relative_to_mean; const double ratio = mastering2_config.bands[j].ratio; if (j == 0 && mfcc_mono[j] < threshold) { mfcc_gains_mono[j] = (threshold - mastering2_config.bands[j].mean) / ratio + mastering2_config.bands[j].mean + mastering2_config.bands[j].gain - threshold; } else { mfcc_gains_mono[j] = (mfcc_mono[j] - mastering2_config.bands[j].mean) / ratio + mastering2_config.bands[j].mean + mastering2_config.bands[j].gain - mfcc_mono[j]; } } // calculate band gain for (int j = 0; j < mfcc_len; j++) { mfcc_gains_mono[j] *= 2.0 / num_filters; } dct.DctType3(mfcc_gains_mono.data(), band_gains_mono.data()); } // apply gain mfcc_calculator.calculateSpectrumFromMelSpectrum(band_gains_mono.data(), width, true, false, spec_gains_mono.data()); for (int i = 0; i < channels; i++) { for (int j = 0; j < spec_len; j++) { const double scale = bakuage::Pow(10, spec_gains_mono[j] / 20); complex_spec[i][j] *= scale; } } // ifft and output for (int i = 0; i < channels; i++) { for (int j = 0; j < spec_len; j++) { fft_output[j][0] = complex_spec[i][j].real(); fft_output[j][1] = complex_spec[i][j].imag(); } fftw_execute(inv_plan); for (int j = 0; j < width; j++) { int k = pos + j; if (0 <= k && k < frames) { result[channels * k + i] += fft_input[j]; } } } pos += shift; } { std::lock_guard<std::recursive_mutex> lock(FFTW::mutex()); fftw_destroy_plan(plan); fftw_destroy_plan(inv_plan); fftw_free(fft_output); fftw_free(fft_input); } *_wave = std::move(result); #endif } }
8,166
https://github.com/riccardopoiani/recsys_2019/blob/master/src/model/KNN/UserSimilarityRecommender.py
Github Open Source
Open Source
MIT
2,020
recsys_2019
riccardopoiani
Python
Code
239
1,279
from course_lib.Base.BaseRecommender import BaseRecommender from course_lib.Base.Recommender_utils import check_matrix, similarityMatrixTopK from course_lib.Base.BaseSimilarityMatrixRecommender import BaseSimilarityMatrixRecommender from course_lib.Base.IR_feature_weighting import okapi_BM_25, TF_IDF import numpy as np import scipy.sparse as sps from course_lib.Base.Similarity.Compute_Similarity import Compute_Similarity class UserSimilarityRecommender(BaseSimilarityMatrixRecommender): """ UserKNN Similarity Recommender""" RECOMMENDER_NAME = "UserSimilarityRecommender" FEATURE_WEIGHTING_VALUES = ["BM25", "TF-IDF", "none"] def __init__(self, URM_train, UCM_train, recommender: BaseRecommender, verbose=True): super(UserSimilarityRecommender, self).__init__(URM_train, verbose=verbose) cold_users_mask = np.ediff1d(URM_train.tocsr().indptr) == 0 self.cold_users = np.arange(URM_train.shape[0])[cold_users_mask] self.UCM_train = sps.hstack([UCM_train, URM_train], format="csr") self.recommender = recommender def fit(self, topK=50, shrink=100, similarity='cosine', normalize=True, feature_weighting="none", **similarity_args): self.topK = topK self.topComputeK = topK + len(self.cold_users) self.shrink = shrink if feature_weighting not in self.FEATURE_WEIGHTING_VALUES: raise ValueError( "Value for 'feature_weighting' not recognized. Acceptable values are {}, provided was '{}'".format( self.FEATURE_WEIGHTING_VALUES, feature_weighting)) if feature_weighting == "BM25": self.UCM_train = self.UCM_train.astype(np.float32) self.UCM_train = okapi_BM_25(self.UCM_train) elif feature_weighting == "TF-IDF": self.UCM_train = self.UCM_train.astype(np.float32) self.UCM_train = TF_IDF(self.UCM_train) similarity = Compute_Similarity(self.UCM_train.T, shrink=shrink, topK=self.topComputeK, normalize=normalize, similarity=similarity, **similarity_args) self.W_sparse = similarity.compute_similarity() self.W_sparse = self.W_sparse.tocsc() for user in self.cold_users: self.W_sparse.data[self.W_sparse.indptr[user]: self.W_sparse.indptr[user+1]] = 0 self.W_sparse.eliminate_zeros() self.W_sparse = self.W_sparse.tocsr() self.W_sparse = similarityMatrixTopK(self.W_sparse, k=self.topK).tocsr() self.W_sparse = check_matrix(self.W_sparse, format='csr') # Add identity matrix to the recommender self.recommender.W_sparse = self.recommender.W_sparse + sps.identity(self.recommender.W_sparse.shape[0], format="csr") def _compute_item_score(self, user_id_array, items_to_compute=None): """ URM_train and W_sparse must have the same format, CSR :param user_id_array: :param items_to_compute: not implemented!! :return: """ self._check_format() def calculate_scores(user): user = user[0] user_weights = self.W_sparse.data[self.W_sparse.indptr[user]:self.W_sparse.indptr[user + 1]] significant_users = self.W_sparse.indices[self.W_sparse.indptr[user]: self.W_sparse.indptr[user + 1]] scores = self.recommender._compute_item_score(significant_users, items_to_compute=None) weighted_scores = np.multiply(scores, np.reshape(user_weights, newshape=(len(user_weights), 1))) return np.sum(weighted_scores, axis=0) item_scores = np.apply_along_axis(calculate_scores, 1, np.reshape(user_id_array, newshape=(len(user_id_array), 1))) return np.array(item_scores).reshape(len(user_id_array), self.n_items)
36,015
https://github.com/maurizioabba/rose/blob/master/src/util/support/FileHelper.h
Github Open Source
Open Source
BSD-3-Clause
2,019
rose
maurizioabba
C
Code
702
1,739
// Consider using $ROSE/src/util/FileSystem.h since that one is documented and uses a proper path type and supports both // version 2 and version 3 of boost::filesystem. // UNDER NO CIRCUMSTANCES SHOULD BOOST_FILESYSTEM_VERSION BE SET!!! // // The boost::filesystem version is not dependent on which compiler we're using, but rather which version // of boost is installed. Hard-coding a boost version number based on the compiler version has a couple of problems: // 1. We don't know whether that filesystem version is available on a user's machine since ROSE supports multiple // versions of boost (e.g., filesystem 3 is not available before boost 1.44) // 2. It pollutes things for the user, who might not want the version we select here (e.g., most users of recent // versions of boost will almost certainly want version 3, not the version 2 we select). // Therefore, we should never select a filesystem version explicitly here, but rather be prepared to handle any version // that is installed. If ROSE cannot support a particular version of boost::filesystem on a particular architecture with a // particular file then that should be documented where we state which versions of boost are supported, and possibly // checked during configuration. [Matzke 11/17/2014]: #include <FileSystem.h> #include <boost/filesystem.hpp> #include <string> using namespace std; using namespace boost::filesystem; class FileHelper { public: // This is initialized in src/frontend/SageIII/sage_support/sage_support.cpp, not FileHelper.C static const string pathDelimiter; static void ensureParentFolderExists(const string& path) { ensureFolderExists(getParentFolder(path)); } static void ensureFolderExists(const string& folder){ path boostPath(folder); create_directories(boostPath); } static void eraseFolder(const string& folder) { path boostPath(folder); remove_all(boostPath); } static string concatenatePaths(const string& path1, const string& path2) { if (path1.size() == 0) { return path2; } if (path2.size() == 0) { return path1; } return path1 + pathDelimiter + path2; } static string getParentFolder(const string& aPath) { path boostPath(aPath); return boostPath.parent_path().string(); } static string getFileName(const string& aPath) { return rose::FileSystem::toString(path(aPath).filename()); } static string makeAbsoluteNormalizedPath(const string& path, const string& workingDirectory) { if (!isAbsolutePath(path)) { //relative path, so prepend the working directory and then normalize return normalizePath(concatenatePaths(workingDirectory, path)); } else { return normalizePath(path); } } static bool isAbsolutePath(const string& path) { return path.compare(0, 1, pathDelimiter) == 0; } //Expects both paths to be absolute. static bool areEquivalentPaths(const string& path1, const string& path2) { //Note: Do not use boost::filesystem::equivalent since the compared paths might not exist, which will cause an error. return normalizePath(path1).compare(normalizePath(path2)) == 0; } static string getIncludedFilePath(const list<string>& prefixPaths, const string& includedPath) { for (list<string>::const_iterator prefixPathPtr = prefixPaths.begin(); prefixPathPtr != prefixPaths.end(); prefixPathPtr++) { string potentialPath = concatenatePaths(*prefixPathPtr, includedPath); if (fileExists(potentialPath)) { return potentialPath; } } //The included file was not found, so return an empty string. return ""; } //Assumes that both arguments are absolute and normalized. //Argument toPath can be either a folder or a file. static string getRelativePath(const string& fromFolder, const string& toPath) { return rose::FileSystem::toString(rose::FileSystem::makeRelative(toPath, fromFolder)); } static bool fileExists(const string& fullFileName) { return exists(fullFileName); } static bool isNotEmptyFolder(const string& fullFolderName) { return exists(fullFolderName) && !is_empty(fullFolderName); } static string normalizePath(const string& aPath) { path boostPath(aPath); string normalizedPath = boostPath.normalize().string(); return normalizedPath; } static string getNormalizedContainingFileName(PreprocessingInfo* preprocessingInfo) { return normalizePath(preprocessingInfo -> get_file_info() -> get_filenameString()); } //Either path1 includes path2 or vice versa static string pickMoreGeneralPath(const string& path1, const string& path2) { string textualPart1 = getTextualPart(path1); string textualPart2 = getTextualPart(path2); //The longer textual part should be more general, assert that string moreGeneralPath = textualPart1.size() > textualPart2.size() ? textualPart1 : textualPart2; ROSE_ASSERT(endsWith(moreGeneralPath, textualPart1)); ROSE_ASSERT(endsWith(moreGeneralPath, textualPart2)); return moreGeneralPath; } static string getTextualPart(const string& path) { string normalizedPath = normalizePath(path); //Remove all leading "../" and "./" (and they can be only leading, since the path is normalized). size_t pos = normalizedPath.rfind(".." + pathDelimiter); if (pos != string::npos) { normalizedPath = normalizedPath.substr(pos + 3); } pos = normalizedPath.rfind("." + pathDelimiter); if (pos != string::npos) { normalizedPath = normalizedPath.substr(pos + 2); } return normalizedPath; } //Count how many leading "../" are in a path (after its normalization) static int countUpsToParentFolder(const string& path) { string normalizedPath = normalizePath(path); string upPath = ".." + pathDelimiter; int counter = 0; size_t pos = normalizedPath.find(upPath); while (pos != string::npos) { counter++; pos = normalizedPath.find(upPath, pos + 3); } return counter; } static bool endsWith(const string& str1, const string& str2) { //checks that str1 ends with str2 return boost::ends_with(str1, str2); } };
13,809
https://github.com/javimartin22/grupo07spq/blob/master/src/main/java/concesionario/cliente/ventana/comercial/VentanaRegistrarCocheConcesionario.java
Github Open Source
Open Source
Apache-2.0
2,020
grupo07spq
javimartin22
Java
Code
577
2,401
package concesionario.cliente.ventana.comercial; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import concesionario.cliente.controller.ComercialController; import concesionario.datos.CocheConcesionario; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JTextField; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import javax.swing.JComboBox; import javax.swing.DefaultComboBoxModel; import javax.swing.JSpinner; import java.awt.Font; /** * Clase para registrar los coches en el concesionario */ public class VentanaRegistrarCocheConcesionario extends JFrame { private static final long serialVersionUID = 1L; private JPanel contentPane; private JTextField modelo; private JTextField marca; private JTextField precio; private JTextField textField_1; final Logger logger = LoggerFactory.getLogger(VentanaRegistrarCocheConcesionario.class); static int iteration = 0; /** * Controlador para la clase ComercialController */ private ComercialController comercialController; /** * Controller para la clase ComercialController * @param comercialController (Controlador de la ventana VentanaRegistrarCocheComercial) * @param nickname (Nickname del comercial) */ public VentanaRegistrarCocheConcesionario (ComercialController comercialController, String nickname) { setTitle("Registro Coche Concesionario"); setResizable(false); this.comercialController = comercialController; iniciarVentanaRegistrarCocheConcesionario(nickname); } /** * Create the frame * @param nickname (Nickname del Comercial) */ public void iniciarVentanaRegistrarCocheConcesionario(String nickname) { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 450, 367); setLocationRelativeTo(null); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); JButton btnCancelar = new JButton("Cancelar"); btnCancelar.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { VentanaMenuComercial vmc = new VentanaMenuComercial(comercialController, nickname); vmc.setVisible(true); dispose(); } }); btnCancelar.setBounds(105, 290, 117, 29); contentPane.add(btnCancelar); JLabel lblNombreDelModelo = new JLabel("Nombre del Modelo:"); lblNombreDelModelo.setFont(new Font("Tahoma", Font.BOLD, 11)); lblNombreDelModelo.setBounds(37, 32, 171, 16); contentPane.add(lblNombreDelModelo); JLabel lblNewLabel = new JLabel("Nombre de la Marca:"); lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 11)); lblNewLabel.setBounds(37, 70, 171, 16); contentPane.add(lblNewLabel); JLabel lblNewLabel_1 = new JLabel("Precio: "); lblNewLabel_1.setFont(new Font("Tahoma", Font.BOLD, 11)); lblNewLabel_1.setBounds(37, 111, 171, 16); contentPane.add(lblNewLabel_1); modelo = new JTextField(); modelo.setBounds(220, 27, 199, 26); contentPane.add(modelo); modelo.setColumns(10); marca = new JTextField(); marca.setBounds(220, 65, 199, 26); contentPane.add(marca); marca.setColumns(10); precio = new JTextField(); precio.setBounds(220, 106, 199, 26); contentPane.add(precio); precio.setColumns(10); JLabel lblColor = new JLabel("Color:"); lblColor.setFont(new Font("Tahoma", Font.BOLD, 11)); lblColor.setBounds(37, 150, 61, 16); contentPane.add(lblColor); JComboBox comboBox = new JComboBox(); comboBox.setModel(new DefaultComboBoxModel(new String[] {"Rojo", "Azul ", "Plata", "Amarillo", "Verde", "Blanco", "Negro", "Blanco Marfil", "Gris"})); comboBox.setBounds(220, 146, 137, 27); contentPane.add(comboBox); JLabel lblUnidades = new JLabel("Numero de Puertas:"); lblUnidades.setFont(new Font("Tahoma", Font.BOLD, 11)); lblUnidades.setBounds(37, 187, 148, 16); contentPane.add(lblUnidades); JLabel lblNewLabel_2 = new JLabel("CV:"); lblNewLabel_2.setFont(new Font("Tahoma", Font.BOLD, 11)); lblNewLabel_2.setBounds(37, 222, 61, 16); contentPane.add(lblNewLabel_2); JLabel lblNewLabel_3 = new JLabel("Unidades: "); lblNewLabel_3.setFont(new Font("Tahoma", Font.BOLD, 11)); lblNewLabel_3.setBounds(37, 258, 171, 16); contentPane.add(lblNewLabel_3); textField_1 = new JTextField(); textField_1.setBounds(220, 217, 199, 26); contentPane.add(textField_1); textField_1.setColumns(10); JSpinner spinner = new JSpinner(); spinner.setBounds(220, 252, 76, 26); contentPane.add(spinner); JSpinner spinner_1 = new JSpinner(); spinner_1.setBounds(220, 182, 76, 26); contentPane.add(spinner_1); JButton btnNewButton = new JButton("Registrar"); btnNewButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (comprobarCampos()) { String ma = marca.getText(); String mo = modelo.getText(); int pr = Integer.parseInt(precio.getText()); int cv = Integer.parseInt(textField_1.getText()); int numPuertas = Integer.parseInt(spinner_1.getValue().toString()); int c = comboBox.getSelectedIndex(); String color = comercialController.comprobarColor(c); int unidades = Integer.parseInt(spinner.getValue().toString()); CocheConcesionario coche = new CocheConcesionario(ma, mo, pr, cv, numPuertas, color, unidades); registrarCoche(coche, nickname); } else { JOptionPane.showMessageDialog(contentPane, "Todos los campos deben estar completos"); logger.error("Todos los campos deben estar correctamente rellenados", iteration++); } } }); btnNewButton.setBounds(259, 290, 117, 29); contentPane.add(btnNewButton); } /** * Metodo para registrar coches * @param coche Objeto de tipo CocheConcesionario * @param nickname Nickname del comercial */ public void registrarCoche(CocheConcesionario coche, String nickname) { if(comercialController.registrarCoche(coche)) { logger.info("El vehiculo ha sido registrado correctamente."); VentanaMenuComercial vmc = new VentanaMenuComercial(comercialController, nickname); vmc.setVisible(true); dispose(); } else { logger.error("Error al registrar el CocheConcesionario."); } } /** * Metodo para comprobar los campos * @return boolean Si los campos no estan vacios, devuelve un True y si no False */ public boolean comprobarCampos() { boolean datos = false; if (!textField_1.getText().isEmpty() && !modelo.getText().isEmpty() && !marca.getText().isEmpty() && !precio.getText().isEmpty()) { datos = true; } return datos; } }
45,292
https://github.com/jamoum/JavaScript_Challenges_Solutions/blob/master/hard/repeating-cycle/code.spec.js
Github Open Source
Open Source
MIT
2,022
JavaScript_Challenges_Solutions
jamoum
JavaScript
Code
114
366
const isRepeatingCycle = require('./code'); describe('Tests', () => { test('Trivially repeating, since array is identical.', () => { expect(isRepeatingCycle([1, 1, 1, 1], 3)).toEqual(true); }); test('Trivially repeating, since the cycle length = length of the array.', () => { expect(isRepeatingCycle([1, 2, 1, 9], 4)).toEqual(true); }); test('Cycle length exceeds array length, so trivially true.', () => { expect(isRepeatingCycle([1, 1, 3, 1, 1], 7)).toEqual(true); }); test('the tests', () => { expect(isRepeatingCycle([1, 2, 3, 1, 2, 3, 1], 3)).toEqual(true); expect(isRepeatingCycle([1, 2, 3, 4, 2, 3, 1], 4)).toEqual(false); expect(isRepeatingCycle([1, 2, 1, 2, 2], 2)).toEqual(false); expect(isRepeatingCycle([1, 2, 1, 2, 1, 2, 1], 3)).toEqual(false); expect(isRepeatingCycle([1, 2, 1, 2, 1, 2, 1], 2)).toEqual(true); expect(isRepeatingCycle([1, 2, 1, 2, 1, 2, 1], 4)).toEqual(true); }); });
37,399
https://github.com/gry260/guolina/blob/master/build/paths/vendor.js
Github Open Source
Open Source
MIT
2,019
guolina
gry260
JavaScript
Code
246
783
var mainBowerFiles = require('main-bower-files'); var config = require('../config'); var rootDir = config.rootDir; var srcDir = config.srcDir; var destDir = config.destDir; var bowerDir = config.bowerDir; /******************************************************************************* ...Few words about vendor files For not including all scripts manually we use plugin called main-bower-files. It returns glob of files based on "main" field in vendor packages "bower.json". Orders of files will be as per our bower.json, so if you have some libraries that should be loaded on first, just move them upwards in project "bower.json". If any of files that you want to access is not listed in vendor package, you can define files for that package manually in bower.json "overrides" field. For more docs visit. https://github.com/ck86/main-bower-files#main-bower-files If for any reasons you don't like this approach, and want list your files manually, you can just pass manual glob string or array to "src" option eg. export.scripts: [ bowerDir + "jquery/dist/jquery.js", bowerDir + "angular/jquery.js", ] ********************************************************************************/ /*********************************************** * Vendor script files ************************************************/ exports.scripts = mainBowerFiles({ filter: [ '**/*.js', '!**/*.min.js' ], paths: rootDir }); /*********************************************** * Vendor style files ************************************************/ exports.styles = mainBowerFiles({ filter: [ '**/*.css', '!**/*.min.css' ], paths: rootDir }); /*********************************************** * Vendor assets files ************************************************/ /* All files which are not .js, .css, .less and fonts */ exports.assets = mainBowerFiles({ filter: [ '**/*', '!**/*.js', '!**/*.css', '!**/*.less', // Ingore fonts '!**/*.otf', '!**/*.eot', '!**/*.ttf', '!**/*.woff', '!**/*.woff2' ], paths: rootDir }); /*********************************************** * Vendor font files ************************************************/ exports.fonts = mainBowerFiles({ filter: [ '**/*.otf', '**/*.eot', '**/*.ttf', '**/*.woff', '**/*.woff2', '**/*.svg' ], paths: rootDir });
39,902
https://github.com/lezaz/lezaz.github.io/blob/master/plugin/site-plugin/src/main/java/com/frankdevhub/site/core/exception/ArgumentIsNullException.java
Github Open Source
Open Source
MIT
2,021
lezaz.github.io
lezaz
Java
Code
15
53
package com.frankdevhub.site.core.exception; public class ArgumentIsNullException extends BusinessException { public ArgumentIsNullException(String message) { super(message); } }
9,764
https://github.com/San3132308912/crypto-accumulators/blob/master/lib/utils/LibConversions.cpp
Github Open Source
Open Source
MIT
2,021
crypto-accumulators
San3132308912
C++
Code
510
1,465
/* * LibConversions2.cpp * * Created on: Apr 19, 2013 * Author: etremel */ #include <iomanip> #include <iostream> #include <sstream> #include <utils/LibConversions.hpp> extern const scalar_t bn_n; using std::dec; using std::hex; using std::istringstream; using std::ostringstream; using std::setfill; using std::setw; using std::string; using std::stringstream; namespace LibConversions { void getModulus(flint::BigInt& modulus) { char buffer[1024]; bzero(buffer, 1024); scalarToString(bn_n, buffer); modulus = flint::BigInt(buffer, 10); } void scalarToMpz(const scalar_t scalar, mpz_t mpz) { mpz_import(mpz, 4, -1, sizeof(scalar[0]), 0, 0, scalar); } void mpzToScalar(const mpz_t mpz, scalar_t scalar) { for(int i = 0; i < 4; i++) { memset(&scalar[i], 0, sizeof(scalar[i])); } mpz_export(scalar, NULL, -1, sizeof(scalar[0]), 0, 0, mpz); } void scalarToString(const scalar_t scalar, char* str) { mpz_t mpz; mpz_init(mpz); scalarToMpz(scalar, mpz); gmp_sprintf(str, "%Zd\n", mpz); mpz_clear(mpz); } void stringToScalar(const char* str, scalar_t scalar) { mpz_t mpz; mpz_init(mpz); gmp_sscanf(str, "%Zd\n", mpz); mpzToScalar(mpz, scalar); mpz_clear(mpz); } void scalarToBigMod(const scalar_t& scalar, flint::BigMod& target) { char buffer[1024]; bzero(buffer, 1024); scalarToString(scalar, buffer); flint::BigInt modulus; getModulus(modulus); target.setModulus(modulus); target.assign(buffer); } void bigModToScalar(const flint::BigMod& bigmod, scalar_t& target) { string str = bigmod.toString(); stringToScalar(str.c_str(), target); } void CryptoPPToFlint(const CryptoPP::Integer& cryptoInt, flint::BigInt& flintInt) { ostringstream outStream; outStream << cryptoInt; //Frustratingly, CryptoPP appends an unnecessary decimal point (".") to the //end of the string representation of its Integer, which prevents it from //being read properly by FLINT. Otherwise I could just redirect the stream. string intermediateString = outStream.str(); string truncatedString = intermediateString.substr(0, intermediateString.size() - 1); if(!flintInt.assign(truncatedString)) std::cerr << "Assign failed!" << std::endl; } void bigIntToBytes(const flint::BigInt& bigint, unsigned char* byteArray) { hexStringToBytes(bigint.toHex(), byteArray); } void bytesToBigInt(const unsigned char* byteArray, int length, flint::BigInt& bigint) { stringstream bytesHexString; bytesHexString << hex << setfill('0'); for(int i = 0; i < length; i++) { bytesHexString << setw(2) << static_cast<int>(byteArray[i]); } //I don't know how to override operator>> properly to take the hex modifier, so I'll just use a constructor... bigint = flint::BigInt(bytesHexString.str().c_str(), 16); } /** * Helper method: ugly hack to blindly "parse" string characters * representing hex values by exploiting their ASCII code values. * @param hexDigit an ASCII character containing a digit 0-F * @return a byte containing its value (as binary, not ASCII), or -1 if * there was an error parsing (i.e. the character was not a * valid hex digit). */ unsigned char valueOfHex(const char& hexDigit) { if(hexDigit >= '0' && hexDigit <= '9') { return hexDigit - '0'; } if(hexDigit >= 'A' && hexDigit <= 'F') { return hexDigit - 'A' + 10; } if(hexDigit >= 'a' && hexDigit <= 'f') { return hexDigit - 'a' + 10; } return -1; } void hexStringToBytes(const string& hexString, unsigned char* byteArray) { if(hexString.length() % 2 != 0) { //Add an implied leading 0, so the first "pair" of digits is just the lower-order one byteArray[0] = valueOfHex(hexString[0]); for(size_t i = 1; i < (hexString.length() + 1) / 2; i++) { byteArray[i] = valueOfHex(hexString[2 * i - 1]) * 16 + valueOfHex(hexString[2 * i]); } } else { for(size_t i = 0; i < hexString.length() / 2; i++) { byteArray[i] = valueOfHex(hexString[2 * i]) * 16 + valueOfHex(hexString[2 * i + 1]); } } } } // namespace LibConversions
50,245
https://github.com/klorel/or-tools/blob/master/examples/data/rcpsp/multi_mode/mmlibplus_jall161_1.mm
Github Open Source
Open Source
Apache-2.0
2,022
or-tools
klorel
Objective-C++
Code
2,840
6,014
jobs (incl. supersource/sink ): 52 RESOURCES - renewable : 2 R - nonrenewable : 4 N - doubly constrained : 0 D ************************************************************************ PRECEDENCE RELATIONS: jobnr. #modes #successors successors 1 1 6 2 3 6 7 8 9 2 6 3 14 10 4 3 6 3 13 10 5 4 6 3 13 12 11 5 6 3 16 12 11 6 6 3 15 13 11 7 6 2 16 10 8 6 3 17 16 12 9 6 1 10 10 6 2 17 12 11 6 3 28 20 17 12 6 2 20 15 13 6 2 22 16 14 6 2 22 16 15 6 4 28 25 22 18 16 6 4 28 25 20 18 17 6 3 25 22 18 18 6 2 21 19 19 6 6 40 35 33 29 26 23 20 6 6 40 35 33 29 27 26 21 6 4 40 35 26 23 22 6 4 35 33 31 24 23 6 3 37 31 27 24 6 3 40 37 27 25 6 7 44 40 39 36 35 34 33 26 6 5 45 39 32 31 30 27 6 5 45 44 39 32 30 28 6 5 40 39 37 32 30 29 6 7 45 44 42 39 38 37 36 30 6 3 43 36 34 31 6 4 51 49 44 36 32 6 2 38 36 33 6 6 51 50 48 47 46 42 34 6 3 48 42 38 35 6 3 47 41 37 36 6 3 50 47 41 37 6 3 49 48 43 38 6 3 51 47 46 39 6 3 50 47 46 40 6 2 47 42 41 6 2 48 46 42 6 1 49 43 6 1 46 44 6 1 46 45 6 1 50 46 6 1 52 47 6 1 52 48 6 1 52 49 6 1 52 50 6 1 52 51 6 1 52 52 1 0 ************************************************************************ REQUESTS/DURATIONS jobnr. mode dur R1 R2 N1 N2 N3 N4 ------------------------------------------------------------------------ 1 1 0 0 0 0 0 0 0 2 1 2 14 18 12 11 11 6 2 6 12 16 12 8 10 6 3 8 10 16 12 7 10 5 4 9 7 15 12 6 10 4 5 18 5 14 12 5 9 2 6 19 3 14 12 4 9 2 3 1 2 12 9 7 9 5 11 2 4 11 8 6 6 4 10 3 7 10 8 5 6 4 10 4 9 10 7 5 4 4 9 5 11 10 6 4 3 4 8 6 15 9 6 2 2 4 8 4 1 1 14 16 17 11 9 15 2 5 11 16 17 10 7 14 3 7 8 14 17 9 6 13 4 8 8 12 16 8 5 12 5 13 4 12 15 6 4 11 6 18 2 10 15 6 4 10 5 1 1 15 13 15 20 7 16 2 3 15 11 13 15 7 15 3 4 12 9 13 13 7 14 4 15 12 7 10 11 7 13 5 17 10 7 7 8 7 11 6 20 8 5 7 7 7 11 6 1 3 15 19 6 17 8 16 2 9 14 19 6 17 7 12 3 16 12 19 5 15 6 12 4 17 12 19 3 15 6 8 5 18 10 19 3 14 5 7 6 19 8 19 1 12 4 6 7 1 1 11 9 15 13 9 5 2 2 11 8 13 12 8 4 3 4 10 7 12 11 8 3 4 16 8 7 9 11 7 3 5 17 7 7 6 10 6 2 6 18 7 6 5 10 6 1 8 1 2 11 14 17 12 5 11 2 4 11 14 14 12 4 10 3 5 11 13 14 11 4 9 4 16 11 12 12 9 4 7 5 18 11 10 11 9 4 7 6 20 11 10 9 8 4 6 9 1 2 10 6 8 12 15 11 2 4 9 6 8 11 14 10 3 6 7 6 8 10 13 9 4 8 6 5 8 9 11 7 5 13 5 5 8 8 10 3 6 16 4 5 8 8 10 2 10 1 9 5 17 16 8 11 11 2 12 5 12 13 8 11 8 3 13 5 11 9 8 9 7 4 15 5 8 7 7 6 5 5 17 5 7 6 7 4 5 6 18 5 6 5 7 2 3 11 1 3 16 20 18 18 20 8 2 8 16 18 15 17 18 8 3 10 12 15 10 14 18 8 4 12 11 13 7 14 18 8 5 13 6 12 4 11 17 8 6 20 4 10 3 10 16 8 12 1 4 19 7 12 12 20 20 2 6 19 6 11 12 17 19 3 7 18 5 11 12 16 19 4 8 16 3 11 12 16 18 5 10 15 2 10 12 15 18 6 18 14 1 10 12 13 18 13 1 8 11 13 18 18 10 12 2 13 11 12 17 16 10 12 3 15 11 11 16 15 8 10 4 16 11 10 15 14 7 10 5 17 11 9 14 13 7 9 6 18 11 9 13 12 6 8 14 1 4 11 7 11 15 16 20 2 7 9 7 10 15 16 19 3 9 8 7 10 15 16 18 4 10 7 7 10 14 16 17 5 13 6 7 10 14 16 16 6 19 5 7 10 14 16 16 15 1 9 18 15 12 15 9 16 2 10 17 15 11 13 8 14 3 12 13 15 9 12 5 13 4 13 12 15 7 10 4 8 5 17 11 15 5 8 4 8 6 18 7 15 3 8 2 5 16 1 1 6 10 18 7 16 14 2 8 6 9 14 6 16 13 3 9 4 7 12 6 15 11 4 15 4 6 9 5 15 9 5 16 2 6 6 5 15 7 6 20 1 4 3 4 14 5 17 1 3 14 14 16 11 5 19 2 4 12 14 14 10 4 16 3 5 12 13 13 10 4 12 4 10 9 13 10 9 3 7 5 15 7 12 10 9 3 6 6 20 6 11 8 9 3 4 18 1 1 10 15 11 5 10 11 2 4 10 15 9 5 10 10 3 5 10 13 8 5 9 10 4 6 10 12 7 4 8 9 5 9 10 12 7 4 7 7 6 11 10 10 6 4 6 7 19 1 3 14 3 18 11 8 11 2 7 13 3 17 11 7 9 3 10 13 3 14 11 7 9 4 13 11 2 13 11 6 8 5 17 11 2 9 11 5 7 6 19 10 2 8 11 5 7 20 1 2 17 14 15 9 17 12 2 3 16 13 14 8 16 9 3 6 16 12 13 8 15 9 4 9 16 11 13 7 11 6 5 18 16 10 12 7 8 4 6 19 16 10 11 7 7 3 21 1 2 16 3 11 13 5 11 2 3 14 3 9 12 4 10 3 7 13 3 9 12 3 9 4 9 13 3 8 11 3 8 5 12 12 2 6 10 2 6 6 16 10 2 6 10 1 5 22 1 6 9 16 7 13 17 6 2 7 9 16 6 12 16 5 3 11 7 13 6 11 16 4 4 17 6 9 5 11 15 3 5 18 4 8 5 10 15 2 6 20 4 6 5 9 14 1 23 1 3 13 14 9 16 17 11 2 4 13 13 9 14 17 10 3 5 12 12 6 13 17 10 4 8 10 12 5 13 17 10 5 11 9 12 3 11 16 10 6 14 8 11 1 11 16 10 24 1 1 11 14 17 18 19 13 2 4 8 12 15 18 15 13 3 7 7 11 13 14 13 13 4 8 6 9 10 12 11 12 5 9 5 6 8 11 6 12 6 18 2 5 5 9 5 12 25 1 6 12 20 9 18 11 12 2 7 11 17 9 13 11 11 3 13 11 17 6 11 7 11 4 14 8 15 5 11 5 11 5 18 6 15 4 8 4 11 6 20 5 13 3 7 1 11 26 1 6 19 4 19 14 17 16 2 7 18 3 17 13 17 15 3 13 16 3 15 13 16 15 4 18 16 3 13 13 16 14 5 19 15 2 13 13 14 13 6 20 14 1 11 13 14 12 27 1 7 14 14 15 19 7 12 2 8 12 13 14 19 5 11 3 9 9 13 14 19 5 9 4 10 8 13 14 18 4 9 5 16 4 13 14 17 4 7 6 20 3 13 14 17 3 7 28 1 1 6 12 8 8 14 7 2 2 6 12 8 8 14 6 3 8 6 12 8 8 14 4 4 14 6 11 7 8 14 3 5 15 5 11 6 8 14 3 6 19 5 11 6 8 14 2 29 1 3 7 18 17 15 14 15 2 4 6 16 16 12 13 14 3 7 6 13 16 9 11 12 4 8 4 9 16 8 10 8 5 13 4 6 16 7 7 5 6 14 3 4 16 5 5 4 30 1 5 17 17 13 10 3 15 2 9 13 16 13 10 2 13 3 10 11 16 13 10 2 12 4 11 10 14 13 10 2 8 5 13 7 13 13 10 2 5 6 17 5 13 13 10 2 4 31 1 3 2 9 13 16 13 16 2 6 2 8 12 16 13 16 3 8 2 8 9 15 12 16 4 9 2 7 9 15 10 16 5 12 2 5 7 13 8 16 6 13 2 5 6 13 8 16 32 1 7 13 15 12 14 15 17 2 8 13 15 12 13 15 15 3 12 13 15 11 9 13 15 4 17 13 15 10 9 13 14 5 18 13 15 8 6 11 13 6 20 13 15 6 4 11 11 33 1 4 7 7 17 11 2 10 2 5 6 7 14 11 2 9 3 7 6 7 13 10 2 9 4 15 6 7 11 10 2 8 5 18 6 7 10 8 2 8 6 19 6 7 8 8 2 7 34 1 1 13 17 13 17 14 3 2 3 11 17 13 15 14 2 3 11 8 15 13 10 12 2 4 13 7 14 12 8 11 1 5 19 5 12 12 4 10 1 6 20 3 12 12 3 9 1 35 1 1 18 10 17 9 20 14 2 2 17 10 13 9 19 14 3 3 17 8 13 9 19 12 4 4 16 6 9 8 19 11 5 8 16 6 7 8 19 10 6 17 16 3 4 8 19 10 36 1 3 10 13 5 18 18 3 2 8 9 13 5 18 18 2 3 14 8 13 5 18 18 2 4 16 7 13 5 17 18 1 5 18 5 13 5 17 18 2 6 19 5 13 5 17 18 1 37 1 1 14 10 18 14 10 18 2 7 12 9 15 12 9 16 3 10 12 9 10 11 7 16 4 14 11 7 8 9 5 15 5 15 7 6 4 5 5 14 6 20 7 6 2 3 3 14 38 1 1 14 4 11 9 13 14 2 6 12 4 10 8 13 13 3 9 9 4 10 7 13 12 4 10 8 4 10 6 13 11 5 12 5 4 9 5 13 10 6 17 4 4 9 5 13 9 39 1 8 10 12 11 4 16 18 2 9 9 10 9 4 15 17 3 10 9 9 8 4 15 15 4 11 8 9 6 4 13 14 5 12 8 7 4 3 13 13 6 17 8 7 3 3 11 13 40 1 3 18 20 18 12 10 16 2 6 17 15 18 9 7 14 3 7 15 12 18 9 6 14 4 8 14 10 18 7 4 14 5 9 14 8 18 6 3 13 6 12 13 4 18 5 1 12 41 1 2 5 15 19 9 12 18 2 3 4 14 15 9 10 17 3 4 3 13 12 9 8 17 4 5 2 13 9 9 8 16 5 7 1 11 6 9 6 16 6 15 1 11 4 9 4 15 42 1 7 9 14 6 10 15 12 2 8 7 13 6 9 13 9 3 9 6 13 5 7 13 8 4 10 5 13 4 6 11 8 5 11 4 11 3 6 11 5 6 12 2 11 3 5 10 4 43 1 3 3 9 5 9 15 16 2 4 3 9 5 6 15 16 3 7 3 7 5 5 15 16 4 8 3 6 5 5 15 16 5 12 3 6 4 2 15 15 6 19 3 5 4 1 15 15 44 1 5 13 4 16 11 12 5 2 7 12 4 14 10 10 4 3 11 12 4 10 9 10 3 4 12 12 4 8 9 9 3 5 13 12 3 6 9 8 2 6 15 12 3 5 8 6 2 45 1 1 18 15 16 12 16 14 2 3 18 13 14 12 15 14 3 10 18 13 13 11 14 13 4 13 18 10 12 11 12 11 5 18 18 10 8 10 8 9 6 19 18 8 8 10 8 8 46 1 1 2 17 10 16 3 11 2 4 2 12 9 15 2 10 3 15 2 12 8 12 2 10 4 16 2 8 6 12 2 10 5 17 1 6 6 10 2 9 6 19 1 6 5 8 2 9 47 1 3 7 9 17 11 19 13 2 4 6 8 15 9 15 11 3 7 6 8 12 9 12 10 4 9 6 6 10 7 9 9 5 12 5 5 7 4 6 9 6 16 5 5 7 3 2 8 48 1 5 17 11 16 19 18 9 2 7 15 10 15 14 14 7 3 9 9 9 11 14 12 6 4 10 8 8 10 12 12 5 5 11 4 7 8 7 8 5 6 12 1 7 5 6 6 3 49 1 7 17 18 9 12 13 16 2 9 15 18 9 10 13 15 3 10 14 17 7 9 13 15 4 15 13 17 6 6 12 15 5 16 8 17 5 6 12 15 6 17 6 16 4 4 12 15 50 1 2 10 8 5 11 13 18 2 3 9 8 3 10 12 17 3 10 8 8 3 9 12 16 4 17 7 8 2 9 11 14 5 18 5 8 1 9 11 14 6 19 4 8 1 8 11 13 51 1 3 12 7 5 16 17 17 2 5 10 7 5 14 15 14 3 6 8 5 4 14 14 12 4 7 8 5 4 11 13 10 5 10 7 3 3 10 10 9 6 12 5 3 3 10 10 7 52 1 0 0 0 0 0 0 0 ************************************************************************ RESOURCE AVAILABILITIES R 1 R 2 N 1 N 2 N 3 N 4 67 61 493 516 506 515 ************************************************************************
30,335
https://github.com/RussellBTech/angular-starter/blob/master/libs/wizard/src/lib/utils/audit.util.ts
Github Open Source
Open Source
MIT
null
angular-starter
RussellBTech
TypeScript
Code
270
755
import { Wizard } from '../wizard.models'; import { arrayToRecord } from './misc.util'; const errorAppend = `<Wizard> `; /** * Find common mistakes in inputs */ export const audit = (sections: Wizard.Section[], pages: Wizard.Page[], routes: Wizard.Route[]) => { const sectionsRecord = arrayToRecord<Wizard.Section>(sections, 'urlSlug'); const pagesRecord: Record<string, Record<string, Wizard.Page>> = {}; pages.forEach((p) => { if (!pagesRecord[p.sectionId]) { pagesRecord[p.sectionId] = {}; } pagesRecord[p.sectionId][p.id] = p; if (!sectionsRecord[p.sectionId]) { console.error(errorAppend + 'Pages sectionID does not match any supplied sections ', p); } }); /** * Create routes record */ const routesRecord: Record<string, Record<string, Wizard.Route>> = {}; routes.forEach((r) => { if (!routesRecord[r.sectionId]) { routesRecord[r.sectionId] = {}; } if (routesRecord[r.sectionId] && routesRecord[r.sectionId][r.urlSlug]) { console.error( errorAppend + `Duplicate urlSlug property found for ${r.urlSlug}. A routes urlSlug must be unique within a section`, r, ); } if (!sectionsRecord[r.sectionId]) { console.error(errorAppend + 'Unable to find that sectionID of ' + r.sectionId + ' for route ', r); } if (!pagesRecord[r.sectionId][r.pageId]) { console.error(errorAppend + `Unable to find a page with a pageId of ${r.pageId} for section ${r.sectionId}`, r); } routesRecord[r.sectionId][r.urlSlug] = r; }); /** * Loop through sections after all records have been created Object.keys(sectionsRecord).forEach(key => { const section: any = <any>sectionsRecord[key]; if (section.sectionNext && !sectionsRecord[section.sectionNext || '']) { console.error(errorAppend + 'Cannot find a section with this sectionNext prop: ', sectionsRecord[key]); } if (!section.sectionNext && !section.sectionLast) { console.error(errorAppend + 'This section is missing either a sectionNext or sessionLast prop. Need either one ', sectionsRecord[key]); } }); */ /** * Loop through Routes after all records have been created */ Object.keys(routesRecord).forEach((key) => { const section = routesRecord[key]; Object.keys(routesRecord).forEach((key2) => { const route = section[key2]; if (!route) { } }); }); };
45,469
https://github.com/CambriconKnight/CNStream/blob/master/modules/ipc/src/server_handler.hpp
Github Open Source
Open Source
Apache-2.0
2,020
CNStream
CambriconKnight
C++
Code
473
1,099
/************************************************************************* * Copyright (C) [2019] by Cambricon, Inc. All rights reserved * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. *************************************************************************/ #ifndef MODULES_IPC_SERVER_HANDLER_HPP_ #define MODULES_IPC_SERVER_HANDLER_HPP_ #include <atomic> #include <cmath> #include <memory> #include <string> #include <vector> #include "cnsocket.hpp" #include "ipc_handler.hpp" namespace cnstream { #define SEND_THREAD_NUM 4 // define threads num for sending data to pipeline using CNPackageQueue = std::unique_ptr<ThreadSafeQueue<FrameInfoPackage>>; /** * @brief for IPCServerHandler, inherited from IPCHandler. */ class IPCServerHandler : public IPCHandler { public: /** * @brief Constructed function. * @param Name : type - define client or server handler * @return None */ explicit IPCServerHandler(const IPCType& type, ModuleIPC* ipc_module); /** * @brief Destructor function. * @return None */ virtual ~IPCServerHandler(); /** * @brief Open resources. * @return Return true if open resources successfully, otherwise, return false. */ bool Open() override; /** * @brief Close resources. * @return Void. */ void Close() override; /** * @brief Shutdown connection between processes. * @return Void. */ void Shutdown() override; /** * @brief Receive FrameInfoPackage with separate thread. * @return Void. */ void RecvPackageLoop() override; /** * @brief Send FrameInfoPackage. * @return Return true if send FrameInfoPackage successfully, otherwise, return false. */ bool Send() override { return false; } /** * @brief Process FrameInfoPackage with separate thread. * @return Void. */ void SendPackageLoop() override; #ifdef UNIT_TEST FrameInfoPackage ReadReceivedData(); #endif private: /** * @brief Listen connections for server * @return Void. */ void ListenConnections(); /** * @brief Process received frame info package, convert FrameInfoPackage to CNFrameInfo and send to pipeline for each * channel. * @return Void. */ void ProcessFrameInfoPackage(size_t channel_idx); private: CNServer server_handle_; // server socket handle std::thread listen_thread_; // thread for listening connection std::thread recv_thread_; // thread for listening received data std::thread send_thread_; // thread for sending data std::atomic<bool> is_running_{false}; // flag to identify thread state std::atomic<bool> is_connected_{false}; // flag to identify connection state std::vector<CNPackageQueue> vec_recv_dataq_; // queues to storage revceived data std::vector<std::thread> vec_process_thread_; // threads for processing received data #ifdef UNIT_TEST ThreadSafeQueue<FrameInfoPackage> recv_pkg_; // received pkg queue for unit_test bool unit_test = true; #endif }; } // namespace cnstream #endif
49,147
https://github.com/envyclient/website/blob/master/app/Http/Controllers/API/AuthController.php
Github Open Source
Open Source
2,023
website
envyclient
PHP
Code
180
587
<?php namespace App\Http\Controllers\API; use App\Http\Controllers\Controller; use App\Http\Resources\UserResource; use App\Models\User; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; class AuthController extends Controller { public function login(Request $request): UserResource|JsonResponse { $data = $this->validate($request, [ 'email' => ['required', 'string', 'email'], 'password' => ['required', 'string'], 'hwid' => ['required', 'string', 'min:40', 'max:40'], ]); if (! auth()->attempt(request(['email', 'password']))) { return self::unauthorized(); } return $this->returnUserObject($request->user(), $data['hwid']); } public function me(Request $request): UserResource|JsonResponse { $data = $this->validate($request, [ 'hwid' => ['required', 'string', 'min:40', 'max:40'], ]); $user = User::where('hwid', $data['hwid'])->firstOrFail(); return $this->returnUserObject($user, $data['hwid']); } private static function returnUserObject(User $user, string $hwid): UserResource|JsonResponse { // check for duplicate hwid $userCheck = User::where('hwid', $hwid)->where('id', '<>', $user->id); if ($userCheck->exists()) { return response()->json(['message' => 'Duplicate hardware identification.'], 403); } // hwid mismatch if ($user->hwid !== null && $user->hwid !== $hwid) { return response()->json(['message' => 'Hardware Identification mismatch.'], 403); } // subscription check if (! $user->hasSubscription()) { return response()->json(['message' => 'User does not have subscription for the client.'], 403); } // ban check if ($user->banned) { return response()->json(['message' => 'Account banned.'], 403); } // update the users hwid $user->update([ 'hwid' => $hwid, ]); return new UserResource($user); } }
5,740
https://github.com/mtn/advent16/blob/master/day19/part1.py
Github Open Source
Open Source
MIT
null
advent16
mtn
Python
Code
89
238
#!/usr/bin/env python3 # https://www.youtube.com/watch?v=uCsD3ZGzMgE inp = 3005290 p2 = 2 while p2 < inp: p2 *= 2 p2 //= 2 print((inp - p2) * 2 + 1) # presents = {i: 1 for i in range(inp)} # nxt = {i:(i+1)%inp for i in range(inp)} # i = 0 # steps = 0 # while True: # nx = nxt[i] # if presents[i]: # presents[i] += presents[nx] # del presents[nx] # nxt[i] = nxt[nx] # del nxt[nx] # i = nxt[i] # if presents[i] == inp: # print(i+1) # break
47,644
https://github.com/ossamafayed/ibm-watson-translation/blob/master/controller/translate.js
Github Open Source
Open Source
MIT
null
ibm-watson-translation
ossamafayed
JavaScript
Code
84
396
const asyncHandler = require("../middleware/async"); const LanguageTranslatorV3 = require('ibm-watson/language-translator/v3'); const { IamAuthenticator } = require('ibm-watson/auth'); const languageTranslator = new LanguageTranslatorV3({ authenticator: new IamAuthenticator({ apikey: '7FUUy47uHfIHo06YwI-Tq7mW1E3kX3y5yzbXWC8oHM8r' }), serviceUrl: 'https://api.au-syd.language-translator.watson.cloud.ibm.com/instances/b7c1c63a-05a2-468a-af91-0711caa1ce30', version: '2021-11-23' }); exports.identify = asyncHandler(async (req, res, next) => { languageTranslator.identify(req.body) .then(response => { res.status(200).json({ sucess: "true", data: response.result }); }) .catch(err => { console.log('error: ', err); }); }); exports.translate = asyncHandler(async (req, res, next) => { languageTranslator.translate(req.body) .then(response => { res.status(200).json({ sucess: "true", data: response.result }); }) .catch(err => { console.log('error: ', err); }); });
3,217
https://github.com/mopsicus/unity-share-plugin-ios-android/blob/master/iOS/Classes/Native/mscorlib_System_Runtime_Serialization_Serializatio2904781384MethodDeclarations.h
Github Open Source
Open Source
MIT
2,016
unity-share-plugin-ios-android
mopsicus
C
Code
164
887
#pragma once #include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <stdint.h> #include <assert.h> #include <exception> // System.Runtime.Serialization.SerializationInfoEnumerator struct SerializationInfoEnumerator_t2904781384; // System.Collections.ArrayList struct ArrayList_t3948406897; // System.Object struct Il2CppObject; // System.String struct String_t; // System.Type struct Type_t; #include "codegen/il2cpp-codegen.h" #include "mscorlib_System_Collections_ArrayList3948406897.h" #include "mscorlib_System_Runtime_Serialization_Serializatio1918496398.h" // System.Void System.Runtime.Serialization.SerializationInfoEnumerator::.ctor(System.Collections.ArrayList) extern "C" void SerializationInfoEnumerator__ctor_m1782497732 (SerializationInfoEnumerator_t2904781384 * __this, ArrayList_t3948406897 * ___list0, const MethodInfo* method) IL2CPP_METHOD_ATTR; // System.Object System.Runtime.Serialization.SerializationInfoEnumerator::System.Collections.IEnumerator.get_Current() extern "C" Il2CppObject * SerializationInfoEnumerator_System_Collections_IEnumerator_get_Current_m1751158349 (SerializationInfoEnumerator_t2904781384 * __this, const MethodInfo* method) IL2CPP_METHOD_ATTR; // System.Runtime.Serialization.SerializationEntry System.Runtime.Serialization.SerializationInfoEnumerator::get_Current() extern "C" SerializationEntry_t1918496398 SerializationInfoEnumerator_get_Current_m1674825235 (SerializationInfoEnumerator_t2904781384 * __this, const MethodInfo* method) IL2CPP_METHOD_ATTR; // System.String System.Runtime.Serialization.SerializationInfoEnumerator::get_Name() extern "C" String_t* SerializationInfoEnumerator_get_Name_m4156977240 (SerializationInfoEnumerator_t2904781384 * __this, const MethodInfo* method) IL2CPP_METHOD_ATTR; // System.Type System.Runtime.Serialization.SerializationInfoEnumerator::get_ObjectType() extern "C" Type_t * SerializationInfoEnumerator_get_ObjectType_m1119292125 (SerializationInfoEnumerator_t2904781384 * __this, const MethodInfo* method) IL2CPP_METHOD_ATTR; // System.Object System.Runtime.Serialization.SerializationInfoEnumerator::get_Value() extern "C" Il2CppObject * SerializationInfoEnumerator_get_Value_m4259496148 (SerializationInfoEnumerator_t2904781384 * __this, const MethodInfo* method) IL2CPP_METHOD_ATTR; // System.Boolean System.Runtime.Serialization.SerializationInfoEnumerator::MoveNext() extern "C" bool SerializationInfoEnumerator_MoveNext_m4116766855 (SerializationInfoEnumerator_t2904781384 * __this, const MethodInfo* method) IL2CPP_METHOD_ATTR; // System.Void System.Runtime.Serialization.SerializationInfoEnumerator::Reset() extern "C" void SerializationInfoEnumerator_Reset_m1660715632 (SerializationInfoEnumerator_t2904781384 * __this, const MethodInfo* method) IL2CPP_METHOD_ATTR;
41,256
https://github.com/Altinn/altinncore/blob/master/src/Altinn.Platform/Altinn.Platform.Storage/Storage.Interface/Models/DeleteStatus.cs
Github Open Source
Open Source
BSD-3-Clause
null
altinncore
Altinn
C#
Code
78
183
using System; using Newtonsoft.Json; namespace Altinn.Platform.Storage.Interface.Models { /// <summary> /// Represents metadata about the delete status of an element /// </summary> public class DeleteStatus { /// <summary> /// Gets or sets if the element is hard deleted. /// </summary> [JsonProperty(PropertyName = "isHardDeleted")] public bool IsHardDeleted { get; set; } /// <summary> /// Gets or sets the date the element was marked for hard delete. /// </summary> [JsonProperty(PropertyName = "hardDeleted")] public DateTime? HardDeleted { get; set; } } }
26,042
https://github.com/looker-open-source/components/blob/master/packages/components/lib/module/Form/Fields/Field/FloatingLabelField.js
Github Open Source
Open Source
MIT
2,023
components
looker-open-source
JavaScript
Code
483
1,388
import _extends from "@babel/runtime/helpers/extends"; import _objectWithoutProperties from "@babel/runtime/helpers/objectWithoutProperties"; const _excluded = ["className", "externalLabel"], _excluded2 = ["ariaLabelOnly", "children", "detail", "disabled", "hideLabel", "id", "inline", "label", "required", "labelOffset", "hasValue", "checkValueOnBlur"]; let _ = t => t, _t; import { width } from '@looker/design-tokens'; import React, { useContext } from 'react'; import styled, { useTheme } from 'styled-components'; import { Space } from '../../../Layout'; import { DISABLED_OPACITY } from '../../constants'; import { FieldsetContext } from '../../../Fieldset'; import { Field } from './Field'; import { FieldDetail } from './FieldDetail'; import { FieldLabel } from './FieldLabel'; import { HelperText } from './HelperText'; import { InputArea } from './InputArea'; import { useFloatingLabel } from './useFloatingLabel'; const getLabelColor = (isFocused, validationMessage) => { if ((validationMessage === null || validationMessage === void 0 ? void 0 : validationMessage.type) === 'error') return 'critical'; if (isFocused) return 'key'; return undefined; }; export const FloatingLabelField = styled(_ref => { let { className, externalLabel: propsExternalLabel } = _ref, props = _objectWithoutProperties(_ref, _excluded); const { ariaLabelOnly, children, detail, disabled, hideLabel, id, inline, label, required, labelOffset, hasValue, checkValueOnBlur } = props, rest = _objectWithoutProperties(props, _excluded2); const { className: labelPositionClass, isFocused, handlers, style } = useFloatingLabel({ checkValueOnBlur, hasValue, labelOffset }); const { defaults: { externalLabel } } = useTheme(); const { fieldsHideLabel } = useContext(FieldsetContext); if (externalLabel || propsExternalLabel || !label || hideLabel || fieldsHideLabel || inline) { return React.createElement(Field, _extends({}, props, { className: className })); } return React.createElement("div", { className: `${className} ${labelPositionClass} floating`, style: style, "data-disabled": disabled }, React.createElement(InputArea, handlers, children), React.createElement(FieldLabel, { ariaLabelOnly: ariaLabelOnly, id: id, label: label, hideLabel: hideLabel, required: required, fontWeight: "normal", color: getLabelColor(isFocused, props.validationMessage) }), React.createElement(Space, { width: "auto", align: "start" }, React.createElement(HelperText, _extends({ id: id }, rest)), detail && React.createElement(FieldDetail, { pt: "u2", color: "text2" }, detail))); }).withConfig({ displayName: "FloatingLabelField", componentId: "sc-1sw05so-0" })(_t || (_t = _` &.floating { display: ${0}; opacity: ${0}; /* Make the top border intersect the the middle of the label */ padding-top: calc(${0} / 2); position: relative; width: ${0}; ${0} label { background: ${0}; border-radius: ${0}; font-size: ${0}; /* Align with the input contents, compensate for left border */ left: calc(${0} + 1px); line-height: initial; padding: 0 ${0}; position: absolute; top: 0; transition: ${0}ms; } &.label-down { label { font-size: ${0}; pointer-events: none; transform: translate(var(--label-translate, 0)); } input::placeholder, textarea::placeholder { color: ${0}; } } & > ${0} { /* Align with the input contents, compensate for left border */ margin: 0 calc(${0} + 1px); } } `), ({ autoResize }) => autoResize ? 'inline-block' : 'block', ({ disabled }) => disabled ? DISABLED_OPACITY : '1', ({ theme }) => theme.fontSizes.xsmall, ({ autoResize }) => autoResize ? 'fit-content' : '100%', width, ({ theme }) => theme.colors.field, ({ theme }) => theme.radii.small, ({ theme }) => theme.fontSizes.xsmall, ({ theme }) => theme.space.u2, ({ theme }) => theme.space.u1, ({ theme }) => theme.transitions.rapid, ({ theme }) => theme.fontSizes.small, ({ theme }) => theme.colors.field, Space, ({ theme }) => theme.space.u3); //# sourceMappingURL=FloatingLabelField.js.map
859
https://github.com/TCC-SocialNetwork/social_framework/blob/master/lib/social_framework/engine.rb
Github Open Source
Open Source
MIT
2,016
social_framework
TCC-SocialNetwork
Ruby
Code
81
426
module SocialFramework class Engine < ::Rails::Engine isolate_namespace SocialFramework config.autoload_paths += %W(#{config.root}/lib/social_framework/graphs/) config.autoload_paths += %W(#{config.root}/lib/social_framework/fabrics/) unless /[\w]+$/.match(Dir.pwd).to_s == "social_framework" initializer :append_migrations do |app| path = config.paths["db"].expanded.first FileUtils.rm_rf("#{path}/tmp") FileUtils.mkdir_p("#{path}/tmp/migrate") migrations_app = Dir.glob(app.config.paths["db/migrate"].first + "/*") migrations_framework = Dir.glob(config.paths["db/migrate"].first + "/*") migrations_framework.each do |m| migrate = m.to_s.scan(/([a-zA-Z_]+[^rb])/).last.first unless migrations_app.any? { |m_app| m_app.include?(migrate) } result = m.split("/").last FileUtils.cp(m, "#{path}/tmp/migrate/#{result}") end end app.config.paths["db/migrate"] << "#{path}/tmp/migrate" end end config.generators do |g| g.test_framework :rspec, :fixture => false g.fixture_replacement :factory_girl, :dir => 'spec/factories' g.assets false g.helper false end end end
25,257
https://github.com/FinnT730/sandstone/blob/master/dist/variables/index.js
Github Open Source
Open Source
MIT
null
sandstone
FinnT730
JavaScript
Code
44
121
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var Objective_1 = require("./Objective"); Object.defineProperty(exports, "Objective", { enumerable: true, get: function () { return Objective_1.Objective; } }); var Selector_1 = require("./Selector"); Object.defineProperty(exports, "Selector", { enumerable: true, get: function () { return Selector_1.Selector; } }); //# sourceMappingURL=index.js.map
45,029
https://github.com/eruffaldi/streamhydra/blob/master/rest/setup.py
Github Open Source
Open Source
Apache-2.0
2,019
streamhydra
eruffaldi
Python
Code
7
27
from distutils.core import setup import py2exe setup(console=['hydrastream.py'])
34,756
https://github.com/yaronshahverdi/client-modules/blob/master/packages/gamut/src/Banner/__tests__/Banner-test.tsx
Github Open Source
Open Source
MIT
null
client-modules
yaronshahverdi
TypeScript
Code
117
369
import { setupEnzyme } from '@codecademy/gamut-tests'; import { IconButton, TextButton } from '../../Button'; import { Banner } from '..'; const onClose = jest.fn(); const onCtaClick = jest.fn(); describe('Banner', () => { const renderWrapper = setupEnzyme(Banner, { onClose, children: 'Hello world', }); beforeEach(() => { jest.resetAllMocks(); }); it('renders children markdown children', () => { const { wrapper } = renderWrapper({}); expect(wrapper.find('p').text()).toEqual('Hello world'); }); it('renders a button when a cta is provided in markdown', () => { const { wrapper } = renderWrapper({ onCtaClick, children: '[Hello](/)', }); const CTA = wrapper.find(TextButton); expect(CTA).toHaveLength(1); expect(CTA.at(0).text()).toEqual('Hello'); CTA.at(0).simulate('click'); expect(onCtaClick).toHaveBeenCalled(); }); it('calls the onClose callback when the close icon is clicked', () => { const { wrapper } = renderWrapper({}); wrapper.find(IconButton).simulate('click'); expect(onClose).toHaveBeenCalled(); }); });
44,430
https://github.com/jamie-l-robertson/portfolio/blob/master/src/components/contactPanel/index.tsx
Github Open Source
Open Source
MIT
2,019
portfolio
jamie-l-robertson
TypeScript
Code
152
458
import * as React from "react"; import { Container, Inner } from "@theme"; import { m } from 'framer-motion'; import { useInView } from "react-intersection-observer"; import { prefersReducedMotionContext } from "@stores/reduceMotion.context"; import Heading from "@components/heading"; import CustomLink from "@components/link"; import config from "@shared"; import { inUp, fade, chained } from "@animations"; import { ContentContainer, Content, ContentMeta } from "./styles"; interface ContactPanelProps { title: string id?: string buttonText: string }; const ContactPanel: React.FC<ContactPanelProps> = ({ title, buttonText = "Send a message", id = undefined }) => { const { ref, inView } = useInView({ rootMargin: '-100px 0px' }); const { reducedMotion } = React.useContext(prefersReducedMotionContext); return ( <Container id={id} style={{ paddingTop: 0 }}> <Inner> <m.div ref={ref} initial="initial" animate={inView ? `animate` : `initial`} custom={reducedMotion} variants={inUp}> <m.div variants={chained}> <Heading level="2" showDot>{title}</Heading> <ContentContainer variants={inUp}> <Content dangerouslySetInnerHTML={{ __html: config.contact.intro }} /> <ContentMeta variants={fade}> <CustomLink href={`mailto:${config.contact.email}?subject=Website%20Enquiry`} blockLink external>{buttonText}</CustomLink> </ContentMeta> </ContentContainer> </m.div> </m.div> </Inner> </Container> ) }; export default ContactPanel;
12,399
https://github.com/Lenscorpx/Etikets-Fret/blob/master/Etikets_Fret/Etikets_Fret/EtiForms/_UserControls/uc_navigateur.Designer.cs
Github Open Source
Open Source
MIT
2,021
Etikets-Fret
Lenscorpx
C#
Code
315
1,404
namespace Etikets_Fret.EtiForms._UserControls { partial class uc_navigateur { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.panel1 = new System.Windows.Forms.Panel(); this.lbl_titre2 = new System.Windows.Forms.Label(); this.progressBar1 = new System.Windows.Forms.ProgressBar(); this.panel2 = new System.Windows.Forms.Panel(); this.webBrowser1 = new System.Windows.Forms.WebBrowser(); this.panel1.SuspendLayout(); this.panel2.SuspendLayout(); this.SuspendLayout(); // // panel1 // this.panel1.Controls.Add(this.lbl_titre2); this.panel1.Controls.Add(this.progressBar1); this.panel1.Dock = System.Windows.Forms.DockStyle.Bottom; this.panel1.Location = new System.Drawing.Point(0, 488); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(994, 43); this.panel1.TabIndex = 1; // // lbl_titre2 // this.lbl_titre2.AutoSize = true; this.lbl_titre2.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lbl_titre2.ForeColor = System.Drawing.Color.Black; this.lbl_titre2.Location = new System.Drawing.Point(453, 20); this.lbl_titre2.Name = "lbl_titre2"; this.lbl_titre2.Size = new System.Drawing.Size(49, 17); this.lbl_titre2.TabIndex = 6; this.lbl_titre2.Text = "etikets"; // // progressBar1 // this.progressBar1.Location = new System.Drawing.Point(219, 6); this.progressBar1.Name = "progressBar1"; this.progressBar1.Size = new System.Drawing.Size(549, 10); this.progressBar1.TabIndex = 5; // // panel2 // this.panel2.Controls.Add(this.webBrowser1); this.panel2.Dock = System.Windows.Forms.DockStyle.Fill; this.panel2.Location = new System.Drawing.Point(0, 0); this.panel2.Name = "panel2"; this.panel2.Size = new System.Drawing.Size(994, 488); this.panel2.TabIndex = 2; // // webBrowser1 // this.webBrowser1.Dock = System.Windows.Forms.DockStyle.Fill; this.webBrowser1.Location = new System.Drawing.Point(0, 0); this.webBrowser1.MinimumSize = new System.Drawing.Size(20, 20); this.webBrowser1.Name = "webBrowser1"; this.webBrowser1.Size = new System.Drawing.Size(994, 488); this.webBrowser1.TabIndex = 0; this.webBrowser1.DocumentCompleted += new System.Windows.Forms.WebBrowserDocumentCompletedEventHandler(this.webBrowser1_DocumentCompleted); this.webBrowser1.Navigated += new System.Windows.Forms.WebBrowserNavigatedEventHandler(this.webBrowser1_Navigated); this.webBrowser1.Navigating += new System.Windows.Forms.WebBrowserNavigatingEventHandler(this.webBrowser1_Navigating); this.webBrowser1.ProgressChanged += new System.Windows.Forms.WebBrowserProgressChangedEventHandler(this.webBrowser1_ProgressChanged); // // uc_navigateur // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.Color.White; this.Controls.Add(this.panel2); this.Controls.Add(this.panel1); this.Name = "uc_navigateur"; this.Size = new System.Drawing.Size(994, 531); this.panel1.ResumeLayout(false); this.panel1.PerformLayout(); this.panel2.ResumeLayout(false); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Panel panel1; private System.Windows.Forms.Panel panel2; private System.Windows.Forms.WebBrowser webBrowser1; private System.Windows.Forms.ProgressBar progressBar1; private System.Windows.Forms.Label lbl_titre2; } }
28,801
https://github.com/jamzrob/lambdanative/blob/master/modules/ln_store/ln_store-tests.scm
Github Open Source
Open Source
BSD-3-Clause
2,021
lambdanative
jamzrob
Scheme
Code
489
1,256
(unit-test "store-data" "Verify the store sets and returns data properly" (lambda () (define store (make-store (time->timestamp (current-time)))) (define str "this is a string") (define int 1234) (define float 3.141526) (define fraction 1/3) (define function sin) (define lst (list (list "a" "b" 1 2 3) (list "c" "d" 4 5 6))) (define bool #t) (define complex 2+3i) (define symbol 'asdf) (define u8vec (u8vector 8 7 3 189 23 21 1)) (define vect (vector 1 2 4 4 3 2 112)) (define vars (list str int float fraction function lst bool complex symbol u8vec vect)) (define varn (list "str" "int" "float" "fraction" "function" "lst" "bool" "complex" "symbol" "u8vect" "vect")) (set! ##now 0.) ;; Set and retrieve all variables (set! part1 (let loop ((k varn) (v vars) (pass #t)) (if (null? k) pass (begin (store-set! store (car k) (car v)) (loop (cdr k) (cdr v) (and pass (equal? (car v) (store-ref store (car k) #f)))) ) ) )) ;; Clear all variables and see if they are gone (and fallback options) (store-clear! store varn) (set! part2 (fx= 0 (apply + (map (lambda (v) (store-ref store v 0)) varn)))) ;; Test data store expiry (set! part3 (let ((v 31)) (store-set! store "v" v) (and (= (store-timedref store "v" #f) v) (begin (set! ##now (+ ##now 32)) (not (store-timedref store "v" #f)) ) (= (store-ref store "v" #f) v) ) )) ;; Test store category retrieval (set! part4 (let ((vars (list "a" "b" "c"))) (for-each (lambda (v) (store-set! store v v "mycat")) vars) (equal? vars (map car (store-listcat store "mycat"))) )) ;; Test timestamps and setnew (set! part5 (let ((v 80)) (store-set! store "ln" v) (set! time-before (store-timestamp store "ln")) (set! ##now (+ ##now 5)) (store-setnew! store "ln" v) (set! time-after (store-timestamp store "ln")) (store-set! store "ln" 1234) (set! time-new (store-timestamp store "ln")) (and (= time-before time-after) (= time-new (+ time-before 5))) )) ;; Return the combined test results (and part1 part2 part3 part4 part5) )) (unit-test "store-events" "Verify the Event functionality of the store" (lambda () (define store (make-store (time->timestamp (current-time)))) (set! ##now 0.5) ;; Event submission and retrival (set! part1 (let ((prio 1) (id "monitor") (payload "alarm")) (store-event-add store prio id payload) (equal? (list (list 0.5 (string-append id ":" payload) prio)) (store-event-listnew store)) )) ;; Event Graylisting (set! part2 (let ((prio 2) (id "monitor") (payload "**alarm**")) (set! ##now (+ ##now 120)) (store-event-add store prio id payload) (set! ##now (+ ##now 15)) (store-event-add store prio id payload) (set! ##now (+ ##now 15)) (store-event-add store prio id payload) (set! ##now (+ ##now 15)) (store-event-add store prio id payload) (equal? (list (list 120.5 (string-append id ":" payload) prio)) (store-event-listnew store 120)) )) ;; Make sure none are missed (set! part3 (let loop ((i 0)) (if (fx= i 10000) (and (= i (length (store-event-listnew store 150))) (= 0 (length (store-event-listnew store ##now)))) (begin (store-event-add store 0 "test" i) (set! ##now (+ ##now (random-real))) (loop (fx+ i 1)) ) ) )) (and part1 part2 part3) )) ;;eof
28,957
https://github.com/flashultra/openfl/blob/master/test/npm/typescript/openfl/display/ShaderJobTest.ts
Github Open Source
Open Source
MIT, LicenseRef-scancode-free-unknown, CC-BY-NC-SA-3.0, OFL-1.1
2,019
openfl
flashultra
TypeScript
Code
202
554
import ShaderJob from "openfl/display/ShaderJob"; import * as assert from "assert"; describe ("TypeScript | ShaderJob", function () { it ("height", function () { // TODO: Confirm functionality var shaderJob = new ShaderJob (); var exists = shaderJob.height; assert.notEqual (exists, null); }); it ("progress", function () { // TODO: Confirm functionality var shaderJob = new ShaderJob (); var exists = shaderJob.progress; assert.notEqual (exists, null); }); it ("shader", function () { // TODO: Confirm functionality var shaderJob = new ShaderJob (); var exists = shaderJob.shader; assert.equal (exists, null); }); it ("target", function () { // TODO: Confirm functionality var shaderJob = new ShaderJob (); var exists = shaderJob.target; assert.equal (exists, null); }); it ("width", function () { // TODO: Confirm functionality var shaderJob = new ShaderJob (); var exists = shaderJob.width; assert.notEqual (exists, null); }); it ("new", function () { // TODO: Confirm functionality var shaderJob = new ShaderJob (); var exists = shaderJob; assert.notEqual (exists, null); }); it ("cancel", function () { // TODO: Confirm functionality var shaderJob = new ShaderJob (); var exists = shaderJob.cancel; assert.notEqual (exists, null); }); it ("start", function () { // TODO: Confirm functionality var shaderJob = new ShaderJob (); var exists = shaderJob.start; assert.notEqual (exists, null); }); });
11,248
https://github.com/ucd-library/wine-price-extraction/blob/master/tesseract/rotate/d7h59w-015.r
Github Open Source
Open Source
MIT
2,021
wine-price-extraction
ucd-library
R
Code
3
88
r=0.05 https://sandbox.dams.library.ucdavis.edu/fcrepo/rest/collection/sherry-lehmann/catalogs/d7h59w/media/images/d7h59w-015/svc:tesseract/full/full/0.05/default.jpg Accept:application/hocr+xml
9,324
https://github.com/popshoplive/react-native-shareplay/blob/master/ios/SharePlay.m
Github Open Source
Open Source
MIT
2,021
react-native-shareplay
popshoplive
Objective-C
Code
23
262
#import <React/RCTBridgeModule.h> @interface RCT_EXTERN_MODULE(SharePlay, NSObject) RCT_EXTERN_METHOD(isSharePlayAvailable:(RCTPromiseResolveBlock)resolve withRejecter:(RCTPromiseRejectBlock)reject) RCT_EXTERN_METHOD(getInitialSession:(RCTPromiseResolveBlock)resolve withRejecter:(RCTPromiseRejectBlock)reject) RCT_EXTERN_METHOD(startActivity:(NSString *)title withOptions:(NSDictionary *)extraInfo withResolver:(RCTPromiseResolveBlock)resolve withRejecter:(RCTPromiseRejectBlock)reject) RCT_EXTERN_METHOD(joinSession) RCT_EXTERN_METHOD(leaveSession) RCT_EXTERN_METHOD(endSession) RCT_EXTERN_METHOD(sendMessage:(NSString *)info withResolver:(RCTPromiseResolveBlock)resolve withRejecter:(RCTPromiseRejectBlock)reject) @end
18,341
https://github.com/moutainhigh/jia/blob/master/jia-api-admin/src/main/java/cn/jia/isp/common/ErrorConstants.java
Github Open Source
Open Source
MIT
2,021
jia
moutainhigh
Java
Code
82
276
package cn.jia.isp.common; import cn.jia.core.exception.EsErrorConstants; /** * 错误常量 * @author chc * @date 2017年12月8日 下午2:47:56 */ public class ErrorConstants extends EsErrorConstants { /** 用户不存在 */ public static final String USER_NOT_EXIST = "EUSER002"; /** 服务器连接失败 */ public static final String ISP_CONN_FAILD = "EISP001"; /** 域名不存在 */ public static final String DOMAIN_NOT_EXIST = "EISP002"; /** 密钥不正确 */ public static final String KEY_INCORRECT = "EISP003"; /** SSL证书没有安装 */ public static final String SSL_NOT_INSTALL = "EISP004"; /** MYSQL服务没有安装 */ public static final String MYSQL_NOT_INSTALL = "EISP005"; }
49,216
https://github.com/Reimnop/Potassium/blob/master/LeaderAnimator/Ease.cs
Github Open Source
Open Source
MIT
2,022
Potassium
Reimnop
C#
Code
1,406
4,010
using System; using System.Collections.Generic; using UnityEngine; namespace LeaderAnimator { public enum Easing { Linear, Instant, InSine, OutSine, InOutSine, InElastic, OutElastic, InOutElastic, InBack, OutBack, InOutBack, InBounce, OutBounce, InOutBounce, InQuad, OutQuad, InOutQuad, InCirc, OutCirc, InOutCirc, InExpo, OutExpo, InOutExpo } /// <summary> /// Static class with useful easer functions that can be used by Tweens. /// </summary> public static class Ease { public static Dictionary<Easing, Func<float, float>> EaseLookup = new Dictionary<Easing, Func<float, float>>() { { Easing.Linear, Linear }, { Easing.Instant, Instant }, { Easing.InSine, SineIn }, { Easing.OutSine, SineOut }, { Easing.InOutSine, SineInOut }, { Easing.InElastic, ElasticIn }, { Easing.OutElastic, ElasticOut }, { Easing.InOutElastic, ElasticInOut }, { Easing.InBack, BackIn }, { Easing.OutBack, BackOut }, { Easing.InOutBack, BackInOut }, { Easing.InBounce, BounceIn }, { Easing.OutBounce, BounceOut }, { Easing.InOutBounce, BounceInOut }, { Easing.InQuad, QuadIn }, { Easing.OutQuad, QuadOut }, { Easing.InOutQuad, QuadInOut }, { Easing.InCirc, CircIn }, { Easing.OutCirc, CircOut }, { Easing.InOutCirc, CircInOut }, { Easing.InExpo, ExpoIn }, { Easing.OutExpo, ExpoOut }, { Easing.InOutExpo, ExpoInOut } }; private const float PI = 3.14159265359f; private const float PI2 = PI / 2; private const float B1 = 1 / 2.75f; private const float B2 = 2 / 2.75f; private const float B3 = 1.5f / 2.75f; private const float B4 = 2.5f / 2.75f; private const float B5 = 2.25f / 2.75f; private const float B6 = 2.625f / 2.75f; /// <summary> /// Ease a value to its target and then back. Use this to wrap another easing function. /// </summary> public static Func<float, float> ToAndFro(Func<float, float> easer) { return t => ToAndFro(easer(t)); } /// <summary> /// Ease a value to its target and then back. /// </summary> public static float ToAndFro(float t) { return t < 0.5f ? t * 2 : 1 + ((t - 0.5f) / 0.5f) * -1; } /// <summary> /// Linear. /// </summary> /// <param name="t">Time elapsed.</param> /// <returns>Eased timescale.</returns> public static float Linear(float t) => t; /// <summary> /// Instant. /// </summary> /// <param name="t">Time elapsed.</param> /// <returns>Eased timescale.</returns> public static float Instant(float t) { if (t == 1.0f) return 1.0f; return 0.0f; } #region Sine /// <summary> /// Sine in. /// </summary> /// <param name="t">Time elapsed.</param> /// <returns>Eased timescale.</returns> public static float SineIn(float t) { if (t == 1) return 1; return -Mathf.Cos(PI2 * t) + 1; } /// <summary> /// Sine out. /// </summary> /// <param name="t">Time elapsed.</param> /// <returns>Eased timescale.</returns> public static float SineOut(float t) { return Mathf.Sin(PI2 * t); } /// <summary> /// Sine in and out /// </summary> /// <param name="t">Time elapsed.</param> /// <returns>Eased timescale.</returns> public static float SineInOut(float t) { return -Mathf.Cos(PI * t) / 2 + 0.5f; } #endregion #region Elastic /// <summary> /// Elastic in. /// </summary> /// <param name="t">Time elapsed.</param> /// <returns>Eased timescale.</returns> public static float ElasticIn(float t) { return (Mathf.Sin(13 * PI2 * t) * Mathf.Pow(2, 10 * (t - 1))); } /// <summary> /// Elastic out. /// </summary> /// <param name="t">Time elapsed.</param> /// <returns>Eased timescale.</returns> public static float ElasticOut(float t) { if (t == 1) return 1; return (Mathf.Sin(-13 * PI2 * (t + 1)) * Mathf.Pow(2, -10 * t) + 1); } /// <summary> /// Elastic in and out. /// </summary> /// <param name="t">Time elapsed.</param> /// <returns>Eased timescale.</returns> public static float ElasticInOut(float t) { if (t < 0.5) { return (0.5f * Mathf.Sin(13 * PI2 * (2 * t)) * Mathf.Pow(2, 10 * ((2 * t) - 1))); } return (0.5f * (Mathf.Sin(-13 * PI2 * ((2 * t - 1) + 1)) * Mathf.Pow(2, -10 * (2 * t - 1)) + 2)); } #endregion #region Back /// <summary> /// Back in. /// </summary> /// <param name="t">Time elapsed.</param> /// <returns>Eased timescale.</returns> public static float BackIn(float t) { return (t * t * (2.70158f * t - 1.70158f)); } /// <summary> /// Back out. /// </summary> /// <param name="t">Time elapsed.</param> /// <returns>Eased timescale.</returns> public static float BackOut(float t) { return (1 - (--t) * (t) * (-2.70158f * t - 1.70158f)); } /// <summary> /// Back in and out. /// </summary> /// <param name="t">Time elapsed.</param> /// <returns>Eased timescale.</returns> public static float BackInOut(float t) { t *= 2; if (t < 1) return (t * t * (2.70158f * t - 1.70158f) / 2); t--; return ((1 - (--t) * (t) * (-2.70158f * t - 1.70158f)) / 2 + .5f); } #endregion #region Bounce /// <summary> /// Bounce in. /// </summary> /// <param name="t">Time elapsed.</param> /// <returns>Eased timescale.</returns> public static float BounceIn(float t) { t = 1 - t; if (t < B1) return (1 - 7.5625f * t * t); if (t < B2) return (1 - (7.5625f * (t - B3) * (t - B3) + .75f)); if (t < B4) return (1 - (7.5625f * (t - B5) * (t - B5) + .9375f)); return (1 - (7.5625f * (t - B6) * (t - B6) + .984375f)); } /// <summary> /// Bounce out. /// </summary> /// <param name="t">Time elapsed.</param> /// <returns>Eased timescale.</returns> public static float BounceOut(float t) { if (t < B1) return (7.5625f * t * t); if (t < B2) return (7.5625f * (t - B3) * (t - B3) + .75f); if (t < B4) return (7.5625f * (t - B5) * (t - B5) + .9375f); return (7.5625f * (t - B6) * (t - B6) + .984375f); } /// <summary> /// Bounce in and out. /// </summary> /// <param name="t">Time elapsed.</param> /// <returns>Eased timescale.</returns> public static float BounceInOut(float t) { if (t < .5) { t = 1 - t * 2; if (t < B1) return ((1 - 7.5625f * t * t) / 2); if (t < B2) return ((1 - (7.5625f * (t - B3) * (t - B3) + .75f)) / 2); if (t < B4) return ((1 - (7.5625f * (t - B5) * (t - B5) + .9375f)) / 2); return ((1 - (7.5625f * (t - B6) * (t - B6) + .984375f)) / 2); } t = t * 2 - 1; if (t < B1) return ((7.5625f * t * t) / 2 + .5f); if (t < B2) return ((7.5625f * (t - B3) * (t - B3) + .75f) / 2 + .5f); if (t < B4) return ((7.5625f * (t - B5) * (t - B5) + .9375f) / 2 + .5f); return ((7.5625f * (t - B6) * (t - B6) + .984375f) / 2 + .5f); } #endregion #region Quad /// <summary> /// Quadratic in. /// </summary> /// <param name="t">Time elapsed.</param> /// <returns>Eased timescale.</returns> public static float QuadIn(float t) { return (t * t); } /// <summary> /// Quadratic out. /// </summary> /// <param name="t">Time elapsed.</param> /// <returns>Eased timescale.</returns> public static float QuadOut(float t) { return (-t * (t - 2)); } /// <summary> /// Quadratic in and out. /// </summary> /// <param name="t">Time elapsed.</param> /// <returns>Eased timescale.</returns> public static float QuadInOut(float t) { return (t <= .5 ? t * t * 2 : 1 - (--t) * t * 2); } #endregion #region Circ /// <summary> /// Circle in. /// </summary> /// <param name="t">Time elapsed.</param> /// <returns>Eased timescale.</returns> public static float CircIn(float t) { return (-(Mathf.Sqrt(1 - t * t) - 1)); } /// <summary> /// Circle out /// </summary> /// <param name="t">Time elapsed.</param> /// <returns>Eased timescale.</returns> public static float CircOut(float t) { return (Mathf.Sqrt(1 - (t - 1) * (t - 1))); } /// <summary> /// Circle in and out. /// </summary> /// <param name="t">Time elapsed.</param> /// <returns>Eased timescale.</returns> public static float CircInOut(float t) { return (t <= .5 ? (Mathf.Sqrt(1 - t * t * 4) - 1) / -2 : (Mathf.Sqrt(1 - (t * 2 - 2) * (t * 2 - 2)) + 1) / 2); } #endregion #region Expo /// <summary> /// Exponential in. /// </summary> /// <param name="t">Time elapsed.</param> /// <returns>Eased timescale.</returns> public static float ExpoIn(float t) { return (Mathf.Pow(2, 10 * (t - 1))); } /// <summary> /// Exponential out. /// </summary> /// <param name="t">Time elapsed.</param> /// <returns>Eased timescale.</returns> public static float ExpoOut(float t) { if (t == 1) return 1; return (-Mathf.Pow(2, -10 * t) + 1); } /// <summary> /// Exponential in and out. /// </summary> /// <param name="t">Time elapsed.</param> /// <returns>Eased timescale.</returns> public static float ExpoInOut(float t) { if (t == 1) return 1; return (t < .5 ? Mathf.Pow(2, 10 * (t * 2 - 1)) / 2 : (-Mathf.Pow(2, -10 * (t * 2 - 1)) + 2) / 2); } #endregion } }
44,275
https://github.com/krpiku20/milis/blob/master/application/core/vendor/shieldon/event-dispatcher/tests/Event/EventDispatcherTest.php
Github Open Source
Open Source
MIT
2,020
milis
krpiku20
PHP
Code
159
553
<?php /** * This file is part of the Shieldon package. * * (c) Terry L. <contact@terryl.in> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * php version 7.1.0 * * @category Web-security * @package Shieldon * @author Terry Lin <contact@terryl.in> * @copyright 2019 terrylinooo * @license https://github.com/terrylinooo/shieldon/blob/2.x/LICENSE MIT * @link https://github.com/terrylinooo/shieldon * @see https://shieldon.io */ declare(strict_types=1); namespace Shieldon\EventTest; use Shieldon\Event\Event; class EventDispatcherTest extends \PHPUnit\Framework\TestCase { public function callListenerByClosure() { Event::addListener('test_1', function() { echo 'This is a closure function call.'; }); } public function callListenerByFunction() { // test_event_disptcher is in bootstrap.php Event::addListener('test_2', 'test_event_disptcher'); } public function callListenerByClass() { $example = new EventDispatcherExample(); Event::addListener('test_3', [$example, 'example1']); } public function testDispatcherByClosure() { $this->callListenerByClosure(); $this->expectOutputString('This is a closure function call.'); Event::doDispatch('test_1'); } public function testDispatcherByFunction() { $this->callListenerByFunction(); $this->expectOutputString('This is a function call.'); Event::doDispatch('test_2'); } public function testDispatcherByClass() { $this->callListenerByClass(); $this->expectOutputString('This is a class call.'); Event::doDispatch('test_3'); } }
14,136
https://github.com/monitor1394/LuaBT/blob/master/LuaBT/bt/core/BehaviourTree.lua
Github Open Source
Open Source
MIT
2,022
LuaBT
monitor1394
Lua
Code
576
1,957
local BehaviourTree = bt.Class("BehaviourTree") bt.BehaviourTree = BehaviourTree function BehaviourTree:ctor() self.id = 0 self.type = nil self.name = "BehaviourTree" self.primeNode = nil self.nodes = {} self.nodesIndex = {} self.subTrees = {} self.debugList = {} self.rootStatus = bt.Status.Resting self.agent = {id = 1001} self.agent.isBTDebug = false self.blackboard = nil self.isRunning = false self.isPaused = false self.isRepeat = true self.tickCount = 0 end function BehaviourTree:start() self.isRunning = true self.rootStatus = self.primeNode.status end function BehaviourTree:update() if not self.isRunning then return end if self:tick(self.agent, self.blackboard) ~= bt.Status.Running and not self.isRepeat then self.stop(self.rootStatus == bt.Status.Success) end end function BehaviourTree:tick(agent, blackboard) if self.rootStatus ~= bt.Status.Running then self.tickCount = self.tickCount + 1 self:debug("bt tick:"..self.tickCount.."-------------"..bt.getStatusInfo(self.rootStatus)) print("info:"..self:getNodeInfo()) self.primeNode:reset() end self.rootStatus = self.primeNode:execute(agent, blackboard) return self.rootStatus end function BehaviourTree:stop(success) if not self.isRunning and not self.isPaused then return end self.isRunning = false self.isPaused = false for k, node in pairs(self.nodes) do node:reset(false) node:onGraphStoped() end end function BehaviourTree:pause() if not self.isRunning then return end self.isRunning = false self.isPaused = true for k, node in pairs(self.nodes) do node:onGraphPaused() end end function BehaviourTree:destroy() for k, node in pairs(self.nodes) do node:destroy() node = nil end self.nodes = nil self.nodesIndex = nil end function BehaviourTree:getNodeInfo() local info = "{" for k,nodeId in pairs(self.nodesIndex) do local node = self.nodes[nodeId] info = info .. "{" info = info .. node.status.."," if #node.outConnections > 0 then for i=1,#node.outConnections do info = info .. node.outConnections[i].status .. "," end end info = string.sub(info,1,string.len(info)-1) info = info .. "}," end info = string.sub(info,1,string.len(info)-1) info = info .. "}" return info end function BehaviourTree:load(fileName) local path = bt.ASSERT_DIR .. fileName .. bt.ASSERT_SUFFIX print("load bt:"..path) local file = io.open(path, "r") if file == nil then print("ERROR:BehaviourTree:load can't open file:".. path) return end local jsonData = file:read("*a") local data = bt.decodeJson(jsonData) self.version = data.version self.type = data.type self.name = fileName local spec, id, type, node, Cls for i, v in pairs(data.nodes) do spec = v id = tonumber(spec["$id"]) if id ~= nil then--不在树中的节点没有id Cls = bt.getCls(spec["$type"], spec) node = Cls.new() node.id = id node.comment = spec["_comment"] node:init(spec) --action if node.isActionNode then if spec["_action"] == nil then print("ERROR:node not contain action : id="..id..",node="..node.name) else Cls = bt.getCls(spec["_action"]["$type"], spec) local action = Cls.new() action:init(spec["_action"]) node.action = action end end --condition if node.isConditionNode then if spec["_condition"] == nil then print("ERROR:node not contain condition : id="..id..",node="..node.name) else Cls = bt.getCls(spec["_condition"]["$type"], spec) local condition = Cls.new() condition:init(spec["_condition"]) node.condition = condition end end --subtree if node.isSubTreeNode then local subTreeId = spec._subTree._value local subTreeName = spec._subTreeName._value if subTreeId ~= nil and subTreeName ~= nil then node.subTree = self:createSubTree(i, subTreeName) end end self.nodes[id] = node table.insert(self.nodesIndex, id) end end --connections for i, v in pairs(data.connections) do spec = v Cls = bt.getCls(spec["$type"], spec) local sourceNodeId = tonumber(spec["_sourceNode"]["$ref"]) local targetNodeId = tonumber(spec["_targetNode"]["$ref"]) local isDisabled = false if spec["_isDisabled"] then isDisabled = true end local sourceNode = self.nodes[sourceNodeId] local targetNode = self.nodes[targetNodeId] local connection = Cls.new() connection:create(i, sourceNode, targetNode, isDisabled) targetNode:addInConnection(connection) sourceNode:addOutConnection(connection) end --primeNode local primeNodeId = tonumber(data["primeNode"]["$ref"]) self.primeNode = self.nodes[primeNodeId] end function BehaviourTree:createSubTree(id,name) local btree = bt.BehaviourTree.new() btree.id = id btree.agent = self.agent btree.blackboard = self.blackboard btree:load(name) self.subTrees[id] = btree return btree end function BehaviourTree:debug(info) if not self.agent.isBTDebug then return end print(info) end function BehaviourTree:addDebugger(tbSocket) table.insert( self.debugList, tbSocket ) self.agent.isBTDebug = true end function BehaviourTree:delDebugger(tbSocket) for i=1,#self.debugList do if self.debugList[i] == tbSocket then table.remove( self.debugList, i ) end end if #self.debugList > 0 then self.agent.isBTDebug = false end end function BehaviourTree:checkDebugger() if not self.agent.isBTDebug then return end local info = self:getNodeInfo() for i,socket in pairs(self.debugList) do print("check debug:",i,info) s2c.btInfo(socket,info) end end
40,808
https://github.com/razib1014/BookStorePGT/blob/master/BS_01_D_09_jan_2019_01_30_PM/bsd1.sql
Github Open Source
Open Source
MIT
null
BookStorePGT
razib1014
SQL
Code
330
1,028
-- phpMyAdmin SQL Dump -- version 4.7.9 -- https://www.phpmyadmin.net/ -- -- Host: localhost -- Generation Time: Jan 09, 2019 at 08:43 AM -- Server version: 10.1.31-MariaDB -- PHP Version: 7.0.28 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `bsd1` -- -- -------------------------------------------------------- -- -- Table structure for table `bookInfo` -- CREATE TABLE `bookInfo` ( `book_id` int(12) NOT NULL, `book_name` varchar(150) NOT NULL, `book_auth` varchar(60) NOT NULL, `book_pub` varchar(60) NOT NULL, `book_cat` varchar(60) NOT NULL, `book_page` int(4) NOT NULL, `book_price` float NOT NULL, `stock_no` int(6) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `bookInfo` -- INSERT INTO `bookInfo` (`book_id`, `book_name`, `book_auth`, `book_pub`, `book_cat`, `book_page`, `book_price`, `stock_no`) VALUES (1, 'Book A', 'Author A', 'Pub A', 'Adventure', 200, 220, 5), (2, 'Book B', 'Auth B', 'Pub B', 'History', 150, 250, 3); -- -------------------------------------------------------- -- -- Table structure for table `userInfo` -- CREATE TABLE `userInfo` ( `id` int(10) NOT NULL, `name` varchar(250) NOT NULL, `uname` varchar(50) NOT NULL, `email` varchar(80) NOT NULL, `passwd` varchar(50) NOT NULL, `image` varchar(100) NOT NULL, `date` datetime NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `userInfo` -- INSERT INTO `userInfo` (`id`, `name`, `uname`, `email`, `passwd`, `image`, `date`) VALUES (1, 'RZ', 'rzrz', 'rz@rz.com', 'rzrz', 'PP_ME_2.png', '2019-01-09 10:12:13'); -- -- Indexes for dumped tables -- -- -- Indexes for table `bookInfo` -- ALTER TABLE `bookInfo` ADD PRIMARY KEY (`book_id`); -- -- Indexes for table `userInfo` -- ALTER TABLE `userInfo` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `uname` (`uname`), ADD UNIQUE KEY `email` (`email`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `bookInfo` -- ALTER TABLE `bookInfo` MODIFY `book_id` int(12) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3; -- -- AUTO_INCREMENT for table `userInfo` -- ALTER TABLE `userInfo` MODIFY `id` int(10) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2; COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
9,658
https://github.com/LiMium/mini-vector-android/blob/master/vector/src/test/java/im/vector/util/EmojiTest.kt
Github Open Source
Open Source
Apache-2.0
2,020
mini-vector-android
LiMium
Kotlin
Code
392
3,920
/* * Copyright 2018 New Vector Ltd * * 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 im.vector.util import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue import org.junit.FixMethodOrder import org.junit.Test import org.junit.runners.MethodSorters @FixMethodOrder(MethodSorters.JVM) class EmojiTest { @Test fun Emoji_null_false() { assertFalse(containsOnlyEmojis(null)) } @Test fun Emoji_empty_false() { assertFalse(containsOnlyEmojis("")) } @Test fun Emoji_letter_false() { assertFalse(containsOnlyEmojis("a")) } @Test fun Emoji_digit_false() { assertFalse(containsOnlyEmojis("1")) } @Test fun Emoji_symbols_false() { assertFalse(containsOnlyEmojis("#")) assertFalse(containsOnlyEmojis("?")) assertFalse(containsOnlyEmojis(".")) } @Test fun Emoji_text_false() { assertFalse(containsOnlyEmojis("This is a long text")) } @Test fun Emoji_space_false() { assertFalse(containsOnlyEmojis(" ")) } @Test fun Emoji_emoji_true() { assertTrue(containsOnlyEmojis("\uD83D\uDE03")) // 😃 } @Test fun Emoji_emojiUtf8_true() { assertTrue(containsOnlyEmojis("😃")) } @Test fun Emoji_emojiMulitple_true() { assertTrue(containsOnlyEmojis("😃😃")) assertTrue(containsOnlyEmojis("😃😃😃")) assertTrue(containsOnlyEmojis("😃😃😃😃😃")) } // Source: https://apps.timwhitlock.info/emoji/tables/unicode @Test fun Emoji_emojiAll_true() { // 1. Emoticons ( 1F601 - 1F64F ) assertTrue(containsOnlyEmojis("😁😃😄😅😆😉😊😋😌😍😏😒" + "😓😔😖😘😚😜😝😞😠😡😢😣" + "😤😥😨😩😪😫😭😰😱😲😳😵" + "😷😸😹😺😻😼😽😾😿🙀🙅🙆" + "🙇🙈🙉🙊🙋🙌🙍🙎🙏")) // 2. Dingbats ( 2702 - 27B0 ) assertTrue(containsOnlyEmojis("✂✅✈✉✊✋✌✏✒✔✖✨✳✴❄❇❌❎❓❔❕❗❤➕➖➗➡➰")) // 3. Transport and map symbols ( 1F680 - 1F6C0 ) assertTrue(containsOnlyEmojis("🚀🚃🚄🚅🚇🚉🚌🚏🚑🚒🚓🚕" + "🚗🚙🚚🚢🚤🚥🚧🚨🚩🚪🚫🚬🚭🚲🚶🚹🚺🚻🚼🚽🚾🛀")) // 4. Enclosed characters ( 24C2 - 1F251 ) assertTrue(containsOnlyEmojis("Ⓜ🅰🅱🅾🅿🆎🆑🆒🆓🆔🆕🆖🆗🆘🆙🆚" + "🇩🇪🇬🇧🇨🇳🇯🇵🇫🇷🇰🇷🇪🇸🇮🇹🇷🇺🇺🇸" + "🈁🈂🈚🈯🈲🈳🈴🈵🈶🈷🈸🈹🈺🉐🉑")) // 5. Uncategorized assertTrue(containsOnlyEmojis("©®‼⁉#⃣8⃣9⃣7⃣0⃣6⃣5⃣4⃣3⃣2⃣1⃣™ℹ↔↕↖↗↘↙↩↪⌚⌛⏩" + "⏪⏫⏬⏰⏳▪▫▶◀◻◼◽◾☀☁☎☑☔☕☝☺♈♉♊♋♌♍♎♏" + "♐♑♒♓♠♣♥♦♨♻♿⚓⚠⚡⚪⚫⚽⚾⛄" + "⛅⛎⛔⛪⛲⛳⛵⛺⛽⤴⤵⬅⬆" + "⬇⬛⬜⭐⭕〰〽㊗㊙🀄🃏🌀🌁🌂🌃🌄🌅🌆🌇🌈🌉🌊🌋🌌🌏🌑🌓🌔🌕🌙🌛" + "🌟🌠🌰🌱🌴🌵🌷🌸🌹🌺🌻🌼🌽🌾🌿🍀🍁🍂🍃🍄🍅🍆🍇🍈🍉🍊🍌🍍🍎🍏" + "🍑🍒🍓🍔🍕🍖🍗🍘🍙🍚🍛🍜🍝" + "🍞🍟🍠🍡🍢🍣🍤🍥🍦🍧🍨🍩🍪🍫🍬🍭🍮🍯🍰🍱🍲🍳🍴🍵🍶🍷🍸🍹🍺🍻🎀🎁" + "🎂🎃🎄🎅🎆🎇🎈🎉🎊🎋🎌🎍🎎🎏🎐🎑🎒🎓🎠🎡🎢🎣🎤🎥🎦🎧🎨🎩🎪🎫🎬🎭" + "🎮🎯🎰🎱🎲🎳🎴🎵🎶🎷" + "🎸🎹🎺🎻🎼🎽🎾🎿🏀🏁🏂🏃🏄🏆🏈🏊🏠🏡🏢🏣🏥🏦🏧🏨🏩🏪🏫🏬🏭🏮🏯🏰" + "🐌🐍🐎🐑🐒🐔🐗🐘🐙🐚🐛🐜🐝🐞🐟🐠🐡🐢🐣🐤🐥🐦🐧🐨🐩🐫🐬🐭🐮🐯🐰🐱" + "🐲🐳🐴🐵🐶🐷🐸🐹🐺🐻" + "🐼🐽🐾👀👂👃👄👅👆👇👈👉👊👋👌👍👎👏👐👑👒👓👔👕👖👗👘👙👚👛👜👝" + "👞👟👠👡👢👣👤👦👧👨👩👪👫👮👯👰👱👲👳👴👵👶👷👸👹👺👻👼👽👾👿💀" + "💁💂💃💄💅💆💇💈💉💊" + "💋💌💍💎💏💐💑💒💓💔💕💖💗💘💙💚💛💜💝💞💟💠💡💢💣💤💥💦💧💨💩💪" + "💫💬💮💯💰💱💲💳💴💵💸💹💺💻💼💽💾💿📀📁📂📃📄📅📆📇📈📉📊📋📌📍" + "📎📏📐📑📒📓📔📕📖📗" + "📘📙📚📛📜📝📞📟📠📡📢📣📤📥📦📧📨📩📪📫📮📰📱📲📳📴📶📷📹📺📻📼" + "🔃🔊🔋🔌🔍🔎🔏🔐🔑🔒🔓🔔🔖🔗🔘🔙🔚🔛🔜🔝🔞🔟🔠🔡🔢🔣🔤🔥🔦🔧🔨🔩" + "🔪🔫🔮🔯🔰🔱🔲🔳🔴🔵" + "🔶🔷🔸🔹🔺🔻🔼🔽🕐🕑🕒🕓🕔🕕🕖🕗🕘🕙🕚🕛🗻🗼🗽🗾🗿")) // 6a. Additional emoticons ( 1F600 - 1F636 ) assertTrue(containsOnlyEmojis("😀😇😈😎😐😑😕😗😙😛😟😦😧😬😮😯😴😶")) // 6b. Additional transport and map symbols ( 1F681 - 1F6C5 ) assertTrue(containsOnlyEmojis("🚁🚂🚆🚈🚊🚍🚎🚐🚔🚖🚘🚛" + "🚜🚝🚞🚟🚠🚡🚣🚦🚮🚯🚰🚱" + "🚳🚴🚵🚷🚸🚿🛁🛂🛃🛄🛅")) // 6c. Other additional symbols ( 1F30D - 1F567 ) assertTrue(containsOnlyEmojis("🌍🌎🌐🌒🌖🌗🌘🌚🌜🌝🌞🌲" + "🌳🍋🍐🍼🏇🏉🏤🐀🐁🐂🐃🐄" + "🐅🐆🐇🐈🐉🐊🐋🐏🐐🐓🐕🐖" + "🐪👥👬👭💭💶💷📬📭📯📵🔀" + "🔁🔂🔄🔅🔆🔇🔉🔕🔬🔭🕜🕝" + "🕞🕟🕠🕡🕢🕣🕤🕥🕦🕧")) } @Test fun Emoji_emojiLetter_false() { // Letter before assertFalse(containsOnlyEmojis("a\uD83D\uDE03")) assertFalse(containsOnlyEmojis("a😃")) // Letter after assertFalse(containsOnlyEmojis("\uD83D\uDE03a")) assertFalse(containsOnlyEmojis("😃a")) // Letters around assertFalse(containsOnlyEmojis("a\uD83D\uDE03b")) assertFalse(containsOnlyEmojis("a😃b")) } @Test fun Emoji_emojiSpace_false() { // Space before assertFalse(containsOnlyEmojis(" \uD83D\uDE03")) assertFalse(containsOnlyEmojis(" 😃")) // Space after assertFalse(containsOnlyEmojis("\uD83D\uDE03 ")) assertFalse(containsOnlyEmojis("😃 ")) // Spaces around assertFalse(containsOnlyEmojis(" \uD83D\uDE03 ")) assertFalse(containsOnlyEmojis(" 😃 ")) } }
21,213
https://github.com/mlmaskey/calvin-network-tools/blob/master/nodejs/cmds/updateLibrary.js
Github Open Source
Open Source
MIT
2,016
calvin-network-tools
mlmaskey
JavaScript
Code
186
585
'use strict'; var exec = require('child_process').exec; var fs = require('fs'); var path = require('path'); var utils = require('../lib/utils'); var runtimePath = path.join(__dirname, '..','..','HEC_Runtime'); var tmpPath = path.join(utils.getUserHome(),'.HEC_Runtime'); var moved = false; module.exports = function(callback) { moveHome(); if( !moved ) { console.log('Failed to move runtime. Please run "cnf library init"'); } console.log('Updating via npm'); exec('npm install -g calvin-network-tools', {}, function (error, stdout, stderr) { if( error ) { console.log(error); } if( stderr ) { console.log(stderr); } if( stdout ) { console.log(stdout); } if( moved ) { try { console.log('Copying runtime back'); fs.renameSync(tmpPath, runtimePath); console.log('Update complete.'); callback(); } catch(e) { console.log('Failed to move runtime. Please run "cnf library init"'); console.log(e); } } } ); } function moveHome() { try { if( utils.fileExistsSync(runtimePath) ) { if( !utils.fileExistsSync(tmpPath) ) { console.log('Attempting to move runtime'); fs.renameSync(runtimePath, tmpPath); } moved = true; } } catch(e) { console.log('Failed to stash runtime in home dir, attempting parent'); moveUp(); } } function moveUp() { try { tmpPath = path.join(__dirname, '..', '..','..','.HEC_Runtime'); if( utils.fileExistsSync(runtimePath) ) { if( !utils.fileExistsSync(tmpPath) ) { console.log('Attempting to move runtime, again'); fs.renameSync(runtimePath, tmpPath); } moved = true; } } catch(e) {} }
20,345
https://github.com/arangodb/arangodb/blob/master/3rdParty/boost/1.78.0/boost/geometry/algorithms/detail/buffer/buffer_policies.hpp
Github Open Source
Open Source
BSL-1.0, Apache-2.0, BSD-3-Clause, ICU, Zlib, GPL-1.0-or-later, OpenSSL, ISC, LicenseRef-scancode-gutenberg-2020, MIT, GPL-2.0-only, CC0-1.0, LicenseRef-scancode-autoconf-simple-exception, LicenseRef-scancode-pcre, Bison-exception-2.2, LicenseRef-scancode-public-domain, JSON, BSD-2-Clause, LicenseRef-scancode-unknown-license-reference, Unlicense, BSD-4-Clause, Python-2.0, LGPL-2.1-or-later
2,023
arangodb
arangodb
C++
Code
784
2,565
// Boost.Geometry (aka GGL, Generic Geometry Library) // Copyright (c) 2012-2014 Barend Gehrels, Amsterdam, the Netherlands. // This file was modified by Oracle on 2017-2020. // Modifications copyright (c) 2017-2020, Oracle and/or its affiliates. // Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle // Use, modification and distribution is subject to the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_GEOMETRY_ALGORITHMS_DETAIL_BUFFER_BUFFER_POLICIES_HPP #define BOOST_GEOMETRY_ALGORITHMS_DETAIL_BUFFER_BUFFER_POLICIES_HPP #include <cstddef> #include <boost/range/value_type.hpp> #include <boost/geometry/core/coordinate_type.hpp> #include <boost/geometry/core/point_type.hpp> #include <boost/geometry/algorithms/detail/overlay/backtrack_check_si.hpp> #include <boost/geometry/algorithms/detail/overlay/traversal_info.hpp> #include <boost/geometry/algorithms/detail/overlay/turn_info.hpp> #include <boost/geometry/strategies/buffer.hpp> namespace boost { namespace geometry { #ifndef DOXYGEN_NO_DETAIL namespace detail { namespace buffer { class backtrack_for_buffer { public : typedef detail::overlay::backtrack_state state_type; template < typename Operation, typename Rings, typename Turns, typename Geometry, typename Strategy, typename RobustPolicy, typename Visitor > static inline void apply(std::size_t size_at_start, Rings& rings, typename boost::range_value<Rings>::type& ring, Turns& turns, typename boost::range_value<Turns>::type const& /*turn*/, Operation& operation, detail::overlay::traverse_error_type /*traverse_error*/, Geometry const& , Geometry const& , Strategy const& , RobustPolicy const& , state_type& state, Visitor& /*visitor*/ ) { #if defined(BOOST_GEOMETRY_COUNT_BACKTRACK_WARNINGS) extern int g_backtrack_warning_count; g_backtrack_warning_count++; #endif //std::cout << "!"; //std::cout << "WARNING " << traverse_error_string(traverse_error) << std::endl; state.m_good = false; // Make bad output clean rings.resize(size_at_start); ring.clear(); // Reject this as a starting point operation.visited.set_rejected(); // And clear all visit info clear_visit_info(turns); } }; struct buffer_overlay_visitor { public : void print(char const* /*header*/) { } template <typename Turns> void print(char const* /*header*/, Turns const& /*turns*/, int /*turn_index*/) { } template <typename Turns> void print(char const* /*header*/, Turns const& /*turns*/, int /*turn_index*/, int /*op_index*/) { } template <typename Turns> void visit_turns(int , Turns const& ) {} template <typename Clusters, typename Turns> void visit_clusters(Clusters const& , Turns const& ) {} template <typename Turns, typename Turn, typename Operation> void visit_traverse(Turns const& /*turns*/, Turn const& /*turn*/, Operation const& /*op*/, const char* /*header*/) { } template <typename Turns, typename Turn, typename Operation> void visit_traverse_reject(Turns const& , Turn const& , Operation const& , detail::overlay::traverse_error_type ) {} template <typename Rings> void visit_generated_rings(Rings const& ) {} }; // Should follow traversal-turn-concept (enrichment, visit structure) // and adds index in piece vector to find it back template <typename Point, typename SegmentRatio> struct buffer_turn_operation : public detail::overlay::traversal_turn_operation<Point, SegmentRatio> { signed_size_type piece_index; signed_size_type index_in_robust_ring; inline buffer_turn_operation() : piece_index(-1) , index_in_robust_ring(-1) {} }; // Version of turn_info for buffer with its turn index and other helper variables template <typename Point, typename SegmentRatio> struct buffer_turn_info : public detail::overlay::turn_info < Point, SegmentRatio, buffer_turn_operation<Point, SegmentRatio> > { typedef Point point_type; std::size_t turn_index; // Information if turn can be used. It is not traversable if it is within // another piece, or within the original (depending on deflation), // or (for deflate) if there are not enough points to traverse it. bool is_turn_traversable; bool close_to_offset; bool is_linear_end_point; bool within_original; signed_size_type count_in_original; // increased by +1 for in ext.ring, -1 for int.ring inline buffer_turn_info() : turn_index(0) , is_turn_traversable(true) , close_to_offset(false) , is_linear_end_point(false) , within_original(false) , count_in_original(0) {} }; struct buffer_less { template <typename Indexed> inline bool operator()(Indexed const& left, Indexed const& right) const { if (! (left.subject->seg_id == right.subject->seg_id)) { return left.subject->seg_id < right.subject->seg_id; } // Both left and right are located on the SAME segment. if (! (left.subject->fraction == right.subject->fraction)) { return left.subject->fraction < right.subject->fraction; } return left.turn_index < right.turn_index; } }; template <typename Strategy> struct piece_get_box { explicit piece_get_box(Strategy const& strategy) : m_strategy(strategy) {} template <typename Box, typename Piece> inline void apply(Box& total, Piece const& piece) const { assert_coordinate_type_equal(total, piece.m_piece_border.m_envelope); if (piece.m_piece_border.m_has_envelope) { geometry::expand(total, piece.m_piece_border.m_envelope, m_strategy); } } Strategy const& m_strategy; }; template <typename Strategy> struct piece_overlaps_box { explicit piece_overlaps_box(Strategy const& strategy) : m_strategy(strategy) {} template <typename Box, typename Piece> inline bool apply(Box const& box, Piece const& piece) const { assert_coordinate_type_equal(box, piece.m_piece_border.m_envelope); if (piece.type == strategy::buffer::buffered_flat_end || piece.type == strategy::buffer::buffered_concave) { // Turns cannot be inside a flat end (though they can be on border) // Neither we need to check if they are inside concave helper pieces // Skip all pieces not used as soon as possible return false; } if (! piece.m_piece_border.m_has_envelope) { return false; } return ! geometry::detail::disjoint::disjoint_box_box(box, piece.m_piece_border.m_envelope, m_strategy); } Strategy const& m_strategy; }; template <typename Strategy> struct turn_get_box { explicit turn_get_box(Strategy const& strategy) : m_strategy(strategy) {} template <typename Box, typename Turn> inline void apply(Box& total, Turn const& turn) const { assert_coordinate_type_equal(total, turn.point); geometry::expand(total, turn.point, m_strategy); } Strategy const& m_strategy; }; template <typename Strategy> struct turn_overlaps_box { explicit turn_overlaps_box(Strategy const& strategy) : m_strategy(strategy) {} template <typename Box, typename Turn> inline bool apply(Box const& box, Turn const& turn) const { assert_coordinate_type_equal(turn.point, box); return ! geometry::detail::disjoint::disjoint_point_box(turn.point, box, m_strategy); } Strategy const& m_strategy; }; struct enriched_map_buffer_include_policy { template <typename Operation> static inline bool include(Operation const& op) { return op != detail::overlay::operation_intersection && op != detail::overlay::operation_blocked; } }; }} // namespace detail::buffer #endif // DOXYGEN_NO_DETAIL }} // namespace boost::geometry #endif // BOOST_GEOMETRY_ALGORITHMS_DETAIL_BUFFER_BUFFER_POLICIES_HPP
2,706
https://github.com/jodavis42/ZeroPhysicsTestbed/blob/master/ZeroLibraries/Common/Utility/Determinism.hpp
Github Open Source
Open Source
MIT
2,022
ZeroPhysicsTestbed
jodavis42
C++
Code
97
145
/////////////////////////////////////////////////////////////////////////////// /// /// Authors: Trevor Sundberg /// Copyright 2017, DigiPen Institute of Technology /// /////////////////////////////////////////////////////////////////////////////// #pragma once namespace Zero { // We use this bool globally to set whether certain operations should be as deterministic as possible. // For example, this means that frame timers would return fixed times, guid generation will generate // guids in a deterministic fashion (non random), etc. This should be set as early in the program as // possible (default false). This is used by the UnitTestSystem to ensure recording and playback are the same. extern bool gDeterministicMode; } // namespace Zero
7,722
https://github.com/narci2010/toceansoft-cas/blob/master/sso-support/sso-support-validate/src/main/java/com/toceansoft/cas/support/validate/imp/mail/MailInformative.java
Github Open Source
Open Source
MIT
null
toceansoft-cas
narci2010
Java
Code
207
629
/* * 版权所有.(c)2010-2018. 拓胜科技 */ package com.toceansoft.cas.support.validate.imp.mail; import java.util.Date; import com.toceansoft.cas.support.validate.Informative; /** * @author Narci.Lee * @date 2018/11/2 * @since */ public class MailInformative implements Informative { //发送邮件的from private String fromMail; //目标邮箱 private String toMail; //邮件标题 private String subject; //邮件内容 private String content; //邮件编码 private String code; //有效时长,秒 private long effective; //信息唯一标志 private String id; public String getFromMail() { return fromMail; } public MailInformative setFromMail(String fromMail) { this.fromMail = fromMail; return this; } public String getToMail() { return toMail; } public MailInformative setToMail(String toMail) { this.toMail = toMail; return this; } public String getSubject() { return subject; } public MailInformative setSubject(String subject) { this.subject = subject; return this; } public String getContent() { return content; } public MailInformative setContent(String content) { this.content = content; return this; } public String getCode() { return code; } public MailInformative setCode(String code) { this.code = code; return this; } public long getEffective() { return effective; } public MailInformative setEffective(long effective) { this.effective = effective; return this; } public String getId() { return id; } public MailInformative setId(String id) { this.id = id; return this; } @Override public long effective() { return getEffective(); } @Override public long time() { return new Date().getTime(); } @Override public String id() { return getId(); } }
16,093
https://github.com/clarartp/twilio-csharp/blob/master/src/Twilio.WinRT/Model/Transcription.cs
Github Open Source
Open Source
Apache-2.0
null
twilio-csharp
clarartp
C#
Code
265
531
using System; namespace Twilio { /// <summary> /// An Transcription instance resource represents a single Twilio Transcription. /// </summary> public sealed class Transcription //: TwilioBase { /// <summary> /// Exception encountered during API request /// </summary> public RestException RestException { get; set; } /// <summary> /// The URI for this resource, relative to https://api.twilio.com /// </summary> public Uri Uri { get; set; } /// <summary> /// A 34 character string that uniquely identifies this resource. /// </summary> public string Sid { get; set; } /// <summary> /// The date that this resource was created /// </summary> public DateTimeOffset DateCreated { get; set; } /// <summary> /// The date that this resource was last updated /// </summary> public DateTimeOffset DateUpdated { get; set; } /// <summary> /// The unique id of the Account responsible for this transcription. /// </summary> public string AccountSid { get; set; } /// <summary> /// A string representing the status of the transcription: in-progress, completed or failed. /// </summary> public string Status { get; set; } /// <summary> /// The unique id of the Recording this Transcription was made of. /// </summary> public string RecordingSid { get; set; } /// <summary> /// The duration of the transcribed audio, in seconds. /// </summary> public int Duration { get; set; } /// <summary> /// The text content of the transcription. /// </summary> public string TranscriptionText { get; set; } /// <summary> /// The charge for this transcript in USD. Populated after the transcript is completed. Note, this value may not be immediately available. /// </summary> public double? Price { get; set; } } }
3,851
https://github.com/PaloBraga/Helloworld-Python/blob/master/exercicio_pag_65.py
Github Open Source
Open Source
Apache-2.0
null
Helloworld-Python
PaloBraga
Python
Code
34
98
print(5+3) print(10-2) print(4*2) print(40/5) numero= 666 print("O número do chefe Felix é "+ str(numero) + "!") #como criar comentarios em python, se utiliza o "#", com isso ele ignora a linha em questão. print("Comentario")
11,306
https://github.com/zouhirzz/FreeRDP/blob/master/winpr/libwinpr/credui/credui.c
Github Open Source
Open Source
Apache-2.0
2,022
FreeRDP
zouhirzz
C
Code
319
1,002
/** * WinPR: Windows Portable Runtime * Credentials Management UI * * Copyright 2012 Marc-Andre Moreau <marcandre.moreau@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. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <winpr/crt.h> #include <winpr/credui.h> /* * Credentials Management UI Functions: * http://msdn.microsoft.com/en-us/library/windows/desktop/aa374731(v=vs.85).aspx#credentials_management_ui_functions */ #ifndef _WIN32 DWORD CredUIPromptForCredentialsW(PCREDUI_INFOW pUiInfo, PCWSTR pszTargetName, PCtxtHandle pContext, DWORD dwAuthError, PWSTR pszUserName, ULONG ulUserNameBufferSize, PWSTR pszPassword, ULONG ulPasswordBufferSize, BOOL* save, DWORD dwFlags) { return 0; } DWORD CredUIPromptForCredentialsA(PCREDUI_INFOA pUiInfo, PCSTR pszTargetName, PCtxtHandle pContext, DWORD dwAuthError, PSTR pszUserName, ULONG ulUserNameBufferSize, PSTR pszPassword, ULONG ulPasswordBufferSize, BOOL* save, DWORD dwFlags) { return 0; } DWORD CredUIParseUserNameW(CONST WCHAR* UserName, WCHAR* user, ULONG userBufferSize, WCHAR* domain, ULONG domainBufferSize) { return 0; } DWORD CredUIParseUserNameA(CONST CHAR* userName, CHAR* user, ULONG userBufferSize, CHAR* domain, ULONG domainBufferSize) { return 0; } DWORD CredUICmdLinePromptForCredentialsW(PCWSTR pszTargetName, PCtxtHandle pContext, DWORD dwAuthError, PWSTR UserName, ULONG ulUserBufferSize, PWSTR pszPassword, ULONG ulPasswordBufferSize, PBOOL pfSave, DWORD dwFlags) { return 0; } DWORD CredUICmdLinePromptForCredentialsA(PCSTR pszTargetName, PCtxtHandle pContext, DWORD dwAuthError, PSTR UserName, ULONG ulUserBufferSize, PSTR pszPassword, ULONG ulPasswordBufferSize, PBOOL pfSave, DWORD dwFlags) { return 0; } DWORD CredUIConfirmCredentialsW(PCWSTR pszTargetName, BOOL bConfirm) { return 0; } DWORD CredUIConfirmCredentialsA(PCSTR pszTargetName, BOOL bConfirm) { return 0; } DWORD CredUIStoreSSOCredW(PCWSTR pszRealm, PCWSTR pszUsername, PCWSTR pszPassword, BOOL bPersist) { return 0; } DWORD CredUIStoreSSOCredA(PCSTR pszRealm, PCSTR pszUsername, PCSTR pszPassword, BOOL bPersist) { return 0; } DWORD CredUIReadSSOCredW(PCWSTR pszRealm, PWSTR* ppszUsername) { return 0; } DWORD CredUIReadSSOCredA(PCSTR pszRealm, PSTR* ppszUsername) { return 0; } #endif
45,478
https://github.com/sonamnamgyel/Student-Information-System/blob/master/app/lang/pt/user/user.php
Github Open Source
Open Source
MIT
2,015
Student-Information-System
sonamnamgyel
PHP
Code
58
199
<?php return array( /* |-------------------------------------------------------------------------- | User Language Lines |-------------------------------------------------------------------------- | | */ 'register' => 'Registrar', 'login' => 'Login', 'login_first' => 'Primeiro Login', 'account' => 'Conta', 'forgot_password' => 'Esqueceu a Senha', 'settings' => 'Configurações', 'profile' => 'Perfil', 'user_account_is_not_confirmed' => 'Conta de usuário não foi confirmada.', 'user_account_updated' => 'Conta de usário atualizada.', 'user_account_created' => 'Conta de usário criada.', );
41,541
https://github.com/ankithans/jan-suvidha/blob/master/api/services/gcloud_bucket.js
Github Open Source
Open Source
MIT
2,021
jan-suvidha
ankithans
JavaScript
Code
77
263
const { Storage } = require("@google-cloud/storage"); // const keyFilename = "Jan-Suvidha-523c6c8c68af.json"; const storage = new Storage({ credentials: JSON.parse(process.env.SERVICE_ACCOUNT), }); // Makes an authenticated API request. const gcloudUpload = async (file) => { try { const bucket = await storage.bucket("jan-suvidha-images"); const result = await bucket.upload(file); const name = myTrim(result[0].metadata.name); const url = `https://storage.googleapis.com/jan-suvidha-images/${name.replace( /\s/g, "" )}`; return url; } catch (err) { console.error("ERROR:", err); } }; function myTrim(x) { return x.replace(/^\s+|\s+$/gm, ""); } module.exports = { gcloudUpload };
9,074
https://github.com/niiknow/lua-script-engine/blob/master/lib/sngin/utils.lua
Github Open Source
Open Source
MIT
2,017
lua-script-engine
niiknow
Lua
Code
189
559
-- our utils lib, nothing here should depend on ngx -- for ngx stuff, put it inside ngin.lua file local _M = {} function _M.trim(str) if (str == nil) then return nil end return string.match(str, '^%s*(.*%S)') or '' end function _M.slugify(str) if (str == nil) then return nil end str = self.trim(str) return string.lower(string.gsub(string.gsub(str,"[^ A-Za-z]"," "),"[ ]+","-")) end function _M.slugemail(str) if (str == nil) then return nil end str = trim(str) return string.lower(string.gsub(str,"[^@0-9A-Za-z]","-")) end function _M.split(str, sep, dest) if (str == nil) then return {} end if sep == nil then sep = "%s" end local t = dest or {} for str in string.gmatch(str, "([^"..sep.."]+)") do table.insert(t, str) end return t end function _M.encodeURIComponent(s) s = string.gsub(s, "([&=+%c])", function (c) return string.format("%%%02X", string.byte(c)) end) s = string.gsub(s, " ", "%20") return s end function _M.sanitizePath(s) -- path should not have double quote, single quote, period -- we purposely left casing because paths are case-sensitive s = string.gsub(s, "[^a-zA-Z0-9.-_/]", "") -- remove double period and forward slash s = string.gsub(string.gsub(s, "%.%.", ""), "//", "/") -- remove trailing forward slash s = string.gsub(s, "/*$", "") return s end return _M
21,626
https://github.com/codyseibert/typr.io/blob/master/client/app/src/snippits/snippits.sass
Github Open Source
Open Source
MIT
2,021
typr.io
codyseibert
Sass
Code
134
598
button.practice border: 0 font-size: 16px background-color: #B9D25B border-radius: 10px padding: 10px .glyphicon margin-right: 10px position: relative top: 5px button.practice:hover background-color: #98BBCD button.practice:active outline: none button.practice:focus outline: none .snippit margin-bottom: 50px h2 margin-top: 50px pre height: 150px .star font-size: 30px position: relative top: 8px margin-left: 10px .filter margin-top: 20px font-size: 20px cursor: pointer i position: relative right: 10px .filter:hover color: $COLOR_P .filter.selected color: $COLOR_P text-shadow: 1px 1px $COLOR_T .fade opacity: 1 .fade.ng-enter transition: 0.5s linear all opacity: 0 .fade.ng-leave transition: 0.5s linear all opacity: 1 .fade.ng-leave.ng-leave-active opacity: 0 .fade.ng-enter.ng-enter-active opacity: 1 .fade.ng-enter-stagger transition-delay: 0.15s animation-delay: 0.15s transition-duration: 0s .fade-no-out opacity: 1 .fade-no-out.ng-enter transition: 0.5s linear all opacity: 0 .fade-no-out.ng-leave transition: 0.0s linear all opacity: 1 .fade-no-out.ng-leave transition: 0.0s linear all opacity: 1 .fade-no-out.ng-leave.ng-leave-active opacity: 0 .fade-no-out.ng-enter.ng-enter-active opacity: 1 .fade-no-out.ng-enter-stagger transition-delay: 0.15s animation-delay: 0.15s transition-duration: 0s
45,489
https://github.com/AndreLucyo2/POO_Avaliacao1-Churrasco/blob/master/src/entidades/dao/ConfraternizacaoDAO.java
Github Open Source
Open Source
MIT
null
POO_Avaliacao1-Churrasco
AndreLucyo2
Java
Code
247
847
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package entidades.dao; import bdFake.BancoFake; import entidades.Confraternizacao; import java.util.ArrayList; /** * * @author Andre */ public class ConfraternizacaoDAO { //CRUD PESSOA ============================================================== public static Confraternizacao findByID(int id) { //percorre a lista se encontrar : for (Confraternizacao evnt : BancoFake.getTB_EVENTO()) { if (evnt.getId() == id) { return evnt; } else { //System.out.println("Confraternizacao " + id + " não encontrada!"); } } return null; } public static boolean add(Confraternizacao confraternizacao) { try { BancoFake.getTB_EVENTO().add(confraternizacao); return true; } catch (Exception e) { e.printStackTrace(); return false; } } public static boolean remove(int id) { try { //percorre a lista se encontrar : for (Confraternizacao evnt : BancoFake.getTB_EVENTO()) { if (evnt.getId() == id) { BancoFake.getTB_EVENTO().remove(evnt); return true; } } System.out.println("Confraternizacao " + id + " não encontrada!"); } catch (Exception e) { e.printStackTrace(); } return false; } public static boolean update(Confraternizacao confraternizacao) { try { //percorre a lista se encontrar : for (Confraternizacao evnt : BancoFake.getTB_EVENTO()) { if (evnt.getId() == confraternizacao.getId()) { //remove a confraternizacao OLD BancoFake.getTB_EVENTO().remove(evnt); //Adiciona a confraternizacao Nova com mesmo id BancoFake.getTB_EVENTO().add(confraternizacao); return true; } } } catch (Exception e) { e.printStackTrace(); } return false; } public static void printAll(ArrayList<Confraternizacao> lista) { if (lista != null) { System.out.println("\nTABELA EVENTO ====================================================="); //percorre a lista for (Confraternizacao evnt : BancoFake.getTB_EVENTO()) { System.out.println(evnt.toString()); } System.out.println("==================================================================="); return; } System.out.println("Lsta Vazia!"); } }
7,420
https://github.com/Ranjan-Padhi/pravega/blob/master/controller/src/main/java/io/pravega/controller/store/stream/records/SubscriberSet.java
Github Open Source
Open Source
Apache-2.0
null
pravega
Ranjan-Padhi
Java
Code
315
1,057
/** * Copyright (c) Dell Inc., or its subsidiaries. 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 */ package io.pravega.controller.store.stream.records; import com.google.common.collect.ImmutableList; import io.pravega.common.ObjectBuilder; import io.pravega.common.io.serialization.RevisionDataInput; import io.pravega.common.io.serialization.RevisionDataOutput; import io.pravega.common.io.serialization.VersionedSerializer; import lombok.Data; import lombok.Getter; import lombok.NonNull; import lombok.Builder; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.util.List; import java.util.stream.Collectors; /** * Data class to capture a subscriber set. */ @Slf4j @Data public class SubscriberSet { public static final SubscriberSetSerializer SERIALIZER = new SubscriberSetSerializer(); @Getter private final ImmutableList<String> subscribers; @Builder public SubscriberSet(@NonNull ImmutableList<String> subscribers) { this.subscribers = subscribers; } /** * This method adds a subscriber in the subscriberSet. * @param subscriberSet Subscriber Set. * @param subscriber subscriber to be added. * @return updated Subscriber Set. */ public static SubscriberSet add(@NonNull SubscriberSet subscriberSet, @NonNull String subscriber) { ImmutableList.Builder<String> builder = ImmutableList.builder(); builder.addAll(subscriberSet.subscribers); builder.add(subscriber); return new SubscriberSet(builder.build()); } /** * This method removes a subscriber from the subscriberSet. * @param subscriberSet Subscriber Set. * @param subscriber subscriber to be removed. * @return updated Subscriber Set. */ public static SubscriberSet remove(@NonNull SubscriberSet subscriberSet, @NonNull String subscriber) { ImmutableList.Builder<String> builder = ImmutableList.builder(); List<String> otherSubscribers = subscriberSet.getSubscribers().stream().filter(s -> !s.equals(subscriber)).collect(Collectors.toList()); builder.addAll(otherSubscribers); return new SubscriberSet(builder.build()); } private static class SubscriberSetBuilder implements ObjectBuilder<SubscriberSet> { } @SneakyThrows(IOException.class) public static SubscriberSet fromBytes(final byte[] data) { return SERIALIZER.deserialize(data); } @SneakyThrows(IOException.class) public byte[] toBytes() { return SERIALIZER.serialize(this).getCopy(); } private static class SubscriberSetSerializer extends VersionedSerializer.WithBuilder<SubscriberSet, SubscriberSet.SubscriberSetBuilder> { @Override protected byte getWriteVersion() { return 0; } @Override protected void declareVersions() { version(0).revision(0, this::write00, this::read00); } private void read00(RevisionDataInput revisionDataInput, SubscriberSet.SubscriberSetBuilder recordBuilder) throws IOException { ImmutableList.Builder<String> builder = ImmutableList.builder(); revisionDataInput.readCollection(DataInput::readUTF, builder); recordBuilder.subscribers(builder.build()); } private void write00(SubscriberSet subscribersRecord, RevisionDataOutput revisionDataOutput) throws IOException { revisionDataOutput.writeCollection(subscribersRecord.getSubscribers(), DataOutput::writeUTF); } @Override protected SubscriberSet.SubscriberSetBuilder newBuilder() { return SubscriberSet.builder(); } } }
19,465
https://github.com/fpl-analytics/gr_crypto/blob/master/scripts/experimental/check_wide.py
Github Open Source
Open Source
MIT
null
gr_crypto
fpl-analytics
Python
Code
61
202
# -*- coding: utf-8 -*- """ Created on Sun Dec 19 15:17:04 2021 @author: Andre """ print(os.getcwd()) # Target is wide. Doing some more investigating here. print(df_filt["Target"].max()) print(df_filt["Target"].min()) plt.hist(df_filt["Target"], bins = 50) plt.hist(df_filt_norm["Target"], bins = 50) check = (df_filt_norm["Target"] * stds["Target"]) + means["Target"] plt.hist(check, bins = 50) check = df_filt.sort_values("Target") outliers = np.abs(df_filt["Target"]) > 0.025 print("Number of outliers is ", np.sum(outliers))
27,689
https://github.com/HectorRPC/Toggl2Excel/blob/master/Toggl.Ultrawave/Network/Request.cs
Github Open Source
Open Source
BSD-3-Clause
2,021
Toggl2Excel
HectorRPC
C#
Code
87
273
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using Toggl.Multivac; namespace Toggl.Ultrawave.Network { internal sealed class Request : IRequest { public Either<string, byte[]> Body { get; } public Uri Endpoint { get; } public HttpMethod HttpMethod { get; } public IEnumerable<HttpHeader> Headers { get; } public Request(string body, Uri endpoint, IEnumerable<HttpHeader> headers, HttpMethod httpMethod) { Ensure.Argument.IsNotNull(body, nameof(body)); // ReSharper disable once PossibleMultipleEnumeration Ensure.Argument.IsNotNull(headers, nameof(headers)); Ensure.Argument.IsNotNull(endpoint, nameof(endpoint)); Body = Either<string, byte[]>.WithLeft(body); // ReSharper disable once PossibleMultipleEnumeration Headers = headers.ToList(); Endpoint = endpoint; HttpMethod = httpMethod; } } }
41,052
https://github.com/kshivamraj32/Automatic-leaf-infection-identifier/blob/master/classifier.py
Github Open Source
Open Source
MIT
2,018
Automatic-leaf-infection-identifier
kshivamraj32
Python
Code
460
1,773
# importing required libraries import numpy as np import pandas as pd import matplotlib.pyplot as plt # import support vector classifier from sklearn.svm import SVC from sklearn.ensemble import RandomForestClassifier from sklearn.linear_model import LogisticRegression from sklearn.neighbors import KNeighborsClassifier from sklearn.naive_bayes import GaussianNB from xgboost import XGBClassifier from sklearn.ensemble import BaggingClassifier from sklearn import tree from sklearn.ensemble import GradientBoostingClassifier from sklearn.ensemble import AdaBoostClassifier from catboost import CatBoostRegressor from sklearn.ensemble import VotingClassifier from sklearn.model_selection import cross_val_score import cv2 # import warnings to remove any type of future warnings import warnings warnings.simplefilter(action='ignore', category=FutureWarning) # reading csv file and extracting class column to y. dataf = pd.read_csv("Datasetinfectedhealthy.csv") # extracting two features X = dataf.drop(['imgid','fortnum'], axis=1) y = X['label'] X = X.drop('label', axis=1) print("\nTraining dataset:-\n") print(X) log = pd.read_csv("datasetlog/Datasetunlabelledlog.csv") log = log.tail(1) X_ul = log.drop(['imgid','fortnum'], axis=1) print("\nTest dataset:-\n") print(X_ul) print("\n*To terminate press (q)*") #X.plot(kind='scatter',x='feature1',y='feature2') #plt.show() Sum = 0 from sklearn.model_selection import train_test_split for n in range(2): x_train, Xi_test, y_train, yi_test = train_test_split(X, y, test_size=0.52, random_state=60) if cv2.waitKey(1) == ord('q' or 'Q'): break #Following are the 11 classifiers. The best model suited for the required dataset can be chosen. #SVM classifier classifierSVM = SVC() classifierSVM.fit(x_train, y_train) pred = classifierSVM.predict(X_ul) #Random Forest classifier classifierRF = RandomForestClassifier(n_estimators =20,criterion = 'entropy',n_jobs=-1) classifierRF.fit(x_train, y_train) pred = classifierRF.predict(X_ul) #Logistic Regression classifier classifierLR = LogisticRegression(C=10) classifierLR.fit(x_train, y_train) pred = classifierLR.predict(X_ul) #KNN classifier classifierKNN = KNeighborsClassifier(n_neighbors = 5, metric = 'minkowski', p = 2) classifierKNN.fit(x_train, y_train) pred = classifierKNN.predict(X_ul) #Naive Bayes classifier classifierNB = GaussianNB() classifierNB.fit(x_train, y_train) pred = classifierNB.predict(X_ul) #XGBoost classifier classifierXGB = XGBClassifier(n_estimators=20,n_jobs=-1) classifierXGB.fit(x_train, y_train) pred = classifierXGB.predict(X_ul) #Bagging Classifier classifierBG = BaggingClassifier(tree.DecisionTreeClassifier(),n_estimators=20,n_jobs=-1) classifierBG.fit(x_train, y_train) pred = classifierBG.predict(X_ul) #Gradient Boosting Classifier classifierGB=GradientBoostingClassifier(n_estimators=20,learning_rate=1.0,max_depth=1).fit(x_train, y_train) pred = classifierGB.predict(X_ul) #Adaboost classifier classifierAB = AdaBoostClassifier(base_estimator=RandomForestClassifier(n_estimators = 20,criterion = 'entropy',n_jobs=-1),n_estimators = 20) classifierAB.fit(x_train, y_train) pred = classifierAB.predict(X_ul) #Catboost Classifier classifierCB=CatBoostRegressor(iterations=20, depth=5, learning_rate=0.1, loss_function='RMSE',silent=True) classifierCB.fit(x_train, y_train,eval_set=(Xi_test, yi_test)) pred = classifierCB.predict(X_ul) th=0.5 #this is done as catboost provides answer in fractions like 1.02,0.98,etc pred[pred>th]=1 pred[pred<=th]=0 #Classifier that can use variable weights from all above classifiers # classifierVC = VotingClassifier(estimators=[('rf', classifierRF),('svm', classifierSVM),('lr',classifierLR ), ('nb', classifierNB),('knn', classifierKNN),('bg', classifierBG),('xgb',classifierXGB),('gb', classifierGB),('ab', classifierAB)],voting='soft', weights=[1,1,1,1,1,1,1,1,1]) # classifierVC.fit(x_train, y_train) # pred = classifierVC.predict(X_ul) #Results from various classifiers; Catboost is not included as it does not provide output in the required format for clf, label in zip([classifierRF,classifierSVM,classifierLR,classifierNB,classifierKNN,classifierBG,classifierXGB,classifierGB,classifierAB],#classifierVC], ['RF', 'SVM', 'LR', 'NB','KNN','BG','XGB','GB','AB']):#,'VT']): scores = cross_val_score(clf, X, [round(i) for i in y], cv=10, scoring='accuracy')#k to be increased for better performance print("Accuracy: %0.4f (+/- %0.2f) [%s]" % (scores.mean(), scores.std(), label)) #After identifying the best model using the above report, all other models can be commented Sum = Sum + pred print(pred) print("\nprediction: %d" %int(Sum/4)) if(Sum < 2): print("The leaf is sufficiently healthy!") else: print("The leaf is infected!") print("\nKeypress on any image window to terminate") #from sklearn.metrics import classification_report, confusion_matrix #print(classification_report(yi_test,y_pred)) #print "\n Average precision percentage: %.2f" %avg_pred + "%" cv2.waitKey(0)
48,530
https://github.com/kirbyfu/ebook-reader/blob/master/src/styles.scss
Github Open Source
Open Source
BSD-3-Clause
2,022
ebook-reader
kirbyfu
SCSS
Code
117
522
@import "tailwindcss/base"; @import "tailwindcss/components"; @import "tailwindcss/utilities"; @import "./mat"; :root { --font-color: rgba(0, 0, 0, 0.87); --background-color: #eceff1; } @layer base { html { width: 100%; height: 100%; } body { @apply font-sans; color: var(--font-color); background-color: var(--background-color); overflow-wrap: break-word; width: 100%; height: 100%; } } @layer utilities { .writing-horizontal-tb { writing-mode: horizontal-tb; } .writing-vertical-rl { writing-mode: vertical-rl; } .px-screen { @apply px-4 md:px-8 lg:max-w-4xl xl:max-w-none 2xl:max-w-6xl mx-auto; } .px-reader { @apply px-4 md:px-8; } .opacity-header-icon { @apply opacity-60 hover:opacity-100 transition-opacity; } .p-header-fa { @apply p-4 xl:p-3; } .-translate-x-header-fa { @apply -translate-x-4 xl:-translate-x-3; } .translate-x-header-fa { @apply translate-x-4 xl:translate-x-3; } .p-header-mat { @apply p-3 xl:p-2.5; } .-translate-x-header-mat { @apply -translate-x-3 xl:-translate-x-2.5; } .translate-x-header-mat { @apply translate-x-3 xl:translate-x-2.5; } }
50,320
https://github.com/amc8391/mage/blob/master/Mage.Sets/src/mage/cards/m/MandateOfPeace.java
Github Open Source
Open Source
MIT
2,022
mage
amc8391
Java
Code
335
1,283
package mage.cards.m; import java.util.List; import java.util.UUID; import java.util.stream.Stream; import mage.MageObject; import mage.abilities.Ability; import mage.abilities.common.CastOnlyDuringPhaseStepSourceAbility; import mage.abilities.effects.ContinuousRuleModifyingEffectImpl; import mage.abilities.effects.Effect; import mage.abilities.effects.OneShotEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.Duration; import mage.constants.Outcome; import mage.constants.TurnPhase; import mage.game.Game; import mage.game.combat.Combat; import mage.game.events.GameEvent; import mage.game.stack.Spell; /** * * @author goesta */ public final class MandateOfPeace extends CardImpl { public MandateOfPeace(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.INSTANT}, "{1}{W}"); // Cast this spell only during combat. this.addAbility(new CastOnlyDuringPhaseStepSourceAbility(TurnPhase.COMBAT)); // Your opponents can't cast spells this turn. this.getSpellAbility().addEffect(new MandateOfPeaceOpponentsCantCastSpellsEffect()); // End the combat phase. this.getSpellAbility().addEffect(new MandateOfPeaceEndCombatEffect()); } private MandateOfPeace(final MandateOfPeace card) { super(card); } @Override public MandateOfPeace copy() { return new MandateOfPeace(this); } } class MandateOfPeaceOpponentsCantCastSpellsEffect extends ContinuousRuleModifyingEffectImpl { public MandateOfPeaceOpponentsCantCastSpellsEffect() { super(Duration.EndOfTurn, Outcome.Benefit); staticText = "Your opponents can't cast spells this turn"; } public MandateOfPeaceOpponentsCantCastSpellsEffect(final MandateOfPeaceOpponentsCantCastSpellsEffect effect) { super(effect); } @Override public MandateOfPeaceOpponentsCantCastSpellsEffect copy() { return new MandateOfPeaceOpponentsCantCastSpellsEffect(this); } @Override public boolean apply(Game game, Ability source) { return true; } @Override public String getInfoMessage(Ability source, GameEvent event, Game game) { MageObject mageObject = game.getObject(source.getSourceId()); if (mageObject != null) { return "You can't cast spells this turn (" + mageObject.getIdName() + ")."; } return null; } @Override public boolean checksEventType(GameEvent event, Game game) { return event.getType() == GameEvent.EventType.CAST_SPELL; } @Override public boolean applies(GameEvent event, Ability source, Game game) { return game.getOpponents(source.getControllerId()).contains(event.getPlayerId()); } } class MandateOfPeaceEndCombatEffect extends OneShotEffect { public MandateOfPeaceEndCombatEffect() { super(Outcome.Benefit); this.staticText = "End the combat phase. <i>(Remove all attackers " + "and blockers from combat. Exile all spells and abilities " + "from the stack, including this spell.)</i>"; } public MandateOfPeaceEndCombatEffect(OneShotEffect effect) { super(effect); } @Override public boolean apply(Game game, Ability source) { Combat combat = game.getCombat(); List<UUID> attackerIds = combat.getAttackers(); List<UUID> blockerIds = combat.getBlockers(); Stream.concat(blockerIds.stream(), attackerIds.stream()) .map(id -> game.getPermanent(id)) .filter(e -> e != null) .forEach(permanent -> permanent.removeFromCombat(game)); combat.endCombat(game); if (!game.getStack().isEmpty()) { game.getStack().stream() .filter(stackObject -> stackObject instanceof Spell) .forEach(stackObject -> ((Spell) stackObject).moveToExile(null, "", null, game)); game.getStack().stream() .filter(stackObject -> stackObject instanceof Ability) .forEach(stackObject -> game.getStack().remove(stackObject, game)); } return true; } @Override public Effect copy() { return new MandateOfPeaceEndCombatEffect(this); } }
31,094
https://github.com/jdrew1303/statechart.ml/blob/master/src/lib/statechart_translator.mli
Github Open Source
Open Source
MIT
2,017
statechart.ml
jdrew1303
OCaml
Code
6
19
val translate : Statechart_t.document -> Statechart_executable.document
27,061
https://github.com/stephenlawrence/gravity/blob/master/lib/ops/opsservice/logforwarders.go
Github Open Source
Open Source
Apache-2.0
2,022
gravity
stephenlawrence
Go
Code
957
2,873
/* Copyright 2018 Gravitational, 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 opsservice import ( "github.com/gravitational/gravity/lib/defaults" "github.com/gravitational/gravity/lib/ops" "github.com/gravitational/gravity/lib/storage" "github.com/gravitational/gravity/lib/utils" "github.com/gravitational/rigging" "github.com/gravitational/trace" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" ) // GetLogForwarders returns a list of configured log forwarders func (o *Operator) GetLogForwarders(key ops.SiteKey) ([]storage.LogForwarder, error) { if o.cfg.LogForwarders == nil { return nil, trace.BadParameter( "this operator does not support log forwarders management") } forwarders, err := o.cfg.LogForwarders.Get() if err != nil { return nil, trace.Wrap(err) } return forwarders, nil } // UpdateForwarders replaces the list of active log forwarders // TODO(r0mant,alexeyk) this is a legacy method used only by UI, alexeyk to remove it when // refactoring resources and use upsert/delete instead func (o *Operator) UpdateLogForwarders(key ops.SiteKey, forwarders []storage.LogForwarderV1) error { if o.cfg.LogForwarders == nil { return trace.BadParameter( "this operator does not support log forwarders management") } forwardersV2 := make([]storage.LogForwarder, len(forwarders)) for i := range forwarders { forwardersV2[i] = storage.NewLogForwarderFromV1(forwarders[i]) } err := o.cfg.LogForwarders.Replace(forwardersV2) if err != nil { return trace.Wrap(err) } err = o.cfg.LogForwarders.Reload() if err != nil { return trace.Wrap(err) } return nil } // CreateLogForwarder creates a new log forwarder func (o *Operator) CreateLogForwarder(key ops.SiteKey, forwarder storage.LogForwarder) error { if o.cfg.LogForwarders == nil { return trace.BadParameter( "this operator does not support log forwarders management") } err := o.cfg.LogForwarders.Create(forwarder) if err != nil { return trace.Wrap(err) } err = o.cfg.LogForwarders.Reload() if err != nil { return trace.Wrap(err) } return nil } // UpdateLogForwarder updates an existing log forwarder func (o *Operator) UpdateLogForwarder(key ops.SiteKey, forwarder storage.LogForwarder) error { if o.cfg.LogForwarders == nil { return trace.BadParameter( "this operator does not support log forwarders management") } err := o.cfg.LogForwarders.Update(forwarder) if err != nil { return trace.Wrap(err) } err = o.cfg.LogForwarders.Reload() if err != nil { return trace.Wrap(err) } return nil } // DeleteLogForwarder deletes a log forwarder func (o *Operator) DeleteLogForwarder(key ops.SiteKey, name string) error { if o.cfg.LogForwarders == nil { return trace.BadParameter( "this operator does not support log forwarders management") } err := o.cfg.LogForwarders.Delete(name) if err != nil { return trace.Wrap(err) } err = o.cfg.LogForwarders.Reload() if err != nil { return trace.Wrap(err) } return nil } // LogForwarderControl defines methods for managing log forwarders in Kubernetes, // mostly so implementation can be substituted in tests w/o Kubernetes type LogForwardersControl interface { // Get returns a list of log forwarders from config map Get() ([]storage.LogForwarder, error) // Replace replaces all log forwarders in config map with the provided ones Replace([]storage.LogForwarder) error // Create adds a new log forwarder in config map Create(storage.LogForwarder) error // Update updates an existing log forwarder in config map Update(storage.LogForwarder) error // Delete deletes log forwarder from config map Delete(string) error // Reload forces log collector to reload forwarder configuration Reload() error } type logForwardersControl struct { client *kubernetes.Clientset } // NewLogForwardersControl returns a default Kubernetes-managed log forwarder controller func NewLogForwardersControl(client *kubernetes.Clientset) LogForwardersControl { return &logForwardersControl{client} } // Get returns a list of log forwarders from config map func (c *logForwardersControl) Get() ([]storage.LogForwarder, error) { configMap, err := c.client.Core().ConfigMaps(defaults.KubeSystemNamespace).Get( defaults.LogForwardersConfigMap, metav1.GetOptions{}) if err != nil { return nil, rigging.ConvertError(err) } var forwarders []storage.LogForwarder for _, data := range configMap.Data { forwarder, err := storage.GetLogForwarderMarshaler().Unmarshal([]byte(data)) if err != nil { return nil, trace.Wrap(err) } forwarders = append(forwarders, forwarder) } return forwarders, nil } // Replace replaces the contents of the forwarder config map with the provided list of forwarders func (c *logForwardersControl) Replace(forwarders []storage.LogForwarder) error { configMap, err := c.client.Core().ConfigMaps(defaults.KubeSystemNamespace).Get( defaults.LogForwardersConfigMap, metav1.GetOptions{}) if err != nil { return rigging.ConvertError(err) } configMap.Data = make(map[string]string) for _, forwarder := range forwarders { bytes, err := storage.GetLogForwarderMarshaler().Marshal(forwarder) if err != nil { return trace.Wrap(err) } configMap.Data[forwarder.GetName()] = string(bytes) } _, err = c.client.Core().ConfigMaps(defaults.KubeSystemNamespace).Update(configMap) if err != nil { return rigging.ConvertError(err) } return nil } // Create adds a new log forwarder to the forwarders config map func (c *logForwardersControl) Create(forwarder storage.LogForwarder) error { configMap, err := c.client.Core().ConfigMaps(defaults.KubeSystemNamespace).Get( defaults.LogForwardersConfigMap, metav1.GetOptions{}) if err != nil { return rigging.ConvertError(err) } _, ok := configMap.Data[forwarder.GetName()] if ok { return trace.AlreadyExists("log forwarder %q already exists", forwarder.GetName()) } bytes, err := storage.GetLogForwarderMarshaler().Marshal(forwarder) if err != nil { return trace.Wrap(err) } if configMap.Data == nil { configMap.Data = make(map[string]string) } configMap.Data[forwarder.GetName()] = string(bytes) _, err = c.client.Core().ConfigMaps(defaults.KubeSystemNamespace).Update(configMap) if err != nil { return rigging.ConvertError(err) } return nil } // Update updates an existing log forwarder in the k8s config map func (c *logForwardersControl) Update(forwarder storage.LogForwarder) error { configMap, err := c.client.Core().ConfigMaps(defaults.KubeSystemNamespace).Get( defaults.LogForwardersConfigMap, metav1.GetOptions{}) if err != nil { return rigging.ConvertError(err) } _, ok := configMap.Data[forwarder.GetName()] if !ok { return trace.NotFound("log forwarder %q not found", forwarder.GetName()) } bytes, err := storage.GetLogForwarderMarshaler().Marshal(forwarder) if err != nil { return trace.Wrap(err) } if configMap.Data == nil { configMap.Data = make(map[string]string) } configMap.Data[forwarder.GetName()] = string(bytes) _, err = c.client.Core().ConfigMaps(defaults.KubeSystemNamespace).Update(configMap) if err != nil { return rigging.ConvertError(err) } return nil } // Delete deletes the specified log forwarder from the k8s config map func (c *logForwardersControl) Delete(name string) error { configMap, err := c.client.Core().ConfigMaps(defaults.KubeSystemNamespace).Get( defaults.LogForwardersConfigMap, metav1.GetOptions{}) if err != nil { return rigging.ConvertError(err) } _, ok := configMap.Data[name] if !ok { return trace.NotFound("log forwarder %q not found", name) } delete(configMap.Data, name) _, err = c.client.Core().ConfigMaps(defaults.KubeSystemNamespace).Update(configMap) if err != nil { return rigging.ConvertError(err) } return nil } // Reload forces log collector to reload forwarder configuration func (c *logForwardersControl) Reload() error { err := c.client.Core().Pods(defaults.KubeSystemNamespace).DeleteCollection(nil, metav1.ListOptions{ LabelSelector: utils.MakeSelector(map[string]string{ "role": "log-collector", }).String(), }) if err != nil { return rigging.ConvertError(err) } return nil }
43,634
https://github.com/pakbkdn/guitardanang/blob/master/resources/views/page/partials/sidebar.blade.php
Github Open Source
Open Source
MIT
2,018
guitardanang
pakbkdn
Blade
Code
78
503
<div class="mega-container visible-lg visible-md"> <div class="navleft-container"> <div class="mega-menu-title"><h3>DANH MỤC SẢN PHẨM <span class="glyphicon glyphicon-list"></span> </h3></div> <div class="mega-menu-category"> <ul class="nav"> @foreach($categories as $category) <li> <a href="{{url('/danh-muc/'.$category->alias)}}">{{$category->name}}</a> </li> @endforeach </ul> </div> </div> </div> <br><br> <div class="fb-page nxpface" data-href="https://www.facebook.com/GuitarDanang189ThaiThiBoi/" data-small-header="false" data-adapt-container-width="true" data-hide-cover="false" data-show-facepile="true"> <blockquote cite="https://www.facebook.com/GuitarDanang189ThaiThiBoi/" class="fb-xfbml-parse-ignore"> <a href="https://www.facebook.com/GuitarDanang189ThaiThiBoi/">Guitar Đà Nẵng</a> </blockquote> </div> <div id="fb-root"></div> <script>(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = 'https://connect.facebook.net/vi_VN/sdk.js#xfbml=1&version=v2.11&appId=222636254944151'; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); </script>
10,929
https://github.com/UniAlteri/statesBundle/blob/master/src/symfony/DependencyInjection/TeknooStatesExtension.php
Github Open Source
Open Source
MIT
null
statesBundle
UniAlteri
PHP
Code
200
566
<?php /** * StatesBundle. * * LICENSE * * This source file is subject to the MIT license and the version 3 of the GPL3 * license that are bundled with this package in the folder licences * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to richarddeloge@gmail.com so we can send you a copy immediately. * * * @copyright Copyright (c) 2009-2017 Richard Déloge (richarddeloge@gmail.com) * * @link http://teknoo.software/states Project website * * @license http://teknoo.software/license/mit MIT License * @author Richard Déloge <richarddeloge@gmail.com> */ namespace Teknoo\Bundle\StatesBundle\DependencyInjection; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\Config\FileLocator; use Symfony\Component\HttpKernel\DependencyInjection\Extension; use Symfony\Component\DependencyInjection\Loader; /** * Class TeknooStatesExtension * This is the class that loads and manages your bundle configuration. * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html} * * * @copyright Copyright (c) 2009-2017 Richard Déloge (richarddeloge@gmail.com) * * @link http://teknoo.software/states Project website * * @license http://teknoo.software/license/mit MIT License * @author Richard Déloge <richarddeloge@gmail.com> */ class TeknooStatesExtension extends Extension { /** * {@inheritdoc} */ public function load(array $configs, ContainerBuilder $container) { $configuration = new Configuration(); $config = $this->processConfiguration($configuration, $configs); $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); if (!empty($config['enable_lifecycable'])) { $loader->load('lifecyclable.yml'); } } }
8,980
https://github.com/franneck94/UdemyCppExt_Template/blob/master/08_OOP/Shapes/distance.hpp
Github Open Source
Open Source
MIT
null
UdemyCppExt_Template
franneck94
C++
Code
19
74
#pragma once #include <cmath> #include <cstdint> double get_distance(const std::uint32_t x1, const std::uint32_t y1, const std::uint32_t x2, const std::uint32_t y2);
36,214
https://github.com/HanweeeeLee/TestModules/blob/master/WebViewToolBar/WebViewToolBar/ViewController.swift
Github Open Source
Open Source
MIT
2,021
TestModules
HanweeeeLee
Swift
Code
55
150
// // ViewController.swift // WebViewToolBar // // Created by hanwe on 2020/12/15. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } @IBAction func action(_ sender: Any) { let vc: WebViewController = WebViewController(nibName: "WebViewController", bundle: nil) self.present(vc, animated: true, completion: nil) } }
32,721
https://github.com/sawyer123456/VUE/blob/master/src/views/swt/index.vue
Github Open Source
Open Source
MIT
null
VUE
sawyer123456
Vue
Code
166
833
<template> <div class="app-container" style="width:500px; margin-left:200px; margin-top:50px;"> <el-form ref="form" :model="form" label-width="180px"> <el-form-item label="联系人编号"> <el-input v-model="form.ctId" minlength="3"/> </el-form-item> <el-form-item label="联系人名"> <el-input v-model="form.ctName"/> </el-form-item> <el-form-item label="联系人性别"> <el-input v-model="form.ctGender"/> </el-form-item> <el-form-item label="联系人电话"> <el-input v-model="form.ctPhone"/> </el-form-item> <el-form-item label="联系人备注"> <el-input v-model="form.ctMemo"/> </el-form-item> <el-form-item label="联系人头衔"> <el-input v-model="form.ctTitle"/> </el-form-item> <el-form-item label="客户编号"> <el-select v-model="form.cusNo" placeholder> <el-option v-for="item in index" :key="item" :label="item.cusNo" :value="item.cusNo"></el-option> </el-select> </el-form-item> <el-form-item> <el-button type="primary" @click="onSubmit">添加</el-button> <el-button @click="onCancel">取消</el-button> </el-form-item> </el-form> </div> </template> <script> import axios from "axios"; import qs from "qs"; export default { data() { return { form: {}, drop: "", index: [] //form 是v-model 的前缀 }; }, mounted() { // 取客户名 axios.get("http://localhost:8080/customer/getCustomerNo").then(res => { this.index = res.data; console.log(this.drop); }); }, methods: { // 提交 onSubmit() { var formData = qs.stringify(this.form); alert(formData); axios.post("http://localhost:8080/contact//addContact", formData); alert("提交成功!"); }, onCancel() {} } }; </script> <!-- <script> import { mapGetters } from 'vuex' export default { name: 'swt', computed: { ...mapGetters([ 'swt' ]) } } </script> <style lang="scss" scoped> .dashboard { &-container { margin: 30px; } &-text { font-size: 30px; line-height: 46px; } } </style> -->
11,816
https://github.com/YiDianerer/mySql-Tool/blob/master/MySqlTool/Class/Tree.cs
Github Open Source
Open Source
Apache-2.0
2,020
mySql-Tool
YiDianerer
C#
Code
251
981
using System; using System.Drawing; using System.Windows.Forms; namespace MySqlTool.Class { public abstract class Tree { public static void Expand(TreeNode treeNode, int level) { treeNode.Expand(); int num = 0; foreach (TreeNode treeNode2 in treeNode.Nodes) { if (++num > level) { break; } treeNode2.Expand(); } } public static void Expand(TreeNode treeNode) { Tree.Expand(treeNode, 2); } public static void CopyTo(TreeView treeView0, TreeView treeView1) { foreach (TreeNode treeNode in treeView0.Nodes) { Tree.CopyTo(treeNode, treeView1); } } public static void CopyTo(TreeNode treeNode, TreeView treeView) { TreeNode treeNode2 = new TreeNode(treeNode.Text, treeNode.ImageIndex, treeNode.SelectedImageIndex); treeNode2.Tag = treeNode.Tag; treeNode2.ForeColor = treeNode.ForeColor; treeView.Nodes.Add(treeNode2); foreach (TreeNode treeNode3 in treeNode.Nodes) { Tree.CopyTo(treeNode3, treeNode2); } } public static void CopyTo(TreeNode treeNode0, TreeNode treeNode1) { TreeNode treeNode2 = new TreeNode(treeNode0.Text, treeNode0.ImageIndex, treeNode0.SelectedImageIndex); treeNode2.Tag = treeNode0.Tag; treeNode2.ForeColor = treeNode0.ForeColor; treeNode1.Nodes.Add(treeNode2); foreach (TreeNode treeNode3 in treeNode0.Nodes) { Tree.CopyTo(treeNode3, treeNode2); } } public static void SetBackColor(TreeView tree, TreeNode treeNode) { foreach (TreeNode treeNode2 in tree.Nodes) { treeNode2.BackColor = Color.White; treeNode2.ForeColor = Color.Black; Tree.SetBackColor(treeNode2); } treeNode.BackColor = Color.RoyalBlue; treeNode.ForeColor = Color.White; } private static void SetBackColor(TreeNode treeNode) { foreach (TreeNode treeNode2 in treeNode.Nodes) { treeNode2.BackColor = Color.White; treeNode2.ForeColor = Color.Black; Tree.SetBackColor(treeNode2); } } public static void SetCheck(TreeNode treeNode) { for (TreeNode parent = treeNode.Parent; parent != null; parent = parent.Parent) { bool flag = treeNode.Checked; if (!flag) { foreach (TreeNode treeNode2 in parent.Nodes) { if (treeNode2.Checked) { flag = true; break; } } } parent.Checked = flag; } Tree.SetSubCheck(treeNode); } private static void SetSubCheck(TreeNode treeNode) { foreach (TreeNode treeNode2 in treeNode.Nodes) { treeNode2.Checked = treeNode.Checked; Tree.SetSubCheck(treeNode2); } } } }
4,740
https://github.com/brigade/dock/blob/master/test/environment/dock_force_destroy.bash
Github Open Source
Open Source
Apache-2.0
2,019
dock
brigade
Shell
Code
106
291
#!/usr/bin/env bats load ../utils setup() { destroy_all_containers original_dir="$(pwd)" cd "$(create_repo my-project)" } teardown() { cd "${original_dir}" } @test "when DOCK_FORCE_DESTROY environment variable specified it destroys already-running container" { file .dock <<-EOF image alpine:latest EOF dock -d nc -l -s 0.0.0.0 -p 5555 run env DOCK_FORCE_DESTROY=1 dock echo [ "$status" -eq 0 ] [[ "$output" =~ "Destroying container" ]] } @test "when DOCK_FORCE_DESTROY environment variable not specified and container already running it fails" { file .dock <<-EOF image alpine:latest EOF dock -d nc -l -s 0.0.0.0 -p 5555 run bash -c "echo | dock echo" [ "$status" -eq 1 ] [[ "$output" =~ "already running" ]] }
30,471
https://github.com/yuaom/LiteGui/blob/master/LiteGui/Control/LGuiWindow.cs
Github Open Source
Open Source
MIT
2,021
LiteGui
yuaom
C#
Code
546
2,134
using System.Collections.Generic; using LiteGui.Graphics; namespace LiteGui.Control { internal static class LGuiWindow { private static readonly Dictionary<int, LGuiWindowContext> WindowList_ = new Dictionary<int, LGuiWindowContext>(); private static readonly List<int> SortedWindowID_ = new List<int>(); private static int CurrentWindow_ = 0; private static int FocusWindow_ = 0; private static int FocusOrder = 1000; internal static void Clear() { WindowList_.Clear(); SortedWindowID_.Clear(); CurrentWindow_ = 0; FocusWindow_ = 0; FocusOrder = 1000; } internal static void Begin() { foreach (var Window in WindowList_) { Window.Value.DrawList.Clear(); } } internal static void End() { LGuiGraphics.SetTargetCommandList(null); SortWindowList(); if (SortedWindowID_.Count > 0) { SortedWindowID_.Sort((Left, Right) => { if (WindowList_[Left].Order < WindowList_[Right].Order) { return -1; } if (WindowList_[Left].Order > WindowList_[Right].Order) { return 1; } return 0; }); LGuiGraphics.SetCurrentLevel(LGuiCommandLevel.Window); foreach (var ID in SortedWindowID_) { LGuiGraphics.AddCommandList(WindowList_[ID].DrawList); } LGuiGraphics.RestoreCurrentLevel(); } } internal static void SortWindowList() { SortedWindowID_.Clear(); foreach (var Window in WindowList_) { if (Window.Value.DrawList.GetCommandCount() > 0) { SortedWindowID_.Add(Window.Key); } } } internal static bool CurrentWindowCanHandleMouseMsg(bool NeedContainerMousePos) { if (CurrentWindow_ == 0) { return true; } for (var Index = SortedWindowID_.Count - 1; Index >= 0; --Index) { var CurrentID = SortedWindowID_[Index]; if (CurrentID == CurrentWindow_) { return !NeedContainerMousePos || LGuiMisc.Contains(ref WindowList_[CurrentID].Rect, ref LGuiContext.IO.MousePos); } if (LGuiMisc.Contains(ref WindowList_[CurrentID].Rect, ref LGuiContext.IO.MousePos)) { return false; } } return true; } internal static bool BeginWindow(string Title, LGuiVec2 Size, LGuiWindowFlags Flags) { return BeginWindow(Title, new LGuiRect(LGuiLayout.GetCurrentLayoutContext().CursorPos, Size), Flags); } internal static bool BeginWindow(string Title, LGuiRect InitRect, LGuiWindowFlags Flags) { if (CurrentWindow_ != 0) { return false; } var ID = LGuiHash.Calculate(Title); if (!WindowList_.ContainsKey(ID)) { WindowList_.Add(ID, new LGuiWindowContext(Title, ID, WindowList_.Count, InitRect, (Flags & LGuiWindowFlags.NoMove) != LGuiWindowFlags.NoMove, (Flags & LGuiWindowFlags.NoFocus) != LGuiWindowFlags.NoFocus)); FocusOrder++; } var Rect = WindowList_[ID].Rect; if (!LGuiMisc.CheckVisible(ref Rect)) { return false; } CurrentWindow_ = ID; if (FocusWindow_ == 0) { FocusWindow_ = CurrentWindow_; WindowList_[FocusWindow_].Order = FocusOrder; } LGuiGraphics.SetTargetCommandList(WindowList_[ID].DrawList); if ((Flags & LGuiWindowFlags.NoTitle) != LGuiWindowFlags.NoTitle) { var TitleRect = new LGuiRect(Rect.Pos, new LGuiVec2(Rect.Width, LGuiContext.Font.FontHeight)); var NoCollapse = ((Flags & LGuiWindowFlags.NoCollapse) == LGuiWindowFlags.NoCollapse); var Expand = LGuiContextCache.GetWindowExpand(Title); var TitleTextOffset = NoCollapse ? 5.0f : 20.0f; if (Expand) { LGuiGraphics.DrawRect(Rect, LGuiStyleColorIndex.Frame, true); } LGuiGraphics.DrawRect(TitleRect, LGuiStyleColorIndex.HeaderActive, true); LGuiGraphics.DrawText(Title, new LGuiVec2(TitleRect.X + TitleTextOffset, TitleRect.Y), LGuiStyleColorIndex.Text); if (!NoCollapse) { if (Expand) { LGuiGraphics.DrawTriangle( new LGuiVec2(TitleRect.X + 5, TitleRect.Top + 5), new LGuiVec2(TitleRect.X + 15, TitleRect.Top + 5), new LGuiVec2(TitleRect.X + 10, TitleRect.Bottom - 5), LGuiStyle.GetColor(LGuiStyleColorIndex.Text), true); } else { LGuiGraphics.DrawTriangle( new LGuiVec2(TitleRect.X + 5, TitleRect.Top + 5), new LGuiVec2(TitleRect.X + 15, TitleRect.CenterY), new LGuiVec2(TitleRect.X + 5, TitleRect.Bottom - 5), LGuiStyle.GetColor(LGuiStyleColorIndex.Text), true); } var ArrowRect = new LGuiRect(TitleRect.X, TitleRect.Y, 20.0f, 20.0f); LGuiMisc.CheckAndSetContextID(ref ArrowRect, ID); if (LGuiMisc.CheckAndSetFocusID(ID)) { Expand = !Expand; LGuiContextCache.SetWindowExpand(Title, Expand); } if (!Expand) { HandleMouseMsg(ref TitleRect); CurrentWindow_ = 0; LGuiGraphics.SetTargetCommandList(null); return false; } } LGuiGraphics.DrawRect(TitleRect, LGuiStyleColorIndex.Border, false); var ContextRect = new LGuiRect(Rect.X, TitleRect.Bottom, Rect.Width, Rect.Height - TitleRect.Height); LGuiFrame.Begin(Title, ContextRect, false); } else { LGuiGraphics.DrawRect(Rect, LGuiStyleColorIndex.Frame, true); LGuiFrame.Begin(Title, Rect, false); } return true; } internal static void EndWindow() { LGuiFrame.End(); LGuiGraphics.SetTargetCommandList(null); if (!CurrentWindowCanHandleMouseMsg(false)) { CurrentWindow_ = 0; return; } HandleMouseMsg(ref WindowList_[CurrentWindow_].Rect); CurrentWindow_ = 0; } private static void HandleMouseMsg(ref LGuiRect Rect) { if (LGuiContext.IO.IsMouseClick(LGuiMouseButtons.Left) && LGuiMisc.Contains(ref Rect, ref LGuiContext.IO.MousePos)) { if (CurrentWindow_ != FocusWindow_ && WindowList_[CurrentWindow_].Focusable) { FocusWindow_ = CurrentWindow_; WindowList_[FocusWindow_].Order = FocusOrder++; SortWindowList(); } WindowList_[CurrentWindow_].MoveOriginPos = Rect.Pos; } if (WindowList_[FocusWindow_].Moveable) { LGuiMisc.CheckAndSetContextID(ref Rect, CurrentWindow_); if (LGuiContext.ActiveID == CurrentWindow_ && LGuiContext.IO.IsMouseDown(LGuiMouseButtons.Left)) { var MoveOriginPos = WindowList_[CurrentWindow_].MoveOriginPos; var MovePos = LGuiContext.IO.GetMouseMovePos(); WindowList_[CurrentWindow_].Rect.Pos = MoveOriginPos + MovePos; } } } } }
2,186
https://github.com/themeteorchef/building-a-nested-comments-feature/blob/master/code/imports/ui/components/Comment/Comment.scss
Github Open Source
Open Source
MIT
2,019
building-a-nested-comments-feature
themeteorchef
SCSS
Code
84
296
@import '../../stylesheets/colors'; .Comment { list-style: none; .deleted { padding: 15px; margin: 0; color: $gray-light; font-style: italic; } } .Comment__author-date { margin: 0 0 15px; padding-bottom: 15px; border-bottom: 1px solid $gray-lighter; .name { margin-right: 7px; } .date { color: $gray-light; font-weight: normal; } } .Comment__comment-frame { border: 1px solid $gray-lighter; border-radius: 3px; } .Comment__comment-body { padding: 15px; > div > *:last-child { margin-bottom: 0; } } .Comment__comment-footer { border-top: 1px solid $gray-lighter; padding: 15px; .comment-reply { float: left; } .comment-delete { float: right; } }
17,758
https://github.com/steinarb/ukelonn/blob/master/ukelonn.web.frontend/src/main/frontend/sagas/modifyuserSaga.js
Github Open Source
Open Source
Apache-2.0
2,020
ukelonn
steinarb
JavaScript
Code
72
258
import { takeLatest, call, put } from 'redux-saga/effects'; import axios from 'axios'; import { MODIFY_USER_REQUEST, MODIFY_USER_RECEIVE, MODIFY_USER_FAILURE, } from '../actiontypes'; // watcher saga export function* requestModifyUserSaga() { yield takeLatest(MODIFY_USER_REQUEST, receiveModifyUserSaga); } function doModifyUser(user) { return axios.post('/ukelonn/api/admin/user/modify', user); } // worker saga function* receiveModifyUserSaga(action) { try { const response = yield call(doModifyUser, action.payload); const users = (response.headers['content-type'] === 'application/json') ? response.data : []; yield put(MODIFY_USER_RECEIVE(users)); } catch (error) { yield put(MODIFY_USER_FAILURE(error)); } }
23,657
https://github.com/coderserdar/CSharpHelperMethods/blob/master/SourceCode/CSharpHelperMethods/YardimciSiniflar/KisiIslemleri.cs
Github Open Source
Open Source
Apache-2.0
2,022
CSharpHelperMethods
coderserdar
C#
Code
423
1,369
using System; using System.Text; using System.Text.RegularExpressions; namespace CSharpHelperMethods.YardimciSiniflar { /// <summary> /// Kişi ile ilişkili yardımcı metotların tamamını içeren sınıf /// </summary> public static class KisiIslemleri { /// <summary> /// Girilen TC Kimlik Numarasının, standart TC Kimlik No algoritmasına uygun olup /// olmadığını kontrol eden metottur. /// </summary> /// <param name="tcKimlikNo">TC Kimlik No</param> /// <returns>TC Kimlik No'nun Uygun Olup Olmadığı Bilgisi</returns> public static bool DogrulaTcKimlikNo(string tcKimlikNo) { var tcNo = Convert.ToInt64(tcKimlikNo); var atcno = tcNo / 100; var btcno = tcNo / 100; var c1 = atcno % 10; atcno /= 10; var c2 = atcno % 10; atcno /= 10; var c3 = atcno % 10; atcno /= 10; var c4 = atcno % 10; atcno /= 10; var c5 = atcno % 10; atcno /= 10; var c6 = atcno % 10; atcno /= 10; var c7 = atcno % 10; atcno /= 10; var c8 = atcno % 10; atcno /= 10; var c9 = atcno % 10; var q1 = (10 - ((c1 + c3 + c5 + c7 + c9) * 3 + c2 + c4 + c6 + c8) % 10) % 10; var q2 = (10 - ((c2 + c4 + c6 + c8 + q1) * 3 + c1 + c3 + c5 + c7 + c9) % 10) % 10; var dogrula = btcno * 100 + q1 * 10 + q2 == tcNo; return dogrula; } /// <summary> /// Girilen IBAN'ın standar IBAN algoritmasına uygun olup olmadığını doğrular /// </summary> /// <code>DogrulaIBAN("TR560006200000012990022604")</code> /// <param name="iban">Uluslar arası banka hesap numarası (IBAN) </param> /// <returns>IBAN uygunsa true, değilse false değeri döner</returns> public static bool DogrulaIBAN(string iban) { iban = iban.ToUpper(); if (string.IsNullOrEmpty(iban)) return false; if (!Regex.IsMatch(iban, "^[A-Z0-9]")) return false; iban = iban.Replace(" ", String.Empty); var bank = iban.Substring(4, iban.Length - 4) + iban.Substring(0, 4); const int asciiShift = 55; var sb = new StringBuilder(); foreach (var c in bank) { sb.Append(char.IsLetter(c) ? c - asciiShift : int.Parse(c.ToString())); } var checkSumString = sb.ToString(); var checksum = int.Parse(checkSumString.Substring(0, 1)); for (var i = 1; i < checkSumString.Length; i++) { var v = int.Parse(checkSumString.Substring(i, 1)); checksum *= 10; checksum += v; checksum %= 97; } return checksum == 1; } /// <summary> /// Ekranlardan girilen bir e-posta adresinin geçerli bir e-posta adresi olup olmadığını /// Kontrol eden metottur /// </summary> /// <param name="ePosta">E-Posta Adresi</param> /// <returns>E-Posta Adresinin Geçerli Olup Olmadığı Bilgisi</returns> public static bool DogrulaEPosta(string ePosta) { const string pattern = @"^(([\w-]+\.)+[\w-]+|([a-zA-Z]{1}|[\w-]{2,}))@" + @"((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\." + @"([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\." + @"([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\." + @"([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|" + @"([a-zA-Z]+[\w-]+\.)+[a-zA-Z]{2,4})$"; return Regex.IsMatch(ePosta, pattern); } } }
20,700
https://github.com/pkudrel/Sabot/blob/master/src/Backup/Program.cs
Github Open Source
Open Source
MIT
null
Sabot
pkudrel
C#
Code
258
956
using System; using System.Data.SqlClient; using System.IO; using System.Linq; using System.Text; using Microsoft.SqlServer.Management.Common; using Microsoft.SqlServer.Management.Smo; namespace Backup { internal class Program { private static void Main(string[] args) { if (args == null || args.Length != 2) { Console.WriteLine("Missing arguments:"); Console.WriteLine( "backup.exe \"server=.;database=test_db;user=sa;password=password\" \"c:\\temp\\script.sql\""); Environment.Exit(1); } Console.WriteLine("Connecting to database"); var serverConnection = new ServerConnection(new SqlConnection(args[0])); var svr = new Server(serverConnection); var database = svr.Databases[svr.ConnectionContext.DatabaseName]; Console.WriteLine("Setting script options"); var scripter1 = new Scripter(svr) { Options = { ScriptSchema = true, ScriptData = true, TargetServerVersion = SqlServerVersion.Version110, Default = true, Indexes = true, ClusteredIndexes = true, FullTextIndexes = true, NonClusteredIndexes = true, DriAll = true, IncludeDatabaseContext = false, NoFileGroup = true, NoTablePartitioningSchemes = true, NoIndexPartitioningSchemes = true } }; var num = 1; scripter1.PrefetchObjects = num != 0; var scripter2 = scripter1; Console.WriteLine("Getting tables"); var list = database.Tables.Cast<Table>().Where(tb => !tb.IsSystemObject).Select(tb => tb.Urn).ToList(); Console.WriteLine("Getting views"); list.AddRange(database.Views.Cast<View>().Where(view => !view.IsSystemObject).Select(view => view.Urn)); Console.WriteLine("Getting stored procedures"); list.AddRange( database.StoredProcedures.Cast<StoredProcedure>().Where(sp => !sp.IsSystemObject).Select(sp => sp.Urn)); Console.WriteLine("Getting indexes"); foreach (Table table in database.Tables) if (!table.Name.Equals("sysdiagrams", StringComparison.CurrentCultureIgnoreCase)) foreach (Index index in table.Indexes) if (index.IndexedColumns.Count > 0) list.Add(index.Urn); else Console.WriteLine("Failed to add index for Table {0}, Index {1}", table.Name, index.Name); Console.WriteLine("Getting foreign keys"); foreach (Table table in database.Tables) if (!table.Name.Equals("sysdiagrams", StringComparison.CurrentCultureIgnoreCase)) foreach (ForeignKey foreignKey in table.ForeignKeys) if (foreignKey.Columns.Count > 0) list.Add(foreignKey.Urn); else Console.WriteLine("Failed to add Foreign Key for Table {0}, Foreign Key {1}", table.Name, foreignKey.Name); Console.WriteLine("Building script"); var stringBuilder = new StringBuilder(); foreach (var str in scripter2.EnumScript(list.ToArray())) { stringBuilder.AppendLine(str); stringBuilder.AppendLine("GO"); } Console.WriteLine("Writing script to disk"); using (var binaryWriter = new BinaryWriter(new FileStream(args[1], FileMode.Create))) { binaryWriter.Write(Encoding.UTF8.GetBytes(stringBuilder.ToString())); binaryWriter.Close(); } serverConnection.Disconnect(); Console.WriteLine("Finished"); } } }
37,132
https://github.com/apache/jena/blob/master/jena-arq/src/main/java/org/apache/jena/sparql/util/IsoMatcher.java
Github Open Source
Open Source
BSD-3-Clause, Apache-2.0
2,023
jena
apache
Java
Code
387
1,012
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.jena.sparql.util ; import static org.apache.jena.atlas.lib.tuple.TupleFactory.tuple ; import java.util.Collection ; import java.util.Iterator ; import java.util.List ; import org.apache.jena.atlas.iterator.Iter; import org.apache.jena.atlas.lib.tuple.Tuple ; import org.apache.jena.graph.Graph ; import org.apache.jena.graph.Node ; import org.apache.jena.graph.Triple ; import org.apache.jena.sparql.core.DatasetGraph ; import org.apache.jena.sparql.core.Quad ; /** * Simple isomorphism testing for on unordered collections. * This code is simple and slow. * For graphs, the Graph isomorphism code in Jena is much better (better tested, better performance) * This code can work on any tuples of nodes. * * See {@link Iso} for isomorphism for ordered lists. * * See {@link IsoAlg} for the isomorphism algorithm. */ public class IsoMatcher { /** Graph isomorphism */ public static boolean isomorphic(Graph g1, Graph g2) { List<Tuple<Node>> x1 = tuplesTriples(g1.find()); List<Tuple<Node>> x2 = tuplesTriples(g2.find()); return isomorphic(x1, x2, NodeUtils.sameRdfTerm); } /** Dataset isomorphism */ public static boolean isomorphic(DatasetGraph dsg1, DatasetGraph dsg2) { List<Tuple<Node>> x1 = tuplesQuads(dsg1.find()); List<Tuple<Node>> x2 = tuplesQuads(dsg2.find()); return isomorphic(x1, x2, NodeUtils.sameRdfTerm); } /** Collection of tuples isomorphism */ public static boolean isomorphic(Collection<Tuple<Node>> x1, Collection<Tuple<Node>> x2) { return isomorphic(x1, x2, NodeUtils.sameRdfTerm); } /** Helper - convert to {@code List<Tuple<Node>>} */ /*package*/ static List<Tuple<Node>> tuplesTriples(Iterator<Triple> iter) { return Iter.iter(iter).map(t->tuple(t.getSubject(), t.getPredicate(), t.getObject())).toList(); } /** Helper - convert to {@code List<Tuple<Node>>} */ public static List<Tuple<Node>> tuplesQuads(Iterator<Quad> iter) { return Iter.iter(iter).map(q->tuple(q.getGraph(), q.getSubject(), q.getPredicate(), q.getObject())).toList(); } /** Collection of tuples isomorphism, with choice of when two nodes are "equal". * See also {@link IsoAlg#isIsomorphic(Collection, Collection, org.apache.jena.sparql.util.Iso.Mappable, EqualityTest)} * for isomorphisms testing for more than just blank nodes. */ public static boolean isomorphic(Collection<Tuple<Node>> x1, Collection<Tuple<Node>> x2, EqualityTest nodeTest) { return IsoAlg.isIsomorphic(x1, x2, nodeTest); } }
37,268
https://github.com/Jonathan1214/myCollege/blob/master/VerilogHDL/chapter2/Ripple_Add.v
Github Open Source
Open Source
MIT
2,020
myCollege
Jonathan1214
Verilog
Code
11
35
module Ripple_Add; FA fa0; FA fa1; FA fa2; FA fa3; endmodule
36,007
https://github.com/MartinDolenc/Programiranje-2-izpit/blob/master/hello/src/hello/SestejBesede.java
Github Open Source
Open Source
MIT
2,018
Programiranje-2-izpit
MartinDolenc
Java
Code
87
341
package hello; import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; public class SestejBesede { // Vržeš txt file v hello folder (project folder) public static void main(String[] args) throws IOException { System.out.println(PrestejBesede("podatki.txt","izhod.txt")); } public static int PrestejBesede(String imeVhod, String imeIzhod) throws IOException{ BufferedReader vhod = new BufferedReader(new FileReader(imeVhod)); PrintWriter izhod = new PrintWriter(new FileWriter(imeIzhod)); int stevilo_besed = 0; while(vhod.ready()){ String vrstica = vhod.readLine().trim(); if(vrstica.equals(""))continue; String[] besede = vrstica.split(" +"); stevilo_besed += besede.length; for(String s : besede){ izhod.println(s); } } vhod.close(); izhod.close(); return stevilo_besed; } }
11,364
https://github.com/LiXiaoRan/Gephi_improved/blob/master/modules/UIComponents/src/main/java/org/gephi/ui/components/richtooltip/JRichTooltipPanel.java
Github Open Source
Open Source
Apache-2.0, CDDL-1.0, GPL-3.0-only, GPL-1.0-or-later, LicenseRef-scancode-unknown-license-reference, LicenseRef-scancode-free-unknown
2,019
Gephi_improved
LiXiaoRan
Java
Code
421
957
/* Copyright 2008-2010 Gephi Authors : Mathieu Bastian <mathieu.bastian@gephi.org> Website : http://www.gephi.org This file is part of Gephi. DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. Copyright 2011 Gephi Consortium. All rights reserved. The contents of this file are subject to the terms of either the GNU General Public License Version 3 only ("GPL") or the Common Development and Distribution License("CDDL") (collectively, the "License"). You may not use this file except in compliance with the License. You can obtain a copy of the License at http://gephi.org/about/legal/license-notice/ or /cddl-1.0.txt and /gpl-3.0.txt. See the License for the specific language governing permissions and limitations under the License. When distributing the software, include this License Header Notice in each file and include the License files at /cddl-1.0.txt and /gpl-3.0.txt. If applicable, add the following below the License Header, with the fields enclosed by brackets [] replaced by your own identifying information: "Portions Copyrighted [year] [name of copyright owner]" If you wish your version of this file to be governed by only the CDDL or only the GPL Version 3, indicate your decision by adding "[Contributor] elects to include this software in this distribution under the [CDDL or GPL Version 3] license." If you do not indicate a single choice of license, a recipient has the option to distribute your version of this file under either the CDDL, the GPL Version 3 or to extend the choice of license to its licensees as provided above. However, if you add GPL Version 3 code and therefore, elected the GPL Version 3 license, then the option applies only if the new code is made subject to such option by the copyright holder. Contributor(s): Portions Copyrighted 2011 Gephi Consortium. */ package org.gephi.ui.components.richtooltip; import javax.swing.JPanel; import javax.swing.UIManager; /** * * @author Mathieu Bastian */ class JRichTooltipPanel extends JPanel { protected RichTooltip tooltipInfo; /** * @see #getUIClassID */ public static final String uiClassID = "RichTooltipPanelUI"; public JRichTooltipPanel(RichTooltip tooltipInfo) { this.tooltipInfo = tooltipInfo; } /* * (non-Javadoc) * * @see javax.swing.JPanel#getUI() */ @Override public RichTooltipPanelUI getUI() { return (RichTooltipPanelUI) ui; } /** * Sets the look and feel (L&amp;F) object that renders this component. * * @param ui * The UI delegate. */ protected void setUI(RichTooltipPanelUI ui) { super.setUI(ui); } /* * (non-Javadoc) * * @see javax.swing.JPanel#getUIClassID() */ @Override public String getUIClassID() { return uiClassID; } /* * (non-Javadoc) * * @see javax.swing.JPanel#updateUI() */ @Override public void updateUI() { if (UIManager.get(getUIClassID()) != null) { setUI((RichTooltipPanelUI) UIManager.getUI(this)); } else { setUI(BasicRichTooltipPanelUI.createUI(this)); } } public RichTooltip getTooltipInfo() { return tooltipInfo; } }
5,536
https://github.com/04116/copa-backend/blob/master/src/api/team/team.repository.ts
Github Open Source
Open Source
Apache-2.0
2,020
copa-backend
04116
TypeScript
Code
76
206
import { EntityRepository, Repository } from "typeorm" import { Team } from "./team.entity" import { Tournament } from "../tournament/tournament.entity" @EntityRepository(Team) export class TeamRepository extends Repository<Team> { async findAll(tournament: Tournament): Promise<Team[]> { // const total = await this.count({ where: { tournament } }) const teams = await this.find({ where: { tournament, }, order: { createdAt: "ASC" } }) return teams } async countTeamDuplicates(tournament: Tournament, name: string) { return this.count({ where: { tournament, name, }, }) } }
21,248
https://github.com/isabella232/accumulo/blob/master/server/monitor/src/main/java/org/apache/accumulo/monitor/servlets/MasterServlet.java
Github Open Source
Open Source
Apache-2.0
2,019
accumulo
isabella232
Java
Code
854
2,984
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.accumulo.monitor.servlets; import java.io.IOException; import java.lang.management.ManagementFactory; import java.text.DateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.accumulo.core.client.impl.Tables; import org.apache.accumulo.core.conf.Property; import org.apache.accumulo.core.master.thrift.DeadServer; import org.apache.accumulo.core.master.thrift.MasterMonitorInfo; import org.apache.accumulo.core.master.thrift.MasterState; import org.apache.accumulo.core.master.thrift.RecoveryStatus; import org.apache.accumulo.core.master.thrift.TabletServerStatus; import org.apache.accumulo.core.util.AddressUtil; import org.apache.accumulo.monitor.Monitor; import org.apache.accumulo.monitor.util.Table; import org.apache.accumulo.monitor.util.TableRow; import org.apache.accumulo.monitor.util.celltypes.DurationType; import org.apache.accumulo.monitor.util.celltypes.NumberType; import org.apache.accumulo.monitor.util.celltypes.PreciseNumberType; import org.apache.accumulo.monitor.util.celltypes.ProgressChartType; import org.apache.accumulo.monitor.util.celltypes.StringType; import org.apache.accumulo.server.monitor.DedupedLogEvent; import org.apache.accumulo.server.monitor.LogService; import org.apache.log4j.Level; import com.google.common.base.Joiner; public class MasterServlet extends BasicServlet { private static final long serialVersionUID = 1L; @Override protected String getTitle(HttpServletRequest req) { List<String> masters = Monitor.getContext().getInstance().getMasterLocations(); return "Master Server" + (masters.size() == 0 ? "" : ":" + AddressUtil.parseAddress(masters.get(0), false).getHost()); } @Override protected void pageBody(HttpServletRequest req, HttpServletResponse response, StringBuilder sb) throws IOException { Map<String,String> tidToNameMap = Tables.getIdToNameMap(Monitor.getContext().getInstance()); doLogEventBanner(sb); TablesServlet.doProblemsBanner(sb); doMasterStatus(req, sb); doRecoveryList(req, sb); TablesServlet.doTableList(req, sb, tidToNameMap); } private void doLogEventBanner(StringBuilder sb) { if (LogService.getInstance().getEvents().size() > 0) { int error = 0, warning = 0, total = 0; for (DedupedLogEvent dev : LogService.getInstance().getEvents()) { switch (dev.getEvent().getLevel().toInt()) { case Level.FATAL_INT: case Level.ERROR_INT: error++; break; case Level.WARN_INT: warning++; break; } total++; } banner(sb, error > 0 ? "error" : "warning", String.format("<a href='/log'>Log Events: %d Error%s, %d Warning%s, %d Total</a>", error, error == 1 ? "" : "s", warning, warning == 1 ? "" : "s", total)); } } private void doMasterStatus(HttpServletRequest req, StringBuilder sb) throws IOException { if (Monitor.getMmi() != null) { String gcStatus = "Waiting"; if (Monitor.getGcStatus() != null) { long start = 0; String label = ""; if (Monitor.getGcStatus().current.started != 0 || Monitor.getGcStatus().currentLog.started != 0) { start = Math.max(Monitor.getGcStatus().current.started, Monitor.getGcStatus().currentLog.started); label = "Running"; } else if (Monitor.getGcStatus().lastLog.finished != 0) { start = Monitor.getGcStatus().lastLog.finished; } if (start != 0) { long diff = System.currentTimeMillis() - start; gcStatus = label + " " + DateFormat.getInstance().format(new Date(start)); gcStatus = gcStatus.replace(" ", "&nbsp;"); long normalDelay = Monitor.getContext().getConfiguration() .getTimeInMillis(Property.GC_CYCLE_DELAY); if (diff > normalDelay * 2) gcStatus = "<span class='warning'>" + gcStatus + "</span>"; } } else { gcStatus = "<span class='error'>Down</span>"; } if (Monitor.getMmi().state != MasterState.NORMAL) { sb.append("<span class='warning'>Master State: " + Monitor.getMmi().state.name() + " Goal: " + Monitor.getMmi().goalState.name() + "</span>\n"); } if (Monitor.getMmi().serversShuttingDown != null && Monitor.getMmi().serversShuttingDown.size() > 0 && Monitor.getMmi().state == MasterState.NORMAL) { sb.append("<span class='warning'>Servers being stopped: " + Joiner.on(", ").join(Monitor.getMmi().serversShuttingDown) + "</span>\n"); } int guessHighLoad = ManagementFactory.getOperatingSystemMXBean().getAvailableProcessors(); List<String> slaves = new ArrayList<>(); for (TabletServerStatus up : Monitor.getMmi().tServerInfo) { slaves.add(up.name); } for (DeadServer down : Monitor.getMmi().deadTabletServers) { slaves.add(down.server); } List<String> masters = Monitor.getContext().getInstance().getMasterLocations(); Table masterStatus = new Table("masterStatus", "Master&nbsp;Status"); masterStatus.addSortableColumn("Master", new StringType<String>(), "The hostname of the master server"); masterStatus.addSortableColumn("#&nbsp;Online<br />Tablet&nbsp;Servers", new PreciseNumberType((int) (slaves.size() * 0.8 + 1.0), slaves.size(), (int) (slaves.size() * 0.6 + 1.0), slaves.size()), "Number of tablet servers currently available"); masterStatus.addSortableColumn("#&nbsp;Total<br />Tablet&nbsp;Servers", new PreciseNumberType(), "The total number of tablet servers configured"); masterStatus.addSortableColumn("Last&nbsp;GC", null, "The last time files were cleaned-up from HDFS."); masterStatus.addSortableColumn("#&nbsp;Tablets", new NumberType<>(0, Integer.MAX_VALUE, 2, Integer.MAX_VALUE), null); masterStatus.addSortableColumn("#&nbsp;Unassigned<br />Tablets", new NumberType<>(0, 0), null); masterStatus.addSortableColumn("Entries", new NumberType<Long>(), "The total number of key/value pairs in Accumulo"); masterStatus.addSortableColumn("Ingest", new NumberType<Long>(), "The number of Key/Value pairs inserted, per second. " + " Note that deleted records are \"inserted\" and will make the ingest " + "rate increase in the near-term."); masterStatus.addSortableColumn("Entries<br />Read", new NumberType<Long>(), "The total number of Key/Value pairs read on the server side. Not" + " all may be returned because of filtering."); masterStatus.addSortableColumn("Entries<br />Returned", new NumberType<Long>(), "The total number of Key/Value pairs returned as a result of scans."); masterStatus.addSortableColumn("Hold&nbsp;Time", new DurationType(0l, 0l), "The maximum amount of time that ingest has been held " + "across all servers due to a lack of memory to store the records"); masterStatus.addSortableColumn("OS&nbsp;Load", new NumberType<>(0., guessHighLoad * 1., 0., guessHighLoad * 3.), "The one-minute load average on the computer that runs the monitor web server."); TableRow row = masterStatus.prepareRow(); row.add(masters.size() == 0 ? "<div class='error'>Down</div>" : AddressUtil.parseAddress(masters.get(0), false).getHost()); row.add(Monitor.getMmi().tServerInfo.size()); row.add(slaves.size()); row.add("<a href='/gc'>" + gcStatus + "</a>"); row.add(Monitor.getTotalTabletCount()); row.add(Monitor.getMmi().unassignedTablets); row.add(Monitor.getTotalEntries()); row.add(Math.round(Monitor.getTotalIngestRate())); row.add(Math.round(Monitor.getTotalScanRate())); row.add(Math.round(Monitor.getTotalQueryRate())); row.add(Monitor.getTotalHoldTime()); row.add(ManagementFactory.getOperatingSystemMXBean().getSystemLoadAverage()); masterStatus.addRow(row); masterStatus.generate(req, sb); } else banner(sb, "error", "Master Server Not Running"); } private void doRecoveryList(HttpServletRequest req, StringBuilder sb) { MasterMonitorInfo mmi = Monitor.getMmi(); if (mmi != null) { Table recoveryTable = new Table("logRecovery", "Log&nbsp;Recovery"); recoveryTable.setSubCaption( "Some tablets were unloaded in an unsafe manner. Write-ahead logs are being recovered."); recoveryTable.addSortableColumn("Server"); recoveryTable.addSortableColumn("Log"); recoveryTable.addSortableColumn("Time", new DurationType(), null); recoveryTable.addSortableColumn("Copy/Sort", new ProgressChartType(), null); int rows = 0; for (TabletServerStatus server : mmi.tServerInfo) { if (server.logSorts != null) { for (RecoveryStatus recovery : server.logSorts) { TableRow row = recoveryTable.prepareRow(); row.add(AddressUtil.parseAddress(server.name, false).getHost()); row.add(recovery.name); row.add((long) recovery.runtime); row.add(recovery.progress); recoveryTable.addRow(row); rows++; } } } if (rows > 0) recoveryTable.generate(req, sb); } } }
41,135
https://github.com/EmmyLua/IntelliJ-EmmyLua/blob/master/src/main/java/com/tang/intellij/lua/debugger/LuaDebuggerEvaluator.kt
Github Open Source
Open Source
Apache-2.0
2,023
IntelliJ-EmmyLua
EmmyLua
Kotlin
Code
299
879
/* * Copyright (c) 2017. tangzx(love.tangzx@qq.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. */ package com.tang.intellij.lua.debugger import com.intellij.openapi.editor.Document import com.intellij.openapi.project.IndexNotReadyException import com.intellij.openapi.project.Project import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiNameIdentifierOwner import com.intellij.psi.util.PsiTreeUtil import com.intellij.xdebugger.XSourcePosition import com.intellij.xdebugger.evaluation.XDebuggerEvaluator import com.tang.intellij.lua.psi.* /** * * Created by tangzx on 2017/5/1. */ abstract class LuaDebuggerEvaluator : XDebuggerEvaluator() { override fun getExpressionRangeAtOffset(project: Project, document: Document, offset: Int, sideEffectsAllowed: Boolean): TextRange? { var currentRange: TextRange? = null PsiDocumentManager.getInstance(project).commitAndRunReadAction { try { val file = PsiDocumentManager.getInstance(project).getPsiFile(document) ?: return@commitAndRunReadAction if (currentRange == null) { val ele = file.findElementAt(offset) if (ele != null && ele.node.elementType == LuaTypes.ID) { val parent = ele.parent when (parent) { is LuaFuncDef, is LuaLocalFuncDef -> currentRange = ele.textRange is LuaClassMethodName, is PsiNameIdentifierOwner -> currentRange = parent.textRange } } } if (currentRange == null) { val expr = PsiTreeUtil.findElementOfClassAtOffset(file, offset, LuaExpr::class.java, false) currentRange = when (expr) { is LuaCallExpr, is LuaClosureExpr, is LuaLiteralExpr -> null else -> expr?.textRange } } } catch (ignored: IndexNotReadyException) { } } return currentRange } override fun evaluate(express: String, xEvaluationCallback: XDebuggerEvaluator.XEvaluationCallback, xSourcePosition: XSourcePosition?) { var expr = express.trim() if (!expr.endsWith(')')) { val lastDot = express.lastIndexOf('.') val lastColon = express.lastIndexOf(':') if (lastColon > lastDot) // a:xx -> a.xx expr = expr.replaceRange(lastColon, lastColon + 1, ".") } eval(expr, xEvaluationCallback, xSourcePosition) } protected abstract fun eval(express: String, xEvaluationCallback: XDebuggerEvaluator.XEvaluationCallback, xSourcePosition: XSourcePosition?) }
17,470