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/sureshsarda/redmart-ticket/blob/master/seeddata.js
|
Github Open Source
|
Open Source
|
MIT
| null |
redmart-ticket
|
sureshsarda
|
JavaScript
|
Code
| 252
| 679
|
/*
* Copyright (C) 2016 Suresh Sarda
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 3, or (at your option) any
* later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; see the file COPYING3. If not see
* <http://www.gnu.org/licenses/>.
*/
exports.USER_LIST = [
{
"name" : "Kalanithi Maran",
"email" : "Kalanithi@gmail.com",
"type" : "CSR"
},
{
"name" : "Kavery Kalanithi",
"email" : "Kavery@gmail.com",
"type" : "CSR"
},
{
"name" : "Naveen Jindal",
"email" : "Naveen@gmail.com.com",
"type" : "CSR"
},
{
"name" : "Kumar Mangalam Birla",
"email" : "Kumar@gmail.com.com",
"type" : "Customer"
},
{
"name" : "Pawan Munjal",
"email" : "Pawan@gmail.com.com",
"type" : "Customer"
},
{
"name" : "Brijmohan Lall Munjal",
"email" : "Brijmohan@gmail.com.com",
"type" : "Customer"
},
{
"name" : "Sunil Kant Munjal",
"email" : "Sunil@gmail.com.com",
"type" : "Customer"
},
{
"name" : "P R Ramasubrahmaneya Rajha",
"email" : "aksahy@gmail.com.com",
"type" : "Customer"
},
{
"name" : "Shinzo Nakanishi",
"email" : "Shinzo@gmail.com.com",
"type" : "Customer"
},
{
"name" : "Murali K Divi",
"email" : "Murali@gmail.com.com",
"type" : "Customer"
}
]
| 2,643
|
https://github.com/fossabot/openvoice/blob/master/config/routes.rb
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,018
|
openvoice
|
fossabot
|
Ruby
|
Code
| 159
| 646
|
Openvoice::Application.routes.draw do
root :to => "user_sessions#new"
match 'login' => 'user_sessions#new', :as => :login
match 'logout' => 'user_sessions#destroy', :as => :logout
match 'signup' => 'users#new', :as => :signup
match 'activate/:activation_code' => 'users#activate', :as => :activate, :activation_code => nil
match 'phone_numbers/get_user' => 'phone_numbers#locate_user'
match 'voicemails/set_transcription' => 'voicemails#set_transcription'
match 'voicemails/recording' => 'voicemails#recording'
match 'voicemails/create' => 'voicemails#create'
match 'users/register_phone' => 'users#register_phone'
match 'incoming_calls/user_menu' => 'incoming_calls#user_menu'
match 'incoming_calls/signal_peer' => 'incoming_calls#signal_peer'
match 'communications/index' => 'communications#index'
match 'communications/handle_incoming_call' => 'communications#handle_incoming_call'
match 'communications/call_screen' => 'communications#call_screen'
match 'contacts/set_name_recording' => 'contacts#set_name_recording'
match 'messagings/create' => 'messagings#create'
match 'messagings/tropo_create' => 'messagings#tropo_create'
resource :user_session
resource :account, :controller => "users"
resources :calls, :only => [:index]
resources :users do
member do
put :suspend
put :unsuspend
delete :purge
end
resources :phone_numbers do
collection do
post :update_attribute_on_the_spot
end
end
resources :voicemails
resources :messagings do
get :autocomplete_contact_name, :on => :collection
end
resources :incoming_calls
resources :outgoing_calls do
get :autocomplete_contact_name, :on => :collection
end
resources :contacts do
collection do
post :update_attribute_on_the_spot
end
end
resources :profiles
resources :fs_profiles
end
end
| 43,978
|
https://github.com/progwml6/JavaCurseAPI/blob/master/src/main/java/com/feed_the_beast/javacurselib/service/contacts/contacts/GroupNotification.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,017
|
JavaCurseAPI
|
progwml6
|
Java
|
Code
| 331
| 1,203
|
package com.feed_the_beast.javacurselib.service.contacts.contacts;
import com.feed_the_beast.javacurselib.common.classes.ExternalCommunityPublicContract;
import com.feed_the_beast.javacurselib.common.classes.GroupMemberContract;
import com.feed_the_beast.javacurselib.common.enums.*;
import com.feed_the_beast.javacurselib.service.groups.groups.GroupMemberSearchRequest;
import com.feed_the_beast.javacurselib.utils.CurseGUID;
import lombok.ToString;
import javax.annotation.Nonnull;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.BiFunction;
/**
* Representation of curse contacts api GroupNotification
*/
@ToString
public class GroupNotification {
public String groupTitle;
public CurseGUID groupID;
public long homeRegionID;
public String homeRegionKey;
public CurseGUID parentGroupID;
public CurseGUID rootGroupID;
public String voiceSessionCode;
public String messageOfTheDay;
public GroupType groupType;
public GroupSubType groupSubtype;
public int displayOrder;
public boolean metaDataOnly;
public boolean allowTemporaryChildGroups;
public boolean forcePushToTalk;
public GroupStatus status;
public boolean isDefaultChannel;
/**
* null when instance is returned from {@code ContacsResponse} or instance if part of {@code GroupChangeNotification}
*
* @see com.feed_the_beast.javacurselib.rest.GroupsWebService.Groups#get(CurseGUID, boolean)
*/
public List<GroupRoleNotification> roles;
public Map<Integer,Set<GroupPermissions>> rolePermissions; // key: roleId, value EnumSet
public GroupMembershipNotification membership; // user's own status in the group
public int memberCount;
public List<GroupEmoticonNotification> emotes; // null in ContactsResponse
/**
* null when instance is part of {@code ContacsResponse} or {@code GroupChangeNotification}
* null when instance is returned by {@link com.feed_the_beast.javacurselib.rest.GroupsWebService.Groups#get(CurseGUID, boolean)}
*
* @see com.feed_the_beast.javacurselib.rest.GroupsWebService.Groups#getMembers(CurseGUID, boolean, int, int)
* @see com.feed_the_beast.javacurselib.rest.GroupsWebService.Groups#searchMembers(CurseGUID, GroupMemberSearchRequest)
*/
public List<GroupMemberContract> members;
public List<ChannelContract> channels;
public GroupMode groupMode;
public boolean isPublic;
public String urlPath;
public String urlHost;
public boolean chatThrottleEnabled;
public int chatThrottleSeconds;
public boolean isStreaming;
public List<ExternalCommunityPublicContract> linkedCommunities; // null in ContactsResponse
public int afkTimerMins;
public long avatarTimestamp;
public boolean flaggedAsInappropriate;
public int membersOnline;
public boolean hideNoAccess;
@Nonnull
public Optional<Integer> getRoleIdbyName(String s) {
for (GroupRoleNotification role: roles) {
if (role.name.equals(s)) {
return Optional.of(role.roleID);
}
}
return Optional.empty();
}
@Nonnull
public Optional<String> getRoleNamebyId(int id) {
for (GroupRoleNotification role: roles) {
if (role.roleID == id) {
return Optional.of(role.name);
}
}
return Optional.empty();
}
@Nonnull
public Optional<String> getChannelNamebyId(CurseGUID id) {
for (ChannelContract c : channels) {
if (c.groupID.equals(id)) {
return Optional.of(c.groupTitle);
}
}
return Optional.empty();
}
@Nonnull
public Optional<CurseGUID> getChannelIdByName(String s) {
return getChannelIdByName(s, String::equals);
}
@Nonnull
public Optional<CurseGUID> getChannelIdByName(String s, BiFunction<String, String, Boolean> function) {
for (ChannelContract c : channels) {
if ( function.apply(c.groupTitle, s)) {
return Optional.of(c.groupID);
}
}
return Optional.empty();
}
}
| 34,967
|
https://github.com/Vin2454/samples/blob/master/AdventureWorks/AdventureWorks.Api.Services/ModelValidators/Sales/AbstractApiSalesTerritoryHistoryRequestModelValidator.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,018
|
samples
|
Vin2454
|
C#
|
Code
| 134
| 600
|
using AdventureWorksNS.Api.Contracts;
using AdventureWorksNS.Api.DataAccess;
using Codenesium.DataConversionExtensions;
using FluentValidation;
using FluentValidation.Results;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace AdventureWorksNS.Api.Services
{
public abstract class AbstractApiSalesTerritoryHistoryRequestModelValidator : AbstractValidator<ApiSalesTerritoryHistoryRequestModel>
{
private int existingRecordId;
private ISalesTerritoryHistoryRepository salesTerritoryHistoryRepository;
public AbstractApiSalesTerritoryHistoryRequestModelValidator(ISalesTerritoryHistoryRepository salesTerritoryHistoryRepository)
{
this.salesTerritoryHistoryRepository = salesTerritoryHistoryRepository;
}
public async Task<ValidationResult> ValidateAsync(ApiSalesTerritoryHistoryRequestModel model, int id)
{
this.existingRecordId = id;
return await this.ValidateAsync(model);
}
public virtual void EndDateRules()
{
}
public virtual void ModifiedDateRules()
{
}
public virtual void RowguidRules()
{
}
public virtual void StartDateRules()
{
}
public virtual void TerritoryIDRules()
{
this.RuleFor(x => x.TerritoryID).MustAsync(this.BeValidSalesTerritoryByTerritoryID).When(x => x?.TerritoryID != null).WithMessage("Invalid reference");
}
private async Task<bool> BeValidSalesPersonByBusinessEntityID(int id, CancellationToken cancellationToken)
{
var record = await this.salesTerritoryHistoryRepository.SalesPersonByBusinessEntityID(id);
return record != null;
}
private async Task<bool> BeValidSalesTerritoryByTerritoryID(int id, CancellationToken cancellationToken)
{
var record = await this.salesTerritoryHistoryRepository.SalesTerritoryByTerritoryID(id);
return record != null;
}
}
}
/*<Codenesium>
<Hash>ce0a713303aab35ad17fba419d37356e</Hash>
</Codenesium>*/
| 5,465
|
https://github.com/IgorAp/TNews/blob/master/tnews/views/index.ejs
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
TNews
|
IgorAp
|
EJS
|
Code
| 239
| 1,589
|
<!DOCTYPE html>
<html lang="pt">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<link rel='stylesheet' href='/stylesheets/style.css' />
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
<title>TNews</title>
</head>
<body>
<%-include('header')%>
<% if(login == false){%>
<div class="container-fluid">
<div class="shadow-sm" style="background-color:rgb(196, 238, 255);margin-top:6em;padding: 2em;border-radius: 0.2em;">
<h2>Bem vindo ao TNews</h2>
<p>Encontre informações relevantes e contribua escrevendo notícias</p>
</div>
</div>
<%}%>
<div class="container" style="<%if(login == true){%>margin-top:6em<%}%>">
<h1 class="text-center">Últimas Notícias</h1>
<div class="row">
<div class="col-md-12">
<button onclick="abrirFeed()" class="btn btn-outline-primary col-md-8 offset-md-2" style="margin-bottom:2em;">Filtrar</button>
</div>
</div>
<div id="feed" class="row">
<% noticias.forEach((noticia)=>{%>
<div class="col-md-6">
<div class="shadow p-3 mb-5 bg-white rounded">
<h5><%=noticia.titulo%></h6>
<a target="_blank" href="/noticia/view/<%=noticia.idnoticia%>">
<img class="img-fluid" style="width: 20em" src="<%=noticia.capa%>" alt="">
</a>
<p style="margin-top:1.5em">Visualizações: <%=noticia.visualizacoes%></p>
</div>
</div>
<%})%>
</div>
<div id="mensagem">
</div>
<button class="btn btn-light col-md-8 offset-md-2" onclick="carregaFeed()">Carregar Notícias</button>
</div>
<%-include noticia/form-avaliar %>
<%-include noticia/feed %>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
<script src="//unpkg.com/jscroll/dist/jquery.jscroll.min.js"></script>
<script>
var x = 0;
var indice = 5;
var podeVotar = "<%=podeVotar%>";
function carregaFeed(){
const http = new XMLHttpRequest();
var dados;
const filtros = {
"categoria":categoria,
"cidade":cidade,
"estado":estado
}
http.onreadystatechange = function(){
dados = JSON.parse(http.responseText||"[]");
dados.forEach(noticia => {
document.getElementById("feed").innerHTML += `
<div class="col-md-6">
<div class="shadow p-3 mb-5 bg-white rounded">
<h5>`+noticia.titulo+`</h6>
<a target="_blank" href="/noticia/view/`+noticia.idnoticia+`">
<img class="img-fluid" style="width: 20em" src="`+noticia.capa+`" alt="">
</a>
<p style="margin-top:1.5em">Visualizações: `+noticia.visualizacoes+`</p>
</div>
</div>
`;
});
if(http.responseText == "[]"){
document.getElementById("mensagem").innerHTML = `
<div class="alert alert-info text-center col-md-8 offset-md-2" role="alert">
Não há notícias para carregar!
</div>
`;
}
}
http.open("POST","/noticia/obter/"+indice,false);
http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
http.send("filtros="+JSON.stringify(filtros));
indice+=5;
}
</script>
</body>
</html>
| 27,409
|
https://github.com/MikeyAlmighty/radio-ui/blob/master/src/components/input/styles.js
|
Github Open Source
|
Open Source
|
MIT
| null |
radio-ui
|
MikeyAlmighty
|
JavaScript
|
Code
| 19
| 51
|
import styled from "styled-components";
import { inputStyles } from "../input-styles";
export const StyledInput = styled.input`
height: 35px;
${inputStyles}
`;
| 8,011
|
https://github.com/AKSoo/datalad/blob/master/datalad/tests/test_strings.py
|
Github Open Source
|
Open Source
|
MIT
| null |
datalad
|
AKSoo
|
Python
|
Code
| 147
| 454
|
# emacs: -*- mode: python; py-indent-offset: 4; tab-width: 4; indent-tabs-mode: nil -*-
# ex: set sts=4 ts=4 sw=4 et:
# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
#
# See COPYING file distributed along with the datalad package for the
# copyright and license terms.
#
# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
from .utils import *
from ..support.strings import apply_replacement_rules
def test_apply_replacement_rules():
# replacement rule should be at least 3 char long
assert_raises(ValueError, apply_replacement_rules, '/', 'some')
assert_raises(ValueError, apply_replacement_rules, ['/a/b', '/'], 'some')
# and pattern should have the separator only twice
assert_raises(ValueError, apply_replacement_rules, '/ab', 'some')
assert_raises(ValueError, apply_replacement_rules, '/a/b/', 'some')
eq_(apply_replacement_rules('/a/b', 'abab'), 'bbbb')
eq_(apply_replacement_rules('/a/', 'abab'), 'bb')
eq_(apply_replacement_rules(['/a/b'], 'abab'), 'bbbb')
eq_(apply_replacement_rules(['/a/b', ',b,ab'], 'abab'), 'abababab')
# with regular expression groups
eq_(apply_replacement_rules(r'/st(.*)n(.*)$/\1-\2', 'string'), 'ri-g')
| 32,640
|
https://github.com/Zweihui/Seraphim/blob/master/app/src/main/java/com/zwh/mvparms/eyepetizer/di/module/VideoListActivityModule.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,020
|
Seraphim
|
Zweihui
|
Java
|
Code
| 54
| 289
|
package com.zwh.mvparms.eyepetizer.di.module;
import com.jess.arms.di.scope.ActivityScope;
import dagger.Module;
import dagger.Provides;
import com.zwh.mvparms.eyepetizer.mvp.contract.VideoListActivityContract;
import com.zwh.mvparms.eyepetizer.mvp.model.VideoListActivityModel;
@Module
public class VideoListActivityModule {
private VideoListActivityContract.View view;
/**
* 构建VideoListActivityModule时,将View的实现类传进来,这样就可以提供View的实现类给presenter
*
* @param view
*/
public VideoListActivityModule(VideoListActivityContract.View view) {
this.view = view;
}
@ActivityScope
@Provides
VideoListActivityContract.View provideVideoListActivityView() {
return this.view;
}
@ActivityScope
@Provides
VideoListActivityContract.Model provideVideoListActivityModel(VideoListActivityModel model) {
return model;
}
}
| 13,130
|
https://github.com/chadmiller/tor/blob/master/src/feature/dircommon/consdiff.c
|
Github Open Source
|
Open Source
|
BSD-2-Clause-NetBSD
| 2,022
|
tor
|
chadmiller
|
C
|
Code
| 6,230
| 15,741
|
/* Copyright (c) 2014, Daniel Martí
* Copyright (c) 2014-2019, The Tor Project, Inc. */
/* See LICENSE for licensing information */
/**
* \file consdiff.c
* \brief Consensus diff implementation, including both the generation and the
* application of diffs in a minimal ed format.
*
* The consensus diff application is done in consdiff_apply_diff, which relies
* on apply_ed_diff for the main ed diff part and on some digest helper
* functions to check the digest hashes found in the consensus diff header.
*
* The consensus diff generation is more complex. consdiff_gen_diff generates
* it, relying on gen_ed_diff to generate the ed diff and some digest helper
* functions to generate the digest hashes.
*
* gen_ed_diff is the tricky bit. In it simplest form, it will take quadratic
* time and linear space to generate an ed diff given two smartlists. As shown
* in its comment section, calling calc_changes on the entire two consensuses
* will calculate what is to be added and what is to be deleted in the diff.
* Its comment section briefly explains how it works.
*
* In our case specific to consensuses, we take advantage of the fact that
* consensuses list routers sorted by their identities. We use that
* information to avoid running calc_changes on the whole smartlists.
* gen_ed_diff will navigate through the two consensuses identity by identity
* and will send small couples of slices to calc_changes, keeping the running
* time near-linear. This is explained in more detail in the gen_ed_diff
* comments.
*
* The allocation strategy tries to save time and memory by avoiding needless
* copies. Instead of actually splitting the inputs into separate strings, we
* allocate cdline_t objects, each of which represents a line in the original
* object or in the output. We use memarea_t allocators to manage the
* temporary memory we use when generating or applying diffs.
**/
#define CONSDIFF_PRIVATE
#include "core/or/or.h"
#include "feature/dircommon/consdiff.h"
#include "lib/memarea/memarea.h"
#include "feature/dirparse/ns_parse.h"
static const char* ns_diff_version = "network-status-diff-version 1";
static const char* hash_token = "hash";
static char *consensus_join_lines(const smartlist_t *inp);
/** Return true iff a and b have the same contents. */
STATIC int
lines_eq(const cdline_t *a, const cdline_t *b)
{
return a->len == b->len && fast_memeq(a->s, b->s, a->len);
}
/** Return true iff a has the same contents as the nul-terminated string b. */
STATIC int
line_str_eq(const cdline_t *a, const char *b)
{
const size_t len = strlen(b);
tor_assert(len <= UINT32_MAX);
cdline_t bline = { b, (uint32_t)len };
return lines_eq(a, &bline);
}
/** Return true iff a begins with the same contents as the nul-terminated
* string b. */
static int
line_starts_with_str(const cdline_t *a, const char *b)
{
const size_t len = strlen(b);
tor_assert(len <= UINT32_MAX);
return a->len >= len && fast_memeq(a->s, b, len);
}
/** Return a new cdline_t holding as its contents the nul-terminated
* string s. Use the provided memory area for storage. */
static cdline_t *
cdline_linecpy(memarea_t *area, const char *s)
{
size_t len = strlen(s);
const char *ss = memarea_memdup(area, s, len);
cdline_t *line = memarea_alloc(area, sizeof(cdline_t));
line->s = ss;
line->len = (uint32_t)len;
return line;
}
/** Add a cdline_t to <b>lst</b> holding as its contents the nul-terminated
* string s. Use the provided memory area for storage. */
STATIC void
smartlist_add_linecpy(smartlist_t *lst, memarea_t *area, const char *s)
{
smartlist_add(lst, cdline_linecpy(area, s));
}
/** Compute the digest of <b>cons</b>, and store the result in
* <b>digest_out</b>. Return 0 on success, -1 on failure. */
/* This is a separate, mockable function so that we can override it when
* fuzzing. */
MOCK_IMPL(STATIC int,
consensus_compute_digest,(const char *cons,
consensus_digest_t *digest_out))
{
int r = crypto_digest256((char*)digest_out->sha3_256,
cons, strlen(cons), DIGEST_SHA3_256);
return r;
}
/** Compute the digest-as-signed of <b>cons</b>, and store the result in
* <b>digest_out</b>. Return 0 on success, -1 on failure. */
/* This is a separate, mockable function so that we can override it when
* fuzzing. */
MOCK_IMPL(STATIC int,
consensus_compute_digest_as_signed,(const char *cons,
consensus_digest_t *digest_out))
{
return router_get_networkstatus_v3_sha3_as_signed(digest_out->sha3_256,
cons);
}
/** Return true iff <b>d1</b> and <b>d2</b> contain the same digest */
/* This is a separate, mockable function so that we can override it when
* fuzzing. */
MOCK_IMPL(STATIC int,
consensus_digest_eq,(const uint8_t *d1,
const uint8_t *d2))
{
return fast_memeq(d1, d2, DIGEST256_LEN);
}
/** Create (allocate) a new slice from a smartlist. Assumes that the start
* and the end indexes are within the bounds of the initial smartlist. The end
* element is not part of the resulting slice. If end is -1, the slice is to
* reach the end of the smartlist.
*/
STATIC smartlist_slice_t *
smartlist_slice(const smartlist_t *list, int start, int end)
{
int list_len = smartlist_len(list);
tor_assert(start >= 0);
tor_assert(start <= list_len);
if (end == -1) {
end = list_len;
}
tor_assert(start <= end);
smartlist_slice_t *slice = tor_malloc(sizeof(smartlist_slice_t));
slice->list = list;
slice->offset = start;
slice->len = end - start;
return slice;
}
/** Helper: Compute the longest common subsequence lengths for the two slices.
* Used as part of the diff generation to find the column at which to split
* slice2 while still having the optimal solution.
* If direction is -1, the navigation is reversed. Otherwise it must be 1.
* The length of the resulting integer array is that of the second slice plus
* one.
*/
STATIC int *
lcs_lengths(const smartlist_slice_t *slice1, const smartlist_slice_t *slice2,
int direction)
{
size_t a_size = sizeof(int) * (slice2->len+1);
/* Resulting lcs lengths. */
int *result = tor_malloc_zero(a_size);
/* Copy of the lcs lengths from the last iteration. */
int *prev = tor_malloc(a_size);
tor_assert(direction == 1 || direction == -1);
int si = slice1->offset;
if (direction == -1) {
si += (slice1->len-1);
}
for (int i = 0; i < slice1->len; ++i, si+=direction) {
const cdline_t *line1 = smartlist_get(slice1->list, si);
/* Store the last results. */
memcpy(prev, result, a_size);
int sj = slice2->offset;
if (direction == -1) {
sj += (slice2->len-1);
}
for (int j = 0; j < slice2->len; ++j, sj+=direction) {
const cdline_t *line2 = smartlist_get(slice2->list, sj);
if (lines_eq(line1, line2)) {
/* If the lines are equal, the lcs is one line longer. */
result[j + 1] = prev[j] + 1;
} else {
/* If not, see what lcs parent path is longer. */
result[j + 1] = MAX(result[j], prev[j + 1]);
}
}
}
tor_free(prev);
return result;
}
/** Helper: Trim any number of lines that are equally at the start or the end
* of both slices.
*/
STATIC void
trim_slices(smartlist_slice_t *slice1, smartlist_slice_t *slice2)
{
while (slice1->len>0 && slice2->len>0) {
const cdline_t *line1 = smartlist_get(slice1->list, slice1->offset);
const cdline_t *line2 = smartlist_get(slice2->list, slice2->offset);
if (!lines_eq(line1, line2)) {
break;
}
slice1->offset++; slice1->len--;
slice2->offset++; slice2->len--;
}
int i1 = (slice1->offset+slice1->len)-1;
int i2 = (slice2->offset+slice2->len)-1;
while (slice1->len>0 && slice2->len>0) {
const cdline_t *line1 = smartlist_get(slice1->list, i1);
const cdline_t *line2 = smartlist_get(slice2->list, i2);
if (!lines_eq(line1, line2)) {
break;
}
i1--;
slice1->len--;
i2--;
slice2->len--;
}
}
/** Like smartlist_string_pos, but uses a cdline_t, and is restricted to the
* bounds of the slice.
*/
STATIC int
smartlist_slice_string_pos(const smartlist_slice_t *slice,
const cdline_t *string)
{
int end = slice->offset + slice->len;
for (int i = slice->offset; i < end; ++i) {
const cdline_t *el = smartlist_get(slice->list, i);
if (lines_eq(el, string)) {
return i;
}
}
return -1;
}
/** Helper: Set all the appropriate changed booleans to true. The first slice
* must be of length 0 or 1. All the lines of slice1 and slice2 which are not
* present in the other slice will be set to changed in their bool array.
* The two changed bool arrays are passed in the same order as the slices.
*/
STATIC void
set_changed(bitarray_t *changed1, bitarray_t *changed2,
const smartlist_slice_t *slice1, const smartlist_slice_t *slice2)
{
int toskip = -1;
tor_assert(slice1->len == 0 || slice1->len == 1);
if (slice1->len == 1) {
const cdline_t *line_common = smartlist_get(slice1->list, slice1->offset);
toskip = smartlist_slice_string_pos(slice2, line_common);
if (toskip == -1) {
bitarray_set(changed1, slice1->offset);
}
}
int end = slice2->offset + slice2->len;
for (int i = slice2->offset; i < end; ++i) {
if (i != toskip) {
bitarray_set(changed2, i);
}
}
}
/*
* Helper: Given that slice1 has been split by half into top and bot, we want
* to fetch the column at which to split slice2 so that we are still on track
* to the optimal diff solution, i.e. the shortest one. We use lcs_lengths
* since the shortest diff is just another way to say the longest common
* subsequence.
*/
static int
optimal_column_to_split(const smartlist_slice_t *top,
const smartlist_slice_t *bot,
const smartlist_slice_t *slice2)
{
int *lens_top = lcs_lengths(top, slice2, 1);
int *lens_bot = lcs_lengths(bot, slice2, -1);
int column=0, max_sum=-1;
for (int i = 0; i < slice2->len+1; ++i) {
int sum = lens_top[i] + lens_bot[slice2->len-i];
if (sum > max_sum) {
column = i;
max_sum = sum;
}
}
tor_free(lens_top);
tor_free(lens_bot);
return column;
}
/**
* Helper: Figure out what elements are new or gone on the second smartlist
* relative to the first smartlist, and store the booleans in the bitarrays.
* True on the first bitarray means the element is gone, true on the second
* bitarray means it's new.
*
* In its base case, either of the smartlists is of length <= 1 and we can
* quickly see what elements are new or are gone. In the other case, we will
* split one smartlist by half and we'll use optimal_column_to_split to find
* the optimal column at which to split the second smartlist so that we are
* finding the smallest diff possible.
*/
STATIC void
calc_changes(smartlist_slice_t *slice1,
smartlist_slice_t *slice2,
bitarray_t *changed1, bitarray_t *changed2)
{
trim_slices(slice1, slice2);
if (slice1->len <= 1) {
set_changed(changed1, changed2, slice1, slice2);
} else if (slice2->len <= 1) {
set_changed(changed2, changed1, slice2, slice1);
/* Keep on splitting the slices in two. */
} else {
smartlist_slice_t *top, *bot, *left, *right;
/* Split the first slice in half. */
int mid = slice1->len/2;
top = smartlist_slice(slice1->list, slice1->offset, slice1->offset+mid);
bot = smartlist_slice(slice1->list, slice1->offset+mid,
slice1->offset+slice1->len);
/* Split the second slice by the optimal column. */
int mid2 = optimal_column_to_split(top, bot, slice2);
left = smartlist_slice(slice2->list, slice2->offset, slice2->offset+mid2);
right = smartlist_slice(slice2->list, slice2->offset+mid2,
slice2->offset+slice2->len);
calc_changes(top, left, changed1, changed2);
calc_changes(bot, right, changed1, changed2);
tor_free(top);
tor_free(bot);
tor_free(left);
tor_free(right);
}
}
/* This table is from crypto.c. The SP and PAD defines are different. */
#define NOT_VALID_BASE64 255
#define X NOT_VALID_BASE64
#define SP NOT_VALID_BASE64
#define PAD NOT_VALID_BASE64
static const uint8_t base64_compare_table[256] = {
X, X, X, X, X, X, X, X, X, SP, SP, SP, X, SP, X, X,
X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
SP, X, X, X, X, X, X, X, X, X, X, 62, X, X, X, 63,
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, X, X, X, PAD, X, X,
X, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, X, X, X, X, X,
X, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, X, X, X, X, X,
X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X,
};
/** Helper: Get the identity hash from a router line, assuming that the line
* at least appears to be a router line and thus starts with "r ".
*
* If an identity hash is found, store it (without decoding it) in
* <b>hash_out</b>, and return 0. On failure, return -1.
*/
STATIC int
get_id_hash(const cdline_t *line, cdline_t *hash_out)
{
if (line->len < 2)
return -1;
/* Skip the router name. */
const char *hash = memchr(line->s + 2, ' ', line->len - 2);
if (!hash) {
return -1;
}
hash++;
const char *hash_end = hash;
/* Stop when the first non-base64 character is found. Use unsigned chars to
* avoid negative indexes causing crashes.
*/
while (base64_compare_table[*((unsigned char*)hash_end)]
!= NOT_VALID_BASE64 &&
hash_end < line->s + line->len) {
hash_end++;
}
/* Empty hash. */
if (hash_end == hash) {
return -1;
}
hash_out->s = hash;
/* Always true because lines are limited to this length */
tor_assert(hash_end >= hash);
tor_assert((size_t)(hash_end - hash) <= UINT32_MAX);
hash_out->len = (uint32_t)(hash_end - hash);
return 0;
}
/** Helper: Check that a line is a valid router entry. We must at least be
* able to fetch a proper identity hash from it for it to be valid.
*/
STATIC int
is_valid_router_entry(const cdline_t *line)
{
if (line->len < 2 || fast_memneq(line->s, "r ", 2))
return 0;
cdline_t tmp;
return (get_id_hash(line, &tmp) == 0);
}
/** Helper: Find the next router line starting at the current position.
* Assumes that cur is lower than the length of the smartlist, i.e. it is a
* line within the bounds of the consensus. The only exception is when we
* don't want to skip the first line, in which case cur will be -1.
*/
STATIC int
next_router(const smartlist_t *cons, int cur)
{
int len = smartlist_len(cons);
tor_assert(cur >= -1 && cur < len);
if (++cur >= len) {
return len;
}
const cdline_t *line = smartlist_get(cons, cur);
while (!is_valid_router_entry(line)) {
if (++cur >= len) {
return len;
}
line = smartlist_get(cons, cur);
}
return cur;
}
/** Helper: compare two base64-encoded identity hashes, which may be of
* different lengths. Comparison ends when the first non-base64 char is found.
*/
STATIC int
base64cmp(const cdline_t *hash1, const cdline_t *hash2)
{
/* NULL is always lower, useful for last_hash which starts at NULL. */
if (!hash1->s && !hash2->s) {
return 0;
}
if (!hash1->s) {
return -1;
}
if (!hash2->s) {
return 1;
}
/* Don't index with a char; char may be signed. */
const unsigned char *a = (unsigned char*)hash1->s;
const unsigned char *b = (unsigned char*)hash2->s;
const unsigned char *a_end = a + hash1->len;
const unsigned char *b_end = b + hash2->len;
while (1) {
uint8_t av = base64_compare_table[*a];
uint8_t bv = base64_compare_table[*b];
if (av == NOT_VALID_BASE64) {
if (bv == NOT_VALID_BASE64) {
/* Both ended with exactly the same characters. */
return 0;
} else {
/* hash2 goes on longer than hash1 and thus hash1 is lower. */
return -1;
}
} else if (bv == NOT_VALID_BASE64) {
/* hash1 goes on longer than hash2 and thus hash1 is greater. */
return 1;
} else if (av < bv) {
/* The first difference shows that hash1 is lower. */
return -1;
} else if (av > bv) {
/* The first difference shows that hash1 is greater. */
return 1;
} else {
a++;
b++;
if (a == a_end) {
if (b == b_end) {
return 0;
} else {
return -1;
}
} else if (b == b_end) {
return 1;
}
}
}
}
/** Structure used to remember the previous and current identity hash of
* the "r " lines in a consensus, to enforce well-ordering. */
typedef struct router_id_iterator_t {
cdline_t last_hash;
cdline_t hash;
} router_id_iterator_t;
/**
* Initializer for a router_id_iterator_t.
*/
#define ROUTER_ID_ITERATOR_INIT { { NULL, 0 }, { NULL, 0 } }
/** Given an index *<b>idxp</b> into the consensus at <b>cons</b>, advance
* the index to the next router line ("r ...") in the consensus, or to
* an index one after the end of the list if there is no such line.
*
* Use <b>iter</b> to record the hash of the found router line, if any,
* and to enforce ordering on the hashes. If the hashes are mis-ordered,
* return -1. Else, return 0.
**/
static int
find_next_router_line(const smartlist_t *cons,
const char *consname,
int *idxp,
router_id_iterator_t *iter)
{
*idxp = next_router(cons, *idxp);
if (*idxp < smartlist_len(cons)) {
memcpy(&iter->last_hash, &iter->hash, sizeof(cdline_t));
if (get_id_hash(smartlist_get(cons, *idxp), &iter->hash) < 0 ||
base64cmp(&iter->hash, &iter->last_hash) <= 0) {
log_warn(LD_CONSDIFF, "Refusing to generate consensus diff because "
"the %s consensus doesn't have its router entries sorted "
"properly.", consname);
return -1;
}
}
return 0;
}
/** Line-prefix indicating the beginning of the signatures section that we
* intend to delete. */
#define START_OF_SIGNATURES_SECTION "directory-signature "
/** Pre-process a consensus in <b>cons</b> (represented as a list of cdline_t)
* to remove the signatures from it. If the footer is removed, return a
* cdline_t containing a delete command to delete the footer, allocated in
* <b>area</>. If no footer is removed, return NULL.
*
* We remove the signatures here because they are not themselves signed, and
* as such there might be different encodings for them.
*/
static cdline_t *
preprocess_consensus(memarea_t *area,
smartlist_t *cons)
{
int idx;
int dirsig_idx = -1;
for (idx = 0; idx < smartlist_len(cons); ++idx) {
cdline_t *line = smartlist_get(cons, idx);
if (line_starts_with_str(line, START_OF_SIGNATURES_SECTION)) {
dirsig_idx = idx;
break;
}
}
if (dirsig_idx >= 0) {
char buf[64];
while (smartlist_len(cons) > dirsig_idx)
smartlist_del(cons, dirsig_idx);
tor_snprintf(buf, sizeof(buf), "%d,$d", dirsig_idx+1);
return cdline_linecpy(area, buf);
} else {
return NULL;
}
}
/** Generate an ed diff as a smartlist from two consensuses, also given as
* smartlists. Will return NULL if the diff could not be generated, which can
* happen if any lines the script had to add matched "." or if the routers
* were not properly ordered.
*
* All cdline_t objects in the resulting object are either references to lines
* in one of the inputs, or are newly allocated lines in the provided memarea.
*
* This implementation is consensus-specific. To generate an ed diff for any
* given input in quadratic time, you can replace all the code until the
* navigation in reverse order with the following:
*
* int len1 = smartlist_len(cons1);
* int len2 = smartlist_len(cons2);
* bitarray_t *changed1 = bitarray_init_zero(len1);
* bitarray_t *changed2 = bitarray_init_zero(len2);
* cons1_sl = smartlist_slice(cons1, 0, -1);
* cons2_sl = smartlist_slice(cons2, 0, -1);
* calc_changes(cons1_sl, cons2_sl, changed1, changed2);
*/
STATIC smartlist_t *
gen_ed_diff(const smartlist_t *cons1_orig, const smartlist_t *cons2,
memarea_t *area)
{
smartlist_t *cons1 = smartlist_new();
smartlist_add_all(cons1, cons1_orig);
cdline_t *remove_trailer = preprocess_consensus(area, cons1);
int len1 = smartlist_len(cons1);
int len2 = smartlist_len(cons2);
smartlist_t *result = smartlist_new();
if (remove_trailer) {
/* There's a delete-the-trailer line at the end, so add it here. */
smartlist_add(result, remove_trailer);
}
/* Initialize the changed bitarrays to zero, so that calc_changes only needs
* to set the ones that matter and leave the rest untouched.
*/
bitarray_t *changed1 = bitarray_init_zero(len1);
bitarray_t *changed2 = bitarray_init_zero(len2);
int i1=-1, i2=-1;
int start1=0, start2=0;
/* To check that hashes are ordered properly */
router_id_iterator_t iter1 = ROUTER_ID_ITERATOR_INIT;
router_id_iterator_t iter2 = ROUTER_ID_ITERATOR_INIT;
/* i1 and i2 are initialized at the first line of each consensus. They never
* reach past len1 and len2 respectively, since next_router doesn't let that
* happen. i1 and i2 are advanced by at least one line at each iteration as
* long as they have not yet reached len1 and len2, so the loop is
* guaranteed to end, and each pair of (i1,i2) will be inspected at most
* once.
*/
while (i1 < len1 || i2 < len2) {
/* Advance each of the two navigation positions by one router entry if not
* yet at the end.
*/
if (i1 < len1) {
if (find_next_router_line(cons1, "base", &i1, &iter1) < 0) {
goto error_cleanup;
}
}
if (i2 < len2) {
if (find_next_router_line(cons2, "target", &i2, &iter2) < 0) {
goto error_cleanup;
}
}
/* If we have reached the end of both consensuses, there is no need to
* compare hashes anymore, since this is the last iteration.
*/
if (i1 < len1 || i2 < len2) {
/* Keep on advancing the lower (by identity hash sorting) position until
* we have two matching positions. The only other possible outcome is
* that a lower position reaches the end of the consensus before it can
* reach a hash that is no longer the lower one. Since there will always
* be a lower hash for as long as the loop runs, one of the two indexes
* will always be incremented, thus assuring that the loop must end
* after a finite number of iterations. If that cannot be because said
* consensus has already reached the end, both are extended to their
* respecting ends since we are done.
*/
int cmp = base64cmp(&iter1.hash, &iter2.hash);
while (cmp != 0) {
if (i1 < len1 && cmp < 0) {
if (find_next_router_line(cons1, "base", &i1, &iter1) < 0) {
goto error_cleanup;
}
if (i1 == len1) {
/* We finished the first consensus, so grab all the remaining
* lines of the second consensus and finish up.
*/
i2 = len2;
break;
}
} else if (i2 < len2 && cmp > 0) {
if (find_next_router_line(cons2, "target", &i2, &iter2) < 0) {
goto error_cleanup;
}
if (i2 == len2) {
/* We finished the second consensus, so grab all the remaining
* lines of the first consensus and finish up.
*/
i1 = len1;
break;
}
} else {
i1 = len1;
i2 = len2;
break;
}
cmp = base64cmp(&iter1.hash, &iter2.hash);
}
}
/* Make slices out of these chunks (up to the common router entry) and
* calculate the changes for them.
* Error if any of the two slices are longer than 10K lines. That should
* never happen with any pair of real consensuses. Feeding more than 10K
* lines to calc_changes would be very slow anyway.
*/
#define MAX_LINE_COUNT (10000)
if (i1-start1 > MAX_LINE_COUNT || i2-start2 > MAX_LINE_COUNT) {
log_warn(LD_CONSDIFF, "Refusing to generate consensus diff because "
"we found too few common router ids.");
goto error_cleanup;
}
smartlist_slice_t *cons1_sl = smartlist_slice(cons1, start1, i1);
smartlist_slice_t *cons2_sl = smartlist_slice(cons2, start2, i2);
calc_changes(cons1_sl, cons2_sl, changed1, changed2);
tor_free(cons1_sl);
tor_free(cons2_sl);
start1 = i1, start2 = i2;
}
/* Navigate the changes in reverse order and generate one ed command for
* each chunk of changes.
*/
i1=len1-1, i2=len2-1;
char buf[128];
while (i1 >= 0 || i2 >= 0) {
int start1x, start2x, end1, end2, added, deleted;
/* We are at a point were no changed bools are true, so just keep going. */
if (!(i1 >= 0 && bitarray_is_set(changed1, i1)) &&
!(i2 >= 0 && bitarray_is_set(changed2, i2))) {
if (i1 >= 0) {
i1--;
}
if (i2 >= 0) {
i2--;
}
continue;
}
end1 = i1, end2 = i2;
/* Grab all contiguous changed lines */
while (i1 >= 0 && bitarray_is_set(changed1, i1)) {
i1--;
}
while (i2 >= 0 && bitarray_is_set(changed2, i2)) {
i2--;
}
start1x = i1+1, start2x = i2+1;
added = end2-i2, deleted = end1-i1;
if (added == 0) {
if (deleted == 1) {
tor_snprintf(buf, sizeof(buf), "%id", start1x+1);
smartlist_add_linecpy(result, area, buf);
} else {
tor_snprintf(buf, sizeof(buf), "%i,%id", start1x+1, start1x+deleted);
smartlist_add_linecpy(result, area, buf);
}
} else {
int i;
if (deleted == 0) {
tor_snprintf(buf, sizeof(buf), "%ia", start1x);
smartlist_add_linecpy(result, area, buf);
} else if (deleted == 1) {
tor_snprintf(buf, sizeof(buf), "%ic", start1x+1);
smartlist_add_linecpy(result, area, buf);
} else {
tor_snprintf(buf, sizeof(buf), "%i,%ic", start1x+1, start1x+deleted);
smartlist_add_linecpy(result, area, buf);
}
for (i = start2x; i <= end2; ++i) {
cdline_t *line = smartlist_get(cons2, i);
if (line_str_eq(line, ".")) {
log_warn(LD_CONSDIFF, "Cannot generate consensus diff because "
"one of the lines to be added is \".\".");
goto error_cleanup;
}
smartlist_add(result, line);
}
smartlist_add_linecpy(result, area, ".");
}
}
smartlist_free(cons1);
bitarray_free(changed1);
bitarray_free(changed2);
return result;
error_cleanup:
smartlist_free(cons1);
bitarray_free(changed1);
bitarray_free(changed2);
smartlist_free(result);
return NULL;
}
/* Helper: Read a base-10 number between 0 and INT32_MAX from <b>s</b> and
* store it in <b>num_out</b>. Advance <b>s</b> to the characer immediately
* after the number. Return 0 on success, -1 on failure. */
static int
get_linenum(const char **s, int *num_out)
{
int ok;
char *next;
if (!TOR_ISDIGIT(**s)) {
return -1;
}
*num_out = (int) tor_parse_long(*s, 10, 0, INT32_MAX, &ok, &next);
if (ok && next) {
*s = next;
return 0;
} else {
return -1;
}
}
/** Apply the ed diff, starting at <b>diff_starting_line</b>, to the consensus
* and return a new consensus, also as a line-based smartlist. Will return
* NULL if the ed diff is not properly formatted.
*
* All cdline_t objects in the resulting object are references to lines
* in one of the inputs; nothing is copied.
*/
STATIC smartlist_t *
apply_ed_diff(const smartlist_t *cons1, const smartlist_t *diff,
int diff_starting_line)
{
int diff_len = smartlist_len(diff);
int j = smartlist_len(cons1);
smartlist_t *cons2 = smartlist_new();
for (int i=diff_starting_line; i<diff_len; ++i) {
const cdline_t *diff_cdline = smartlist_get(diff, i);
char diff_line[128];
if (diff_cdline->len > sizeof(diff_line) - 1) {
log_warn(LD_CONSDIFF, "Could not apply consensus diff because "
"an ed command was far too long");
goto error_cleanup;
}
/* Copy the line to make it nul-terminated. */
memcpy(diff_line, diff_cdline->s, diff_cdline->len);
diff_line[diff_cdline->len] = 0;
const char *ptr = diff_line;
int start = 0, end = 0;
int had_range = 0;
int end_was_eof = 0;
if (get_linenum(&ptr, &start) < 0) {
log_warn(LD_CONSDIFF, "Could not apply consensus diff because "
"an ed command was missing a line number.");
goto error_cleanup;
}
if (*ptr == ',') {
/* Two-item range */
had_range = 1;
++ptr;
if (*ptr == '$') {
end_was_eof = 1;
end = smartlist_len(cons1);
++ptr;
} else if (get_linenum(&ptr, &end) < 0) {
log_warn(LD_CONSDIFF, "Could not apply consensus diff because "
"an ed command was missing a range end line number.");
goto error_cleanup;
}
/* Incoherent range. */
if (end <= start) {
log_warn(LD_CONSDIFF, "Could not apply consensus diff because "
"an invalid range was found in an ed command.");
goto error_cleanup;
}
} else {
/* We'll take <n1> as <n1>,<n1> for simplicity. */
end = start;
}
if (end > j) {
log_warn(LD_CONSDIFF, "Could not apply consensus diff because "
"its commands are not properly sorted in reverse order.");
goto error_cleanup;
}
if (*ptr == '\0') {
log_warn(LD_CONSDIFF, "Could not apply consensus diff because "
"a line with no ed command was found");
goto error_cleanup;
}
if (*(ptr+1) != '\0') {
log_warn(LD_CONSDIFF, "Could not apply consensus diff because "
"an ed command longer than one char was found.");
goto error_cleanup;
}
char action = *ptr;
switch (action) {
case 'a':
case 'c':
case 'd':
break;
default:
log_warn(LD_CONSDIFF, "Could not apply consensus diff because "
"an unrecognised ed command was found.");
goto error_cleanup;
}
/** $ is not allowed with non-d actions. */
if (end_was_eof && action != 'd') {
log_warn(LD_CONSDIFF, "Could not apply consensus diff because "
"it wanted to use $ with a command other than delete");
goto error_cleanup;
}
/* 'a' commands are not allowed to have ranges. */
if (had_range && action == 'a') {
log_warn(LD_CONSDIFF, "Could not apply consensus diff because "
"it wanted to add lines after a range.");
goto error_cleanup;
}
/* Add unchanged lines. */
for (; j && j > end; --j) {
cdline_t *cons_line = smartlist_get(cons1, j-1);
smartlist_add(cons2, cons_line);
}
/* Ignore removed lines. */
if (action == 'c' || action == 'd') {
while (--j >= start) {
/* Skip line */
}
}
/* Add new lines in reverse order, since it will all be reversed at the
* end.
*/
if (action == 'a' || action == 'c') {
int added_end = i;
i++; /* Skip the line with the range and command. */
while (i < diff_len) {
if (line_str_eq(smartlist_get(diff, i), ".")) {
break;
}
if (++i == diff_len) {
log_warn(LD_CONSDIFF, "Could not apply consensus diff because "
"it has lines to be inserted that don't end with a \".\".");
goto error_cleanup;
}
}
int added_i = i-1;
/* It would make no sense to add zero new lines. */
if (added_i == added_end) {
log_warn(LD_CONSDIFF, "Could not apply consensus diff because "
"it has an ed command that tries to insert zero lines.");
goto error_cleanup;
}
while (added_i > added_end) {
cdline_t *added_line = smartlist_get(diff, added_i--);
smartlist_add(cons2, added_line);
}
}
}
/* Add remaining unchanged lines. */
for (; j > 0; --j) {
cdline_t *cons_line = smartlist_get(cons1, j-1);
smartlist_add(cons2, cons_line);
}
/* Reverse the whole thing since we did it from the end. */
smartlist_reverse(cons2);
return cons2;
error_cleanup:
smartlist_free(cons2);
return NULL;
}
/** Generate a consensus diff as a smartlist from two given consensuses, also
* as smartlists. Will return NULL if the consensus diff could not be
* generated. Neither of the two consensuses are modified in any way, so it's
* up to the caller to free their resources.
*/
smartlist_t *
consdiff_gen_diff(const smartlist_t *cons1,
const smartlist_t *cons2,
const consensus_digest_t *digests1,
const consensus_digest_t *digests2,
memarea_t *area)
{
smartlist_t *ed_diff = gen_ed_diff(cons1, cons2, area);
/* ed diff could not be generated - reason already logged by gen_ed_diff. */
if (!ed_diff) {
goto error_cleanup;
}
/* See that the script actually produces what we want. */
smartlist_t *ed_cons2 = apply_ed_diff(cons1, ed_diff, 0);
if (!ed_cons2) {
/* LCOV_EXCL_START -- impossible if diff generation is correct */
log_warn(LD_BUG|LD_CONSDIFF, "Refusing to generate consensus diff because "
"the generated ed diff could not be tested to successfully generate "
"the target consensus.");
goto error_cleanup;
/* LCOV_EXCL_STOP */
}
int cons2_eq = 1;
if (smartlist_len(cons2) == smartlist_len(ed_cons2)) {
SMARTLIST_FOREACH_BEGIN(cons2, const cdline_t *, line1) {
const cdline_t *line2 = smartlist_get(ed_cons2, line1_sl_idx);
if (! lines_eq(line1, line2) ) {
cons2_eq = 0;
break;
}
} SMARTLIST_FOREACH_END(line1);
} else {
cons2_eq = 0;
}
smartlist_free(ed_cons2);
if (!cons2_eq) {
/* LCOV_EXCL_START -- impossible if diff generation is correct. */
log_warn(LD_BUG|LD_CONSDIFF, "Refusing to generate consensus diff because "
"the generated ed diff did not generate the target consensus "
"successfully when tested.");
goto error_cleanup;
/* LCOV_EXCL_STOP */
}
char cons1_hash_hex[HEX_DIGEST256_LEN+1];
char cons2_hash_hex[HEX_DIGEST256_LEN+1];
base16_encode(cons1_hash_hex, HEX_DIGEST256_LEN+1,
(const char*)digests1->sha3_256, DIGEST256_LEN);
base16_encode(cons2_hash_hex, HEX_DIGEST256_LEN+1,
(const char*)digests2->sha3_256, DIGEST256_LEN);
/* Create the resulting consensus diff. */
char buf[160];
smartlist_t *result = smartlist_new();
tor_snprintf(buf, sizeof(buf), "%s", ns_diff_version);
smartlist_add_linecpy(result, area, buf);
tor_snprintf(buf, sizeof(buf), "%s %s %s", hash_token,
cons1_hash_hex, cons2_hash_hex);
smartlist_add_linecpy(result, area, buf);
smartlist_add_all(result, ed_diff);
smartlist_free(ed_diff);
return result;
error_cleanup:
if (ed_diff) {
/* LCOV_EXCL_START -- ed_diff is NULL except in unreachable cases above */
smartlist_free(ed_diff);
/* LCOV_EXCL_STOP */
}
return NULL;
}
/** Fetch the digest of the base consensus in the consensus diff, encoded in
* base16 as found in the diff itself. digest1_out and digest2_out must be of
* length DIGEST256_LEN or larger if not NULL.
*/
int
consdiff_get_digests(const smartlist_t *diff,
char *digest1_out,
char *digest2_out)
{
smartlist_t *hash_words = NULL;
const cdline_t *format;
char cons1_hash[DIGEST256_LEN], cons2_hash[DIGEST256_LEN];
char *cons1_hash_hex, *cons2_hash_hex;
if (smartlist_len(diff) < 2) {
log_info(LD_CONSDIFF, "The provided consensus diff is too short.");
goto error_cleanup;
}
/* Check that it's the format and version we know. */
format = smartlist_get(diff, 0);
if (!line_str_eq(format, ns_diff_version)) {
log_warn(LD_CONSDIFF, "The provided consensus diff format is not known.");
goto error_cleanup;
}
/* Grab the base16 digests. */
hash_words = smartlist_new();
{
const cdline_t *line2 = smartlist_get(diff, 1);
char *h = tor_memdup_nulterm(line2->s, line2->len);
smartlist_split_string(hash_words, h, " ", 0, 0);
tor_free(h);
}
/* There have to be three words, the first of which must be hash_token. */
if (smartlist_len(hash_words) != 3 ||
strcmp(smartlist_get(hash_words, 0), hash_token)) {
log_info(LD_CONSDIFF, "The provided consensus diff does not include "
"the necessary digests.");
goto error_cleanup;
}
/* Expected hashes as found in the consensus diff header. They must be of
* length HEX_DIGEST256_LEN, normally 64 hexadecimal characters.
* If any of the decodings fail, error to make sure that the hashes are
* proper base16-encoded digests.
*/
cons1_hash_hex = smartlist_get(hash_words, 1);
cons2_hash_hex = smartlist_get(hash_words, 2);
if (strlen(cons1_hash_hex) != HEX_DIGEST256_LEN ||
strlen(cons2_hash_hex) != HEX_DIGEST256_LEN) {
log_info(LD_CONSDIFF, "The provided consensus diff includes "
"base16-encoded digests of incorrect size.");
goto error_cleanup;
}
if (base16_decode(cons1_hash, DIGEST256_LEN,
cons1_hash_hex, HEX_DIGEST256_LEN) != DIGEST256_LEN ||
base16_decode(cons2_hash, DIGEST256_LEN,
cons2_hash_hex, HEX_DIGEST256_LEN) != DIGEST256_LEN) {
log_info(LD_CONSDIFF, "The provided consensus diff includes "
"malformed digests.");
goto error_cleanup;
}
if (digest1_out) {
memcpy(digest1_out, cons1_hash, DIGEST256_LEN);
}
if (digest2_out) {
memcpy(digest2_out, cons2_hash, DIGEST256_LEN);
}
SMARTLIST_FOREACH(hash_words, char *, cp, tor_free(cp));
smartlist_free(hash_words);
return 0;
error_cleanup:
if (hash_words) {
SMARTLIST_FOREACH(hash_words, char *, cp, tor_free(cp));
smartlist_free(hash_words);
}
return 1;
}
/** Apply the consensus diff to the given consensus and return a new
* consensus, also as a line-based smartlist. Will return NULL if the diff
* could not be applied. Neither the consensus nor the diff are modified in
* any way, so it's up to the caller to free their resources.
*/
char *
consdiff_apply_diff(const smartlist_t *cons1,
const smartlist_t *diff,
const consensus_digest_t *digests1)
{
smartlist_t *cons2 = NULL;
char *cons2_str = NULL;
char e_cons1_hash[DIGEST256_LEN];
char e_cons2_hash[DIGEST256_LEN];
if (consdiff_get_digests(diff, e_cons1_hash, e_cons2_hash) != 0) {
goto error_cleanup;
}
/* See that the consensus that was given to us matches its hash. */
if (!consensus_digest_eq(digests1->sha3_256,
(const uint8_t*)e_cons1_hash)) {
char hex_digest1[HEX_DIGEST256_LEN+1];
char e_hex_digest1[HEX_DIGEST256_LEN+1];
log_warn(LD_CONSDIFF, "Refusing to apply consensus diff because "
"the base consensus doesn't match the digest as found in "
"the consensus diff header.");
base16_encode(hex_digest1, HEX_DIGEST256_LEN+1,
(const char *)digests1->sha3_256, DIGEST256_LEN);
base16_encode(e_hex_digest1, HEX_DIGEST256_LEN+1,
e_cons1_hash, DIGEST256_LEN);
log_warn(LD_CONSDIFF, "Expected: %s; found: %s",
hex_digest1, e_hex_digest1);
goto error_cleanup;
}
/* Grab the ed diff and calculate the resulting consensus. */
/* Skip the first two lines. */
cons2 = apply_ed_diff(cons1, diff, 2);
/* ed diff could not be applied - reason already logged by apply_ed_diff. */
if (!cons2) {
goto error_cleanup;
}
cons2_str = consensus_join_lines(cons2);
consensus_digest_t cons2_digests;
if (consensus_compute_digest(cons2_str, &cons2_digests) < 0) {
/* LCOV_EXCL_START -- digest can't fail */
log_warn(LD_CONSDIFF, "Could not compute digests of the consensus "
"resulting from applying a consensus diff.");
goto error_cleanup;
/* LCOV_EXCL_STOP */
}
/* See that the resulting consensus matches its hash. */
if (!consensus_digest_eq(cons2_digests.sha3_256,
(const uint8_t*)e_cons2_hash)) {
log_warn(LD_CONSDIFF, "Refusing to apply consensus diff because "
"the resulting consensus doesn't match the digest as found in "
"the consensus diff header.");
char hex_digest2[HEX_DIGEST256_LEN+1];
char e_hex_digest2[HEX_DIGEST256_LEN+1];
base16_encode(hex_digest2, HEX_DIGEST256_LEN+1,
(const char *)cons2_digests.sha3_256, DIGEST256_LEN);
base16_encode(e_hex_digest2, HEX_DIGEST256_LEN+1,
e_cons2_hash, DIGEST256_LEN);
log_warn(LD_CONSDIFF, "Expected: %s; found: %s",
hex_digest2, e_hex_digest2);
goto error_cleanup;
}
goto done;
error_cleanup:
tor_free(cons2_str); /* Sets it to NULL */
done:
if (cons2) {
smartlist_free(cons2);
}
return cons2_str;
}
/** Any consensus line longer than this means that the input is invalid. */
#define CONSENSUS_LINE_MAX_LEN (1<<20)
/**
* Helper: For every NL-terminated line in <b>s</b>, add a cdline referring to
* that line (without trailing newline) to <b>out</b>. Return -1 if there are
* any non-NL terminated lines; 0 otherwise.
*
* Unlike tor_split_lines, this function avoids ambiguity on its
* handling of a final line that isn't NL-terminated.
*
* All cdline_t objects are allocated in the provided memarea. Strings
* are not copied: if <b>s</b> changes or becomes invalid, then all
* generated cdlines will become invalid.
*/
STATIC int
consensus_split_lines(smartlist_t *out, const char *s, memarea_t *area)
{
const char *end_of_str = s + strlen(s);
tor_assert(*end_of_str == '\0');
while (*s) {
const char *eol = memchr(s, '\n', end_of_str - s);
if (!eol) {
/* File doesn't end with newline. */
return -1;
}
if (eol - s > CONSENSUS_LINE_MAX_LEN) {
/* Line is far too long. */
return -1;
}
cdline_t *line = memarea_alloc(area, sizeof(cdline_t));
line->s = s;
line->len = (uint32_t)(eol - s);
smartlist_add(out, line);
s = eol+1;
}
return 0;
}
/** Given a list of cdline_t, return a newly allocated string containing
* all of the lines, terminated with NL, concatenated.
*
* Unlike smartlist_join_strings(), avoids lossy operations on empty
* lists. */
static char *
consensus_join_lines(const smartlist_t *inp)
{
size_t n = 0;
SMARTLIST_FOREACH(inp, const cdline_t *, cdline, n += cdline->len + 1);
n += 1;
char *result = tor_malloc(n);
char *out = result;
SMARTLIST_FOREACH_BEGIN(inp, const cdline_t *, cdline) {
memcpy(out, cdline->s, cdline->len);
out += cdline->len;
*out++ = '\n';
} SMARTLIST_FOREACH_END(cdline);
*out++ = '\0';
tor_assert(out == result+n);
return result;
}
/** Given two consensus documents, try to compute a diff between them. On
* success, retun a newly allocated string containing that diff. On failure,
* return NULL. */
char *
consensus_diff_generate(const char *cons1,
const char *cons2)
{
consensus_digest_t d1, d2;
smartlist_t *lines1 = NULL, *lines2 = NULL, *result_lines = NULL;
int r1, r2;
char *result = NULL;
r1 = consensus_compute_digest_as_signed(cons1, &d1);
r2 = consensus_compute_digest(cons2, &d2);
if (BUG(r1 < 0 || r2 < 0))
return NULL; // LCOV_EXCL_LINE
memarea_t *area = memarea_new();
lines1 = smartlist_new();
lines2 = smartlist_new();
if (consensus_split_lines(lines1, cons1, area) < 0)
goto done;
if (consensus_split_lines(lines2, cons2, area) < 0)
goto done;
result_lines = consdiff_gen_diff(lines1, lines2, &d1, &d2, area);
done:
if (result_lines) {
result = consensus_join_lines(result_lines);
smartlist_free(result_lines);
}
memarea_drop_all(area);
smartlist_free(lines1);
smartlist_free(lines2);
return result;
}
/** Given a consensus document and a diff, try to apply the diff to the
* consensus. On success return a newly allocated string containing the new
* consensus. On failure, return NULL. */
char *
consensus_diff_apply(const char *consensus,
const char *diff)
{
consensus_digest_t d1;
smartlist_t *lines1 = NULL, *lines2 = NULL;
int r1;
char *result = NULL;
memarea_t *area = memarea_new();
r1 = consensus_compute_digest_as_signed(consensus, &d1);
if (BUG(r1 < 0))
goto done;
lines1 = smartlist_new();
lines2 = smartlist_new();
if (consensus_split_lines(lines1, consensus, area) < 0)
goto done;
if (consensus_split_lines(lines2, diff, area) < 0)
goto done;
result = consdiff_apply_diff(lines1, lines2, &d1);
done:
smartlist_free(lines1);
smartlist_free(lines2);
memarea_drop_all(area);
return result;
}
/** Return true iff, based on its header, <b>document</b> is likely
* to be a consensus diff. */
int
looks_like_a_consensus_diff(const char *document, size_t len)
{
return (len >= strlen(ns_diff_version) &&
fast_memeq(document, ns_diff_version, strlen(ns_diff_version)));
}
| 49,847
|
https://github.com/c4dt/mlbench-core/blob/master/mlbench_core/dataset/linearmodels/pytorch/__init__.py
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,022
|
mlbench-core
|
c4dt
|
Python
|
Code
| 7
| 25
|
from .dataloader import LMDBDataset
__all__ = ["LMDBDataset"]
| 20,007
|
https://github.com/wujianbing/rbac_shiro/blob/master/src/test/java/com/jack/rbac_shiro/RbacShiroApplicationTests.java
|
Github Open Source
|
Open Source
|
MIT
| null |
rbac_shiro
|
wujianbing
|
Java
|
Code
| 16
| 77
|
package com.jack.rbac_shiro;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class RbacShiroApplicationTests {
@Test
void contextLoads() {
}
}
| 46,920
|
https://github.com/k-t/SharpHaven/blob/master/SharpHaven/UI/Widgets/Combat/CombatWindow.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
SharpHaven
|
k-t
|
C#
|
Code
| 363
| 1,390
|
using System;
using Haven;
using Haven.Utils;
using SharpHaven.Client;
using SharpHaven.Graphics;
namespace SharpHaven.UI.Widgets
{
public class CombatWindow : Window
{
private static readonly Drawable iptex;
static CombatWindow()
{
iptex = App.Resources.Get<Drawable>("gfx/hud/combat/ip");
}
private CombatRelation relation;
private Delayed<GameAction> attackMove = new Delayed<GameAction>();
private Delayed<GameAction> attack = new Delayed<GameAction>();
private Delayed<GameAction> maneuver = new Delayed<GameAction>();
private readonly Label lblCurrentAttack;
private readonly Label lblCurrentManeuver;
private readonly Label lblInitiative;
public CombatWindow(Widget parent)
: base(parent, "Combat")
{
var lblAttack = new Label(this, Fonts.Text);
lblAttack.AutoSize = true;
lblAttack.Move(10, 5);
lblAttack.Text = "Attack:";
lblCurrentAttack = new Label(this, Fonts.Text);
lblCurrentAttack.Move(50, 35);
var lblManeuver = new Label(this, Fonts.Text);
lblAttack.AutoSize = true;
lblManeuver.Move(10, 55);
lblManeuver.Text = "Maneuver:";
lblCurrentManeuver = new Label(this, Fonts.Text);
lblCurrentManeuver.Move(50, 85);
lblInitiative = new Label(this, Fonts.Text);
lblInitiative.Move(205 + iptex.Width, 30);
Margin = 5;
Size = new Point2D(300, 120);
}
public Delayed<GameAction> Attack
{
get { return attack; }
set
{
attack = value ?? new Delayed<GameAction>();
UpdateAttackLabel();
}
}
public DateTime AttackCooldown
{
get;
set;
}
public Delayed<GameAction> AttackMove
{
get { return attackMove; }
set
{
attackMove = value ?? new Delayed<GameAction>();
UpdateAttackLabel();
}
}
public Delayed<GameAction> Maneuver
{
get { return maneuver; }
set
{
maneuver = value ?? new Delayed<GameAction>();
UpdateManeuverLabel();
}
}
public CombatRelation Relation
{
get { return relation; }
set
{
if (relation != null)
relation.Changed -= OnRelationChanged;
relation = value;
OnRelationChanged();
if (relation != null)
relation.Changed += OnRelationChanged;
}
}
protected override void OnDraw(DrawingContext dc)
{
base.OnDraw(dc);
dc.PushMatrix();
dc.Translate(Margin, Margin);
var hasMove = (AttackMove.Value != null);
if (hasMove)
dc.Draw(AttackMove.Value.Image, 15, 20);
if (Attack.Value != null)
{
var p = hasMove ? new Point2D(18, 23) : new Point2D(15, 20);
dc.Draw(Attack.Value.Image, p);
}
if (Maneuver.Value != null)
{
dc.Draw(Maneuver.Value.Image, 15, 70);
}
dc.Draw(iptex, 200, 32);
var now = DateTime.Now;
if (now < AttackCooldown)
{
dc.SetColor(255, 0, 128, 255);
dc.DrawRectangle(200, 55, (int)(AttackCooldown - now).TotalMilliseconds / 100, 20);
dc.ResetColor();
}
dc.PopMatrix();
}
private void UpdateAttackLabel()
{
if (Attack.Value != null)
lblCurrentAttack.Text = Attack.Value.Name;
else if (AttackMove.Value != null)
lblCurrentAttack.Text = AttackMove.Value.Name;
else
lblCurrentAttack.Text = "";
}
private void UpdateManeuverLabel()
{
if (Maneuver.Value != null)
lblCurrentManeuver.Text = Maneuver.Value.Name;
else
lblCurrentManeuver.Text = "";
}
private void OnRelationChanged()
{
lblInitiative.Text = (Relation != null)
? Relation.Initiative.ToString()
: "";
}
}
}
| 28,994
|
https://github.com/TRRogen/HY/blob/master/HY/HY/Find/M/HYRecommendAppMessage.h
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,016
|
HY
|
TRRogen
|
Objective-C
|
Code
| 77
| 236
|
//
// HYRecommendAppMessage.h
// HY
//
// Created by tarena04 on 16/6/14.
// Copyright © 2016年 tarena. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface HYRecommendAppMessage : NSObject
/** 应用名称 **/
@property (nonatomic,copy) NSString *title;
/** 应用图片 **/
@property (nonatomic,copy) NSString *iconUrl;
/** 应用地址 **/
@property (nonatomic,copy) NSString *url;
/** 应用 **/
@property (nonatomic,copy) NSNumber *groupIndex;
/** 应用 **/
@property (nonatomic,copy) NSNumber *orderIndex;
/** 应用 **/
@property (nonatomic,copy) NSNumber *type;
/** 应用 **/
@property (nonatomic,copy) NSString *ID;
@end
| 28,362
|
https://github.com/dotnet/aspnetcore/blob/master/src/Mvc/test/Mvc.FunctionalTests/ContentNegotiationTest.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,023
|
aspnetcore
|
dotnet
|
C#
|
Code
| 1,225
| 5,707
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Runtime.Serialization;
using System.Text;
using BasicWebSite.Models;
using Microsoft.AspNetCore.Mvc.Formatters.Xml;
using Microsoft.AspNetCore.Testing;
using Newtonsoft.Json;
namespace Microsoft.AspNetCore.Mvc.FunctionalTests;
public class ContentNegotiationTest : IClassFixture<MvcTestFixture<BasicWebSite.StartupWithoutEndpointRouting>>
{
public ContentNegotiationTest(MvcTestFixture<BasicWebSite.StartupWithoutEndpointRouting> fixture)
{
Client = fixture.CreateDefaultClient();
}
public HttpClient Client { get; }
[Fact]
public async Task ProducesAttribute_SingleContentType_PicksTheFirstSupportedFormatter()
{
// Arrange
// Selects custom even though it is last in the list.
var expectedContentType = MediaTypeHeaderValue.Parse("application/custom;charset=utf-8");
var expectedBody = "Written using custom format.";
// Act
var response = await Client.GetAsync("http://localhost/Normal/WriteUserUsingCustomFormat");
// Assert
Assert.Equal(expectedContentType, response.Content.Headers.ContentType);
var body = await response.Content.ReadAsStringAsync();
Assert.Equal(expectedBody, body);
}
[Fact]
public async Task ProducesAttribute_MultipleContentTypes_RunsConnegToSelectFormatter()
{
// Arrange
var expectedContentType = MediaTypeHeaderValue.Parse("application/json;charset=utf-8");
var expectedBody = $"{{{Environment.NewLine} \"name\": \"My name\",{Environment.NewLine}" +
$" \"address\": \"My address\"{Environment.NewLine}}}";
// Act
var response = await Client.GetAsync("http://localhost/Normal/MultipleAllowedContentTypes");
// Assert
Assert.Equal(expectedContentType, response.Content.Headers.ContentType);
var body = await response.Content.ReadAsStringAsync();
Assert.Equal(expectedBody, body);
}
[Fact]
public async Task NoProducesAttribute_ActionReturningString_RunsUsingTextFormatter()
{
// Arrange
var expectedContentType = MediaTypeHeaderValue.Parse("text/plain;charset=utf-8");
var expectedBody = "NormalController";
// Act
var response = await Client.GetAsync("http://localhost/Normal/ReturnClassName");
// Assert
Assert.Equal(expectedContentType, response.Content.Headers.ContentType);
var body = await response.Content.ReadAsStringAsync();
Assert.Equal(expectedBody, body);
}
[Fact]
public async Task NoProducesAttribute_ActionReturningAnyObject_RunsUsingDefaultFormatters()
{
// Arrange
var expectedContentType = MediaTypeHeaderValue.Parse("application/json;charset=utf-8");
// Act
var response = await Client.GetAsync("http://localhost/Normal/ReturnUser");
// Assert
Assert.Equal(expectedContentType, response.Content.Headers.ContentType);
}
[Theory]
[InlineData("/;q=0.9")]
[InlineData("/;q=0.9, invalid;q=0.5;application/json;q=0.1")]
[InlineData("/invalid;q=0.9, application/json;q=0.1,invalid;q=0.5")]
[InlineData("text/html, application/json, image/jpeg, *; q=.2, */*; q=.2")]
public async Task ContentNegotiationWithPartiallyValidAcceptHeader_SkipsInvalidEntries(string acceptHeader)
{
// Arrange
var expectedContentType = MediaTypeHeaderValue.Parse("application/json;charset=utf-8");
var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/ContentNegotiation/UserInfo_ProducesWithTypeOnly");
request.Headers.TryAddWithoutValidation("Accept", acceptHeader);
// Act
var response = await Client.SendAsync(request);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(expectedContentType, response.Content.Headers.ContentType);
}
[Fact]
public async Task ProducesAttributeWithTypeOnly_RunsRegularContentNegotiation()
{
// Arrange
var expectedContentType = MediaTypeHeaderValue.Parse("application/json;charset=utf-8");
var expectedOutput = "{\"name\":\"John\",\"address\":\"One Microsoft Way\"}";
var request = new HttpRequestMessage(
HttpMethod.Get,
"http://localhost/ContentNegotiation/UserInfo_ProducesWithTypeOnly");
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// Act
var response = await Client.SendAsync(request);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(expectedContentType, response.Content.Headers.ContentType);
var actual = await response.Content.ReadAsStringAsync();
Assert.Equal(expectedOutput, actual);
}
[ConditionalFact]
// Mono issue - https://github.com/aspnet/External/issues/18
[FrameworkSkipCondition(RuntimeFrameworks.Mono)]
public async Task ProducesAttribute_WithTypeAndContentType_UsesContentType()
{
// Arrange
var expectedContentType = MediaTypeHeaderValue.Parse("application/xml;charset=utf-8");
var expectedOutput = "<User xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\" " +
"xmlns=\"http://schemas.datacontract.org/2004/07/BasicWebSite.Models\">" +
"<Address>One Microsoft Way</Address><Name>John</Name></User>";
var request = new HttpRequestMessage(
HttpMethod.Get,
"http://localhost/ContentNegotiation/UserInfo_ProducesWithTypeAndContentType");
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
// Act
var response = await Client.SendAsync(request);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(expectedContentType, response.Content.Headers.ContentType);
var actual = await response.Content.ReadAsStringAsync();
XmlAssert.Equal(expectedOutput, actual);
}
[Theory]
[InlineData("http://localhost/FallbackOnTypeBasedMatch/UseTheFallback_WithDefaultFormatters")]
[InlineData("http://localhost/FallbackOnTypeBasedMatch/OverrideTheFallback_WithDefaultFormatters")]
public async Task NoAcceptAndRequestContentTypeHeaders_UsesFirstFormatterWhichCanWriteType(string url)
{
// Arrange
var expectedContentType = MediaTypeHeaderValue.Parse("application/json;charset=utf-8");
// Act
var response = await Client.GetAsync(url + "?input=100");
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(expectedContentType, response.Content.Headers.ContentType);
var actual = await response.Content.ReadAsStringAsync();
Assert.Equal("100", actual);
}
[Fact]
public async Task NoMatchingFormatter_ForTheGivenContentType_Returns406()
{
// Arrange & Act
var response = await Client.GetAsync("http://localhost/Normal/ReturnUser_NoMatchingFormatter");
// Assert
Assert.Equal(HttpStatusCode.NotAcceptable, response.StatusCode);
}
[Theory]
[InlineData(
"ContactInfoUsingV3Format",
"text/vcard; version=v3.0; charset=utf-8",
@"BEGIN:VCARD
FN:John Williams
END:VCARD
")]
[InlineData(
"ContactInfoUsingV4Format",
"text/vcard; version=v4.0; charset=utf-8",
@"BEGIN:VCARD
FN:John Williams
GENDER:M
END:VCARD
")]
public async Task ProducesAttribute_WithMediaTypeHavingParameters_IsCaseInsensitiveMatch(
string action,
string expectedMediaType,
string expectedResponseBody)
{
// Arrange & Act
var response = await Client.GetAsync("http://localhost/ProducesWithMediaTypeParameters/" + action);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.NotNull(response.Content);
var contentType = response.Content.Headers.ContentType;
Assert.NotNull(contentType);
Assert.Equal(expectedMediaType, contentType.ToString());
var actualResponseBody = await response.Content.ReadAsStringAsync();
Assert.Equal(expectedResponseBody, actualResponseBody, ignoreLineEndingDifferences: true);
}
[Fact]
public async Task ProducesAttribute_OnAction_OverridesTheValueOnClass()
{
// Arrange
// Value on the class is application/json.
var expectedContentType = MediaTypeHeaderValue.Parse(
"application/custom_ProducesContentBaseController_Action;charset=utf-8");
var expectedBody = "ProducesContentBaseController";
// Act
var response = await Client.GetAsync("http://localhost/ProducesContentBase/ReturnClassName");
// Assert
Assert.Equal(expectedContentType, response.Content.Headers.ContentType);
var body = await response.Content.ReadAsStringAsync();
Assert.Equal(expectedBody, body);
}
[Fact]
public async Task ProducesAttribute_OnDerivedClass_OverridesTheValueOnBaseClass()
{
// Arrange
var expectedContentType = MediaTypeHeaderValue.Parse(
"application/custom_ProducesContentOnClassController;charset=utf-8");
var expectedBody = "ProducesContentOnClassController";
// Act
var response = await Client.GetAsync(
"http://localhost/ProducesContentOnClass/ReturnClassNameWithNoContentTypeOnAction");
// Assert
Assert.Equal(expectedContentType, response.Content.Headers.ContentType);
var body = await response.Content.ReadAsStringAsync();
Assert.Equal(expectedBody, body);
}
[Fact]
public async Task ProducesAttribute_OnDerivedAction_OverridesTheValueOnBaseClass()
{
// Arrange
var expectedContentType = MediaTypeHeaderValue.Parse(
"application/custom_NoProducesContentOnClassController_Action;charset=utf-8");
var expectedBody = "NoProducesContentOnClassController";
// Act
var response = await Client.GetAsync("http://localhost/NoProducesContentOnClass/ReturnClassName");
// Assert
Assert.Equal(expectedContentType, response.Content.Headers.ContentType);
var body = await response.Content.ReadAsStringAsync();
Assert.Equal(expectedBody, body);
}
[Fact]
public async Task ProducesAttribute_OnDerivedAction_OverridesTheValueOnBaseAction()
{
// Arrange
var expectedContentType = MediaTypeHeaderValue.Parse(
"application/custom_NoProducesContentOnClassController_Action;charset=utf-8");
var expectedBody = "NoProducesContentOnClassController";
// Act
var response = await Client.GetAsync("http://localhost/NoProducesContentOnClass/ReturnClassName");
// Assert
Assert.Equal(expectedContentType, response.Content.Headers.ContentType);
var body = await response.Content.ReadAsStringAsync();
Assert.Equal(expectedBody, body);
}
[Fact]
public async Task ProducesAttribute_OnDerivedClassAndAction_OverridesTheValueOnBaseClass()
{
// Arrange
var expectedContentType = MediaTypeHeaderValue.Parse(
"application/custom_ProducesContentOnClassController_Action;charset=utf-8");
var expectedBody = "ProducesContentOnClassController";
// Act
var response = await Client.GetAsync(
"http://localhost/ProducesContentOnClass/ReturnClassNameContentTypeOnDerivedAction");
// Assert
Assert.Equal(expectedContentType, response.Content.Headers.ContentType);
var body = await response.Content.ReadAsStringAsync();
Assert.Equal(expectedBody, body);
}
[Fact]
public async Task ProducesAttribute_IsNotHonored_ForJsonResult()
{
// Arrange
var expectedContentType = MediaTypeHeaderValue.Parse("application/json;charset=utf-8");
var expectedBody = "{\"methodName\":\"Produces_WithNonObjectResult\"}";
// Act
var response = await Client.GetAsync("http://localhost/ProducesJson/Produces_WithNonObjectResult");
// Assert
Assert.Equal(expectedContentType, response.Content.Headers.ContentType);
var body = await response.Content.ReadAsStringAsync();
Assert.Equal(expectedBody, body);
}
[ConditionalFact]
// Mono issue - https://github.com/aspnet/External/issues/18
[FrameworkSkipCondition(RuntimeFrameworks.Mono)]
public async Task XmlFormatter_SupportedMediaType_DoesNotChangeAcrossRequests()
{
// Arrange
var expectedContentType = MediaTypeHeaderValue.Parse("application/xml;charset=utf-8");
var expectedBody = @"<User xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" " +
@"xmlns=""http://schemas.datacontract.org/2004/07/BasicWebSite.Models""><Address>" +
@"One Microsoft Way</Address><Name>John</Name></User>";
for (int i = 0; i < 5; i++)
{
var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/ContentNegotiation/UserInfo");
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
request.Headers.AcceptCharset.Add(new StringWithQualityHeaderValue("utf-8"));
// Act and Assert
var response = await Client.SendAsync(request);
Assert.Equal(expectedContentType, response.Content.Headers.ContentType);
var body = await response.Content.ReadAsStringAsync();
Assert.Equal(expectedBody, body);
}
}
[Theory]
[InlineData(null)]
[InlineData("text/plain")]
[InlineData("text/plain; charset=utf-8")]
[InlineData("text/html, application/xhtml+xml, image/jxr, */*")] // typical browser accept header
public async Task ObjectResult_WithStringReturnType_DefaultToTextPlain(string acceptMediaType)
{
// Arrange
var request = new HttpRequestMessage(HttpMethod.Get, "FallbackOnTypeBasedMatch/ReturnString");
request.Headers.Accept.ParseAdd(acceptMediaType);
// Act
var response = await Client.SendAsync(request);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal("text/plain; charset=utf-8", response.Content.Headers.ContentType.ToString());
var actualBody = await response.Content.ReadAsStringAsync();
Assert.Equal("Hello World!", actualBody);
}
[Fact]
public async Task ObjectResult_WithStringReturnType_AndNonTextPlainMediaType_DoesNotReturnTextPlain()
{
// Arrange
var targetUri = "http://localhost/FallbackOnTypeBasedMatch/ReturnString";
var request = new HttpRequestMessage(HttpMethod.Get, targetUri);
request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/json"));
// Act
var response = await Client.SendAsync(request);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal("application/json; charset=utf-8", response.Content.Headers.ContentType.ToString());
var actualBody = await response.Content.ReadAsStringAsync();
Assert.Equal("\"Hello World!\"", actualBody);
}
[Fact]
public async Task NoMatchOn_RequestContentType_FallsBackOnTypeBasedMatch_NoMatchFound_Returns406()
{
// Arrange
var targetUri = "http://localhost/FallbackOnTypeBasedMatch/FallbackGivesNoMatch/?input=1234";
var content = new StringContent("1234", Encoding.UTF8, "application/custom");
var request = new HttpRequestMessage(HttpMethod.Post, targetUri);
request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/custom1"));
request.Content = content;
// Act
var response = await Client.SendAsync(request);
// Assert
Assert.Equal(HttpStatusCode.NotAcceptable, response.StatusCode);
}
[Fact]
public async Task InvalidResponseContentType_WithNotMatchingAcceptHeader_Returns406()
{
// Arrange
var targetUri = "http://localhost/InvalidContentType/SetResponseContentTypeJson";
var request = new HttpRequestMessage(HttpMethod.Get, targetUri);
request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/custom1"));
// Act
var response = await Client.SendAsync(request);
// Assert
Assert.Equal(HttpStatusCode.NotAcceptable, response.StatusCode);
}
[Fact]
public async Task InvalidResponseContentType_WithMatchingAcceptHeader_Returns406()
{
// Arrange
var targetUri = "http://localhost/InvalidContentType/SetResponseContentTypeJson";
var request = new HttpRequestMessage(HttpMethod.Get, targetUri);
request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/json"));
// Act
var response = await Client.SendAsync(request);
// Assert
Assert.Equal(HttpStatusCode.NotAcceptable, response.StatusCode);
}
[Fact]
public async Task InvalidResponseContentType_WithoutAcceptHeader_Returns406()
{
// Arrange
var targetUri = "http://localhost/InvalidContentType/SetResponseContentTypeJson";
var request = new HttpRequestMessage(HttpMethod.Get, targetUri);
// Act
var response = await Client.SendAsync(request);
// Assert
Assert.Equal(HttpStatusCode.NotAcceptable, response.StatusCode);
}
[Fact]
public async Task ProducesAttribute_And_FormatFilterAttribute_Conflicting()
{
// Arrange & Act
var response = await Client.GetAsync(
"http://localhost/FormatFilter/ProducesTakesPrecedenceOverUserSuppliedFormatMethod?format=json");
// Assert
// Explicit content type set by the developer takes precedence over the format requested by the end user
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}
[Fact]
public async Task ProducesAttribute_And_FormatFilterAttribute_Collaborating()
{
// Arrange & Act
var response = await Client.GetAsync(
"http://localhost/FormatFilter/ProducesTakesPrecedenceOverUserSuppliedFormatMethod");
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var body = await response.Content.ReadAsStringAsync();
Assert.Equal("MethodWithFormatFilter", body);
}
[Fact]
public async Task ProducesAttribute_CustomMediaTypeWithJsonSuffix_RunsConnegAndSelectsJsonFormatter()
{
// Arrange
var expectedMediaType = MediaTypeHeaderValue.Parse("application/vnd.example.contact+json; v=2; charset=utf-8");
var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/ProducesWithMediaTypeSuffixesController/ContactInfo");
request.Headers.Add("Accept", "application/vnd.example.contact+json; v=2");
// Act
var response = await Client.SendAsync(request);
// Assert
Assert.Equal(expectedMediaType, response.Content.Headers.ContentType);
var body = await response.Content.ReadAsStringAsync();
var contact = JsonConvert.DeserializeObject<Contact>(body);
Assert.Equal("Jason Ecsemelle", contact.Name);
}
[Fact]
public async Task ProducesAttribute_CustomMediaTypeWithXmlSuffix_RunsConnegAndSelectsXmlFormatter()
{
// Arrange
var expectedMediaType = MediaTypeHeaderValue.Parse("application/vnd.example.contact+xml; v=2; charset=utf-8");
var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/ProducesWithMediaTypeSuffixesController/ContactInfo");
request.Headers.Add("Accept", "application/vnd.example.contact+xml; v=2");
// Act
var response = await Client.SendAsync(request);
// Assert
Assert.Equal(expectedMediaType, response.Content.Headers.ContentType);
var bodyStream = await response.Content.ReadAsStreamAsync();
var xmlDeserializer = new DataContractSerializer(typeof(Contact));
var contact = xmlDeserializer.ReadObject(bodyStream) as Contact;
Assert.Equal("Jason Ecsemelle", contact.Name);
}
[Fact]
public async Task FormatFilter_XmlAsFormat_ReturnsXml()
{
// Arrange
var expectedBody = "<FormatFilterController.Customer xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\""
+ " xmlns=\"http://schemas.datacontract.org/2004/07/BasicWebSite.Controllers.ContentNegotiation\">"
+ "<Name>John</Name></FormatFilterController.Customer>";
// Act
var response = await Client.GetAsync(
"http://localhost/FormatFilter/CustomerInfo?format=xml");
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal("application/xml; charset=utf-8", response.Content.Headers.ContentType.ToString());
var body = await response.Content.ReadAsStringAsync();
Assert.Equal(expectedBody, body);
}
}
| 17,136
|
https://github.com/SteveGreatApe/AvrKeyboard/blob/master/avrkeyboard/src/main/java/com/greatape/avrkeyboard/textField/TextField.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
AvrKeyboard
|
SteveGreatApe
|
Java
|
Code
| 1,919
| 6,835
|
/* Copyright 2017 Great Ape Software 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 com.greatape.avrkeyboard.textField;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.MotionEvent;
import com.greatape.avrkeyboard.model.AvrKeyboard;
import com.greatape.avrkeyboard.model.KeyItem;
import com.greatape.avrkeyboard.styles.TextFieldStyle;
import com.greatape.avrkeyboard.styles.TextFieldStyleDefault;
import com.greatape.avrkeyboard.util.AvrUtil;
import com.greatape.avrutils.objects.LayoutLink;
import com.greatape.avrutils.objects.LinkedObjects;
import org.gearvrf.GVRContext;
import org.gearvrf.GVRDrawFrameListener;
import org.gearvrf.GVRMaterial;
import org.gearvrf.GVRMesh;
import org.gearvrf.GVRMeshCollider;
import org.gearvrf.GVRPhongShader;
import org.gearvrf.GVRRenderData;
import org.gearvrf.GVRSceneObject;
import org.gearvrf.GVRShaderId;
import org.gearvrf.GVRTexture;
import org.gearvrf.IHoverEvents;
import org.gearvrf.ITouchEvents;
import org.gearvrf.utility.Colors;
import org.joml.Vector3f;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* @author Steve Townsend
*/
public class TextField extends GVRSceneObject implements GVRDrawFrameListener, KeyItem.KeyListener, LayoutLink.LinkOwner, LinkedObjects.Linkable {
private static final int TEXT_PIXEL_HEIGHT = 75;
private static final float CURSOR_ZPOS = 0.0001f;
private final static int CursorRenderingOrderBoost = 3;
private final static int CharacterRenderingOrderBoost = 2;
private final static int SpaceRenderingOrderBoost = 1;
private static final int KEY_CODE_DELETE_ALL = 1;
private static final int KEY_CODE_BACK = 2;
private final TextFieldStyle mStyle;
private final boolean mReadOnly;
private final AvrKeyboard mAvrKeyboard;
private GVRTexture mSpaceTexture;
private int mBitmapHeight;
private float mTextDrawPosY;
private float mFontWidth;
private List<TextFieldItem> mTextFieldItems = new ArrayList<>();
private List<GVRSceneObject> mTextMarkers = new ArrayList<>();
private int mMaxNumberOfCharacters;
private boolean mExpandable;
private TextFieldKey mClearButton;
private TextFieldKey mBackButton;
private Paint mPaint;
private int mCursorIndex;
private float mBaseLinePos;
private boolean mFocused;
private Listener mListener;
private float mCursorFlashCountdown;
private boolean mCursorFlashOn;
private GVRSceneObject mCursor;
private float mCursorHeight;
private float mCursorBaseLinePos;
private float mPixelsToSizeRatio;
private GVRSceneObject mPhantomCursor;
private int mActivePhantomCursorIndex;
private boolean mProportional;
private ArrayList<Float> mCharacterWidths;
private int mBaseRenderingOrder;
private LinkedObjects mLinkedObjects;
private LayoutLink.LinkParent mParentLink;
private boolean mAutoShiftOnEmptyFocus;
interface Listener {
void onClaimFocus(TextField textField);
void onBack(TextField textField);
}
public TextField(GVRContext gvrContext, boolean readOnly, AvrKeyboard avrKeyboard) {
this(gvrContext, new TextFieldStyleDefault(), readOnly, avrKeyboard);
}
public TextField(GVRContext gvrContext, TextFieldStyle style, boolean readOnly, AvrKeyboard avrKeyboard) {
super(gvrContext);
setName("TextField");
mReadOnly = readOnly;
mStyle = style;
mAvrKeyboard = avrKeyboard;
mBaseRenderingOrder = GVRRenderData.GVRRenderingOrder.TRANSPARENT;
initPaint();
mTextFieldItems = new ArrayList<>();
if (!mReadOnly) {
mCursor = createCursor(gvrContext, false);
mPhantomCursor = createCursor(gvrContext, true);
mActivePhantomCursorIndex = -1;
updateCursorIndex(0);
Bitmap spaceBitmap = KeyItem.sCreateResourceBitmap(gvrContext, mStyle.space_drawable, style.cursor_color);
mSpaceTexture = AvrUtil.bitmapTexture(gvrContext, spaceBitmap);
} else {
mExpandable = true;
}
mLinkedObjects = new LinkedObjects(this);
mCharacterWidths = new ArrayList<>();
}
public void setProportional(boolean proportional) {
if (!mReadOnly) {
throw new RuntimeException("Only read only text fields can be proportional.");
}
mProportional = proportional;
}
boolean isReadOnly() {
return mReadOnly;
}
public void setRenderingOrder(int renderingOrder) {
mBaseRenderingOrder = renderingOrder;
}
public void setParentLink(LayoutLink.LinkParent parentLink) {
mParentLink = parentLink;
}
private GVRSceneObject createCursor(GVRContext gvrContext, boolean isPhantom) {
GVRSceneObject cursor = new GVRSceneObject(gvrContext, mStyle.cursor_width, mCursorHeight);
GVRRenderData renderData = cursor.getRenderData();
renderData.setRenderingOrder(mBaseRenderingOrder + CursorRenderingOrderBoost);
// TODO: Latest Post 3.3 requires this change
GVRMaterial material = new GVRMaterial(gvrContext, new GVRShaderId(GVRPhongShader.class));
// else for 3.3
// GVRMaterial material = new GVRMaterial(gvrContext);
// renderData.setShaderTemplate(GVRPhongShader.class);
// END 3.3
int alpha = Color.alpha(mStyle.cursor_color);
material.setDiffuseColor(
Colors.byteToGl(Color.red(mStyle.cursor_color)),
Colors.byteToGl(Color.green(mStyle.cursor_color)),
Colors.byteToGl(Color.blue(mStyle.cursor_color)),
Colors.byteToGl(isPhantom ? alpha / 2 : alpha));
renderData.setAlphaBlend(true);
renderData.setMaterial(material);
cursor.setEnable(false);
addChildObject(cursor);
gvrContext.getMainScene().bindShaders(cursor);
return cursor;
}
public void setFocused() {
characterSelected(mTextFieldItems.size());
}
public void setExpandable(boolean expandable) {
mExpandable = mReadOnly || expandable;
if (mExpandable) {
doSetNumberOfCharacters(mTextFieldItems.size());
}
}
void setListener(Listener listener) {
mListener = listener;
}
public void setNumberOfCharacters(int maxNumberOfCharacters) {
mMaxNumberOfCharacters = maxNumberOfCharacters;
mExpandable = false;
while (mTextFieldItems.size() > mMaxNumberOfCharacters) {
removeCharacter(mMaxNumberOfCharacters);
}
doSetNumberOfCharacters(mMaxNumberOfCharacters);
}
public String getCurrentText() {
StringBuilder result = new StringBuilder();
for (TextFieldItem textFieldItem : mTextFieldItems) {
result.append(textFieldItem.getCharacter());
}
return result.toString();
}
public TextFieldStyle getStyle() {
return mStyle;
}
public void close() {
// To ensure we remove the listener
setFocused(false);
}
void setHover(boolean hover) {
for (TextFieldItem textFieldItem : mTextFieldItems) {
textFieldItem.setHover(hover);
}
}
public void setAutoShiftOnEmptyFocus(boolean enabled) {
if (mAutoShiftOnEmptyFocus != enabled) {
mAutoShiftOnEmptyFocus = enabled;
}
}
void setFocused(boolean focused) {
if (!mReadOnly && focused != mFocused) {
mFocused = focused;
if (mFocused) {
checkAutoShift();
getGVRContext().registerDrawFrameListener(this);
updateCursorIndex(mCursorIndex);
restartFlash();
} else {
getGVRContext().unregisterDrawFrameListener(this);
mCursor.setEnable(false);
}
}
}
private void checkAutoShift() {
if (mAutoShiftOnEmptyFocus) {
if (mTextFieldItems.size() == 0) {
mAvrKeyboard.setShiftMode(AvrKeyboard.MODE_SHIFTED, AvrKeyboard.SHIFT_FIRST_LETTER_UPPERCASE);
} else {
mAvrKeyboard.cancelAutoShift();
}
}
}
@Override
public void onDrawFrame(float frameTime) {
mCursorFlashCountdown -= frameTime;
if (mCursorFlashCountdown <= 0) {
mCursorFlashOn = !mCursorFlashOn;
mCursorFlashCountdown = mCursorFlashOn ? mStyle.cursor_flash_on_time : mStyle.cursor_flash_off_time;
mCursor.setEnable(mCursorFlashOn);
}
}
void addBackButton() {
mBackButton = addButton(mStyle.back_button, KEY_CODE_BACK);
updateLayout();
}
public void addClearButton() {
mClearButton = addButton(mStyle.delete_all_button, KEY_CODE_DELETE_ALL);
updateLayout();
}
private TextFieldKey addButton(TextFieldStyle.Button style, int keyCode) {
TextFieldKey textFieldKey = TextFieldKey.create(getGVRContext(), style, keyCode, this, mBaseRenderingOrder);
addChildObject(textFieldKey);
return textFieldKey;
}
@Override
public void onLongPress(KeyItem keyItem) {
onKeyTapped(keyItem);
}
@Override
public void onKeyTapped(KeyItem keyItem) {
if (keyItem instanceof TextFieldKey) {
TextFieldKey textFieldKey = (TextFieldKey) keyItem;
switch (textFieldKey.getCode()) {
case KEY_CODE_DELETE_ALL:
deleteAll();
break;
case KEY_CODE_BACK:
if (mListener != null) {
mListener.onBack(this);
}
break;
}
}
}
private void setPhantomCursor(int index) {
index = Math.min(index, mTextFieldItems.size());
if (index != mActivePhantomCursorIndex) {
if (index >= 0) {
if (mActivePhantomCursorIndex < 0) {
mPhantomCursor.setEnable(true);
}
float xPos = xPos(index, true);
mPhantomCursor.getTransform().setPosition(xPos, mCursorBaseLinePos, CURSOR_ZPOS + 0.1f);
} else {
mPhantomCursor.setEnable(false);
}
mActivePhantomCursorIndex = index;
}
}
private GVRSceneObject newSpaceLine(int position) {
GVRContext gvrContext = getGVRContext();
GVRSceneObject space = new SpaceObject(gvrContext, mSpaceTexture, position);
space.getTransform().setPosition(position * mFontWidth, mBaseLinePos, 0.0001f);
return space;
}
void removeCharacter() {
if (mCursorIndex > 0) {
removeCharacter(mCursorIndex - 1);
if (mExpandable) {
doSetNumberOfCharacters(mTextFieldItems.size());
} else {
updateLayout();
}
}
}
private void removeCharacter(int index) {
TextFieldItem character = mTextFieldItems.remove(index);
mCharacterWidths.remove(index);
removeChildObject(character);
if (mCursorIndex > index) {
updateCursorIndex(mCursorIndex - 1);
}
}
public void setText(final String text) {
while (mCursorIndex > 0) {
removeCharacter(0);
}
for (int index = 0; index < text.length(); index++) {
addCharacter(text.charAt(index));
}
updateAfterCharactersAdded();
}
void append(final char keyChar) {
this.getGVRContext().runOnGlThread(new Runnable() {
@Override
public void run() {
if (mExpandable || mTextFieldItems.size() < mMaxNumberOfCharacters) {
int newCharIndex = mCursorIndex;
TextFieldItem character = addCharacter(keyChar);
character.getTransform().setPosition(xPos(newCharIndex), 0, 0);
updateAfterCharactersAdded();
}
}
});
}
private void updateAfterCharactersAdded() {
if (mExpandable) {
doSetNumberOfCharacters(mTextFieldItems.size());
}
mLinkedObjects.positionUpdated();
if (mParentLink != null) {
mParentLink.sizeUpdated();
}
}
private TextFieldItem addCharacter(char keyChar) {
float[] widthArray = new float[1];
Bitmap bitmap = createBitmap(keyChar, widthArray);
float width = widthArray[0] * mPixelsToSizeRatio;
TextFieldItem character = new TextFieldItem(getGVRContext(), width, mStyle.font_height, bitmap, keyChar, TextField.this);
mCharacterWidths.add(mCursorIndex, width);
character.getRenderData().setRenderingOrder(mBaseRenderingOrder + CharacterRenderingOrderBoost);
mTextFieldItems.add(mCursorIndex, character);
addChildObject(character);
updateCursorIndex(mCursorIndex + 1);
for (int updateIndex = mCursorIndex - 1; updateIndex < mTextFieldItems.size(); updateIndex++) {
mTextFieldItems.get(updateIndex).getTransform().setPositionX(xPos(updateIndex));
}
return character;
}
private void updateCursorIndex(int index) {
mCursorIndex = index;
if (mFocused) {
if (mCursorIndex == 0) {
checkAutoShift();
}
mCursor.getTransform().setPosition(xPos(index, true), mCursorBaseLinePos, CURSOR_ZPOS);
restartFlash();
}
}
private void restartFlash() {
mCursorFlashOn = true;
mCursorFlashCountdown = mStyle.cursor_flash_on_time;
mCursor.setEnable(true);
}
private float xPos(int index) {
return xPos(index, false);
}
private float xPos(int index, boolean beforeCharPos) {
float xPos;
if (mProportional) {
float totalWidth = 0;
float offset = 0;
for (int chr = 0; chr < mCharacterWidths.size(); chr++) {
float chrWidth = mCharacterWidths.get(chr);
totalWidth += chrWidth;
if (chr < index) {
offset += chrWidth;
} else if (!beforeCharPos && chr == index) {
offset += chrWidth / 2;
}
}
xPos = offset - totalWidth / 2;
} else {
xPos = mFontWidth * (((float) index) - ((float) mTextMarkers.size()) / 2);
if (!beforeCharPos) {
xPos += mFontWidth / 2;
}
}
return xPos;
}
private void updateLayout() {
int maxCount = Math.max(mTextMarkers.size(), mTextFieldItems.size());
for (int index = 0; index < maxCount; index++) {
float xPos = xPos(index);
if (index < mTextMarkers.size()) {
mTextMarkers.get(index).getTransform().setPositionX(xPos);
}
if (index < mTextFieldItems.size()) {
mTextFieldItems.get(index).getTransform().setPositionX(xPos);
}
}
if (mBackButton != null) {
mBackButton.getTransform().setPositionX(xPos(-1) - mStyle.back_button.margin);
}
if (mClearButton != null) {
mClearButton.getTransform().setPositionX(xPos(maxCount) + mStyle.delete_all_button.margin);
}
updateCursorIndex(mCursorIndex);
}
private void deleteAll() {
for (TextFieldItem textFieldItem : mTextFieldItems) {
removeChildObject(textFieldItem);
}
mTextFieldItems.clear();
mCharacterWidths.clear();
if (mExpandable) {
doSetNumberOfCharacters(0);
}
updateCursorIndex(0);
}
private void doSetNumberOfCharacters(int numberOfCharacters) {
if (numberOfCharacters == 0) {
numberOfCharacters = 1;
}
if (!mReadOnly) {
if (mTextMarkers.size() > numberOfCharacters) {
removeToMatch(numberOfCharacters);
} else {
addToMatch(numberOfCharacters);
}
}
updateLayout();
mLinkedObjects.positionUpdated();
if (mParentLink != null) {
mParentLink.sizeUpdated();
}
}
private void addToMatch(int numberOfCharacters) {
int oldSize = mTextMarkers.size();
for (int position = oldSize; position < numberOfCharacters; position++) {
GVRSceneObject space = newSpaceLine(position);
mTextMarkers.add(position, space);
addChildObject(space);
}
}
private void removeToMatch(int numberOfCharacters) {
for (int i = mTextMarkers.size() - 1; i >= numberOfCharacters; i--) {
GVRSceneObject subLine = mTextMarkers.get(i);
removeChildObject(subLine);
mTextMarkers.remove(i);
}
}
private void initPaint() {
mPaint = new Paint();
mPaint.setTypeface(mStyle.textStyle.font_typeface);
mPaint.setFlags(Paint.ANTI_ALIAS_FLAG);
mPaint.setStyle(Paint.Style.FILL);
mPaint.setTextSize(TEXT_PIXEL_HEIGHT);
Paint.FontMetrics fontMetrics = mPaint.getFontMetrics();
float totalHeight = fontMetrics.bottom - fontMetrics.top;
mPixelsToSizeRatio = mStyle.font_height / totalHeight;
mFontWidth = Math.max(mPaint.measureText("M"), mPaint.measureText("W")) * mPixelsToSizeRatio;
mCursorHeight = mStyle.font_height * (fontMetrics.descent - fontMetrics.ascent) / totalHeight;
mBitmapHeight = (int) totalHeight;
mTextDrawPosY = -fontMetrics.top;
float totalMid = (fontMetrics.bottom + fontMetrics.top) / 2f;
mBaseLinePos = mStyle.font_height * totalMid / totalHeight;
float ascDescMid = (fontMetrics.descent + fontMetrics.ascent) / 2f;
mCursorBaseLinePos = mStyle.font_height * (totalMid - ascDescMid) / totalHeight;
mPaint.setFakeBoldText(true);
mPaint.setColor(Color.WHITE);
mPaint.setFilterBitmap(true);
mPaint.setTextAlign(Paint.Align.CENTER);
}
private Bitmap createBitmap(char keyChar, float[] widthArray) {
char[] charArray = new char[]{keyChar};
mPaint.getTextWidths(charArray, 0, 1, widthArray);
int width = (int) widthArray[0];
Bitmap bitmap = Bitmap.createBitmap(width > 0 ? width : 1, mBitmapHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
canvas.drawColor(0);
canvas.drawText(charArray, 0, 1, ((float) width) / 2, mTextDrawPosY, mPaint);
return bitmap;
}
private void characterSelected(int index) {
updateCursorIndex(Math.min(index, mTextFieldItems.size()));
if (mListener != null) {
mListener.onClaimFocus(this);
}
}
void getBoundsObjects(List<GVRSceneObject> objects, Vector3f offset) {
objects.add(createBoundsObject(offset));
}
private GVRSceneObject createBoundsObject(Vector3f offset) {
float width = 0;
if (mProportional) {
for (int chr = 0; chr < mCharacterWidths.size(); chr++) {
width += mCharacterWidths.get(chr);
}
} else {
width = mFontWidth * mTextMarkers.size();
}
float extraXOffset = 0;
if (mBackButton != null) {
float extraWidth = mFontWidth + mStyle.back_button.margin;
width += extraWidth;
extraXOffset -= extraWidth / 2;
}
if (mClearButton != null) {
float extraWidth = mFontWidth + mStyle.delete_all_button.margin;
width += extraWidth;
extraXOffset += extraWidth / 2;
}
GVRMesh mesh = getGVRContext().createQuad(width, mCursorHeight);
if (extraXOffset != 0) {
AvrUtil.offsetQuad(mesh, extraXOffset, 0, 0);
}
if (offset != null) {
AvrUtil.offsetQuad(mesh, offset.x, offset.y, offset.z);
}
return new GVRSceneObject(getGVRContext(), mesh);
}
@Override
public void addLink(LayoutLink layoutLink) {
mLinkedObjects.addLink(layoutLink);
}
@Override
public GVRSceneObject getSceneObject() {
return this;
}
@Override
public List<GVRSceneObject> getLinkToBoundsObjects() {
return Collections.singletonList(createBoundsObject(null));
}
@Override
public List<GVRSceneObject> getBoundsObjects() {
return Collections.singletonList(createBoundsObject(null));
}
@Override
public void positionUpdated() {
mLinkedObjects.positionUpdated();
}
@Override
public String toString() {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(getCurrentText());
stringBuilder.append(" ");
stringBuilder.append(getTransform());
return stringBuilder.toString();
}
public class SpaceObject extends GVRSceneObject implements ITouchEvents, IHoverEvents {
private int mIndex;
private boolean mClickLeft;
private boolean mIsSelected;
SpaceObject(GVRContext gvrContext, GVRTexture texture, int index) {
super(gvrContext, mStyle.space_width * mFontWidth, mStyle.space_height * mStyle.font_height, texture);
this.mIndex = index;
getRenderData().setRenderingOrder(mBaseRenderingOrder + SpaceRenderingOrderBoost);
//
GVRMesh colliderMesh = gvrContext.createQuad(mFontWidth, mStyle.font_height);
final float[] textureCoords = colliderMesh.getTexCoords();
for (int coord = 1; coord < textureCoords.length; coord += 2) {
textureCoords[coord] = textureCoords[coord] - mBaseLinePos;
}
colliderMesh.setTexCoords(textureCoords);
attachCollider(new GVRMeshCollider(colliderMesh));
}
void onClickChar(float[] hitLocation) {
// TODO: Resurrect Phantom cursor for hover. Problem is GVRPickerInput doesn't deliver hover moves or location with move events.
if (hitLocation != null) {
mClickLeft = hitLocation[0] < 0f;
characterSelected(selectedIndex());
}
}
void setSelected(boolean selected) {
if (mIsSelected && !selected) {
setPhantomCursor(-1);
}
mIsSelected = selected;
}
int selectedIndex() {
return mClickLeft || mIndex >= mTextFieldItems.size() ? mIndex : mIndex + 1;
}
@Override
public void onHoverEnter(GVRSceneObject sceneObject) {
setSelected(true);
}
@Override
public void onHoverExit(GVRSceneObject sceneObject) {
setSelected(false);
}
@Override
public void onTouch(GVRSceneObject sceneObject, MotionEvent motionEvent, float[] hitLocation) {
final int action = motionEvent.getAction();
StringBuilder location = new StringBuilder();
if (hitLocation != null) {
location.append(hitLocation[0]).append(",").append(hitLocation[1]).append(",").append(hitLocation[2]);
} else {
location.append("null");
}
switch (action) {
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_DOWN:
break;
case MotionEvent.ACTION_UP:
onClickChar(hitLocation);
break;
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_OUTSIDE:
break;
}
}
}
}
| 16,431
|
https://github.com/bitwize/rscheme/blob/master/lib/app/ibis/backend/errors.scm
|
Github Open Source
|
Open Source
|
TCL
| 2,022
|
rscheme
|
bitwize
|
Scheme
|
Code
| 87
| 269
|
(define-message-table ibis 704)
(define-class <service-error> (<error-message>))
#|
(define-method display-object ((self <service-error>) port)
(format port "SRV-~03d " (msg-code self))
(apply format port (default-msg-text self) (msg-args self))
(newline port))
(define (service-error code text . args)
(let ((e (make <service-error>
msg-code: code
msg-args: args
default-msg-text: text)))
(note (+ 4000 code) "~a" (apply format #f text args))
(error e)))
|#
(define-macro (service-error code text . args)
`(service-error* (alloc-message error ,(+ 4000 code) ,text)
(vector ,@args)))
(define (service-error* message args)
(let ((e (make <service-error>
message: message
arguments: args)))
(display e)
(error e)))
| 4,197
|
https://github.com/raymundoxmartinez/ardio/blob/master/src/components/molecules/ExperienceCard/ExperienceCard.stories.tsx
|
Github Open Source
|
Open Source
|
MIT
| null |
ardio
|
raymundoxmartinez
|
TypeScript
|
Code
| 57
| 157
|
import * as React from "react"
import { storiesOf } from "@storybook/react"
import ExperienceCard from "./ExperienceCard"
import readme from "./docs.md"
storiesOf("ExperienceCard", module)
.addParameters({
readme: { content: readme },
options: {
theme: {},
},
})
.add("ExperienceCard", () => {
return (
<ExperienceCard
experience={{
image: "/mars2.jpeg",
title: "Mars",
description: "This is a trip to mars.",
}}
/>
)
})
| 50,510
|
https://github.com/zhouxh/pinkyLam-Blog-Server/blob/master/pinkyLam-service/src/main/java/com/pinkyLam/blog/dao/ArticleCateLabelDao.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,017
|
pinkyLam-Blog-Server
|
zhouxh
|
Java
|
Code
| 85
| 387
|
package com.pinkylam.blog.dao;
import java.util.List;
import javax.transaction.Transactional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import com.pinkylam.blog.entity.ArticleCateLabel;
/**
* @author Pinky Lam 908716835@qq.com
* @date 2017年7月14日 上午10:02:47
*/
@Repository
public interface ArticleCateLabelDao extends JpaRepository<ArticleCateLabel, Long> {
@Modifying(clearAutomatically = true)
@Transactional
@Query(nativeQuery = true, value = "DELETE FROM ARTICLE_CATE_LABEL WHERE ARTICLE_ID=:articleId")
int deleteArticleCateLabel(@Param("articleId") Long articleId);
@Modifying(clearAutomatically = true)
@Transactional
@Query(nativeQuery = true, value = "DELETE FROM ARTICLE_CATE_LABEL WHERE ARTICLE_ID=:articleId AND CATE_LABEL_ID NOT IN:cateLabelId")
int deleteArticleCateLabel(@Param("articleId") Long articleId, @Param("cateLabelId") List<Long> cateLabelIds);
public ArticleCateLabel findArticleCateLabelByCateLabelId(Long cateLabelId);
}
| 33,316
|
https://github.com/Skillshare/php-client/blob/master/src/SplitIO/Component/Http/Uri.php
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
php-client
|
Skillshare
|
PHP
|
Code
| 638
| 1,871
|
<?php
namespace SplitIO\Component\Http;
/**
* Basic URI parser implementation.
*
* @link https://github.com/guzzle/psr7/blob/master/src/Uri.php This class is based upon
* URI implementation in guzzlehttp/psr7.
*/
class Uri
{
private static $schemes = array(
'http' => 80,
'https' => 443,
);
private static $charUnreserved = 'a-zA-Z0-9_\-\.~';
private static $charSubDelims = '!\$&\'\(\)\*\+,;=';
private static $replaceQuery = array('=' => '%3D', '&' => '%26');
/** @var string Uri scheme. */
private $scheme = '';
/** @var string Uri user info. */
private $userInfo = '';
/** @var string Uri user info. */
private $user = '';
/** @var string Uri user info. */
private $pass = '';
/** @var string Uri host. */
private $host = '';
/** @var int|null Uri port. */
private $port;
/** @var string Uri path. */
private $path = '';
/** @var string Uri query string. */
private $query = '';
/** @var string Uri fragment. */
private $fragment = '';
/**
* @param string $uri URI to parse and wrap.
*/
public function __construct($uri = '')
{
if ($uri != null) {
$parts = parse_url($uri);
if ($parts === false) {
throw new \InvalidArgumentException("Unable to parse URI: $uri");
}
$this->applyParts($parts);
}
}
public function getScheme()
{
return $this->scheme;
}
public function getAuthority()
{
if (empty($this->host)) {
return '';
}
$authority = $this->host;
if (!empty($this->userInfo)) {
$authority = $this->userInfo . '@' . $authority;
}
if ($this->isNonStandardPort($this->scheme, $this->host, $this->port)) {
$authority .= ':' . $this->port;
}
return $authority;
}
public function getUserInfo()
{
return $this->userInfo;
}
public function getUser()
{
return $this->user;
}
public function getPass()
{
return $this->pass;
}
public function getHost()
{
return $this->host;
}
public function getPort()
{
return $this->port;
}
public function getPath()
{
return $this->path == null ? '' : $this->path;
}
public function getQuery()
{
return $this->query;
}
public function getFragment()
{
return $this->fragment;
}
/**
* Apply parse_url parts to a URI.
*
* @param $parts Array of parse_url parts to apply.
*/
private function applyParts(array $parts)
{
$this->scheme = isset($parts['scheme'])
? $this->filterScheme($parts['scheme'])
: '';
$this->userInfo = isset($parts['user']) ? $parts['user'] : '';
$this->user = isset($parts['user']) ? $parts['user'] : '';
$this->pass = isset($parts['pass']) ? $parts['pass'] : '';
$this->host = isset($parts['host']) ? $parts['host'] : '';
$this->port = !empty($parts['port'])
? $this->filterPort($this->scheme, $this->host, $parts['port'])
: null;
$this->path = isset($parts['path'])
? $this->filterPath($parts['path'])
: '';
$this->query = isset($parts['query'])
? $this->filterQueryAndFragment($parts['query'])
: '';
$this->fragment = isset($parts['fragment'])
? $this->filterQueryAndFragment($parts['fragment'])
: '';
if (isset($parts['pass'])) {
$this->userInfo .= ':' . $parts['pass'];
}
}
/**
* Is a given port non-standard for the current scheme?
*
* @param string $scheme
* @param string $host
* @param int $port
* @return bool
*/
private static function isNonStandardPort($scheme, $host, $port)
{
if (!$scheme && $port) {
return true;
}
if (!$host || !$port) {
return false;
}
return !isset(static::$schemes[$scheme]) || $port !== static::$schemes[$scheme];
}
/**
* @param string $scheme
*
* @return string
*/
private function filterScheme($scheme)
{
$scheme = strtolower($scheme);
$scheme = rtrim($scheme, ':/');
return $scheme;
}
/**
* @param string $scheme
* @param string $host
* @param int $port
*
* @return int|null
*
* @throws \InvalidArgumentException If the port is invalid.
*/
private function filterPort($scheme, $host, $port)
{
if (null !== $port) {
$port = (int) $port;
if (1 > $port || 0xffff < $port) {
throw new \InvalidArgumentException(
sprintf('Invalid port: %d. Must be between 1 and 65535', $port)
);
}
}
return $this->isNonStandardPort($scheme, $host, $port) ? $port : null;
}
/**
* Filters the path of a URI
*
* @param $path
*
* @return string
*/
private function filterPath($path)
{
return preg_replace_callback(
'/(?:[^' . self::$charUnreserved . self::$charSubDelims . ':@\/%]+|%(?![A-Fa-f0-9]{2}))/',
array($this, 'rawurlencodeMatchZero'),
$path
);
}
/**
* Filters the query string or fragment of a URI.
*
* @param $str
*
* @return string
*/
private function filterQueryAndFragment($str)
{
return preg_replace_callback(
'/(?:[^' . self::$charUnreserved . self::$charSubDelims . '%:@\/\?]+|%(?![A-Fa-f0-9]{2}))/',
array($this, 'rawurlencodeMatchZero'),
$str
);
}
private function rawurlencodeMatchZero(array $match)
{
return rawurlencode($match[0]);
}
}
| 17,405
|
https://github.com/forgottenlands/ForgottenCore406/blob/master/src/server/scripts/Northrend/ChamberOfAspects/RubySanctum/ruby_sanctum.h
|
Github Open Source
|
Open Source
|
OpenSSL
| 2,019
|
ForgottenCore406
|
forgottenlands
|
C
|
Code
| 439
| 1,700
|
/*
* Copyright (C) 2008 - 2012 TrinityCore <http://www.trinitycore.org/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef RUBY_SANCTUM_H_
#define RUBY_SANCTUM_H_
#include "SpellScript.h"
#include "Map.h"
#include "Creature.h"
#define RSScriptName "instance_ruby_sanctum"
uint32 const EncounterCount = 4;
Position const HalionControllerSpawnPos = {3156.037f, 533.2656f, 72.97205f, 0.0f};
enum DataTypes
{
// Encounter States/Boss GUIDs
DATA_BALTHARUS_THE_WARBORN = 0,
DATA_GENERAL_ZARITHRIAN = 1,
DATA_SAVIANA_RAGEFIRE = 2,
DATA_HALION = 3,
// Etc
DATA_TWILIGHT_HALION = 4,
DATA_XERESTRASZA = 5,
DATA_CRYSTAL_CHANNEL_TARGET = 6,
DATA_BALTHARUS_SHARED_HEALTH = 7,
DATA_ZARITHIAN_SPAWN_STALKER_1 = 8,
DATA_ZARITHIAN_SPAWN_STALKER_2 = 9,
DATA_HALION_CONTROLLER = 10,
DATA_HALION_SHARED_HEALTH = 11,
DATA_BURNING_TREE_1 = 12,
DATA_BURNING_TREE_2 = 13,
DATA_BURNING_TREE_3 = 14,
DATA_BURNING_TREE_4 = 15,
DATA_FLAME_RING = 16,
DATA_TWILIGHT_FLAME_RING = 17,
DATA_EXIT_PORTAL_1 = 18,
DATA_EXIT_PORTAL_2 = 19,
DATA_ENTER_PORTAL = 20,
};
enum SharedActions
{
ACTION_INTRO_BALTHARUS = -3975101,
ACTION_BALTHARUS_DEATH = -3975102,
ACTION_INTRO_HALION = -4014601,
};
enum CreaturesIds
{
// Baltharus the Warborn
NPC_BALTHARUS_THE_WARBORN = 39751,
NPC_BALTHARUS_THE_WARBORN_CLONE = 39899,
NPC_BALTHARUS_TARGET = 26712,
// General Zarithrian
NPC_GENERAL_ZARITHRIAN = 39746,
NPC_ONYX_FLAMECALLER = 39814,
NPC_ZARITHIAN_SPAWN_STALKER = 39794,
// Saviana Ragefire
NPC_SAVIANA_RAGEFIRE = 39747,
// Halion
NPC_HALION = 39863,
NPC_TWILIGHT_HALION = 40142,
NPC_HALION_CONTROLLER = 40146,
NPC_LIVING_INFERNO = 40681,
NPC_LIVING_EMBER = 40683,
NPC_ORB_CARRIER = 40081,
NPC_ORB_ROTATION_FOCUS = 40091,
NPC_SHADOW_ORB_N = 40083,
NPC_SHADOW_ORB_S = 40100,
NPC_SHADOW_ORB_E = 40468,
NPC_SHADOW_ORB_W = 40469,
NPC_METEOR_STRIKE_MARK = 40029,
NPC_METEOR_STRIKE_NORTH = 40041,
NPC_METEOR_STRIKE_EAST = 40042,
NPC_METEOR_STRIKE_WEST = 40043,
NPC_METEOR_STRIKE_SOUTH = 40044,
NPC_METEOR_STRIKE_FLAME = 40055,
NPC_COMBUSTION = 40001,
NPC_CONSUMPTION = 40135,
// Xerestrasza
NPC_XERESTRASZA = 40429,
};
enum GameObjectsIds
{
GO_HALION_PORTAL_1 = 202794, // Unknown spell 75074, should be somehow be linked to 74807
GO_HALION_PORTAL_2 = 202795, // Also spell 75074
GO_HALION_PORTAL_EXIT = 202796, // Leave Twilight Realm (74812)
GO_FIRE_FIELD = 203005,
GO_FLAME_WALLS = 203006,
GO_FLAME_RING = 203007,
GO_TWILIGHT_FLAME_RING = 203624,
GO_BURNING_TREE_1 = 203034,
GO_BURNING_TREE_2 = 203035,
GO_BURNING_TREE_3 = 203036,
GO_BURNING_TREE_4 = 203037,
};
enum WorldStatesRS
{
WORLDSTATE_CORPOREALITY_MATERIAL = 5049,
WORLDSTATE_CORPOREALITY_TWILIGHT = 5050,
WORLDSTATE_CORPOREALITY_TOGGLE = 5051,
};
enum InstanceSpell
{
SPELL_BERSERK = 26662,
SPELL_TWILIGHT_REALM = 74807,
};
template<class AI>
CreatureAI* GetRubySanctumAI(Creature* creature)
{
if (InstanceMap* instance = creature->GetMap()->ToInstanceMap())
if (instance->GetInstanceScript())
if (instance->GetScriptId() == sObjectMgr->GetScriptId(RSScriptName))
return new AI(creature);
return NULL;
}
#endif // RUBY_SANCTUM_H_
| 32,805
|
https://github.com/civicsource/sockettes/blob/master/test/stubs/index.js
|
Github Open Source
|
Open Source
|
MIT
| 2,016
|
sockettes
|
civicsource
|
JavaScript
|
Code
| 15
| 43
|
import crosstab from "./crosstab";
import websocket from "./websocket";
export default function() {
crosstab();
websocket();
}
| 32,802
|
https://github.com/libris/librisxl/blob/master/rest/src/main/groovy/whelk/rest/api/RestMetrics.groovy
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,023
|
librisxl
|
libris
|
Groovy
|
Code
| 125
| 572
|
package whelk.rest.api
import groovy.transform.CompileStatic
import io.prometheus.client.Counter
import io.prometheus.client.Gauge
import io.prometheus.client.Histogram
import io.prometheus.client.Summary
@CompileStatic
class RestMetrics {
static final Counter requests = Counter.build()
.name("api_requests_total").help("Total requests to API.")
.labelNames("method").register()
static final Counter failedRequests = Counter.build()
.name("api_failed_requests_total").help("Total failed requests to API.")
.labelNames("method", "status").register()
static final Gauge ongoingRequests = Gauge.build()
.name("api_ongoing_requests_total").help("Total ongoing API requests.")
.labelNames("method").register()
static final Summary requestsLatency = Summary.build()
.name("api_requests_latency_seconds")
.help("API request latency in seconds.")
.labelNames("method")
.quantile(0.5f, 0.05f)
.quantile(0.95f, 0.01f)
.quantile(0.99f, 0.001f)
.register()
static final Histogram requestsLatencyHistogram = Histogram.build()
.name("api_requests_latency_seconds_histogram").help("API request latency in seconds.")
.labelNames("method")
.register()
Measurement measure(String metricLabel) {
return new Measurement(metricLabel)
}
class Measurement {
String metricLabel
Summary.Timer requestTimer
Histogram.Timer requestTimer2
Measurement(String metricLabel) {
this.metricLabel = metricLabel
RestMetrics.this.requests.labels(metricLabel).inc()
RestMetrics.this.ongoingRequests.labels(metricLabel).inc()
requestTimer = requestsLatency.labels(metricLabel).startTimer()
requestTimer2 = requestsLatencyHistogram.labels(metricLabel).startTimer()
}
void complete() {
RestMetrics.this.ongoingRequests.labels(metricLabel).dec()
requestTimer.observeDuration()
requestTimer2.observeDuration()
}
}
}
| 19,898
|
https://github.com/rafrex/detect-passive-events/blob/master/src/__tests__/noPassiveSupport.test.ts
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
detect-passive-events
|
rafrex
|
TypeScript
|
Code
| 51
| 140
|
// mock needs be defined before import so the imported file uses the mock when it's executed
Object.defineProperty(window, 'addEventListener', {
value: jest.fn().mockImplementation((eventName, callback, useCapture) => {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const capture = Boolean(useCapture);
}),
});
import { supportsPassiveEvents } from '../index';
test("browser doesn't support passive events", () => {
expect(supportsPassiveEvents).toBe(false);
});
| 13,799
|
https://github.com/lcb/applicake/blob/master/appliapps/tpp/searchengines/modifications.py
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,016
|
applicake
|
lcb
|
Python
|
Code
| 862
| 3,141
|
import re
from string import Template
from Unimod.unimod import database
def genmodstr_to_engine(static_genmodstr, var_genmodstr, engine):
"""
Main method you should use this
Converts "generic" modification string into engine specific strings
unimod avg = mono * 1.001191917
@param static_genmodstr: generic mod string for static modifications to use
@param var_genmodstr: generic mod string for variable modifications to use
@param engine: search engine
@return: engine_specific_static_mod_string, engine_specific_variable_mod_string, template(omssa)
"""
if engine is "XTandem":
conv = XTandemModConverter()
elif engine is "Omssa":
conv = OmssaModConverter()
elif engine is "Myrimatch":
conv = MyrimatchModConverter()
elif engine is "Comet":
conv = CometModConverter()
else:
raise Exception("No converter found for engine " + engine)
try:
return conv.genmodstrs_to_engine(static_genmodstr, var_genmodstr)
except Exception, e:
raise Exception("Malformed modification string! " + e.message)
class AbstractModConverter(object):
def genmodstrs_to_engine(self, static_genmodstr, var_genmodstr):
"""
Method to overwrite in child classes. Is expected to convert generic modification strings to engine
specifig strings
@param static_genmodstr: generic mod string for static
@param var_genmodstr: generic mod string for variable
@return static_mods, var_mods, template(needed e.g. for omssa)
"""
raise NotImplementedError
def _get_nameresiduelist_from_modstr(self, modstr):
try:
p = re.compile("(.+) *\((.*)\)$")
m = p.match(modstr.strip())
rawname, rawresidues = m.group(1), m.group(2)
name = rawname.strip()
residues = list(rawresidues.replace(")", "").strip())
return name, residues
except Exception, e:
raise Exception("Malformed modification string '%s'. Should be 'Name (Residues)'" % modstr)
def _get_mass_from_unimod_or_string(self, key):
entry = database.get_label(key)
if entry:
return float(entry['delta_mono_mass']), float(entry['delta_avge_mass'])
else:
# if its not a unimod entry try to parse masses from name itself
try:
mm, am = key.split("/")
return float(mm), float(am)
except:
raise Exception(key + ": not found unimod and no valid mono/avg mass pair")
def _modstr_to_list(self, modstr):
modlist = []
for mod in modstr.split(";"):
# skip if empty ;;
if not mod:
continue
name, residuearr = self._get_nameresiduelist_from_modstr(mod)
mono, avg = self._get_mass_from_unimod_or_string(name)
modlist.append([name, mono, avg, residuearr])
return modlist
class XTandemModConverter(AbstractModConverter):
def genmodstrs_to_engine(self, static_genmodstr, var_genmodstr):
terminal_mods = ""
smods = []
for mod in self._modstr_to_list(static_genmodstr):
name, mono, avg, residues = mod
for residue in residues:
smods.append("%f@%s" % (mono, residue))
vmods = []
for mod in self._modstr_to_list(var_genmodstr):
name, mono, avg, residues = mod
for residue in residues:
#Peptide terminal modifications can be specified with the symbol '[' for N-terminus and ']' for C-terminus, such as 42.0@[ .
if residue == "n":
residue = "["
if residue == "c":
residue = "]"
vmods.append("%f@%s" % (mono, residue))
return ",".join(smods), ",".join(vmods), terminal_mods
class OmssaModConverter(AbstractModConverter):
__tplheader = """<?xml version="1.0"?>
<MSModSpecSet
xmlns="http://www.ncbi.nlm.nih.gov"
xmlns:xs="http://www.w3.org/2001/XMLSchema-instance"
xs:schemaLocation="http://www.ncbi.nlm.nih.gov OMSSA.xsd"
>"""
__tpl = """<MSModSpec>
<MSModSpec_mod>
<MSMod value="usermod$I">$NUM</MSMod>
</MSModSpec_mod>
<MSModSpec_type>
<MSModType value="modaa">0</MSModType>
</MSModSpec_type>
<MSModSpec_name>$NAME</MSModSpec_name>
<MSModSpec_monomass>$MONOMASS</MSModSpec_monomass>
<MSModSpec_averagemass>$AVGMASS</MSModSpec_averagemass>
<MSModSpec_n15mass>0</MSModSpec_n15mass>
<MSModSpec_residues>
<MSModSpec_residues_E>$RESIDUE</MSModSpec_residues_E>
</MSModSpec_residues>
</MSModSpec>"""
__tplNterm = """<MSModSpec>
<MSModSpec_mod>
<MSMod value="usermod$I">$NUM</MSMod>
</MSModSpec_mod>
<MSModSpec_type>
<MSModType value="modnp">5</MSModType>
</MSModSpec_type>
<MSModSpec_name>$NAME</MSModSpec_name>
<MSModSpec_monomass>$MONOMASS</MSModSpec_monomass>
<MSModSpec_averagemass>$AVGMASS</MSModSpec_averagemass>
<MSModSpec_n15mass>0</MSModSpec_n15mass>
</MSModSpec>"""
__tplCterm = """<MSModSpec>
<MSModSpec_mod>
<MSMod value="usermod$I">$NUM</MSMod>
</MSModSpec_mod>
<MSModSpec_type>
<MSModType value="modcp">7</MSModType>
</MSModSpec_type>
<MSModSpec_name>$NAME</MSModSpec_name>
<MSModSpec_monomass>$MONOMASS</MSModSpec_monomass>
<MSModSpec_averagemass>$AVGMASS</MSModSpec_averagemass>
<MSModSpec_n15mass>0</MSModSpec_n15mass>
</MSModSpec>"""
__tpltail = """</MSModSpecSet>"""
def genmodstrs_to_engine(self, static_genmodstr, var_genmodstr):
modtpl = self.__tplheader
i = 0
smods = []
for mod in self._modstr_to_list(static_genmodstr):
name, mono, avg, residues = mod
for res in residues:
i += 1
if i > 9:
raise Exception("For Omssa only up to 10 modifications are suported")
no = i + 118
smods.append(str(no))
dict_ = {"I": i, "NUM": no, "NAME": name, "MONOMASS": mono, "AVGMASS": avg, "RESIDUE": res}
modtpl += Template(self.__tpl).safe_substitute(dict_)
vmods = []
for mod in self._modstr_to_list(var_genmodstr):
name, mono, avg, residues = mod
for res in residues:
i += 1
if i > 9:
raise Exception("For Omssa only up to 10 modifications are suported")
no = i + 118
vmods.append(str(no))
dict_ = {"I": i, "NUM": no, "NAME": name, "MONOMASS": mono, "AVGMASS": avg, "RESIDUE": res}
if res == "n":
tpl = self.__tplNterm
elif res == "c":
tpl = self.__tplCterm
else:
tpl = self.__tpl
modtpl += Template(tpl).safe_substitute(dict_)
modtpl += self.__tpltail
return ",".join(smods), ",".join(vmods), modtpl
class MyrimatchModConverter(AbstractModConverter):
def genmodstrs_to_engine(self, static_genmodstr, var_genmodstr):
smods = []
for mod in self._modstr_to_list(static_genmodstr):
name, mono, avg, residues = mod
for residue in residues:
smods.append("%s %f" % (residue, mono))
vmods = []
for mod in self._modstr_to_list(var_genmodstr):
name, mono, avg, residues = mod
# special handling for n/c term modifications
# variableModifications += nTerm + aminoAcidsAtTarget + cTerm + " " + symbols[symbolsCounter++] + " " + tempPtm.getMass() + " ";
nTerm = ''
cTerm = ''
if 'n' in residues:
residues.remove('n')
nTerm = "("
if 'c' in residues:
residues.remove('c')
cTerm = ")"
middle = ""
if residues:
middle= "[%s]" % "".join(residues)
vmods.append("%s%s%s * %f" % (nTerm,middle,cTerm, mono))
return " ".join(smods), " ".join(vmods), None
class CometModConverter(AbstractModConverter):
__fullnames = {"A": "alanine", "C": "cysteine", "D": "aspartic_acid", "E": "glutamic_acid", "F": "phenylalanine",
"G": "glycine", "H": "histidine", "I": "isoleucine", "K": "lysine", "L": "leucine",
"M": "methionine", "N": "asparagine", "O": "ornithine", "P": "proline", "Q": "glutamine",
"R": "arginine", "S": "serine", "T": "threonine", "V": "valine", "W": "tryptophan",
"Y": "tyrosine"}
def genmodstrs_to_engine(self, static_genmodstr, var_genmodstr):
smods = ""
for mod in self._modstr_to_list(static_genmodstr):
name, mono, avg, residues = mod
for residue in residues:
try:
smods += "add_%s_%s = %f\n" % (residue, self.__fullnames[residue], mono)
except KeyError, e:
raise Exception("Residue " + e.message + " not known")
vmods = ""
i=0
for mod in self._modstr_to_list(var_genmodstr):
name, mono, avg, residues = mod
if 'n' in residues:
residues.remove('n')
vmods += "variable_N_terminus = %s\n" % mono
if 'c' in residues:
residues.remove('c')
vmods += "variable_C_terminus = %s\n" % mono
if not residues: continue
i+=1
if i > 6: raise Exception("Comet only supports up to 6 variable mods")
vmods += "variable_mod0%s = %f %s 0 3\n" % (i, mono, "".join(residues))
return smods, vmods, None
| 23,017
|
https://github.com/ungdev/UA-api/blob/master/src/controllers/admin/users/getCarts.ts
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
UA-api
|
ungdev
|
TypeScript
|
Code
| 196
| 505
|
import { NextFunction, Request, Response } from 'express';
import { fetchCarts } from '../../../operations/carts';
import { filterCartWithCartItemsAdmin } from '../../../utils/filters';
import { notFound, success } from '../../../utils/responses';
import { hasPermission } from '../../../middlewares/authentication';
import { fetchUser } from '../../../operations/user';
import { Error, Permission, ItemCategory } from '../../../types';
import { isPartnerSchool } from '../../../utils/helpers';
export default [
// Middlewares
...hasPermission(Permission.admin),
// Controller
async (request: Request, response: Response, next: NextFunction) => {
try {
const user = await fetchUser(request.params.userId);
if (!user) return notFound(response, Error.UserNotFound);
// Retrieve user carts. The boolean `true` is used to include the
// Cart#cartItems[x]#item property (and the details of the cartItem)
const carts = await fetchCarts(user.id, true);
const adminCarts = carts.map((cart) => ({
...cart,
// Compute the price of each cart. In order to do so, we check whether
// the bought item is a `ItemCategory.ticket` and whether the recipient
// is eligible for a discount
totalPrice: cart.cartItems
.map(
(cartItem) =>
(cartItem.item.category === ItemCategory.ticket &&
cartItem.item.reducedPrice &&
isPartnerSchool(cartItem.forUser.email)
? cartItem.item.reducedPrice
: cartItem.item.price) * cartItem.quantity,
)
.reduce((price1, price2) => price1 + price2, 0),
}));
// Then we filter the object to reduce output
return success(response, adminCarts.map(filterCartWithCartItemsAdmin));
} catch (error) {
return next(error);
}
},
];
| 27,714
|
https://github.com/sampanu/DC-ILR-1819-ValidationService/blob/master/src/ESFA.DC.ILR.ValidationService.Rules.Tests/Learner/ULN/ULN_02RuleTests.cs
|
Github Open Source
|
Open Source
|
MIT
| null |
DC-ILR-1819-ValidationService
|
sampanu
|
C#
|
Code
| 390
| 2,081
|
using System;
using System.Collections.Generic;
using System.Linq;
using ESFA.DC.ILR.Tests.Model;
using ESFA.DC.ILR.ValidationService.Interface;
using ESFA.DC.ILR.ValidationService.Rules.Constants;
using ESFA.DC.ILR.ValidationService.Rules.Learner.ULN;
using ESFA.DC.ILR.ValidationService.Rules.Query.Interface;
using ESFA.DC.ILR.ValidationService.Rules.Tests.Abstract;
using FluentAssertions;
using Moq;
using Xunit;
namespace ESFA.DC.ILR.ValidationService.Rules.Tests.Learner.ULN
{
public class ULN_02RuleTests : AbstractRuleTests<ULN_02Rule>
{
[Fact]
public void RuleName()
{
NewRule().RuleName.Should().Be("ULN_02");
}
[Fact]
public void LearningDeliveryFAMConditionMet_False()
{
var learningDeliveryFAMs = new List<TestLearningDeliveryFAM>
{
new TestLearningDeliveryFAM
{
LearnDelFAMType = "SOF",
LearnDelFAMCode = "1"
}
};
var learningDeliveryFAMQueryServiceMock = new Mock<ILearningDeliveryFAMQueryService>();
learningDeliveryFAMQueryServiceMock.Setup(qs => qs.HasLearningDeliveryFAMCodeForType(learningDeliveryFAMs, "SOF", "1")).Returns(true);
NewRule(learningDeliveryFAMQueryServiceMock.Object).LearningDeliveryFAMConditionMet(learningDeliveryFAMs).Should().BeFalse();
}
[Fact]
public void LearningDeliveryFAMConditionMet_True()
{
var learningDeliveryFAMs = new List<TestLearningDeliveryFAM>
{
new TestLearningDeliveryFAM
{
LearnDelFAMType = "ACT",
LearnDelFAMCode = "1"
}
};
var learningDeliveryFAMQueryServiceMock = new Mock<ILearningDeliveryFAMQueryService>();
learningDeliveryFAMQueryServiceMock.Setup(qs => qs.HasLearningDeliveryFAMCodeForType(learningDeliveryFAMs, "SOF", "1")).Returns(false);
NewRule(learningDeliveryFAMQueryServiceMock.Object).LearningDeliveryFAMConditionMet(learningDeliveryFAMs).Should().BeTrue();
}
[Fact]
public void ULNConditionMet_False_FundModel()
{
NewRule().ULNConditionMet(35, ValidationConstants.TemporaryULN).Should().BeFalse();
}
[Fact]
public void ULNConditionMet_False_ULN()
{
NewRule().ULNConditionMet(10, 123456789).Should().BeFalse();
}
[Fact]
public void ULNConditionMet_True()
{
NewRule().ULNConditionMet(10, ValidationConstants.TemporaryULN).Should().BeTrue();
}
[Theory]
[InlineData(35, ValidationConstants.TemporaryULN, "SOF")]
[InlineData(10, 123456789, "SOF")]
[InlineData(10, ValidationConstants.TemporaryULN, "ACT")]
public void ConditionMet_False(int fundModel, long uln, string famType)
{
var learningDeliveryFAMs = new List<TestLearningDeliveryFAM>
{
new TestLearningDeliveryFAM
{
LearnDelFAMType = famType,
LearnDelFAMCode = "1"
}
};
var learningDeliveryFAMQueryServiceMock = new Mock<ILearningDeliveryFAMQueryService>();
learningDeliveryFAMQueryServiceMock.Setup(qs => qs.HasLearningDeliveryFAMCodeForType(learningDeliveryFAMs, "SOF", "1")).Returns(true);
NewRule(learningDeliveryFAMQueryServiceMock.Object).ConditionMet(fundModel, uln, learningDeliveryFAMs).Should().BeFalse();
}
[Fact]
public void ConditionMet_True()
{
var learningDeliveryFAMs = new List<TestLearningDeliveryFAM>
{
new TestLearningDeliveryFAM
{
LearnDelFAMType = "ACT",
LearnDelFAMCode = "1"
}
};
var learningDeliveryFAMQueryServiceMock = new Mock<ILearningDeliveryFAMQueryService>();
learningDeliveryFAMQueryServiceMock.Setup(qs => qs.HasLearningDeliveryFAMCodeForType(learningDeliveryFAMs, "SOF", "1")).Returns(false);
NewRule(learningDeliveryFAMQueryServiceMock.Object).ConditionMet(10, ValidationConstants.TemporaryULN, learningDeliveryFAMs).Should().BeTrue();
}
[Fact]
public void Validate_NoErrors()
{
var learner = new TestLearner()
{
ULN = 9999999999,
LearningDeliveries = new TestLearningDelivery[]
{
new TestLearningDelivery()
{
FundModel = 10,
LearningDeliveryFAMs = new List<TestLearningDeliveryFAM>
{
new TestLearningDeliveryFAM
{
LearnDelFAMType = "SOF",
LearnDelFAMCode = "1"
}
}
},
}
};
var fams = learner.LearningDeliveries.SelectMany(ld => ld.LearningDeliveryFAMs);
var learningDeliveryFAMQueryServiceMock = new Mock<ILearningDeliveryFAMQueryService>();
learningDeliveryFAMQueryServiceMock.Setup(qs => qs.HasLearningDeliveryFAMCodeForType(fams, "SOF", "1")).Returns(true);
using (var validationErrorHandlerMock = BuildValidationErrorHandlerMockForNoError())
{
NewRule(learningDeliveryFAMQueryServiceMock.Object, validationErrorHandlerMock.Object).Validate(learner);
}
}
[Fact]
public void Validate_Error()
{
var learner = new TestLearner()
{
ULN = 9999999999,
LearningDeliveries = new TestLearningDelivery[]
{
new TestLearningDelivery()
{
FundModel = 10,
LearningDeliveryFAMs = new List<TestLearningDeliveryFAM>
{
new TestLearningDeliveryFAM
{
LearnDelFAMType = "ACT",
LearnDelFAMCode = "1"
}
}
},
}
};
var learningDeliveryFAMQueryServiceMock = new Mock<ILearningDeliveryFAMQueryService>();
learningDeliveryFAMQueryServiceMock.Setup(qs => qs.HasLearningDeliveryFAMCodeForType(learner.LearningDeliveries.SelectMany(ld => ld.LearningDeliveryFAMs), "SOF", "1")).Returns(false);
using (var validationErrorHandlerMock = BuildValidationErrorHandlerMockForError())
{
NewRule(learningDeliveryFAMQueryServiceMock.Object, validationErrorHandlerMock.Object).Validate(learner);
}
}
[Fact]
public void BuildErrorMessageParameters()
{
var validationErrorHandlerMock = new Mock<IValidationErrorHandler>();
validationErrorHandlerMock.Setup(veh => veh.BuildErrorMessageParameter("ULN", (long)1234567890)).Verifiable();
NewRule(validationErrorHandler: validationErrorHandlerMock.Object).BuildErrorMessageParameters(1234567890);
validationErrorHandlerMock.Verify();
}
private ULN_02Rule NewRule(ILearningDeliveryFAMQueryService learningDeliveryFAMQueryService = null, IValidationErrorHandler validationErrorHandler = null)
{
return new ULN_02Rule(learningDeliveryFAMQueryService, validationErrorHandler);
}
}
}
| 31,747
|
https://github.com/crackersamdjam/DMOJ-Solutions/blob/master/Uncategorized/joi14op6.cpp
|
Github Open Source
|
Open Source
|
MIT
| null |
DMOJ-Solutions
|
crackersamdjam
|
C++
|
Code
| 184
| 741
|
#ifdef ONLINE_JUDGE
#include "secret.h"
#endif
#include <bits/stdc++.h>
#define gc getchar_unlocked()
#define pc(x) putchar_unlocked(x)
template<typename T> void scan(T &x) {x = 0;register bool _=0;register T c=gc;_=c==45;c=_?gc:c;while(c<48||c>57)c=gc;for(;c<48||c>57;c=gc);for(;c>47&&c<58;c=gc)x=(x<<3)+(x<<1)+(c&15);x=_?-x:x;}
template<typename T> void print(T n) {register bool _=0;_=n<0;n=_?-n:n;char snum[65];int i=0;do{snum[i++]=n%10+48;n/= 10;}while(n);--i;if (_)pc(45);while(i>=0)pc(snum[i--]);pc(10);}
template<typename First, typename ... Ints>
void scan(First &arg, Ints&... rest) {scan(arg);scan(rest...);}
using namespace std;
const int MM = 1001;
int ans[MM][MM];
#ifndef ONLINE_JUDGE
int Secret(int a, int b){
return a+b;
}
#endif
int Query(int a, int b){
if(a == b)
return ans[a][a];
for(int i = a; i < b; i++){
if(ans[a][i] != -1 and ans[i+1][b] != -1)
return Secret(ans[a][i], ans[i+1][b]);
}
}
void make(int l, int r){
if(l == r)
return;
int m = (l+r)/2;
for(int i = m-1; i >= l; i--)
ans[i][m] = Secret(ans[i][i], ans[i+1][m]);
for(int i = m+2; i <= r; i++)
ans[m+1][i] = Secret(ans[m+1][i-1], ans[i][i]);
make(l, m);
make(m+1, r);
}
void Init(int n, int a[]){
memset(ans, -1, sizeof ans);
for(int i = 0; i < n; i++)
ans[i][i] = a[i];
make(0, n-1);
}
#ifndef ONLINE_JUDGE
int main(){
int ina[] = {1,2,3,4,5};
Init(5, ina);
print(Query(0, 1));
print(Query(1, 2));
print(Query(0, 2));
return 0;
}
#endif
| 5,485
|
https://github.com/ContextMapper/context-map-discovery/blob/master/src/main/java/org/contextmapper/discovery/strategies/boundedcontexts/OASBoundedContextDiscoveryStrategy.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,022
|
context-map-discovery
|
ContextMapper
|
Java
|
Code
| 753
| 2,689
|
/*
* Copyright 2020 The Context Mapper Project Team
*
* 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.contextmapper.discovery.strategies.boundedcontexts;
import com.google.common.collect.Sets;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.Operation;
import io.swagger.v3.oas.models.PathItem;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.Content;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.responses.ApiResponse;
import io.swagger.v3.parser.OpenAPIV3Parser;
import io.swagger.v3.parser.core.models.ParseOptions;
import io.swagger.v3.parser.models.RefType;
import org.contextmapper.discovery.cml.CMLPrimitiveTypeMapper;
import org.contextmapper.discovery.model.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* Discovers Bounded Contexts with OpenAPI specifications as input.
*
* @author Stefan Kapferer
*/
public class OASBoundedContextDiscoveryStrategy implements BoundedContextDiscoveryStrategy {
private static Logger LOG = LoggerFactory.getLogger(OASBoundedContextDiscoveryStrategy.class);
private static final String JSON_MEDIA_TYPE = "application/json";
private Set<String> oasLocations;
private CMLPrimitiveTypeMapper typeMapper;
private Map<Aggregate, Map<String, DomainObject>> domainObjectMap;
private OpenAPI currentOAS;
public OASBoundedContextDiscoveryStrategy(String... oasLocations) {
this.oasLocations = Sets.newHashSet(oasLocations);
this.typeMapper = new CMLPrimitiveTypeMapper();
this.domainObjectMap = new HashMap<>();
}
@Override
public Set<BoundedContext> discoverBoundedContexts() {
var boundedContexts = Sets.<BoundedContext>newHashSet();
for (String location : this.oasLocations) {
var parseResult = new OpenAPIV3Parser().readLocation(location, null, new ParseOptions());
if (!parseResult.getMessages().isEmpty())
LOG.error("Parsing the OAS '" + location + "' resulted in validation errors: " + String.join(", ", parseResult.getMessages()));
currentOAS = parseResult.getOpenAPI();
if (currentOAS == null)
throw new RuntimeException("Could not successfully parse OAS!");
boundedContexts.add(discoverBoundedContext(currentOAS));
}
return boundedContexts;
}
private BoundedContext discoverBoundedContext(OpenAPI oas) {
var bc = new BoundedContext(oas.getInfo().getTitle());
for (Map.Entry<String, PathItem> entry : oas.getPaths().entrySet()) {
bc.addAggregate(discoverAggregate(entry.getKey(), entry.getValue()));
}
return bc;
}
private Aggregate discoverAggregate(String pathItemKey, PathItem pathItem) {
var aggregateName = pathItemKey.substring(1).replace("/", "_"); // path key must start with '/'!
var aggregate = new Aggregate(aggregateName);
aggregate.setDiscoveryComment(pathItem.getSummary());
var service = new Service(aggregateName + "Service");
service.setDiscoveryComment("This service contains all operations of the following endpoint: " + pathItemKey);
aggregate.addService(service);
addOperationToService(service, discoverOperation(aggregate, pathItem.getGet()));
addOperationToService(service, discoverOperation(aggregate, pathItem.getPut()));
addOperationToService(service, discoverOperation(aggregate, pathItem.getPost()));
addOperationToService(service, discoverOperation(aggregate, pathItem.getDelete()));
addOperationToService(service, discoverOperation(aggregate, pathItem.getOptions()));
addOperationToService(service, discoverOperation(aggregate, pathItem.getHead()));
addOperationToService(service, discoverOperation(aggregate, pathItem.getPatch()));
addOperationToService(service, discoverOperation(aggregate, pathItem.getTrace()));
return aggregate;
}
private void addOperationToService(Service service, Method operation) {
if (operation != null)
service.addOperation(operation);
}
private Method discoverOperation(Aggregate aggregate, Operation oasOperation) {
if (oasOperation == null || oasOperation.getOperationId() == null || "".equals(oasOperation.getOperationId()))
return null;
var operation = new Method(oasOperation.getOperationId());
// parameters
if (oasOperation.getParameters() != null) {
for (io.swagger.v3.oas.models.parameters.Parameter parameter : oasOperation.getParameters()) {
operation.addParameter(discoverParameter(aggregate, parameter));
}
}
// request body
if (oasOperation.getRequestBody() != null && oasOperation.getRequestBody().getContent() != null &&
oasOperation.getRequestBody().getContent().containsKey(JSON_MEDIA_TYPE)) {
operation.addParameter(new Parameter("input",
createType4JSONContent(oasOperation.getRequestBody().getContent(), aggregate,
formatTypeName(oasOperation.getOperationId() + "ParameterType"))));
}
// return type (currently an endpoint can only have one response, otherwise we do not discover)
if (oasOperation.getResponses() != null && oasOperation.getResponses().size() == 1) {
String responseKey = oasOperation.getResponses().keySet().iterator().next();
ApiResponse response = oasOperation.getResponses().get(responseKey);
// we currently only support json; TODO: implement more generic solution
if (response.getContent() != null && response.getContent().containsKey(JSON_MEDIA_TYPE))
operation.setReturnType(createType4JSONContent(response.getContent(), aggregate, oasOperation.getOperationId() + "ReturnType"));
}
return operation;
}
private Parameter discoverParameter(Aggregate aggregate, io.swagger.v3.oas.models.parameters.Parameter oasParameter) {
var schema = oasParameter.getSchema();
if (isRefSchema(schema))
schema = resolveSchemaByRef(schema.get$ref());
return new Parameter(oasParameter.getName(), createType4Schema(aggregate, schema, oasParameter.getName() + "Type"));
}
private Type createType4JSONContent(Content content, Aggregate aggregate, String inputTypeName) {
Schema schema = content.get(JSON_MEDIA_TYPE).getSchema();
var typeName = inputTypeName;
if (isRefSchema(schema)) {
typeName = getTypeNameFromSchemaRef(schema.get$ref());
schema = resolveSchemaByRef(schema.get$ref());
}
return createType4Schema(aggregate, schema, typeName);
}
private Type createType4Schema(Aggregate aggregate, Schema inputSchema, String inputTypeName) {
var schema = inputSchema;
var typeName = inputTypeName;
if (isRefSchema(schema)) {
typeName = getTypeNameFromSchemaRef(schema.get$ref());
schema = resolveSchemaByRef(schema.get$ref());
}
switch (schema.getType()) {
case "object":
DomainObject object = createEntity4Schema(aggregate, formatTypeName(typeName), schema);
return new Type(object);
case "array":
ArraySchema arraySchema = (ArraySchema) schema;
Type type = createType4Schema(aggregate, arraySchema.getItems(), typeName);
type.setCollectionType("List");
return type;
default:
return new Type(typeMapper.mapType(schema.getType()));
}
}
private DomainObject createEntity4Schema(Aggregate aggregate, String objectName, Schema objectSchema) {
if (!domainObjectMap.containsKey(aggregate))
domainObjectMap.put(aggregate, new HashMap<>());
// don't create a new object, if an entity with that name already exists
if (domainObjectMap.get(aggregate).containsKey(objectName))
return domainObjectMap.get(aggregate).get(objectName);
// create entity
var domainObject = new DomainObject(DomainObjectType.ENTITY, objectName);
for (String propertyKey : (Set<String>) objectSchema.getProperties().keySet()) {
var property = (Schema) objectSchema.getProperties().get(propertyKey);
if (isRefSchema(property))
property = resolveSchemaByRef(property.get$ref());
Type type = null;
switch (property.getType()) {
case "object":
type = new Type(createEntity4Schema(aggregate, formatTypeName(propertyKey + "Type"), property));
break;
default:
type = new Type(typeMapper.mapType(property.getType()));
}
domainObject.addAttribute(new Attribute(type, propertyKey));
}
aggregate.addDomainObject(domainObject);
domainObjectMap.get(aggregate).put(objectName, domainObject);
return domainObject;
}
private String formatTypeName(String typeName) {
return typeName.substring(0, 1).toUpperCase() + (typeName.length() > 1 ? typeName.substring(1) : "");
}
private boolean isRefSchema(Schema schema) {
return schema.get$ref() != null && !"".equals(schema.get$ref());
}
private Schema resolveSchemaByRef(String ref) {
return currentOAS.getComponents().getSchemas().get(getTypeNameFromSchemaRef(ref));
}
private String getTypeNameFromSchemaRef(String ref) {
return ref.replace(RefType.SCHEMAS.getInternalPrefix(), "");
}
}
| 49,496
|
https://github.com/GentlemanMC/yoinkhack/blob/master/src/main/java/cat/yoink/yoinkhack/api/waypoint/Waypoint.java
|
Github Open Source
|
Open Source
|
WTFPL
| 2,021
|
yoinkhack
|
GentlemanMC
|
Java
|
Code
| 483
| 2,147
|
package cat.yoink.yoinkhack.api.waypoint;
import cat.yoink.yoinkhack.Client;
import cat.yoink.yoinkhack.api.util.RenderUtil;
import cat.yoink.yoinkhack.api.util.font.FontUtil;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.BufferBuilder;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.Vec3d;
import java.awt.*;
/**
* @author yoink
* @since 8/28/2020
*/
public class Waypoint
{
private final Minecraft mc = Minecraft.getMinecraft();
private final float x;
private final float y;
private final float z;
private final String name;
private final int dimension;
private final String ip;
private float hue;
public Waypoint(float x, float y, float z, String name, int dimension, String ip)
{
this.x = x;
this.y = y;
this.z = z;
this.name = name;
this.dimension = dimension;
this.ip = ip;
hue = 0f;
}
public void renderBox()
{
if (mc.isIntegratedServerRunning() || ip.equals("Singleplayer"))
{
rBox();
}
else
{
if (mc.getCurrentServerData() == null) return;
if (mc.getCurrentServerData().serverIP.equalsIgnoreCase(ip) && mc.player.dimension == dimension) rBox();
}
}
public void renderTag()
{
if (mc.isIntegratedServerRunning() || ip.equals("Singleplayer"))
{
rTag();
}
else
{
if (mc.getCurrentServerData() == null) return;
if (mc.getCurrentServerData().serverIP.equalsIgnoreCase(ip) && mc.player.dimension == dimension) rTag();
}
}
private void rBox()
{
hue += Client.INSTANCE.settingManager.getSettingEasy("Waypoints", 8).getIntValue() / 1000f;
int rgb = Color.HSBtoRGB(hue, 1.0F, 1.0F);
int r = rgb >> 16 & 255;
int g = rgb >> 8 & 255;
int b = rgb & 255;
AxisAlignedBB axisAlignedBB = new AxisAlignedBB(x - 0.38f - mc.getRenderManager().viewerPosX, y - mc.getRenderManager().viewerPosY, z - 0.38f - mc.getRenderManager().viewerPosZ, x + 0.38f - mc.getRenderManager().viewerPosX, y + 1.97f - mc.getRenderManager().viewerPosY, z + 0.38f - mc.getRenderManager().viewerPosZ);
if (Client.INSTANCE.settingManager.getSettingEasy("Waypoints", 3).getEnumValue().equals("Rainbow"))
{
RenderUtil.drawBox(axisAlignedBB, r / 255f, g / 255f, b / 255f, Client.INSTANCE.settingManager.getSettingEasy("Waypoints", 7).getIntValue() / 255f);
}
else
{
RenderUtil.drawBox(axisAlignedBB, Client.INSTANCE.settingManager.getSettingEasy("Waypoints", 4).getIntValue() / 255f, Client.INSTANCE.settingManager.getSettingEasy("Waypoints", 5).getIntValue() / 255f, Client.INSTANCE.settingManager.getSettingEasy("Waypoints", 6).getIntValue() / 255f, Client.INSTANCE.settingManager.getSettingEasy("Waypoints", 7).getIntValue() / 255f);
}
}
private void rTag()
{
String display = name;
GlStateManager.pushMatrix();
GlStateManager.translate(x - mc.getRenderManager().viewerPosX, y + 2.3f - mc.getRenderManager().viewerPosY, z - mc.getRenderManager().viewerPosZ);
GlStateManager.glNormal3f(0.0F, 1.0F, 0.0F);
GlStateManager.rotate(-mc.getRenderManager().playerViewY, 0.0F, 1.0F, 0.0F);
GlStateManager.rotate((float) ((mc.getRenderManager().options.thirdPersonView == 2) ? -1 : 1) * mc.getRenderManager().playerViewX, 1.0F, 0.0F, 0.0F);
float f = (float) (new Vec3d(mc.getRenderManager().viewerPosX, mc.getRenderManager().viewerPosY, mc.getRenderManager().viewerPosZ)).distanceTo(new Vec3d(x, y + 2.3, z));
if (f < 2) f = 2;
float m = (f / 8f) * (float) (Math.pow(1.2589254f, 3.3));
GlStateManager.scale(m, m, m);
GlStateManager.scale(-0.025F, -0.025F, 0.025F);
GlStateManager.disableLighting();
GlStateManager.depthMask(false);
GlStateManager.disableDepth();
GlStateManager.tryBlendFuncSeparate(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA, GlStateManager.SourceFactor.ONE, GlStateManager.DestFactor.ZERO);
if (Client.INSTANCE.settingManager.getSettingEasy("Waypoints", 2).getBoolValue())
{
display += String.format(" \u00A77%d %d %d", Math.round(x), Math.round(y), Math.round(z));
}
int i = FontUtil.getStringWidth(display) / 2;
GlStateManager.disableTexture2D();
Tessellator tessellator = Tessellator.getInstance();
BufferBuilder bufferbuilder = tessellator.getBuffer();
bufferbuilder.begin(7, DefaultVertexFormats.POSITION_COLOR);
bufferbuilder.pos(-i - 1, -1, 0.0D).color(0.0F, 0.0F, 0.0F, 0.25F).endVertex();
bufferbuilder.pos(-i - 1, 8, 0.0D).color(0.0F, 0.0F, 0.0F, 0.25F).endVertex();
bufferbuilder.pos(i + 1, 8, 0.0D).color(0.0F, 0.0F, 0.0F, 0.25F).endVertex();
bufferbuilder.pos(i + 1, -1, 0.0D).color(0.0F, 0.0F, 0.0F, 0.25F).endVertex();
tessellator.draw();
GlStateManager.enableTexture2D();
FontUtil.drawString(display, -FontUtil.getStringWidth(display) / 2f, 0, 553648127);
GlStateManager.enableDepth();
GlStateManager.depthMask(true);
FontUtil.drawString(display, -FontUtil.getStringWidth(display) / 2f, 0, -1);
GlStateManager.enableLighting();
GlStateManager.depthMask(true);
GlStateManager.disableBlend();
GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F);
GlStateManager.popMatrix();
}
public float getX()
{
return x;
}
public float getY()
{
return y;
}
public float getZ()
{
return z;
}
public String getName()
{
return name;
}
public int getDimension()
{
return dimension;
}
public String getIp()
{
return ip;
}
}
| 26,716
|
https://github.com/xsrust/rails/blob/master/lib/translation.rb
|
Github Open Source
|
Open Source
|
LicenseRef-scancode-unknown-license-reference, MIT
| 2,019
|
rails
|
xsrust
|
Ruby
|
Code
| 243
| 1,065
|
require 'net/http'
module TranslationIO
GETTEXT_METHODS = [
:nsgettext, :pgettext, :npgettext, :sgettext, :ngettext, :gettext,
:np_, :ns_, :Nn_, :n_, :p_, :s_, :N_, :_
]
TEXT_DOMAIN = 'app'
end
require 'translation_io/config'
require 'translation_io/railtie'
require 'translation_io/client'
require 'translation_io/flat_hash'
require 'translation_io/yaml_conversion'
require 'translation_io/controller'
require 'translation_io/extractor'
require 'translation_io/yaml_entry'
module TranslationIO
module Proxy
end
class << self
attr_reader :config
attr_accessor :client
def configure(&block)
ENV['LANG'] = 'en_US.UTF-8' if ENV['LANG'].blank?
@config ||= Config.new
yield @config
# setup for default config (aka should work the same but avoid app/views/branded)
@config.set_domain(@config.domains.nil? ? nil : @config.domains.first)
unless @config.disable_gettext
require_gettext_dependencies
add_missing_locales
add_parser_for_erb_source_formats(@config.erb_source_formats)
if Rails.env.development?
GetText::TextDomainManager.cached = false
end
# include is private until Ruby 2.1
Proxy.send(:include, GetText)
if @config.domains.nil?
Proxy.bindtextdomain(@config.text_domain, {
:path => @config.locales_path,
:output_charset => @config.charset
})
else
@config.domains.each do |domain|
Proxy.bindtextdomain(domain[:name], {
path: @config.locales_path,
output_charset: @config.charset
})
end
end
Proxy.textdomain(@config.text_domain)
Object.delegate *GETTEXT_METHODS, :to => Proxy
end
@client = Client.new(@config.api_key, @config.endpoint)
return true
end
def require_gettext_dependencies
require 'gettext'
require 'gettext/po'
require 'gettext/po_parser'
require 'gettext/tools'
require 'gettext/text_domain_manager'
require 'gettext/tools/xgettext'
end
# Missing languages from Locale that are in Translation.io
def add_missing_locales
Locale::Info.three_languages['wee'] = Locale::Info::Language.new('', 'wee', 'I', 'L', 'Lower Sorbian')
Locale::Info.three_languages['wen'] = Locale::Info::Language.new('', 'wen', 'I', 'L', 'Upper Sorbian')
end
def add_parser_for_erb_source_formats(new_erb_formats)
existing_extensions = GetText::ErbParser.instance_variable_get("@config")[:extnames]
new_extensions = new_erb_formats.collect { |ext| ".#{ext}" }
GetText::ErbParser.instance_variable_get("@config")[:extnames] = (existing_extensions + new_extensions).uniq
end
def info(message, level = 0, verbose_level = 0)
verbose = @config.try(:verbose) || 0
if verbose >= verbose_level
indent = (1..level).to_a.collect { " " }.join('')
puts "#{indent}* #{message}"
end
end
def normalize_path(relative_or_absolute_path)
File.expand_path(relative_or_absolute_path).gsub("#{Dir.pwd}/", '')
end
def version
Gem::Specification::find_by_name('translation').version.to_s
end
end
end
| 22,676
|
https://github.com/justin-zimmermann/ctr4ever-Data-Analysis/blob/master/data/log_records/2011/610.php
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
ctr4ever-Data-Analysis
|
justin-zimmermann
|
PHP
|
Code
| 69
| 294
|
<?php echo "Vous n'avez pas la permission d'accéder à cette page"; exit(); ?>
46.105.196.7 2011-12-26 15 1'25''06
46.105.196.7 2011-12-26 16 27''53
46.105.196.7 2011-12-26 3 1'12''90
46.105.196.7 2011-12-26 9 1'55''37
46.105.196.7 2011-12-26 10 37''38
46.105.196.7 2011-12-26 29 2'09''83
46.105.196.7 2011-12-26 32 41''79
46.105.196.7 2011-12-26 27 2'04''58
46.105.196.7 2011-12-26 17 1'15''31
46.105.196.7 2011-12-31 21 2'05''00
46.105.196.7 2011-12-31 17 1'14''32
46.105.196.7 2011-12-31 13 1'41''31
46.105.196.7 2011-12-31 14 33''27
46.105.196.7 2011-12-31 5 1'31''92
| 1,646
|
https://github.com/Dazmen/portfolio/blob/master/src/components/projectCard.js
|
Github Open Source
|
Open Source
|
MIT
| null |
portfolio
|
Dazmen
|
JavaScript
|
Code
| 259
| 955
|
import React from 'react';
import styled from 'styled-components';
// icon imports
import { makeStyles } from '@material-ui/core/styles';
import GroupIcon from '@material-ui/icons/Group';
import PersonIcon from '@material-ui/icons/Person';
import GitHubIcon from '@material-ui/icons/GitHub';
import LinkIcon from '@material-ui/icons/Link';
const ProjectCard = ({ project }) => {
const classes = useStyles();
return (
<Card>
<ImgContainer>
<img src={project.picture} alt='project preview' style={{maxWidth:'100%'}}/>
</ImgContainer>
<TextContainer>
<TitleCont>
<H2>{project.title}</H2>
{project.solo ? <PersonIcon className={classes.icon}/> : <GroupIcon className={classes.icon}/>}
</TitleCont>
<p style={{color:'#CAC5C2'}}>{project.description}</p>
<p style={{color:'#00ff01'}}>{project.techStack}</p>
<ul>
{project.bulletPoints.map((bullet, i) => {
return <li style={{color:'white'}} key={i}>{bullet}</li>
})}
</ul>
<IconCont>
<a href={project.gitLink} target='_blank' rel='noopener noreferrer'>
<GitHubIcon className={classes.iconLink}/>
</a>
<a href={project.deployLink} target='_blank' rel='noopener noreferrer'>
<LinkIcon className={classes.iconLink} />
</a>
</IconCont>
</TextContainer>
</Card>
)
};
export default ProjectCard;
const TitleCont = styled.div`
width: 100%;
text-align: center;
display: flex;
align-items: center;
justify-content: center;
`;
const H2 = styled.h2`
display: inline-block;
color: #00ff01;
margin: 0;
`;
const ImgContainer = styled.div`
width: 40%;
display:flex;
align-items: center;
@media(max-width: 1000px){
width: 60%;
}
@media(max-width: 700px){
width: 80%;
}
`;
const Card = styled.div`
width: 100%;
display: flex;
justify-content: space-around;
margin: 40px 0;
@media(max-width: 1000px){
flex-direction: column-reverse;
align-items: center;
}
`;
const TextContainer = styled.div`
width: 40%;
font-size: 18px;
@media(max-width: 1000px){
width: 60%;
margin: 0 0 30px 0;
}
@media(max-width: 700px){
width: 80%;
}
`;
const IconCont = styled.div`
display: flex;
justify-content: space-evenly;
flex-wrap: wrap;
width: 100%;
padding: 10px 0;
@media (max-width: 1100px){
width: 60%;
margin: 0 auto;
}
@media (max-width: 800px){
width: 80%;
}
`;
const useStyles = makeStyles((theme) => ({
icon: {
width: 30,
height: 30,
margin: '0px 0px 0px 20px;',
color: '#CAC5C2'
},
iconLink: {
width: 30,
height: 30,
color: '#00ff01'
}
}));
| 32,449
|
https://github.com/massx1/syncope/blob/master/client/cli/src/main/java/org/apache/syncope/client/cli/commands/EntitlementCommand.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
syncope
|
massx1
|
Java
|
Code
| 282
| 729
|
/*
* 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.syncope.client.cli.commands;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.Parameters;
import org.apache.syncope.client.cli.SyncopeServices;
import org.apache.syncope.common.lib.wrap.EntitlementTO;
import org.apache.syncope.common.rest.api.service.EntitlementService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Parameters(
commandNames = "entitlement",
optionPrefixes = "-",
separators = "=",
commandDescription = "Apache Syncope entitlement service")
public class EntitlementCommand extends AbstractCommand {
private static final Logger LOG = LoggerFactory.getLogger(EntitlementCommand.class);
private final String helpMessage = "Usage: entitlement [options]\n"
+ " Options:\n"
+ " -h, --help \n"
+ " -l, --list \n"
+ " -lo, --list-own \n";
@Parameter(names = { "-lo", "--list-own" })
public boolean listOwn = false;
@Override
public void execute() {
final EntitlementService entitlementService = SyncopeServices.get(EntitlementService.class);
LOG.debug("Entitlement service successfully created");
if (help) {
LOG.debug("- entitlement help command");
System.out.println(helpMessage);
} else if (list) {
System.out.println("All entitlement:");
for (final EntitlementTO entitlementTO : entitlementService.getAllEntitlements()) {
System.out.println(" *** " + entitlementTO.getElement());
}
} else if (listOwn) {
System.out.println("All own entitlement:");
for (final EntitlementTO entitlementTO : entitlementService.getOwnEntitlements()) {
System.out.println(" *** " + entitlementTO.getElement());
}
} else {
System.out.println(helpMessage);
}
}
}
| 34,607
|
https://github.com/ShMPMat/LanguageGenerator/blob/master/src/shmp/lang/generator/util/ChangeParagigmCopy.kt
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
LanguageGenerator
|
ShMPMat
|
Kotlin
|
Code
| 281
| 1,120
|
package shmp.lang.generator.util
import shmp.lang.language.category.CategorySource
import shmp.lang.language.category.paradigm.ExponenceCluster
import shmp.lang.language.category.paradigm.ExponenceValue
import shmp.lang.language.category.paradigm.SpeechPartChangeParadigm
import shmp.lang.language.category.realization.CategoryApplicator
import shmp.lang.language.lexis.TypedSpeechPart
import shmp.lang.language.syntax.SyntaxRelation
import shmp.random.singleton.chanceOf
import shmp.random.singleton.testProbability
fun copyApplicators(
cluster: ExponenceCluster,
applicator: Map<ExponenceValue, CategoryApplicator>,
sourceMap: Map<SyntaxRelation, SyntaxRelation>
): Pair<ExponenceCluster, Map<ExponenceValue, CategoryApplicator>> {
val newCategories = cluster.categories.map {
it.copy(
source = when (it.source) {
is CategorySource.Agreement ->
if (it.source.relation in sourceMap.keys)
it.source.copy(relation = sourceMap.getValue(it.source.relation))
else it.source.copy()
is CategorySource.Self -> CategorySource.Self
}
)
}
val newClusterValues = cluster.possibleValues.map { v ->
v.categoryValues.map { cv ->
newCategories.flatMap { it.actualSourcedValues }.first { cv.categoryValue == it.categoryValue }
}
}.toSet()
val newCluster = ExponenceCluster(newCategories, newClusterValues)
return newCluster to applicator.map { (value, applicator) ->
val newValue = newCluster.possibleValues.first { nv ->
value.categoryValues.all { c -> c.categoryValue in nv.categoryValues.map { it.categoryValue } }
}
newValue to applicator.copy()
}.toMap()
}
fun SpeechPartChangeParadigm.copyForNewSpeechPart(
speechPart: TypedSpeechPart = this.speechPart,
sourceMap: Map<SyntaxRelation, SyntaxRelation> = mapOf(),
clusterPredicate: (ExponenceCluster) -> Boolean
): SpeechPartChangeParadigm {
val newApplicators = exponenceClusters
.mapNotNull { cluster ->
val applicator = applicators.getValue(cluster)
if (!clusterPredicate(cluster))
return@mapNotNull null
copyApplicators(cluster, applicator, sourceMap)
}
return SpeechPartChangeParadigm(
speechPart,
newApplicators.map { it.first },
newApplicators.toMap(),
prosodyChangeParadigm.copy()
)
}
fun SpeechPartChangeParadigm.substituteWith(from: SpeechPartChangeParadigm) =
0.9.chanceOf<SpeechPartChangeParadigm> { fullSubstituteWith(from) }
?: partialSubstituteWith(from)
private fun SpeechPartChangeParadigm.fullSubstituteWith(from: SpeechPartChangeParadigm): SpeechPartChangeParadigm {
val copy = from.copyForNewSpeechPart { getCluster(it) != null }
return combineParadigms(this, copy)
}
private fun SpeechPartChangeParadigm.partialSubstituteWith(from: SpeechPartChangeParadigm): SpeechPartChangeParadigm {
val copy = from.copyForNewSpeechPart { getCluster(it) != null && 0.5.testProbability() }
return combineParadigms(this, copy)
}
private fun combineParadigms(old: SpeechPartChangeParadigm, new: SpeechPartChangeParadigm): SpeechPartChangeParadigm {
val newOrder = old.exponenceClusters.map { new.getCluster(it) ?: it }
val newApplicators = newOrder.map {
it to (new.applicators[it] ?: old.applicators.getValue(it))
}.toMap()
return old.copy(exponenceClusters = newOrder, applicators = newApplicators)
}
//private fun hasSameCategorySet(first: SpeechPartChangeParadigm, second: SpeechPartChangeParadigm) =
// first.exponenceClusters.size == second.exponenceClusters.size && first.exponenceClusters.all { cluster ->
// second.getCluster(cluster) != null
// }
| 47,726
|
https://github.com/Merchello/Merchello/blob/master/src/Merchello.Web/Models/VirtualContent/IProductContentFactory.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
Merchello
|
Merchello
|
C#
|
Code
| 49
| 160
|
namespace Merchello.Web.Models.VirtualContent
{
using Merchello.Web.Models.ContentEditing;
/// <summary>
/// Defines a ProductContentFactory.
/// </summary>
internal interface IProductContentFactory
{
/// <summary>
/// The build content.
/// </summary>
/// <param name="display">
/// The display.
/// </param>
/// <returns>
/// The <see cref="IProductContent"/>.
/// </returns>
IProductContent BuildContent(ProductDisplay display);
IProductVariantContent BuildContent(ProductVariantDisplay display);
}
}
| 23,334
|
https://github.com/Creoles/hathaway/blob/master/cooking.conf.js
|
Github Open Source
|
Open Source
|
ISC
| null |
hathaway
|
Creoles
|
JavaScript
|
Code
| 88
| 346
|
var path = require('path');
var cooking = require('cooking');
cooking.set({
entry: {
app: ['babel-polyfill', './src/app.js'],
vendor1: ["vue", "vue-router", "vuex", "vue-i18n", "vuedraggable"],
vendor2: ['element-ui']
},
dist: './dist',
template: './index.tpl',
devServer: {
port: 8080,
publicPath: '/'
},
// production
clean: true,
hash: true,
// sourceMap: true,
minimize: true,
chunk: {
'vendor1': {
names: ['vendor1', 'vendor2'],
minChunks: 3
}
}, // see https://cookingjs.github.io/zh-cn/configuration.html#chunk
publicPath: '/',
assetsPath: 'static',
urlLoaderLimit: 10000,
extractCSS: '[name].[contenthash:7].css',
alias: {
'src': path.join(__dirname, 'src'),
'assets': path.join(__dirname, 'src/assets')
},
// static: 'assets',
extends: ['vue2', 'sass', 'buble', 'autoprefixer']
});
module.exports = cooking.resolve();
| 37,245
|
https://github.com/Fikri-mtwoo/IuranBulananWarga/blob/master/application/views/iuran/tambah.php
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
IuranBulananWarga
|
Fikri-mtwoo
|
PHP
|
Code
| 107
| 558
|
<!-- <?php var_dump($warga)?> -->
<div class="container-fluid">
<!-- Page Heading -->
<div class="d-sm-flex align-items-center justify-content-between mb-4">
<h1 class="h3 mb-0 text-gray-800">Data Iuran</h1>
</div>
<div class="row">
<div class="col-md-12">
<nav aria-label="breadcrumb">
<ol class="breadcrumb">
<li class="breadcrumb-item"><a href="#">Home</a></li>
<li class="breadcrumb-item"><a href="<?=base_url('Iuran')?>">Iuran</a></li>
<li class="breadcrumb-item active" aria-current="page">Data Iuran</li>
</ol>
</nav>
</div>
</div>
<div class="row justify-content-md-center">
<div class="col-md-6 col-md-auto">
<div class="flashinsertpetugas" data-notif="<?=$this->session->userdata('flash')?>"></div>
<div class="card">
<div class="card-header">
Data Iuran
</div>
<div class="card-body">
<form action="" method="post">
<div class="form-row">
<div class="form-group col-md-12">
<label for="total">Total Iuran</label>
<input type="number" name="total" id="total" class="form-control" placeholder="50000">
<?=form_error('total')?>
</div>
<div class="form-group col-md-12">
<label for="rincian">Rincian Iuran</label>
<textarea name="rincian" id="rincian" cols="30" rows="10" class="form-control"></textarea>
<?=form_error('rincian')?>
</div>
</div>
<button type="submit" class="btn btn-success btn-block">Tambah</button>
</form>
</div>
</div>
</div>
</div>
</div>
| 44,512
|
https://github.com/shannonjin/cvat/blob/master/cvat/src/app/models/annotation-formats/annotation-format.ts
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
cvat
|
shannonjin
|
TypeScript
|
Code
| 26
| 84
|
import { Annotation } from './annotation';
export interface AnnotationFormat{
id: number;
dumpers: Annotation[];
loaders: Annotation[];
name: string;
created_date: string;
updated_date: string;
handler_file: string;
owner: number;
}
| 39,544
|
https://github.com/austincap/worldline/blob/master/node_modules/neo4j-driver-core/types/integer.d.ts
|
Github Open Source
|
Open Source
|
Unlicense
| null |
worldline
|
austincap
|
TypeScript
|
Code
| 1,805
| 3,759
|
/**
* Copyright (c) "Neo4j"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* 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.
*/
/**
* Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as *signed* integers.
* See exported functions for more convenient ways of operating integers.
* Use `int()` function to create new integers, `isInt()` to check if given object is integer,
* `inSafeRange()` to check if it is safe to convert given value to native number,
* `toNumber()` and `toString()` to convert given integer to number or string respectively.
* @access public
* @exports Integer
* @class A Integer class for representing a 64 bit two's-complement integer value.
* @param {number} low The low (signed) 32 bits of the long
* @param {number} high The high (signed) 32 bits of the long
* @constructor
*/
declare class Integer {
low: number;
high: number;
constructor(low?: number, high?: number);
inSafeRange(): boolean;
/**
* Converts the Integer to an exact javascript Number, assuming it is a 32 bit integer.
* @returns {number}
* @expose
*/
toInt(): number;
/**
* Converts the Integer to a the nearest floating-point representation of this value (double, 53 bit mantissa).
* @returns {number}
* @expose
*/
toNumber(): number;
/**
* Converts the Integer to a BigInt representation of this value
* @returns {bigint}
* @expose
*/
toBigInt(): bigint;
/**
* Converts the Integer to native number or -Infinity/+Infinity when it does not fit.
* @return {number}
* @package
*/
toNumberOrInfinity(): number;
/**
* Converts the Integer to a string written in the specified radix.
* @param {number=} radix Radix (2-36), defaults to 10
* @returns {string}
* @override
* @throws {RangeError} If `radix` is out of range
* @expose
*/
toString(radix?: number): string;
/**
* Gets the high 32 bits as a signed integer.
* @returns {number} Signed high bits
* @expose
*/
getHighBits(): number;
/**
* Gets the low 32 bits as a signed integer.
* @returns {number} Signed low bits
* @expose
*/
getLowBits(): number;
/**
* Gets the number of bits needed to represent the absolute value of this Integer.
* @returns {number}
* @expose
*/
getNumBitsAbs(): number;
/**
* Tests if this Integer's value equals zero.
* @returns {boolean}
* @expose
*/
isZero(): boolean;
/**
* Tests if this Integer's value is negative.
* @returns {boolean}
* @expose
*/
isNegative(): boolean;
/**
* Tests if this Integer's value is positive.
* @returns {boolean}
* @expose
*/
isPositive(): boolean;
/**
* Tests if this Integer's value is odd.
* @returns {boolean}
* @expose
*/
isOdd(): boolean;
/**
* Tests if this Integer's value is even.
* @returns {boolean}
* @expose
*/
isEven(): boolean;
/**
* Tests if this Integer's value equals the specified's.
* @param {!Integer|number|string} other Other value
* @returns {boolean}
* @expose
*/
equals(other: Integerable): boolean;
/**
* Tests if this Integer's value differs from the specified's.
* @param {!Integer|number|string} other Other value
* @returns {boolean}
* @expose
*/
notEquals(other: Integerable): boolean;
/**
* Tests if this Integer's value is less than the specified's.
* @param {!Integer|number|string} other Other value
* @returns {boolean}
* @expose
*/
lessThan(other: Integerable): boolean;
/**
* Tests if this Integer's value is less than or equal the specified's.
* @param {!Integer|number|string} other Other value
* @returns {boolean}
* @expose
*/
lessThanOrEqual(other: Integerable): boolean;
/**
* Tests if this Integer's value is greater than the specified's.
* @param {!Integer|number|string} other Other value
* @returns {boolean}
* @expose
*/
greaterThan(other: Integerable): boolean;
/**
* Tests if this Integer's value is greater than or equal the specified's.
* @param {!Integer|number|string} other Other value
* @returns {boolean}
* @expose
*/
greaterThanOrEqual(other: Integerable): boolean;
/**
* Compares this Integer's value with the specified's.
* @param {!Integer|number|string} other Other value
* @returns {number} 0 if they are the same, 1 if the this is greater and -1
* if the given one is greater
* @expose
*/
compare(other: Integerable): number;
/**
* Negates this Integer's value.
* @returns {!Integer} Negated Integer
* @expose
*/
negate(): Integer;
/**
* Returns the sum of this and the specified Integer.
* @param {!Integer|number|string} addend Addend
* @returns {!Integer} Sum
* @expose
*/
add(addend: Integerable): Integer;
/**
* Returns the difference of this and the specified Integer.
* @param {!Integer|number|string} subtrahend Subtrahend
* @returns {!Integer} Difference
* @expose
*/
subtract(subtrahend: Integerable): Integer;
/**
* Returns the product of this and the specified Integer.
* @param {!Integer|number|string} multiplier Multiplier
* @returns {!Integer} Product
* @expose
*/
multiply(multiplier: Integerable): Integer;
/**
* Returns this Integer divided by the specified.
* @param {!Integer|number|string} divisor Divisor
* @returns {!Integer} Quotient
* @expose
*/
div(divisor: Integerable): Integer;
/**
* Returns this Integer modulo the specified.
* @param {!Integer|number|string} divisor Divisor
* @returns {!Integer} Remainder
* @expose
*/
modulo(divisor: Integerable): Integer;
/**
* Returns the bitwise NOT of this Integer.
* @returns {!Integer}
* @expose
*/
not(): Integer;
/**
* Returns the bitwise AND of this Integer and the specified.
* @param {!Integer|number|string} other Other Integer
* @returns {!Integer}
* @expose
*/
and(other: Integerable): Integer;
/**
* Returns the bitwise OR of this Integer and the specified.
* @param {!Integer|number|string} other Other Integer
* @returns {!Integer}
* @expose
*/
or(other: Integerable): Integer;
/**
* Returns the bitwise XOR of this Integer and the given one.
* @param {!Integer|number|string} other Other Integer
* @returns {!Integer}
* @expose
*/
xor(other: Integerable): Integer;
/**
* Returns this Integer with bits shifted to the left by the given amount.
* @param {number|!Integer} numBits Number of bits
* @returns {!Integer} Shifted Integer
* @expose
*/
shiftLeft(numBits: number | Integer): Integer;
/**
* Returns this Integer with bits arithmetically shifted to the right by the given amount.
* @param {number|!Integer} numBits Number of bits
* @returns {!Integer} Shifted Integer
* @expose
*/
shiftRight(numBits: number | Integer): Integer;
/**
* Signed zero.
* @type {!Integer}
* @expose
*/
static ZERO: Integer;
/**
* Signed one.
* @type {!Integer}
* @expose
*/
static ONE: Integer;
/**
* Signed negative one.
* @type {!Integer}
* @expose
*/
static NEG_ONE: Integer;
/**
* Maximum signed value.
* @type {!Integer}
* @expose
*/
static MAX_VALUE: Integer;
/**
* Minimum signed value.
* @type {!Integer}
* @expose
*/
static MIN_VALUE: Integer;
/**
* Minimum safe value.
* @type {!Integer}
* @expose
*/
static MIN_SAFE_VALUE: Integer;
/**
* Maximum safe value.
* @type {!Integer}
* @expose
*/
static MAX_SAFE_VALUE: Integer;
/**
* An indicator used to reliably determine if an object is a Integer or not.
* @type {boolean}
* @const
* @expose
* @private
*/
static __isInteger__: boolean;
/**
* Tests if the specified object is a Integer.
* @access private
* @param {*} obj Object
* @returns {boolean}
* @expose
*/
static isInteger(obj: any): boolean;
/**
* Returns a Integer representing the given 32 bit integer value.
* @access private
* @param {number} value The 32 bit integer in question
* @returns {!Integer} The corresponding Integer value
* @expose
*/
static fromInt(value: number): Integer;
/**
* Returns a Integer representing the 64 bit integer that comes by concatenating the given low and high bits. Each is
* assumed to use 32 bits.
* @access private
* @param {number} lowBits The low 32 bits
* @param {number} highBits The high 32 bits
* @returns {!Integer} The corresponding Integer value
* @expose
*/
static fromBits(lowBits: number, highBits: number): Integer;
/**
* Returns a Integer representing the given value, provided that it is a finite number. Otherwise, zero is returned.
* @access private
* @param {number} value The number in question
* @returns {!Integer} The corresponding Integer value
* @expose
*/
static fromNumber(value: number): Integer;
/**
* Returns a Integer representation of the given string, written using the specified radix.
* @access private
* @param {string} str The textual representation of the Integer
* @param {number=} radix The radix in which the text is written (2-36), defaults to 10
* @returns {!Integer} The corresponding Integer value
* @expose
*/
static fromString(str: string, radix?: number): Integer;
/**
* Converts the specified value to a Integer.
* @access private
* @param {!Integer|number|string|bigint|!{low: number, high: number}} val Value
* @returns {!Integer}
* @expose
*/
static fromValue(val: Integerable): Integer;
/**
* Converts the specified value to a number.
* @access private
* @param {!Integer|number|string|!{low: number, high: number}} val Value
* @returns {number}
* @expose
*/
static toNumber(val: Integerable): number;
/**
* Converts the specified value to a string.
* @access private
* @param {!Integer|number|string|!{low: number, high: number}} val Value
* @param {number} radix optional radix for string conversion, defaults to 10
* @returns {string}
* @expose
*/
static toString(val: Integerable, radix?: number): string;
/**
* Checks if the given value is in the safe range in order to be converted to a native number
* @access private
* @param {!Integer|number|string|!{low: number, high: number}} val Value
* @param {number} radix optional radix for string conversion, defaults to 10
* @returns {boolean}
* @expose
*/
static inSafeRange(val: Integerable): boolean;
}
declare type Integerable = number | string | Integer | {
low: number;
high: number;
} | bigint;
/**
* Cast value to Integer type.
* @access public
* @param {Mixed} value - The value to use.
* @return {Integer} - An object of type Integer.
*/
declare const int: typeof Integer.fromValue;
/**
* Check if a variable is of Integer type.
* @access public
* @param {Mixed} value - The variable to check.
* @return {Boolean} - Is it of the Integer type?
*/
declare const isInt: typeof Integer.isInteger;
/**
* Check if a variable can be safely converted to a number
* @access public
* @param {Mixed} value - The variable to check
* @return {Boolean} - true if it is safe to call toNumber on variable otherwise false
*/
declare const inSafeRange: typeof Integer.inSafeRange;
/**
* Converts a variable to a number
* @access public
* @param {Mixed} value - The variable to convert
* @return {number} - the variable as a number
*/
declare const toNumber: typeof Integer.toNumber;
/**
* Converts the integer to a string representation
* @access public
* @param {Mixed} value - The variable to convert
* @param {number} radix - radix to use in string conversion, defaults to 10
* @return {string} - returns a string representation of the integer
*/
declare const toString: typeof Integer.toString;
export { int, isInt, inSafeRange, toNumber, toString };
export default Integer;
| 22,606
|
https://github.com/Val-istar-Guo/web-template/blob/master/template/framework/request.ts
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
web-template
|
Val-istar-Guo
|
TypeScript
|
Code
| 46
| 164
|
import request from 'superagent'
import { PORT, HOST } from './constants'
// 解决兼容ssr请求时端,本地端口号和地址缺失的问题
export default request
.agent()
.use(request => {
if (process.env.WEB_CONTAINER === 'ssr' && request.url[0] === '/') {
const host = HOST === '0.0.0.0' ? '127.0.0.1' : HOST
request.url = `${host}:${PORT}${request.url}`
}
return request;
})
| 2,979
|
https://github.com/micedre/sugoi-ui/blob/master/src/components/detailsOrganization/index.tsx
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
sugoi-ui
|
micedre
|
TypeScript
|
Code
| 403
| 1,522
|
import { Button, Grid, Typography } from '@material-ui/core';
import { useSnackbar } from 'notistack';
import React, { useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { useHistory, useParams } from 'react-router-dom';
import { useDeleteOrganization } from '../../hooks/organization/useDeleteOrganization';
import useGetOrganization from '../../hooks/organization/useGetOrganization';
import useUpdateOrganization from '../../hooks/organization/useUpdateOrganization';
import useRealmConfig from '../../hooks/realm/useRealmConfig/useRealmConfig';
import { useForms } from '../../hooks/technics/useForms';
import organization from '../../model/api/organization';
import DataViewer from '../commons/dataViewer/dataviewer';
import ErrorBoundary from '../commons/error/Error';
import { Loader } from '../commons/loader/loader';
import LoadingButton from '../commons/loadingButton';
import Title from '../commons/title/title';
interface props {
data: organization;
fieldToDisplay: any;
id: string;
dispatch: React.Dispatch<any>;
}
const DetailOrganization = () => {
const { realm, id, userStorage } = useParams<any>();
const { push } = useHistory();
const { organizationConfig } = useRealmConfig(realm);
const {
loading,
organization,
execute,
error: errorGet,
} = useGetOrganization(id, realm, userStorage);
const { enqueueSnackbar } = useSnackbar();
const { t } = useTranslation();
const {
execute: executeUpdate,
loading: loadingUpdate,
error: errorUpdate,
} = useUpdateOrganization();
const {
execute: executeDelete,
loading: loadingDelete,
error: errorDelete,
} = useDeleteOrganization();
const {
formValues,
updateIFormValues,
handleChange,
handleReset,
} = useForms({});
useEffect(() => {
if (organization) {
updateIFormValues(organization);
}
}, [organization, updateIFormValues]);
useEffect(() => {
if (errorDelete) {
enqueueSnackbar(
t('detail_organization.error') + errorDelete,
{
variant: 'error',
},
);
}
}, [enqueueSnackbar, errorDelete, t]);
useEffect(() => {
if (errorUpdate) {
enqueueSnackbar(
t('detail_organization.error') + errorUpdate,
{
variant: 'error',
},
);
}
}, [enqueueSnackbar, errorUpdate, t]);
useEffect(() => {
if (errorGet) {
enqueueSnackbar(t('detail_organization.error') + errorGet, {
variant: 'error',
});
}
}, [enqueueSnackbar, errorGet, t]);
const handleDelete = () => {
executeDelete(
((organization as unknown) as organization)?.identifiant ||
'',
realm,
userStorage,
).then(() =>
push(
'/realm/' +
realm +
(userStorage
? '/us/' + userStorage + '/organizations'
: '/organizations'),
),
);
};
const handleUpdate = () => {
executeUpdate(id, formValues, realm, userStorage).then(() =>
execute(id, realm, userStorage),
);
};
return (
<>
<Title title={t('detail_organization.title') + id} />
{loading ? (
<Loader />
) : (
<ErrorBoundary>
{organization ? (
<>
<DataViewer
data={formValues}
fieldToDisplay={
organizationConfig
}
handleChange={handleChange}
buttons={
<Grid
container
direction="row"
justify="center"
spacing={3}
>
<Grid item>
<LoadingButton
variant="contained"
color="primary"
loading={
loadingUpdate
}
handleClick={
handleUpdate
}
>
{t(
'detail_organization.buttons.save',
)}
</LoadingButton>
</Grid>
<Grid item>
<LoadingButton
variant="contained"
color="secondary"
loading={
loadingDelete
}
handleClick={
handleDelete
}
>
{t(
'detail_organization.buttons.delete',
)}
</LoadingButton>
</Grid>
<Grid item>
<Button
variant="contained"
color="default"
onClick={
handleReset
}
>
{t(
'detail_organization.buttons.reset',
)}
</Button>
</Grid>
</Grid>
}
create={false}
/>
</>
) : (
<Typography variant="h6" gutterBottom>
{t(
'detail_organization.organization_not_found',
)}
</Typography>
)}
</ErrorBoundary>
)}
</>
);
};
export default DetailOrganization;
| 2,348
|
https://github.com/AniketGurav/text-recognition/blob/master/web_demo.py
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
text-recognition
|
AniketGurav
|
Python
|
Code
| 352
| 1,217
|
# -*- coding: utf-8 -*-
from os import listdir
import os
from app import app
import urllib.request
from flask import Flask, render_template, request, redirect, flash
from wtforms import Form, TextField, validators, SubmitField, DecimalField, IntegerField
from werkzeug.utils import secure_filename
from keras import backend as K
from PIL import Image
import torch
from torch.autograd import Variable
import craft
import dataset
import utils
import models.VGG_BiLSTM_CTC as crnn
import models.ResNet_BiLSTM_CTC as crnn
"""
config
"""
model_path = './trained_weights/VGG_BiLSTM_CTC_cs.pth'
alphabet = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\';:.-! )"$\\#%,@&/?([]{}+-=*^|'
nclass = len(alphabet) + 1
nc = 1
imgH = 32
hidden_size = 256
converter = utils.strLabelConverter(alphabet)
model = crnn.CRNN(imgH, nc, nclass, hidden_size)
if torch.cuda.is_available():
model = torch.nn.DataParallel(model).cuda()
model.load_state_dict(torch.load(model_path))
def show_predict(image_directory, filename):
output_dir = 'static/images/cropped_craft'
prediction_result = craft.detect_text(image_directory, output_dir, crop_type='polly',
export_extra=True, refiner=False, cuda=True)
cropped_dir = output_dir + "/" + filename[:-4] + "_crops"
transformer = dataset.resizeNormalize((100, 32))
predicted_text = ""
for cropped in listdir(cropped_dir):
img = cropped_dir + "/" + cropped
image = Image.open(img).convert("L")
image = transformer(image)
if torch.cuda.is_available():
image = image.cuda()
image = image.view(1, *image.size())
image = Variable(image)
model.eval()
preds = model(image)
_, preds = preds.max(2)
preds = preds.transpose(1, 0).contiguous().view(-1)
preds_size = Variable(torch.IntTensor([preds.size(0)]))
sim_pred = converter.decode(preds.data, preds_size.data, raw=False)
predicted_text = predicted_text + sim_pred[2:len(predicted_text) - 1] + "\n"
return predicted_text, output_dir
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])
BASE_DIR = os.path.dirname(__file__)
UPLOAD_FOLDER = os.path.join(BASE_DIR, 'static/images')
MODEL_DIR = os.path.join(BASE_DIR, 'model')
# Create app
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
@app.route('/')
def upload_form():
return render_template('index.html')
@app.route("/", methods=['GET', 'POST'])
def home():
K.clear_session()
if request.method == 'POST':
# check if the post request has the file part
if 'file' not in request.files:
flash('No file part')
return redirect(request.url)
file = request.files['file']
if file.filename == '':
flash('No file selected for uploading')
return redirect(request.url)
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
filepath=os.path.join(UPLOAD_FOLDER, filename)
file.save(filepath)
result, output_dir = show_predict(filepath, filename)
filename = filename[:-4] + ".png"
response = {}
response['path'] = output_dir + "/" + filename
response['text'] = result
return render_template('index.html', response=response)
else:
flash('Allowed file types are txt, pdf, png, jpg, jpeg, gif')
return redirect(request.url)
if __name__ == "__main__":
print(("* Loading Keras model and Flask starting server..."
"please wait until server has fully started"))
app.run(host="0.0.0.0", port=8081, debug=True )
| 49,790
|
https://github.com/alanxie29/subscription-bot/blob/master/api/src/models/subscription.js
|
Github Open Source
|
Open Source
|
MIT
| null |
subscription-bot
|
alanxie29
|
JavaScript
|
Code
| 61
| 180
|
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const SubscriptionSchema = new Schema({
name: {
type: String,
required: true,
trim: true,
},
description: {
type: String,
required: true,
trim: true
},
startDate: {
type: Date,
required: true,
},
renewalPeriod: {
type: String,
required: true,
trim: true,
},
price: {
type: Number,
required: true,
trim: true,
},
});
module.exports = mongoose.model('Subscription', SubscriptionSchema)
| 49,383
|
https://github.com/mohsinalimat/DevToysMac/blob/master/DevToys/DevToys/Body/Graphic/Image Converter/ImageConverter.swift
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
DevToysMac
|
mohsinalimat
|
Swift
|
Code
| 526
| 1,731
|
//
// ImageConverter.swift
// DevToys
//
// Created by yuki on 2022/02/04.
//
import CoreUtil
struct ImageConvertTask {
let image: NSImage
let title: String
let size: CGSize
let destinationURL: URL
let isDone: Promise<Void, Error>
}
enum ImageConverter {
private static let destinationDirectory = FileManager.default.urls(for: .picturesDirectory, in: .userDomainMask)[0].appendingPathComponent("DevToys") => {
try? FileManager.default.createDirectory(at: $0, withIntermediateDirectories: true, attributes: nil)
}
static func convert(_ item: ImageItem, format: ImageFormatType, resize: Bool, size: CGSize, scale: ImageScaleMode) -> ImageConvertTask {
var image = item.image
if resize {
switch scale {
case .scaleToFill: if let rimage = image.resizedAspectFill(to: size) { image = rimage }
case .scaleToFit: if let rimage = image.resizedAspectFit(to: size) { image = rimage }
}
}
let filename = "\(item.title.split(separator: ".").dropLast().joined(separator: ".")).\(format.exp)"
let destinationURL = destinationDirectory.appendingPathComponent(filename)
let isDone = exportPromise(image, to: format, destinationURL: destinationURL)
.receive(on: .main)
.peek{ NSWorkspace.shared.activateFileViewerSelecting([destinationURL]) }
return ImageConvertTask(image: item.image, title: item.title, size: item.image.size, destinationURL: destinationURL, isDone: isDone)
}
private static func exportPromise(_ image: NSImage, to format: ImageFormatType, destinationURL: URL) -> Promise<Void, Error> {
switch format {
case .webp: return WebpImageExporter.export(image, to: destinationURL)
case .heic: return HeicImageExporter.export(image, to: destinationURL)
case .png: return DefaultImageExporter.exportPNG(image, to: destinationURL)
case .jpg: return DefaultImageExporter.exportJPEG(image, to: destinationURL)
case .gif: return DefaultImageExporter.exportGIF(image, to: destinationURL)
case .tiff: return DefaultImageExporter.exportTIFF(image, to: destinationURL)
}
}
}
enum ImageFormatType: String, TextItem {
case png = "PNG Format"
case jpg = "JPEG Format"
case tiff = "TIFF Format"
case gif = "GIF Format"
case webp = "Webp Format"
case heic = "Heic Format"
var title: String { rawValue.localized() }
var exp: String {
switch self {
case .png: return "png"
case .jpg: return "jpg"
case .gif: return "gif"
case .tiff: return "tiff"
case .webp: return "webp"
case .heic: return "heic"
}
}
}
enum ImageScaleMode: String, TextItem {
case scaleToFill = "Scale to Fill"
case scaleToFit = "Scale to Fit"
var title: String { rawValue.localized() }
}
extension NSImage {
func resizedAspectFill(to newSize: CGSize) -> NSImage? {
guard let bitmapRep = NSBitmapImageRep(
bitmapDataPlanes: nil, pixelsWide: Int(newSize.width), pixelsHigh: Int(newSize.height),
bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false,
colorSpaceName: .calibratedRGB, bytesPerRow: 0, bitsPerPixel: 0
) else { return nil }
let scale = self.size.aspectFillRatio(fillInside: newSize)
bitmapRep.size = newSize
NSGraphicsContext.saveGraphicsState()
NSGraphicsContext.current = NSGraphicsContext(bitmapImageRep: bitmapRep)
self.draw(in: CGRect(center: newSize.convertToPoint()/2, size: self.size * scale), from: .zero, operation: .copy, fraction: 1.0)
NSGraphicsContext.restoreGraphicsState()
let resizedImage = NSImage(size: newSize)
resizedImage.addRepresentation(bitmapRep)
return resizedImage
}
func resizedAspectFit(to newSize: CGSize) -> NSImage? {
guard let bitmapRep = NSBitmapImageRep(
bitmapDataPlanes: nil, pixelsWide: Int(newSize.width), pixelsHigh: Int(newSize.height),
bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false,
colorSpaceName: .calibratedRGB, bytesPerRow: 0, bitsPerPixel: 0
) else { return nil }
let scale = self.size.aspectFitRatio(fitInside: newSize)
bitmapRep.size = newSize
NSGraphicsContext.saveGraphicsState()
NSGraphicsContext.current = NSGraphicsContext(bitmapImageRep: bitmapRep)
NSColor.black.setFill()
NSRect(size: newSize).fill()
draw(in: CGRect(center: newSize.convertToPoint()/2, size: self.size * scale), from: .zero, operation: .copy, fraction: 1.0)
NSGraphicsContext.restoreGraphicsState()
let resizedImage = NSImage(size: newSize)
resizedImage.addRepresentation(bitmapRep)
return resizedImage
}
func resized(to newSize: NSSize) -> NSImage {
if let bitmapRep = NSBitmapImageRep(
bitmapDataPlanes: nil, pixelsWide: Int(newSize.width), pixelsHigh: Int(newSize.height),
bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false,
colorSpaceName: .calibratedRGB, bytesPerRow: 0, bitsPerPixel: 0
) {
bitmapRep.size = newSize
NSGraphicsContext.saveGraphicsState()
NSGraphicsContext.current = NSGraphicsContext(bitmapImageRep: bitmapRep)
draw(in: NSRect(x: 0, y: 0, width: newSize.width, height: newSize.height), from: .zero, operation: .copy, fraction: 1.0)
NSGraphicsContext.restoreGraphicsState()
let resizedImage = NSImage(size: newSize)
resizedImage.addRepresentation(bitmapRep)
return resizedImage
}
fatalError()
}
}
| 29,557
|
https://github.com/8834341/cocos-animator/blob/master/animator-editor/assets/script/editor/menu/LineToSubItem.ts
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
cocos-animator
|
8834341
|
TypeScript
|
Code
| 92
| 284
|
import Events, { EventName } from "../../common/util/Events";
import State from "../data/State";
import UnitStateMachine from "../fsm/UnitStateMachine";
const { ccclass, property } = cc._decorator;
@ccclass
export default class LineToSubItem extends cc.Component {
@property(cc.Label) NameLabel: cc.Label = null;
private _state: State = null;
/**
* 连线目标状态机
*/
private _toStateMachine: UnitStateMachine = null;
public onInit(state: State = null, to: UnitStateMachine = null) {
if (state) {
this._state = state;
this._toStateMachine = to;
this.NameLabel.string = state.name;
} else {
this.NameLabel.string = '<- empty ->';
}
}
private onClickSelect() {
Events.emit(EventName.CLOSE_MENU);
this._state && Events.emit(EventName.LINE_TO_MACHINE_STATE, this._state, this._toStateMachine);
}
}
| 43,186
|
https://github.com/chenxygx/PythonSimple/blob/master/MachineLearning/Factorization Machine/FM_test.py
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
PythonSimple
|
chenxygx
|
Python
|
Code
| 162
| 652
|
# coding:UTF-8
import numpy as np
from FM_train import getPrediction
def loadDataSet(data):
'''导入测试数据集
input: data(string)测试数据
output: dataMat(list)特征
'''
dataMat = []
fr = open(data) # 打开文件
for line in fr.readlines():
lines = line.strip().split("\t")
lineArr = []
for i in range(len(lines)):
lineArr.append(float(lines[i]))
dataMat.append(lineArr)
fr.close()
return dataMat
def loadModel(model_file):
'''导入FM模型
input: model_file(string)FM模型
output: w0, np.mat(w).T, np.mat(v)FM模型的参数
'''
f = open(model_file)
line_index = 0
w0 = 0.0
w = []
v = []
for line in f.readlines():
lines = line.strip().split("\t")
if line_index == 0: # w0
w0 = float(lines[0].strip())
elif line_index == 1: # w
for x in lines:
w.append(float(x.strip()))
else:
v_tmp = []
for x in lines:
v_tmp.append(float(x.strip()))
v.append(v_tmp)
line_index += 1
f.close()
return w0, np.mat(w).T, np.mat(v)
def save_result(file_name, result):
'''保存最终的预测结果
input: file_name(string)需要保存的文件名
result(mat):对测试数据的预测结果
'''
f = open(file_name, "w")
f.write("\n".join(str(x) for x in result))
f.close()
if __name__ == "__main__":
# 1、导入测试数据
dataTest = loadDataSet("test_data.txt")
# 2、导入FM模型
w0, w , v = loadModel("weights")
# 3、预测
result = getPrediction(dataTest, w0, w, v)
# 4、保存最终的预测结果
save_result("predict_result", result)
| 24,163
|
https://github.com/michealdunne14/InternetCookBookFYP/blob/master/app/src/test/java/com/example/internetcookbook/StartFragmentTest.kt
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
InternetCookBookFYP
|
michealdunne14
|
Kotlin
|
Code
| 8
| 31
|
package com.example.internetcookbook
import org.junit.Assert.*
class StartFragmentTest {
}
| 23,819
|
https://github.com/qodeca/Pollution-Warning-Display/blob/master/client/src/actions/index.js
|
Github Open Source
|
Open Source
|
Unlicense
| 2,019
|
Pollution-Warning-Display
|
qodeca
|
JavaScript
|
Code
| 75
| 169
|
export const pollutionData = data => {
return {
type: 'DATA',
payload: data
}
};
export const advertisementsData = data => {
return {
type: 'ADS_LIST',
payload: data
}
};
export const selectedAdvertisement = data => {
return {
type: 'SELECTED_AD',
payload: data
}
};
export const timeToSkipAd = data => {
return {
type: 'AD_TIME',
payload: data
}
};
export const timeToSkipInfo = data => {
return {
type: 'INFO_TIME',
payload: data
}
};
| 36,686
|
https://github.com/hpcloud/jclouds-labs/blob/master/cdmi/src/test/java/org/jclouds/snia/cdmi/v1/features/ContainerApiExpectTest.java
|
Github Open Source
|
Open Source
|
Apache-1.1
| null |
jclouds-labs
|
hpcloud
|
Java
|
Code
| 212
| 676
|
/**
* Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. jclouds 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.jclouds.snia.cdmi.v1.features;
import static com.google.common.base.Charsets.UTF_8;
import static com.google.common.io.BaseEncoding.base64;
import static org.testng.Assert.assertEquals;
import org.jclouds.http.HttpRequest;
import org.jclouds.http.HttpResponse;
import org.jclouds.snia.cdmi.v1.CDMIApi;
import org.jclouds.snia.cdmi.v1.internal.BaseCDMIApiExpectTest;
import org.jclouds.snia.cdmi.v1.parse.ParseContainerTest;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableMultimap;
/**
*
* @author Adrian Cole
*/
@Test(groups = "unit", testName = "ContainerAsyncApiTest")
public class ContainerApiExpectTest extends BaseCDMIApiExpectTest {
public void testGetContainerWhenResponseIs2xx() throws Exception {
HttpRequest get = HttpRequest
.builder()
.method("GET")
.endpoint("http://localhost:8080/MyContainer/")
.headers(ImmutableMultimap.<String, String> builder().put("X-CDMI-Specification-Version", "1.0.1")
.put("TID", "tenantId")
.put("Authorization", "Basic " + base64().encode("username:password".getBytes(UTF_8)))
.put("Accept", "application/cdmi-container").build()).build();
HttpResponse getResponse = HttpResponse.builder().statusCode(200).payload(payloadFromResource("/container.json"))
.build();
CDMIApi apiWhenContainersExist = requestSendsResponse(get, getResponse);
assertEquals(apiWhenContainersExist.getApi().get("MyContainer/"), new ParseContainerTest().expected());
}
}
| 1,537
|
https://github.com/westfallon/smartMuseum/blob/master/app/src/main/java/com/example/smartmuseum/util/RegexUtils.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
smartMuseum
|
westfallon
|
Java
|
Code
| 34
| 154
|
package com.example.smartmuseum.util;
import java.util.regex.Pattern;
/**
* 放各种校验
*/
public class RegexUtils {
/**
* 手机号的校验(没有放很复杂的校验,1开头的十位数字即可)
* @param tel
* @return
*/
public static boolean validateMobilePhone(String tel){
Pattern telPattern = Pattern.compile("^[1]\\d{10}$");
return telPattern.matcher(tel).matches();
}
}
| 14,097
|
https://github.com/sthima/cielo-API-3.0-Nodejs/blob/master/sdk/ecommerce/environment.ts
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,020
|
cielo-API-3.0-Nodejs
|
sthima
|
TypeScript
|
Code
| 65
| 253
|
import { IEnvironment } from '../environment';
export class Environment implements IEnvironment {
private apiUrl: string;
private apiQueryUrl: string;
public static PRODUCTION() {
return new Environment(
'https://api.cieloecommerce.cielo.com.br/',
'https://apiquery.cieloecommerce.cielo.com.br/'
);
}
public static SANDBOX() {
return new Environment(
'https://apisandbox.cieloecommerce.cielo.com.br/',
'https://apiquerysandbox.cieloecommerce.cielo.com.br/'
);
}
constructor(apiUrl: string, apiQueryUrl: string) {
this.apiUrl = apiUrl;
this.apiQueryUrl = apiQueryUrl;
}
getApiUrl(): string {
return this.apiUrl;
}
getApiQueryURL(): string {
return this.apiQueryUrl;
}
}
| 31,971
|
https://github.com/Rufaim/entry-booking-control/blob/master/.gitignore
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
entry-booking-control
|
Rufaim
|
Ignore List
|
Code
| 3
| 12
|
*.pb.go
*.log
*.db
| 16,859
|
https://github.com/OpenMTR/OpenMTR/blob/master/OpenMTRDemo/Filters/IsolateOdoFilter.Designer.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,018
|
OpenMTR
|
OpenMTR
|
C#
|
Code
| 332
| 1,374
|
namespace OpenMTRDemo.Filters
{
partial class IsolateOdoFilter
{
/// <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.thresholdTrackBar = new System.Windows.Forms.TrackBar();
this.thresholdNumeric = new System.Windows.Forms.NumericUpDown();
this.label1 = new System.Windows.Forms.Label();
this.isolateButton = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.thresholdTrackBar)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.thresholdNumeric)).BeginInit();
this.SuspendLayout();
//
// thresholdTrackBar
//
this.thresholdTrackBar.LargeChange = 100;
this.thresholdTrackBar.Location = new System.Drawing.Point(6, 22);
this.thresholdTrackBar.Maximum = 10000;
this.thresholdTrackBar.Name = "thresholdTrackBar";
this.thresholdTrackBar.Size = new System.Drawing.Size(135, 45);
this.thresholdTrackBar.TabIndex = 3;
this.thresholdTrackBar.TickStyle = System.Windows.Forms.TickStyle.None;
this.thresholdTrackBar.Value = 300;
this.thresholdTrackBar.ValueChanged += new System.EventHandler(this.threshold_ValueChanged);
//
// thresholdNumeric
//
this.thresholdNumeric.DecimalPlaces = 2;
this.thresholdNumeric.Increment = new decimal(new int[] {
1,
0,
0,
131072});
this.thresholdNumeric.Location = new System.Drawing.Point(147, 22);
this.thresholdNumeric.Name = "thresholdNumeric";
this.thresholdNumeric.Size = new System.Drawing.Size(66, 20);
this.thresholdNumeric.TabIndex = 4;
this.thresholdNumeric.Value = new decimal(new int[] {
3,
0,
0,
0});
this.thresholdNumeric.ValueChanged += new System.EventHandler(this.threshold_ValueChanged);
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(27, 45);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(186, 13);
this.label1.TabIndex = 5;
this.label1.Text = "Isolated image size % of primary image";
//
// isolateButton
//
this.isolateButton.Location = new System.Drawing.Point(157, 60);
this.isolateButton.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.isolateButton.Name = "isolateButton";
this.isolateButton.Size = new System.Drawing.Size(56, 19);
this.isolateButton.TabIndex = 6;
this.isolateButton.Text = "Isolate";
this.isolateButton.UseVisualStyleBackColor = true;
this.isolateButton.Click += new System.EventHandler(this.isolateButton_Click);
//
// IsolateFilter
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.isolateButton);
this.Controls.Add(this.label1);
this.Controls.Add(this.thresholdNumeric);
this.Controls.Add(this.thresholdTrackBar);
this.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.MaximumSize = new System.Drawing.Size(220, 122);
this.MinimumSize = new System.Drawing.Size(220, 25);
this.Name = "IsolateFilter";
this.Size = new System.Drawing.Size(216, 84);
this.Controls.SetChildIndex(this.thresholdTrackBar, 0);
this.Controls.SetChildIndex(this.thresholdNumeric, 0);
this.Controls.SetChildIndex(this.label1, 0);
this.Controls.SetChildIndex(this.isolateButton, 0);
((System.ComponentModel.ISupportInitialize)(this.thresholdTrackBar)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.thresholdNumeric)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.TrackBar thresholdTrackBar;
private System.Windows.Forms.NumericUpDown thresholdNumeric;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Button isolateButton;
}
}
| 21,803
|
https://github.com/Lingaro/magento2-module-codegen/blob/master/src/Lingaro/Magento2Codegen/Model/Template.php
|
Github Open Source
|
Open Source
|
MIT
| 2,023
|
magento2-module-codegen
|
Lingaro
|
PHP
|
Code
| 207
| 628
|
<?php
/**
* Copyright © 2023 Lingaro sp. z o.o. All rights reserved.
* See LICENSE for license details.
*/
declare(strict_types=1);
namespace Lingaro\Magento2Codegen\Model;
use Lingaro\Magento2Codegen\Service\TemplateType\TypeInterface;
class Template
{
private ?string $name = null;
private ?string $description = null;
private ?string $afterGenerateConfig = null;
private array $propertiesConfig = [];
private ?TypeInterface $typeService;
private bool $isAbstract = false;
/**
* @var Template[]
*/
private array $dependencies = [];
public function getName(): ?string
{
return $this->name;
}
public function setName(string $name): self
{
$this->name = $name;
return $this;
}
public function getDescription(): ?string
{
return $this->description;
}
public function setDescription(string $description): self
{
$this->description = $description;
return $this;
}
public function getDependencies(): array
{
return $this->dependencies;
}
public function setDependencies(array $dependencies): self
{
$this->dependencies = $dependencies;
return $this;
}
public function getAfterGenerateConfig(): ?string
{
return $this->afterGenerateConfig;
}
public function setAfterGenerateConfig(string $afterGenerateConfig): self
{
$this->afterGenerateConfig = $afterGenerateConfig;
return $this;
}
public function getPropertiesConfig(): array
{
return $this->propertiesConfig;
}
public function setPropertiesConfig(array $propertiesConfig): self
{
$this->propertiesConfig = $propertiesConfig;
return $this;
}
public function getTypeService(): ?TypeInterface
{
return $this->typeService;
}
public function setTypeService(TypeInterface $typeService): self
{
$this->typeService = $typeService;
return $this;
}
public function getIsAbstract(): bool
{
return $this->isAbstract;
}
public function setIsAbstract(bool $isAbstract): self
{
$this->isAbstract = $isAbstract;
return $this;
}
}
| 39,660
|
https://github.com/pk044/kebs/blob/master/instances/src/main/scala/pl/iterators/kebs/instances/util/CurrencyString.scala
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
kebs
|
pk044
|
Scala
|
Code
| 35
| 135
|
package pl.iterators.kebs.instances.util
import pl.iterators.kebs.instances.InstanceConverter
import pl.iterators.kebs.instances.util.CurrencyString.CurrencyFormat
import java.util.Currency
trait CurrencyString {
implicit val currencyFormatter: InstanceConverter[Currency, String] =
InstanceConverter[Currency, String](_.toString, Currency.getInstance, Some(CurrencyFormat))
}
object CurrencyString {
private[instances] val CurrencyFormat = "ISO-4217 standard format e.g. USD"
}
| 8,706
|
https://github.com/sonntagsgesicht/auxilium/blob/master/auxilium/tools/dulwich_tools.py
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
auxilium
|
sonntagsgesicht
|
Python
|
Code
| 716
| 2,337
|
# -*- coding: utf-8 -*-
# auxilium
# --------
# Python project for an automated test and deploy toolkit.
#
# Author: sonntagsgesicht
# Version: 0.2.7, copyright Monday, 01 November 2021
# Website: https://github.com/sonntagsgesicht/auxilium
# License: Apache License 2.0 (see LICENSE file)
from logging import log, DEBUG, INFO, ERROR
from os import getcwd
from .const import ICONS
from .setup_tools import EXT
from .system_tools import script, shell
LEVEL = DEBUG
BRANCH = 'master'
IMP = "from sys import exit", \
"from dulwich.repo import Repo", \
"from dulwich.porcelain import *"
def init_git(path=getcwd(), venv=None):
log(INFO, ICONS["init"] + "init local `git` repo")
return script("Repo.init('.')",
imports=IMP, path=path, venv=venv)
def clone_git(remote, path=getcwd(), venv=None):
log(INFO, ICONS["clone"] + "clone remote `git` repo")
log(DEBUG, ICONS[""] + clean_url(remote))
return script("clone(%r, '.')" % remote,
imports=IMP, path=path, venv=venv)
def branch_git(branch, path=getcwd(), venv=None):
log(INFO, ICONS["branch"] + "create branch for local `git` repo")
return script("branch_create('.', %r)" % branch,
imports=IMP, path=path, venv=venv)
def checkout_git(branch, path=getcwd(), venv=None):
log(INFO, ICONS["checkout"] + "checkout %r from local `git` repo" % branch)
return shell("git checkout %r" % branch,
path=path, venv=venv)
def add_git(path=getcwd(), venv=None):
"""add files to local `git` repo"""
log(INFO, ICONS["add"] + "add/stage files to local `git` repo")
code = False
code = code or script("exit(Repo('.').stage(status().unstaged))",
imports=IMP, path=path, venv=venv)
code = code or script("exit(Repo('.').stage(status().untracked))",
imports=IMP, path=path, venv=venv)
return code
def status_git(level=INFO, path=getcwd(), venv=None):
"""check status of local `git` repo"""
log(INFO, ICONS["status"] + "check file status in local `git` repo")
code = False
code = code or script(
"print('add : ' + "
"', '.join(p.decode() for p in status().staged['add']))",
imports=IMP, level=level, path=path, venv=venv)
code = code or script(
"print('delete : ' + "
"', '.join(p.decode() for p in status().staged['delete']))",
imports=IMP, level=level, path=path, venv=venv)
code = code or script(
"print('modify : ' + "
"', '.join(p.decode() for p in status().staged['modify']))",
imports=IMP, level=level, path=path, venv=venv)
code = code or script(
"print('unstaged : ' + "
"', '.join(p.decode() for p in status().unstaged))",
imports=IMP, level=level, path=path, venv=venv)
code = code or script(
"print('untracked : ' + "
"', '.join(p for p in status().untracked))",
imports=IMP, level=level, path=path, venv=venv)
return code
def commit_git(msg='', level=LEVEL, path=getcwd(), venv=None):
"""commit changes to local `git` repo"""
msg = (msg if msg else 'Commit') + EXT
log(INFO, ICONS["commit"] + "commit changes to local `git` repo")
return script("print('[' + (commit(message=%r)).decode()[:6] + '] ' + %r)"
% (msg, msg), imports=IMP, level=level, path=path, venv=venv)
def has_status_git(path=getcwd(), venv=None):
return script("exit(any(tuple(status().staged.values()) + "
"(status().unstaged, status().untracked)))",
imports=IMP, path=path, venv=venv)
def has_staged_git(path=getcwd(), venv=None):
return script("exit(any(tuple(status().staged.values())))",
imports=IMP, path=path, venv=venv)
def has_unstaged_git(path=getcwd(), venv=None):
return script("exit(any((status().unstaged, status().untracked)))",
imports=IMP, path=path, venv=venv)
def add_and_commit_git(msg='', level=LEVEL, path=getcwd(), venv=None):
code = False
# todo: check .gitignore
if has_unstaged_git(path=path, venv=venv):
code = code or add_git(path=path, venv=venv)
if not has_staged_git(path=path, venv=venv):
log(INFO, ICONS["missing"] + "no changes to commit")
return code
code = code or commit_git(msg, level=level, path=path, venv=venv)
return code
def tag_git(tag, msg='few', level=LEVEL, path=getcwd(), venv=None):
"""tag current branch of local `git` repo"""
tag_exists = script("exit(%r in tag_list('.'))" % bytearray(tag.encode()),
imports=IMP, path=path, venv=venv)
if tag_exists:
log(ERROR, ICONS["error"] +
"tag %r exists in current branch of local `git` repo" % tag)
return 1
log(INFO, ICONS["tag"] + "tagging last commit")
script("print('tag: %s')" % tag,
imports=IMP, level=level, path=path, venv=venv)
if msg:
script("print('message: %s')" % msg,
imports=IMP, level=level, path=path, venv=venv)
script("print(log(max_entries=1))",
imports=IMP, level=level, path=path, venv=venv)
return script("exit(tag_create('.', tag=%r, message=%r))" % (tag, msg),
imports=IMP, path=path, venv=venv)
def build_url(url, usr='', pwd='None'): # nosec
pwd = ':' + str(pwd) if pwd and pwd != 'None' else ''
usr = str(usr) if usr else 'token-user' if pwd else ''
remote = \
'https://' + usr + pwd + '@' + url.replace('https://', '')
return remote
def clean_url(url):
if '@' not in url:
return url
http, last = url.split('//', 1)
usr_pwd, url = last.split('@', 1)
usr, _ = usr_pwd.split(':', 1) if ':' in usr_pwd else (usr_pwd, '')
return http + '//' + usr + '@' + url
def push_git(remote='None', branch=BRANCH, path=getcwd(), venv=None):
"""push to given branch of remote `git` repo"""
log(INFO, ICONS["push"] + "push to %r to remote `git` repo" % branch)
log(DEBUG, ICONS[""] + clean_url(remote))
return script("push('.', %r, %r)" % (remote, branch),
imports=IMP, path=path, venv=venv)
def fetch_git(remote='None', path=getcwd(), venv=None):
"""fetch from remote `git` repo"""
log(INFO, ICONS["pull"] + "fetch from remote `git` repo")
log(DEBUG, ICONS[""] + clean_url(remote))
return script("fetch('.', %r)" % remote,
imports=IMP, path=path, venv=venv)
def pull_git(remote='None', path=getcwd(), venv=None):
"""pull from remote `git` repo"""
log(INFO, ICONS["pull"] + "pull from remote `git` repo")
log(DEBUG, ICONS[""] + clean_url(remote))
return script("pull('.', %r)" % remote,
imports=IMP, path=path, venv=venv)
| 16,520
|
https://github.com/gruiick/openclassrooms-py/blob/master/01-Apprenez/1.TP01.py
|
Github Open Source
|
Open Source
|
BSD-2-Clause
| null |
openclassrooms-py
|
gruiick
|
Python
|
Code
| 146
| 341
|
#!/usr/bin/env python3
# coding: utf-8
# $Id: 1.TP01.py 1.2 $
# SPDX-License-Identifier: BSD-2-Clause
entrée = input("Saisissez une année : ")
year = int(entrée)
# Naïf
"""
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
print('bissextile')
else:
print('pas bissextile')
else:
print('bissextile')
else:
print('pas bissextile')
"""
# Correction 1
"""
bissextile = False
if year % 400 == 0:
bissextile = True
elif year % 100 == 0:
bissextile = False
elif year % 4 == 0:
bissextile = True
else: # ce bloc n'est pas nécessaire, sauf à la compréhension du code (ZoP)
bissextile = False
if bissextile:
print('bissextile.')
else:
print('pas bissextile.')
"""
# Correction 1, optimisation
# mais pas forcément plus facile à lire
if year % 400 == 0 or (year % 4 == 0 and year % 100 != 0):
print('bissextile.')
else:
print('pas bissextile.')
| 13,451
|
https://github.com/piougy/CzechIdMng/blob/master/Realization/backend/core/core-impl/src/main/java/eu/bcvsolutions/idm/core/scheduler/task/impl/RebuildRoleCatalogueIndexTaskExecutor.java
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
CzechIdMng
|
piougy
|
Java
|
Code
| 308
| 1,626
|
package eu.bcvsolutions.idm.core.scheduler.task.impl;
import java.util.List;
import java.util.UUID;
import org.quartz.DisallowConcurrentExecution;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import com.google.common.collect.ImmutableMap;
import eu.bcvsolutions.forest.index.service.api.ForestIndexService;
import eu.bcvsolutions.idm.core.api.domain.CoreResultCode;
import eu.bcvsolutions.idm.core.api.entity.AbstractEntity_;
import eu.bcvsolutions.idm.core.api.exception.ResultCodeException;
import eu.bcvsolutions.idm.core.api.service.ConfigurationService;
import eu.bcvsolutions.idm.core.api.service.IdmRoleCatalogueService;
import eu.bcvsolutions.idm.core.model.entity.IdmForestIndexEntity;
import eu.bcvsolutions.idm.core.model.entity.IdmRoleCatalogue;
import eu.bcvsolutions.idm.core.model.repository.IdmRoleCatalogueRepository;
import eu.bcvsolutions.idm.core.model.service.impl.DefaultForestIndexService;
import eu.bcvsolutions.idm.core.scheduler.api.service.AbstractSchedulableTaskExecutor;
/**
* Rebuild forest index for role catalogue.
*
* @author Radek Tomiška
*
*/
@DisallowConcurrentExecution
@Component(RebuildRoleCatalogueIndexTaskExecutor.TASK_NAME)
public class RebuildRoleCatalogueIndexTaskExecutor extends AbstractSchedulableTaskExecutor<Boolean> {
private static final org.slf4j.Logger LOG = org.slf4j.LoggerFactory.getLogger(RebuildRoleCatalogueIndexTaskExecutor.class);
public static final String TASK_NAME = "core-rebuild-role-catalogue-index-long-running-task";
//
@Autowired private IdmRoleCatalogueRepository roleCatalogueRepository;
@Autowired private IdmRoleCatalogueService roleCatalogueService;
@Autowired private ForestIndexService<IdmForestIndexEntity, UUID> forestIndexService;
@Autowired private ConfigurationService configurationService;
@Override
public String getName() {
return TASK_NAME;
}
@Override
public Boolean process() {
if (!configurationService.getBooleanValue(DefaultForestIndexService.PROPERTY_INDEX_ENABLED, true)) {
throw new ResultCodeException(CoreResultCode.FOREST_INDEX_DISABLED, ImmutableMap.of("property", DefaultForestIndexService.PROPERTY_INDEX_ENABLED));
}
String longRunningTaskId = configurationService.getValue(roleCatalogueService.getConfigurationPropertyName(IdmRoleCatalogueService.CONFIGURATION_PROPERTY_REBUILD));
if (StringUtils.hasLength(longRunningTaskId) && !longRunningTaskId.equals(getLongRunningTaskId().toString())) {
throw new ResultCodeException(CoreResultCode.FOREST_INDEX_RUNNING, ImmutableMap.of("type", IdmRoleCatalogue.FOREST_TREE_TYPE));
}
//
LOG.info("Starting rebuilding index for role catalogue.");
//
// clear all rgt, lft
try {
forestIndexService.dropIndexes(IdmRoleCatalogue.FOREST_TREE_TYPE);
} finally {
configurationService.setBooleanValue(roleCatalogueService.getConfigurationPropertyName(IdmRoleCatalogueService.CONFIGURATION_PROPERTY_VALID), false);
}
try {
configurationService.setValue(roleCatalogueService.getConfigurationPropertyName(IdmRoleCatalogueService.CONFIGURATION_PROPERTY_REBUILD), getLongRunningTaskId().toString());
//
count = roleCatalogueRepository.findAll(PageRequest.of(0, 1)).getTotalElements();
counter = 0L;
boolean canContinue = true;
Page<IdmRoleCatalogue> roots = roleCatalogueRepository.findRoots(
PageRequest.of(
0,
100,
new Sort(Direction.ASC, AbstractEntity_.id.getName())
)
);
while (canContinue) {
canContinue = processChildren(roots.getContent());
if (!canContinue) {
break;
}
if (!roots.hasNext()) {
break;
}
roots = roleCatalogueRepository.findRoots(roots.nextPageable());
}
//
if (count.equals(counter)) {
configurationService.deleteValue(roleCatalogueService.getConfigurationPropertyName(IdmRoleCatalogueService.CONFIGURATION_PROPERTY_VALID));
LOG.info("Forest index for role catalogue was successfully rebuilt (index size [{}]).", counter);
return Boolean.TRUE;
}
//
LOG.warn("Forest index for role catalogue rebuild was canceled (index size [{}]).", counter);
return Boolean.FALSE;
} finally {
configurationService.deleteValue(roleCatalogueService.getConfigurationPropertyName(IdmRoleCatalogueService.CONFIGURATION_PROPERTY_REBUILD));
}
}
private boolean processChildren(List<IdmRoleCatalogue> nodes) {
boolean canContinue = true;
for(IdmRoleCatalogue node : nodes) {
if (node.getForestIndex() == null) {
forestIndexService.index(node.getForestTreeType(), node.getId(), node.getParentId());
}
counter++;
canContinue = updateState();
if (!canContinue) {
break;
}
// proces nodes childred
canContinue = processChildren(roleCatalogueRepository.findDirectChildren(node, null).getContent());
if (!canContinue) {
break;
}
};
return canContinue;
}
@Override
public boolean isRecoverable() {
return true;
}
}
| 20,973
|
https://github.com/HakanAkca/etreprof-mb/blob/master/resources/assets/sass/public/public.scss
|
Github Open Source
|
Open Source
|
MIT
| null |
etreprof-mb
|
HakanAkca
|
SCSS
|
Code
| 35
| 204
|
// Fonts
//@import url(https://fonts.googleapis.com/css?family=Raleway:300,400,600);
@import url('https://fonts.googleapis.com/css?family=Lato|Shadows+Into+Light');
@import url('http://maxcdn.bootstrapcdn.com/font-awesome/latest/css/font-awesome.min.css');
// Variables
@import "variables";
// Bootstrap
@import "node_modules/bootstrap-sass/assets/stylesheets/bootstrap";
// Styles customisés
@import "layout";
@import "form";
@import "typography";
@import "fx";
@import "discussions";
@import "membres";
@import "../select2/core";
@import "fontawesome-stars-o";
| 17,620
|
https://github.com/amousty/Resume_V2/blob/master/projects/Ret_V2/views/map.php
|
Github Open Source
|
Open Source
|
MTLL
| null |
Resume_V2
|
amousty
|
PHP
|
Code
| 152
| 646
|
<?php
header('content-type: application/xhtml+xml;charset=utf-8');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr">
<head>
<?php require_once $_SERVER['DOCUMENT_ROOT']. '../inc/include_css_js.inc.php'; ?>
<link href="../css/map.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<?php require_once $_SERVER['DOCUMENT_ROOT']. '../inc/header.inc.php'; ?>
<div id="page" class="container">
<!-- Partie map-->
<div id = "gamescreen">
<!-- Divison pour la map-->
<div id = "map" class="col-8">
<!-- La carte est générée ici. -->
</div>
<div id="ressources" class="col-2">
<img src="../img/resources/food.png"/>
<label id="nourriture"></label><br />
<img src="../img/resources/wood.png"/>
<label id="bois"></label><br />
<img src="../img/resources/rock.jpg"/>
<label id="pierre"></label><br />
</div>
<!-- Divison pour la vue villages-->
<div id = "village">
<div id="infoVillage"></div>
<div id="btnCreerBat"></div>
<div id="infoPersonnage"></div>
<div id="vueVillage"></div>
</div>
<!-- Partie bouton-->
<div id = "bouton">
<input type="button" class ="btn" id = "logout" value="Log out"/>
<input type="button" class ="btn" id = "reset" value="Reset"/>
<input type="button" class ="btn" id = "return" value="Return"/>
</div>
</div> <!-- Fin de gamescreen-->
</div> <!-- end page content -->
<?php require_once $_SERVER['DOCUMENT_ROOT']. '../inc/footer.inc.php'; ?>
<script src="../js/map.js" type="text/javascript" ></script>
</body>
</html>
| 8,835
|
https://github.com/TonyJenkins/python-workout/blob/master/40-bowl-limits/bowl_tester.py
|
Github Open Source
|
Open Source
|
Unlicense
| 2,021
|
python-workout
|
TonyJenkins
|
Python
|
Code
| 42
| 149
|
#!/usr/bin/env python3
"""
Exercise 40: Ice Cream Bowl Limit
Class tester for Bowl class.
"""
from bowl import Bowl
from scoop import Scoop
if __name__ == '__main__':
the_bowl = Bowl()
the_bowl.add_scoops(
Scoop('Chocolate'),
Scoop('Vanilla'),
Scoop('Mint Choc Chip'),
Scoop('Rum and Raisin'),
Scoop('Strawberry'),
)
print(the_bowl)
| 38,265
|
https://github.com/JochemKuijpers/gg_raytracer/blob/master/src/main/java/nl/jochemkuijpers/app/scenes/StackedShapeScene.java
|
Github Open Source
|
Open Source
|
MIT
| null |
gg_raytracer
|
JochemKuijpers
|
Java
|
Code
| 124
| 355
|
package nl.jochemkuijpers.app.scenes;
import nl.jochemkuijpers.math.Color;
import nl.jochemkuijpers.math.Vector3;
import nl.jochemkuijpers.raytrace.materials.*;
import nl.jochemkuijpers.raytrace.shapes.with_material.Box;
import nl.jochemkuijpers.raytrace.shapes.with_material.Sphere;
public class StackedShapeScene extends SimpleScene {
@Override
protected void createScene() {
// just a bunch of colored shapes :)
for (int j = 0; j < 6; j++) {
for (int i = 0; i < 6; i++) {
boolean transparent = (i + j) % 2 == 0;
float absorbtion = transparent ? 0.15f : 0.7f;
Material material = new ComplexMaterial(
transparent, absorbtion, 1.56f,
Color.createHSL((i * 6 + j) * 10f, 0.75f, 0.5f),
sunVector
);
sceneObjects.add(new Box(new Vector3(-10f + i * 4 , 1.01f, -10f + j * 4), 1f, material));
sceneObjects.add(new Sphere(new Vector3(-10f + i * 4 , 3.5f, -10f + j * 4), 1f, material));
}
}
}
}
| 37,706
|
https://github.com/ejc123/geotrellis/blob/master/spark/src/test/scala/geotrellis/spark/io/hadoop/formats/NetCdfInputFormatSpec.scala
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
geotrellis
|
ejc123
|
Scala
|
Code
| 500
| 1,372
|
package geotrellis.spark.io.hadoop.formats
import org.scalatest.{FunSpec, Matchers}
import org.joda.time.{DateTimeZone, DateTime}
class NetCdfInputFormatSpec extends FunSpec with Matchers {
describe("Type and Date reader") {
val DateTime19500101 = new DateTime(1950, 1, 1, 0, 0, 0, DateTimeZone.UTC)
def testWithDefaultDate(timeType: String) = {
val (typ, date) = NetCdfInputFormat.readTypeAndDate(
s"$timeType since 1950-01-01",
"T" * timeType.length + "*******YYYY*DD*MM"
)
typ should be (timeType)
date should be (DateTime19500101)
}
it("should read input with the default date time format and seconds type") {
testWithDefaultDate("seconds")
}
it("should read input with the default date time format and minutes type") {
testWithDefaultDate("minutes")
}
it("should read input with the default date time format and hours type") {
testWithDefaultDate("hours")
}
it("should read input with the default date time format and days type") {
testWithDefaultDate("days")
}
it("should read input with the default date time format and months type") {
testWithDefaultDate("months")
}
it("should read input with the default date time format and years type") {
testWithDefaultDate("years")
}
it("should read input with date with offsets") {
val (typ, date) = NetCdfInputFormat.readTypeAndDate(
"days since 1950-01-01",
"TTTT*******YYYY*DD*MM",
5, 3, 3
)
typ should be ("days")
date should be (new DateTime(1955, 4, 4, 0, 0, 0, DateTimeZone.UTC))
}
it("should read input with other formatting") {
val (typ, date) = NetCdfInputFormat.readTypeAndDate(
"1971-3-3 with DaYs",
"YYYY*M*D******TTTT"
)
typ should be ("days")
date should be (new DateTime(1971, 3, 3, 0, 0, 0, DateTimeZone.UTC))
}
it("should read input with hours included") {
val (typ, date) = NetCdfInputFormat.readTypeAndDate(
"1971-3-3 with DaYs 23",
"YYYY*M*D******TTTT**hh"
)
typ should be ("days")
date should be (new DateTime(1971, 3, 3, 23, 0, 0, DateTimeZone.UTC))
}
it("should read input with minutes included") {
val (typ, date) = NetCdfInputFormat.readTypeAndDate(
"1971-3-3 with DaYs 23",
"YYYY*M*D******TTTT**mm"
)
typ should be ("days")
date should be (new DateTime(1971, 3, 3, 0, 23, 0, DateTimeZone.UTC))
}
it("should read input with seconds included") {
val (typ, date) = NetCdfInputFormat.readTypeAndDate(
"1971-3-3 with DaYs 23",
"YYYY*M*D******TTTT**ss"
)
typ should be ("days")
date should be (new DateTime(1971, 3, 3, 0, 0, 23, DateTimeZone.UTC))
}
}
describe("Date Incrementer") {
val base = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeZone.UTC)
it("should increment date with correct number of seconds") {
val res = NetCdfInputFormat.incrementDate("seconds", 200.1337, base)
res should be (new DateTime(2000, 1, 1, 0, 3, 20, DateTimeZone.UTC))
}
it("should increment date with correct number of minutes") {
val res = NetCdfInputFormat.incrementDate("minutes", 200.1, base)
res should be (new DateTime(2000, 1, 1, 3, 20, 6, DateTimeZone.UTC))
}
it("should increment date with correct number of hours") {
val res = NetCdfInputFormat.incrementDate("hours", 25.5, base)
res should be (new DateTime(2000, 1, 2, 1, 30, 0, DateTimeZone.UTC))
}
it("should increment date with correct number of days") {
val res = NetCdfInputFormat.incrementDate("days", 25.5, base)
res should be (new DateTime(2000, 1, 26, 12, 0, 0, DateTimeZone.UTC))
}
it("should increment date with correct number of months") {
val res = NetCdfInputFormat.incrementDate("months", 39.9, base)
res should be (new DateTime(2003, 4, 1, 0, 0, 0, DateTimeZone.UTC))
}
it("should increment date with correct number of years") {
val res = NetCdfInputFormat.incrementDate("years", 40.5, base)
res should be (new DateTime(2040, 7, 1, 0, 0, 0, DateTimeZone.UTC))
}
}
}
| 44,977
|
https://github.com/NYPL-Simplified/audiobook-android/blob/master/org.librarysimplified.audiobook.open_access/src/main/java/org/librarysimplified/audiobook/open_access/ExoAudioBookPlayer.kt
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,022
|
audiobook-android
|
NYPL-Simplified
|
Kotlin
|
Code
| 2,461
| 9,098
|
package org.librarysimplified.audiobook.open_access
import android.content.Context
import android.media.AudioManager
import android.media.PlaybackParams
import android.net.Uri
import android.os.Build
import com.google.android.exoplayer.ExoPlaybackException
import com.google.android.exoplayer.ExoPlayer
import com.google.android.exoplayer.MediaCodecAudioTrackRenderer
import com.google.android.exoplayer.MediaCodecSelector
import com.google.android.exoplayer.audio.AudioCapabilities
import com.google.android.exoplayer.extractor.ExtractorSampleSource
import com.google.android.exoplayer.upstream.Allocator
import com.google.android.exoplayer.upstream.DefaultAllocator
import com.google.android.exoplayer.upstream.DefaultUriDataSource
import io.reactivex.Observable
import io.reactivex.disposables.Disposable
import io.reactivex.subjects.BehaviorSubject
import net.jcip.annotations.GuardedBy
import org.joda.time.Duration
import org.librarysimplified.audiobook.api.PlayerEvent
import org.librarysimplified.audiobook.api.PlayerEvent.PlayerEventError
import org.librarysimplified.audiobook.api.PlayerEvent.PlayerEventPlaybackRateChanged
import org.librarysimplified.audiobook.api.PlayerEvent.PlayerEventWithSpineElement.PlayerEventChapterCompleted
import org.librarysimplified.audiobook.api.PlayerEvent.PlayerEventWithSpineElement.PlayerEventChapterWaiting
import org.librarysimplified.audiobook.api.PlayerEvent.PlayerEventWithSpineElement.PlayerEventPlaybackPaused
import org.librarysimplified.audiobook.api.PlayerEvent.PlayerEventWithSpineElement.PlayerEventPlaybackProgressUpdate
import org.librarysimplified.audiobook.api.PlayerEvent.PlayerEventWithSpineElement.PlayerEventPlaybackStarted
import org.librarysimplified.audiobook.api.PlayerEvent.PlayerEventWithSpineElement.PlayerEventPlaybackStopped
import org.librarysimplified.audiobook.api.PlayerPlaybackRate
import org.librarysimplified.audiobook.api.PlayerPlaybackRate.NORMAL_TIME
import org.librarysimplified.audiobook.api.PlayerPosition
import org.librarysimplified.audiobook.api.PlayerSpineElementDownloadStatus
import org.librarysimplified.audiobook.api.PlayerSpineElementDownloadStatus.PlayerSpineElementDownloadExpired
import org.librarysimplified.audiobook.api.PlayerSpineElementDownloadStatus.PlayerSpineElementDownloadFailed
import org.librarysimplified.audiobook.api.PlayerSpineElementDownloadStatus.PlayerSpineElementDownloaded
import org.librarysimplified.audiobook.api.PlayerSpineElementDownloadStatus.PlayerSpineElementDownloading
import org.librarysimplified.audiobook.api.PlayerSpineElementDownloadStatus.PlayerSpineElementNotDownloaded
import org.librarysimplified.audiobook.api.PlayerType
import org.librarysimplified.audiobook.open_access.ExoAudioBookPlayer.ExoPlayerState.ExoPlayerStateInitial
import org.librarysimplified.audiobook.open_access.ExoAudioBookPlayer.ExoPlayerState.ExoPlayerStatePlaying
import org.librarysimplified.audiobook.open_access.ExoAudioBookPlayer.ExoPlayerState.ExoPlayerStateStopped
import org.librarysimplified.audiobook.open_access.ExoAudioBookPlayer.ExoPlayerState.ExoPlayerStateWaitingForElement
import org.librarysimplified.audiobook.open_access.ExoAudioBookPlayer.SkipChapterStatus.SKIP_TO_CHAPTER_NONEXISTENT
import org.librarysimplified.audiobook.open_access.ExoAudioBookPlayer.SkipChapterStatus.SKIP_TO_CHAPTER_NOT_DOWNLOADED
import org.librarysimplified.audiobook.open_access.ExoAudioBookPlayer.SkipChapterStatus.SKIP_TO_CHAPTER_READY
import org.slf4j.LoggerFactory
import java.util.concurrent.Callable
import java.util.concurrent.ScheduledExecutorService
import java.util.concurrent.ScheduledFuture
import java.util.concurrent.TimeUnit.SECONDS
import java.util.concurrent.atomic.AtomicBoolean
/**
* An ExoPlayer player.
*/
class ExoAudioBookPlayer private constructor(
private val engineProvider: ExoEngineProvider,
private val engineExecutor: ScheduledExecutorService,
private val context: Context,
private val statusEvents: BehaviorSubject<PlayerEvent>,
private val book: ExoAudioBook,
private val exoPlayer: ExoPlayer,
manifestUpdates: Observable<Unit>
) : PlayerType {
private val manifestSubscription: Disposable
private val log = LoggerFactory.getLogger(ExoAudioBookPlayer::class.java)
private val bufferSegmentSize = 64 * 1024
private val bufferSegmentCount = 256
private val userAgent = "${this.engineProvider.name()}/${this.engineProvider.version()}"
private val closed = AtomicBoolean(false)
init {
this.manifestSubscription = manifestUpdates.subscribe {
this.onManifestUpdated()
}
}
private fun onManifestUpdated() {
this.statusEvents.onNext(PlayerEvent.PlayerEventManifestUpdated)
}
/*
* The current playback state.
*/
private sealed class ExoPlayerState {
/*
* The initial state; no spine element is selected, the player is not playing.
*/
object ExoPlayerStateInitial : ExoPlayerState()
/*
* The player is currently playing the given spine element.
*/
data class ExoPlayerStatePlaying(
var spineElement: ExoSpineElement,
val observerTask: ScheduledFuture<*>
) :
ExoPlayerState()
/*
* The player is waiting until the given spine element is downloaded before continuing playback.
*/
data class ExoPlayerStateWaitingForElement(
var spineElement: ExoSpineElement
) :
ExoPlayerState()
/*
* The player was playing the given spine element but is currently paused.
*/
data class ExoPlayerStateStopped(
var spineElement: ExoSpineElement
) :
ExoPlayerState()
}
@Volatile
private var currentPlaybackRate: PlayerPlaybackRate = NORMAL_TIME
@Volatile
private var currentPlaybackOffset: Long = 0
set(value) {
this.log.trace("currentPlaybackOffset: {}", value)
field = value
}
private val stateLock: Any = Object()
@GuardedBy("stateLock")
private var state: ExoPlayerState = ExoPlayerStateInitial
private val downloadEventSubscription: Disposable
private val allocator: Allocator = DefaultAllocator(this.bufferSegmentSize)
private var exoAudioRenderer: MediaCodecAudioTrackRenderer? = null
private fun stateSet(state: ExoPlayerState) {
synchronized(this.stateLock) { this.state = state }
}
private fun stateGet(): ExoPlayerState =
synchronized(this.stateLock) { this.state }
/*
* A listener registered with the underlying ExoPlayer instance to observe state changes.
*/
private val exoPlayerEventListener = object : ExoPlayer.Listener {
override fun onPlayerError(error: ExoPlaybackException?) {
this@ExoAudioBookPlayer.log.error("onPlayerError: ", error)
this@ExoAudioBookPlayer.statusEvents.onNext(
PlayerEventError(
spineElement = this@ExoAudioBookPlayer.currentSpineElement(),
exception = error,
errorCode = -1,
offsetMilliseconds = this@ExoAudioBookPlayer.currentPlaybackOffset
)
)
}
override fun onPlayerStateChanged(playWhenReady: Boolean, stateNow: Int) {
val stateName = this.stateName(stateNow)
this@ExoAudioBookPlayer.log.debug(
"onPlayerStateChanged: {} {} ({})", playWhenReady, stateName, stateNow
)
}
private fun stateName(playbackState: Int): String {
return when (playbackState) {
ExoPlayer.STATE_BUFFERING -> "buffering"
ExoPlayer.STATE_ENDED -> "ended"
ExoPlayer.STATE_IDLE -> "idle"
ExoPlayer.STATE_PREPARING -> "preparing"
ExoPlayer.STATE_READY -> "ready"
else -> "unrecognized state"
}
}
override fun onPlayWhenReadyCommitted() {
this@ExoAudioBookPlayer.log.debug("onPlayWhenReadyCommitted")
}
}
init {
this.exoPlayer.addListener(this.exoPlayerEventListener)
/*
* Subscribe to notifications of download changes. This is only needed because the
* player may be waiting for a chapter to be downloaded and needs to know when it can
* safely play the chapter.
*/
this.downloadEventSubscription =
this.book.spineElementDownloadStatus.subscribe(
{ status -> this.engineExecutor.execute { this.onDownloadStatusChanged(status) } },
{ exception -> this.log.error("download status error: ", exception) }
)
}
companion object {
fun create(
book: ExoAudioBook,
engineProvider: ExoEngineProvider,
context: Context,
engineExecutor: ScheduledExecutorService,
manifestUpdates: Observable<Unit>
): ExoAudioBookPlayer {
val statusEvents =
BehaviorSubject.create<PlayerEvent>()
/*
* Initialize the audio player on the engine thread.
*/
return engineExecutor.submit(
Callable {
/*
* The rendererCount parameter is not well documented. It appears to be the number of
* renderers that are required to render a single track. To render a piece of video that
* had video, audio, and a subtitle track would require three renderers. Audio books should
* require just one.
*/
val player =
ExoPlayer.Factory.newInstance(1)
return@Callable ExoAudioBookPlayer(
book = book,
context = context,
engineProvider = engineProvider,
engineExecutor = engineExecutor,
exoPlayer = player,
statusEvents = statusEvents,
manifestUpdates = manifestUpdates
)
}
).get(5L, SECONDS)
}
}
/**
* A playback observer that is called repeatedly to observe the current state of the player.
*/
private inner class PlaybackObserver(
private val spineElement: ExoSpineElement,
private var initialSeek: Long?
) : Runnable {
private var gracePeriod: Int = 1
override fun run() {
val bookPlayer = this@ExoAudioBookPlayer
val duration = bookPlayer.exoPlayer.duration
val position = bookPlayer.exoPlayer.currentPosition
bookPlayer.log.debug("playback: {}/{}", position, duration)
this.spineElement.duration = Duration.millis(duration)
/*
* Perform the initial seek, if necessary.
*/
val seek = this.initialSeek
if (seek != null) {
bookPlayer.engineExecutor.execute {
if (seek < 0L) {
bookPlayer.seek(duration + seek)
} else {
bookPlayer.seek(seek)
}
}
this.initialSeek = null
}
/*
* Report the current playback status.
*/
bookPlayer.currentPlaybackOffset = position
bookPlayer.statusEvents.onNext(
PlayerEventPlaybackProgressUpdate(this.spineElement, position)
)
/*
* Provide a short grace period before indicating that the current spine element has
* finished playing. This avoids a situation where the player indicates that it is at
* the end of the audio but the sound hardware has not actually finished playing the last
* chunk.
*/
if (position >= duration) {
if (this.gracePeriod == 0) {
bookPlayer.currentPlaybackOffset = bookPlayer.exoPlayer.duration
bookPlayer.engineExecutor.execute {
bookPlayer.opCurrentTrackFinished()
}
}
--this.gracePeriod
}
}
}
private fun openSpineElement(
spineElement: ExoSpineElement,
offset: Long
): ScheduledFuture<*> {
this.log.debug("openSpineElement: {} (offset {})", spineElement.index, offset)
/*
* Set up an audio renderer for the spine element and tell ExoPlayer to prepare it and then
* play when ready.
*/
val dataSource =
DefaultUriDataSource(this.context, null, this.userAgent)
val uri =
Uri.fromFile(spineElement.partFile)
val sampleSource =
ExtractorSampleSource(
uri,
dataSource,
this.allocator,
this.bufferSegmentCount * this.bufferSegmentSize,
null,
null,
0
)
this.exoAudioRenderer =
MediaCodecAudioTrackRenderer(
sampleSource,
MediaCodecSelector.DEFAULT,
null,
true,
null,
null,
AudioCapabilities.getCapabilities(this.context),
AudioManager.STREAM_MUSIC
)
this.exoPlayer.prepare(this.exoAudioRenderer)
this.seek(offset)
this.exoPlayer.playWhenReady = true
this.setPlayerPlaybackRate(this.currentPlaybackRate)
return this.schedulePlaybackObserverForSpineElement(spineElement, initialSeek = null)
}
/**
* Schedule a playback observer that will check the current state of playback once per second.
*/
private fun schedulePlaybackObserverForSpineElement(
spineElement: ExoSpineElement,
initialSeek: Long?
): ScheduledFuture<*> {
return this.engineExecutor.scheduleAtFixedRate(
this.PlaybackObserver(spineElement, initialSeek), 1L, 1L, SECONDS
)
}
/**
* The download status of a spine element has changed. We only actually care about
* the spine element that we're either currently playing or are currently waiting for.
* Everything else is uninteresting.
*/
private fun onDownloadStatusChanged(status: PlayerSpineElementDownloadStatus) {
ExoEngineThread.checkIsExoEngineThread()
return when (val currentState = this.stateGet()) {
ExoPlayerStateInitial -> Unit
/*
* If the we're playing the current spine element, and the status is anything other
* than "downloaded", stop everything.
*/
is ExoPlayerStatePlaying -> {
if (currentState.spineElement == status.spineElement) {
when (status) {
is PlayerSpineElementNotDownloaded,
is PlayerSpineElementDownloading,
is PlayerSpineElementDownloadExpired,
is PlayerSpineElementDownloadFailed -> {
this.log.debug("spine element status changed, stopping playback")
this.playNothing()
}
is PlayerSpineElementDownloaded -> Unit
}
} else {
}
}
/*
* If the we're stopped on the current spine element, and the status is anything other
* than "downloaded", stop everything.
*/
is ExoPlayerStateStopped -> {
if (currentState.spineElement == status.spineElement) {
when (status) {
is PlayerSpineElementNotDownloaded,
is PlayerSpineElementDownloading,
is PlayerSpineElementDownloadExpired,
is PlayerSpineElementDownloadFailed -> {
this.log.debug("spine element status changed, stopping playback")
this.playNothing()
}
is PlayerSpineElementDownloaded -> Unit
}
} else {
}
}
/*
* If we're waiting for the spine element in question, and the status is now "downloaded",
* then start playing.
*/
is ExoPlayerStateWaitingForElement -> {
if (currentState.spineElement == status.spineElement) {
when (status) {
is PlayerSpineElementNotDownloaded,
is PlayerSpineElementDownloading,
is PlayerSpineElementDownloadExpired,
is PlayerSpineElementDownloadFailed -> Unit
is PlayerSpineElementDownloaded -> {
this.log.debug("spine element status changed, trying to start playback")
this.playSpineElementIfAvailable(currentState.spineElement, 0)
Unit
}
}
} else {
}
}
}
}
/**
* Configure the current player to use the given playback rate.
*/
private fun setPlayerPlaybackRate(newRate: PlayerPlaybackRate) {
this.log.debug("setPlayerPlaybackRate: {}", newRate)
this.statusEvents.onNext(PlayerEventPlaybackRateChanged(newRate))
/*
* If the player has not started playing a track, then attempting to set the playback
* rate on the player will actually end up blocking until another track is loaded.
*/
if (this.exoAudioRenderer != null) {
if (Build.VERSION.SDK_INT >= 23) {
val params = PlaybackParams()
params.speed = newRate.speed.toFloat()
this.exoPlayer.sendMessage(this.exoAudioRenderer, 2, params)
}
}
}
/**
* Forcefully stop playback and reset the player.
*/
private fun playNothing() {
this.log.debug("playNothing")
fun resetPlayer() {
this.log.debug("playNothing: resetting player")
this.exoPlayer.stop()
this.exoPlayer.seekTo(0L)
this.currentPlaybackOffset = 0
this.stateSet(ExoPlayerStateInitial)
}
return when (val currentState = this.stateGet()) {
ExoPlayerStateInitial -> resetPlayer()
is ExoPlayerStatePlaying -> {
currentState.observerTask.cancel(true)
resetPlayer()
this.statusEvents.onNext(PlayerEventPlaybackStopped(currentState.spineElement, 0))
}
is ExoPlayerStateWaitingForElement -> {
resetPlayer()
this.statusEvents.onNext(PlayerEventPlaybackStopped(currentState.spineElement, 0))
}
is ExoPlayerStateStopped -> {
resetPlayer()
this.statusEvents.onNext(PlayerEventPlaybackStopped(currentState.spineElement, 0))
}
}
}
private fun playFirstSpineElementIfAvailable(offset: Long): SkipChapterStatus {
this.log.debug("playFirstSpineElementIfAvailable: {}", offset)
val firstElement = this.book.spine.firstOrNull()
if (firstElement == null) {
this.log.debug("no available initial spine element")
return SKIP_TO_CHAPTER_NONEXISTENT
}
return this.playSpineElementIfAvailable(firstElement, offset)
}
private fun playLastSpineElementIfAvailable(offset: Long): SkipChapterStatus {
this.log.debug("playLastSpineElementIfAvailable: {}", offset)
val lastElement = this.book.spine.lastOrNull()
if (lastElement == null) {
this.log.debug("no available final spine element")
return SKIP_TO_CHAPTER_NONEXISTENT
}
return this.playSpineElementIfAvailable(lastElement, offset)
}
private fun playNextSpineElementIfAvailable(
element: ExoSpineElement,
offset: Long
): SkipChapterStatus {
this.log.debug("playNextSpineElementIfAvailable: {} {}", element.index, offset)
val next = element.next as ExoSpineElement?
if (next == null) {
this.log.debug("spine element {} has no next element", element.index)
return SKIP_TO_CHAPTER_NONEXISTENT
}
return this.playSpineElementIfAvailable(next, offset)
}
private fun playPreviousSpineElementIfAvailable(
element: ExoSpineElement,
offset: Long
): SkipChapterStatus {
this.log.debug("playPreviousSpineElementIfAvailable: {} {}", element.index, offset)
val previous = element.previous as ExoSpineElement?
if (previous == null) {
this.log.debug("spine element {} has no previous element", element.index)
return SKIP_TO_CHAPTER_NONEXISTENT
}
return this.playSpineElementIfAvailable(previous, offset)
}
private fun playSpineElementIfAvailable(
element: ExoSpineElement,
offset: Long
): SkipChapterStatus {
this.log.debug("playSpineElementIfAvailable: {}", element.index)
this.playNothing()
return when (val downloadStatus = element.downloadStatus) {
is PlayerSpineElementNotDownloaded,
is PlayerSpineElementDownloading,
is PlayerSpineElementDownloadExpired,
is PlayerSpineElementDownloadFailed -> {
this.log.debug(
"playSpineElementIfAvailable: spine element {} is not downloaded ({}), cannot continue",
element.index, downloadStatus
)
this.stateSet(ExoPlayerStateWaitingForElement(spineElement = element))
this.statusEvents.onNext(PlayerEventChapterWaiting(element))
SKIP_TO_CHAPTER_NOT_DOWNLOADED
}
is PlayerSpineElementDownloaded -> {
this.playSpineElementUnconditionally(element, offset)
SKIP_TO_CHAPTER_READY
}
}
}
private fun playSpineElementUnconditionally(element: ExoSpineElement, offset: Long = 0) {
this.log.debug("playSpineElementUnconditionally: {}", element.index)
this.stateSet(
ExoPlayerStatePlaying(
spineElement = element,
observerTask = this.openSpineElement(element, offset)
)
)
this.statusEvents.onNext(PlayerEventPlaybackStarted(element, offset))
this.currentPlaybackOffset = offset
}
private fun seek(offsetMs: Long) {
this.log.debug("seek: {}", offsetMs)
this.exoPlayer.seekTo(offsetMs)
this.currentPlaybackOffset = offsetMs
}
private fun opSetPlaybackRate(newRate: PlayerPlaybackRate) {
ExoEngineThread.checkIsExoEngineThread()
this.log.debug("opSetPlaybackRate: {}", newRate)
this.currentPlaybackRate = newRate
this.setPlayerPlaybackRate(newRate)
}
private fun opPlay() {
ExoEngineThread.checkIsExoEngineThread()
this.log.debug("opPlay")
return when (val state = this.stateGet()) {
is ExoPlayerStateInitial -> {
this.playFirstSpineElementIfAvailable(offset = 0)
Unit
}
is ExoPlayerStatePlaying ->
this.log.debug("opPlay: already playing")
is ExoPlayerStateStopped ->
this.opPlayStopped(state)
is ExoPlayerStateWaitingForElement -> {
this.playSpineElementIfAvailable(state.spineElement, offset = 0)
Unit
}
}
}
private fun opPlayStopped(state: ExoPlayerStateStopped) {
ExoEngineThread.checkIsExoEngineThread()
this.log.debug("opPlayStopped")
this.exoPlayer.playWhenReady = true
this.stateSet(
ExoPlayerStatePlaying(
spineElement = state.spineElement,
observerTask = this.schedulePlaybackObserverForSpineElement(
spineElement = state.spineElement,
initialSeek = null
)
)
)
this.statusEvents.onNext(
PlayerEventPlaybackStarted(
state.spineElement, this.currentPlaybackOffset
)
)
}
private fun opCurrentTrackFinished() {
ExoEngineThread.checkIsExoEngineThread()
this.log.debug("opCurrentTrackFinished")
return when (val state = this.stateGet()) {
is ExoPlayerStateInitial,
is ExoPlayerStateWaitingForElement,
is ExoPlayerStateStopped -> {
this.log.error("current track is finished but the player thinks it is not playing!")
throw Unimplemented()
}
is ExoPlayerStatePlaying -> {
this.statusEvents.onNext(PlayerEventChapterCompleted(state.spineElement))
when (this.playNextSpineElementIfAvailable(state.spineElement, offset = 0)) {
SKIP_TO_CHAPTER_NOT_DOWNLOADED,
SKIP_TO_CHAPTER_READY -> Unit
SKIP_TO_CHAPTER_NONEXISTENT ->
this.playNothing()
}
}
}
}
/**
* The status of an attempt to switch to a chapter.
*/
private enum class SkipChapterStatus {
/**
* The chapter is not downloaded and therefore cannot be played at the moment.
*/
SKIP_TO_CHAPTER_NOT_DOWNLOADED,
/**
* The chapter does not exist and will never exist.
*/
SKIP_TO_CHAPTER_NONEXISTENT,
/**
* The chapter exists and is ready for playback.
*/
SKIP_TO_CHAPTER_READY
}
private fun opSkipToNextChapter(offset: Long): SkipChapterStatus {
ExoEngineThread.checkIsExoEngineThread()
this.log.debug("opSkipToNextChapter")
return when (val state = this.stateGet()) {
is ExoPlayerStateInitial ->
this.playFirstSpineElementIfAvailable(offset)
is ExoPlayerStatePlaying ->
this.playNextSpineElementIfAvailable(state.spineElement, offset)
is ExoPlayerStateStopped ->
this.playNextSpineElementIfAvailable(state.spineElement, offset)
is ExoPlayerStateWaitingForElement ->
this.playNextSpineElementIfAvailable(state.spineElement, offset)
}
}
private fun opSkipToPreviousChapter(offset: Long): SkipChapterStatus {
ExoEngineThread.checkIsExoEngineThread()
this.log.debug("opSkipToPreviousChapter")
return when (val state = this.stateGet()) {
ExoPlayerStateInitial ->
this.playLastSpineElementIfAvailable(offset)
is ExoPlayerStatePlaying ->
this.playPreviousSpineElementIfAvailable(state.spineElement, offset)
is ExoPlayerStateWaitingForElement ->
this.playPreviousSpineElementIfAvailable(state.spineElement, offset)
is ExoPlayerStateStopped ->
this.playPreviousSpineElementIfAvailable(state.spineElement, offset)
}
}
private fun opPause() {
ExoEngineThread.checkIsExoEngineThread()
this.log.debug("opPause")
return when (val state = this.stateGet()) {
is ExoPlayerStateInitial ->
this.log.debug("not pausing in the initial state")
is ExoPlayerStatePlaying ->
this.opPausePlaying(state)
is ExoPlayerStateStopped ->
this.log.debug("not pausing in the stopped state")
is ExoPlayerStateWaitingForElement ->
this.log.debug("not pausing in the waiting state")
}
}
private fun opPausePlaying(state: ExoPlayerStatePlaying) {
ExoEngineThread.checkIsExoEngineThread()
this.log.debug("opPausePlaying: offset: {}", this.currentPlaybackOffset)
state.observerTask.cancel(true)
this.exoPlayer.playWhenReady = false
this.stateSet(ExoPlayerStateStopped(spineElement = state.spineElement))
this.statusEvents.onNext(
PlayerEventPlaybackPaused(
state.spineElement, this.currentPlaybackOffset
)
)
}
private fun opSkipPlayhead(milliseconds: Long) {
this.log.debug("opSkipPlayhead")
return when {
milliseconds == 0L -> {
}
milliseconds > 0 -> opSkipForward(milliseconds)
else -> opSkipBack(milliseconds)
}
}
private fun opSkipForward(milliseconds: Long) {
ExoEngineThread.checkIsExoEngineThread()
this.log.debug("opSkipForward")
assert(milliseconds > 0, { "Milliseconds must be positive" })
val offset =
Math.min(this.exoPlayer.duration, this.exoPlayer.currentPosition + milliseconds)
this.seek(offset)
return when (val state = this.stateGet()) {
ExoPlayerStateInitial,
is ExoPlayerStatePlaying,
is ExoPlayerStateWaitingForElement -> Unit
is ExoPlayerStateStopped ->
this.statusEvents.onNext(
PlayerEventPlaybackPaused(
state.spineElement, this.currentPlaybackOffset
)
)
}
}
private fun opSkipBack(milliseconds: Long) {
ExoEngineThread.checkIsExoEngineThread()
this.log.debug("opSkipBack")
assert(milliseconds < 0, { "Milliseconds must be negative" })
/*
* If the current time is in the range [00:00, 00:04], skipping back should switch
* to the previous spine element and then jump 15 seconds back from the end of that
* element. Otherwise, it should simply skip backwards, clamping the minimum to 00:00.
*/
val current = this.exoPlayer.currentPosition
if (current <= 4_000L) {
this.opSkipToPreviousChapter(milliseconds)
} else {
this.seek(Math.max(0L, current + milliseconds))
}
return when (val state = this.stateGet()) {
ExoPlayerStateInitial,
is ExoPlayerStatePlaying,
is ExoPlayerStateWaitingForElement -> Unit
is ExoPlayerStateStopped ->
this.statusEvents.onNext(
PlayerEventPlaybackPaused(
state.spineElement, this.currentPlaybackOffset
)
)
}
}
private fun opPlayAtLocation(location: PlayerPosition) {
ExoEngineThread.checkIsExoEngineThread()
this.log.debug("opPlayAtLocation: {}", location)
val currentSpineElement =
this.currentSpineElement()
val requestedSpineElement =
this.book.spineElementForPartAndChapter(location.part, location.chapter)
as ExoSpineElement?
if (requestedSpineElement == null) {
return this.log.debug("spine element does not exist")
}
/*
* If the current spine element is the same as the requested spine element, then it's more
* efficient to simply seek to the right offset and start playing.
*/
if (requestedSpineElement == currentSpineElement) {
this.seek(location.offsetMilliseconds)
this.opPlay()
} else {
this.playSpineElementIfAvailable(requestedSpineElement, location.offsetMilliseconds)
}
}
private fun currentSpineElement(): ExoSpineElement? {
return when (val state = this.stateGet()) {
ExoPlayerStateInitial -> null
is ExoPlayerStatePlaying -> state.spineElement
is ExoPlayerStateWaitingForElement -> null
is ExoPlayerStateStopped -> state.spineElement
}
}
private fun opMovePlayheadToLocation(location: PlayerPosition) {
ExoEngineThread.checkIsExoEngineThread()
this.log.debug("opMovePlayheadToLocation: {}", location)
this.opPlayAtLocation(location)
this.opPause()
}
private fun opClose() {
ExoEngineThread.checkIsExoEngineThread()
this.log.debug("opClose")
this.manifestSubscription.dispose()
this.downloadEventSubscription.dispose()
this.playNothing()
this.exoPlayer.release()
this.statusEvents.onComplete()
}
override val isPlaying: Boolean
get() {
this.checkNotClosed()
return when (this.stateGet()) {
is ExoPlayerStateInitial -> false
is ExoPlayerStatePlaying -> true
is ExoPlayerStateStopped -> false
is ExoPlayerStateWaitingForElement -> true
}
}
private fun checkNotClosed() {
if (this.closed.get()) {
throw IllegalStateException("Player has been closed")
}
}
override var playbackRate: PlayerPlaybackRate
get() {
this.checkNotClosed()
return this.currentPlaybackRate
}
set(value) {
this.checkNotClosed()
this.engineExecutor.execute { this.opSetPlaybackRate(value) }
}
override val events: Observable<PlayerEvent>
get() {
this.checkNotClosed()
return this.statusEvents
}
override fun play() {
this.checkNotClosed()
this.engineExecutor.execute { this.opPlay() }
}
override fun pause() {
this.checkNotClosed()
this.engineExecutor.execute { this.opPause() }
}
override fun skipToNextChapter() {
this.checkNotClosed()
this.engineExecutor.execute { this.opSkipToNextChapter(offset = 0) }
}
override fun skipToPreviousChapter() {
this.checkNotClosed()
this.engineExecutor.execute { this.opSkipToPreviousChapter(offset = 0) }
}
override fun skipPlayhead(milliseconds: Long) {
this.checkNotClosed()
this.engineExecutor.execute { this.opSkipPlayhead(milliseconds) }
}
override fun playAtLocation(location: PlayerPosition) {
this.checkNotClosed()
this.engineExecutor.execute { this.opPlayAtLocation(location) }
}
override fun movePlayheadToLocation(location: PlayerPosition) {
this.checkNotClosed()
this.engineExecutor.execute { this.opMovePlayheadToLocation(location) }
}
override fun playAtBookStart() {
this.checkNotClosed()
this.engineExecutor.execute { this.opPlayAtLocation(this.book.spine.first().position) }
}
override fun movePlayheadToBookStart() {
this.checkNotClosed()
this.engineExecutor.execute { this.opMovePlayheadToLocation(this.book.spine.first().position) }
}
override val isClosed: Boolean
get() = this.closed.get()
override fun close() {
if (this.closed.compareAndSet(false, true)) {
this.engineExecutor.execute { this.opClose() }
}
}
}
| 20,057
|
https://github.com/tchivs/BlazorComponent/blob/master/src/Component/BlazorComponent/Components/Input/Content/Control/InputSlot/DefaultSlot/Label/BInputLabel.razor.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
BlazorComponent
|
tchivs
|
C#
|
Code
| 44
| 133
|
using Microsoft.AspNetCore.Components;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlazorComponent
{
public partial class BInputLabel<TValue, TInput> : ComponentPartBase<TInput>
where TInput : IInput<TValue>
{
public bool HasLabel => Component.HasLabel;
public string Label => Component.Label;
public RenderFragment LabelContent => Component.LabelContent;
}
}
| 39,507
|
https://github.com/swtcpro/jingtum-lib-objectc/blob/master/WebSocketClient/jingtum-lib/NSString+sha.h
|
Github Open Source
|
Open Source
|
MIT, Apache-2.0
| 2,018
|
jingtum-lib-objectc
|
swtcpro
|
Objective-C
|
Code
| 46
| 153
|
//
// NSString+sha.h
// WebSocketClient
//
// Created by tongmuxu on 2018/6/30.
// Copyright © 2018年 tongmuxu. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <CommonCrypto/CommonDigest.h>
#import <CommonCrypto/CommonCryptor.h>
@interface NSString (sha)
-(NSString *) sha1;
-(NSString *) sha224;
-(NSString *) sha256;
-(NSString *) sha384;
-(NSString *) sha512;
@end
| 31,244
|
https://github.com/framptonjs/frampton-style/blob/master/src/types.ts
|
Github Open Source
|
Open Source
|
MIT
| null |
frampton-style
|
framptonjs
|
TypeScript
|
Code
| 8
| 17
|
export interface StyleMap {
[name: string]: string;
}
| 25,509
|
https://github.com/mehulsbhatt/js-dossier/blob/master/src/java/com/github/jsdossier/Flags.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,016
|
js-dossier
|
mehulsbhatt
|
Java
|
Code
| 382
| 969
|
/*
Copyright 2013-2016 Jason Leyba
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.github.jsdossier;
import static com.google.common.base.Preconditions.checkArgument;
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;
import org.kohsuke.args4j.Option;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.Path;
/**
* Describes the runtime configuration for the app.
*/
class Flags {
boolean displayHelp;
boolean printConfig;
int numThreads = Runtime.getRuntime().availableProcessors() * 2;
Path config = null;
private final FileSystem fileSystem;
private Flags(FileSystem fileSystem) {
this.fileSystem = fileSystem;
}
@Option(
name = "--help", aliases = "-h",
usage = "Print this help message and exit.")
private void setDisplayHelp(boolean help) {
this.displayHelp = help;
}
@Option(
name = "--config", aliases = "-c",
required = true,
metaVar = "CONFIG",
usage = "Path to the JSON configuration file to use.")
private void setConfigPath(String path) {
config = fileSystem.getPath(path).toAbsolutePath().normalize();
checkArgument(Files.exists(config), "Path does not exist: %s", config);
checkArgument(Files.isReadable(config), "Path is not readable: %s", config);
}
@Option(
name = "--print_config", aliases = "-p",
usage = "Whether to print diagnostic information about the parsed JSON configuration, " +
"including all resolved paths.")
private void setPrintConfig(boolean print) {
this.printConfig = print;
}
@Option(
name = "--num_threads",
usage = "The number of threads to use for rendering. Defaults to 2 times the number of " +
"available processors")
private void setNumThreads(int n) {
checkArgument(n >= 1, "invalid number of flags: %s", n);
this.numThreads = n;
}
/**
* Parses the given command line flags, exiting the program if there are any errors or if usage
* information was requested with the {@link #displayHelp --help} flag.
*/
synchronized static Flags parse(String[] args, FileSystem fileSystem) {
final Flags flags = new Flags(fileSystem);
CmdLineParser parser = new CmdLineParser(flags);
parser.setUsageWidth(79);
try {
parser.parseArgument(args);
} catch (CmdLineException e) {
if (!flags.displayHelp) {
System.err.println(e.getMessage());
}
flags.displayHelp = true;
}
if (flags.displayHelp) {
System.err.println("\nUsage: dossier [options] -c CONFIG");
System.err.println("\nwhere options include:\n");
parser.printUsage(System.err);
System.err.println("\nThe JSON configuration file may have the following options:\n");
System.err.println(Config.getOptionsText(false));
System.exit(1);
}
return flags;
}
}
| 12,004
|
https://github.com/luoxiaowang/webpack-react/blob/master/webpack.production.config.js
|
Github Open Source
|
Open Source
|
MIT
| 2,016
|
webpack-react
|
luoxiaowang
|
JavaScript
|
Code
| 95
| 538
|
var path = require('path');
var webpack = require('webpack');
var node_modules_dir = path.resolve(__dirname, 'node_modules');
var config = {
entry: {
app:path.resolve(__dirname, 'app/main.js'),
mobile: path.resolve(__dirname, 'app/mobile.js'),
commons: ['react', 'react-dom']//将经常用的库js包打到commons.js中,此js中的内容不会经常变动
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].js' // 注意我们使用了变量
},
module: {
loaders: [{
test: /\.js$/,
// 这里再也不需通过任何第三方来加载
exclude: [node_modules_dir],
loader: 'babel'
},{
test: /\.css$/,
loader: 'style-loader!css-loader!postcss-loader'
},{
test: /\.less$/,
loader: 'style-loader!css-loader!postcss-loader!less-loader'
}, {
test: /\.(png|jpg|gif|woff|woff2)$/,
loader: 'url-loader?limit=8192'
}]
},
plugins: [
//这个插件可以将多个打包后的资源中的公共部分打包成单独的文件,公共文件必须引入
new webpack.optimize.CommonsChunkPlugin({
name: "commons", //上面配置的公共内容
filename: "commons.js",
minChunks: 2//当项目中引用次数超过2次的包自动打入commons.js中,可自行根据需要进行调整优化
}),
new webpack.optimize.UglifyJsPlugin({ //压缩版
compress: {
warnings: false
},
})
]
};
module.exports = config;
| 40,369
|
https://github.com/andrasigneczi/TravelOptimizer/blob/master/DataCollector/mozilla/xulrunner-sdk/include/mozilla/dom/telephony/TelephonyParent.h
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,018
|
TravelOptimizer
|
andrasigneczi
|
C++
|
Code
| 211
| 855
|
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
#ifndef mozilla_dom_telephony_TelephonyParent_h
#define mozilla_dom_telephony_TelephonyParent_h
#include "mozilla/dom/telephony/TelephonyCommon.h"
#include "mozilla/dom/telephony/PTelephonyParent.h"
#include "mozilla/dom/telephony/PTelephonyRequestParent.h"
#include "nsITelephonyService.h"
BEGIN_TELEPHONY_NAMESPACE
class TelephonyParent : public PTelephonyParent
, public nsITelephonyListener
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSITELEPHONYLISTENER
TelephonyParent();
protected:
virtual ~TelephonyParent() {}
virtual void
ActorDestroy(ActorDestroyReason aWhy) override;
virtual bool
RecvPTelephonyRequestConstructor(PTelephonyRequestParent* aActor, const IPCTelephonyRequest& aRequest) override;
virtual PTelephonyRequestParent*
AllocPTelephonyRequestParent(const IPCTelephonyRequest& aRequest) override;
virtual bool
DeallocPTelephonyRequestParent(PTelephonyRequestParent* aActor) override;
virtual bool
Recv__delete__() override;
virtual bool
RecvRegisterListener() override;
virtual bool
RecvUnregisterListener() override;
virtual bool
RecvStartTone(const uint32_t& aClientId, const nsString& aTone) override;
virtual bool
RecvStopTone(const uint32_t& aClientId) override;
virtual bool
RecvGetMicrophoneMuted(bool* aMuted) override;
virtual bool
RecvSetMicrophoneMuted(const bool& aMuted) override;
virtual bool
RecvGetSpeakerEnabled(bool* aEnabled) override;
virtual bool
RecvSetSpeakerEnabled(const bool& aEnabled) override;
private:
bool mActorDestroyed;
bool mRegistered;
};
class TelephonyRequestParent : public PTelephonyRequestParent
, public nsITelephonyListener
, public nsITelephonyDialCallback
{
friend class TelephonyParent;
public:
NS_DECL_ISUPPORTS
NS_DECL_NSITELEPHONYLISTENER
NS_DECL_NSITELEPHONYCALLBACK
NS_DECL_NSITELEPHONYDIALCALLBACK
protected:
TelephonyRequestParent();
virtual ~TelephonyRequestParent() {}
virtual void
ActorDestroy(ActorDestroyReason aWhy) override;
nsresult
SendResponse(const IPCTelephonyResponse& aResponse);
private:
bool mActorDestroyed;
};
END_TELEPHONY_NAMESPACE
#endif /* mozilla_dom_telephony_TelephonyParent_h */
| 46,254
|
https://github.com/stemmlerjs/univjobs-front-static/blob/master/src/components/student-pack/styles/Pack.sass
|
Github Open Source
|
Open Source
|
MIT
| null |
univjobs-front-static
|
stemmlerjs
|
Sass
|
Code
| 108
| 449
|
.pack
padding-top: 2rem;
h3
text-align: center;
.pack-container
max-width: 1250px;
margin: 0 auto;
padding: 2rem;
display: flex;
flex-direction: row;
justify-content: space-evenly;
flex-wrap: wrap;
position: relative;
.hidden-transparency
background-image: linear-gradient(to bottom, rgba(255, 255, 255, 0), white);
height: 100%;
width: 100%;
position: absolute;
.pack-item
max-width: 300px;
box-shadow: 4px 4px 12px rgba(0,0,0,.04);
padding: 1rem;
border-radius: 4px;
margin-bottom: 1rem;
text-decoration: none;
color: inherit;
.logo-container
height: 80px;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
margin-bottom: 1rem;
img
margin: 0;
max-height: 75px;
.description
min-height: 125px;
font-size: 16px;
.offering-container
font-size: 16px;
.offering-description
opacity: 0.5;
font-size: 16px;
.offering
margin-top: 0.5rem;
background: #42c93f;
color: white;
font-family: 'Roboto';
display: inline-block;
border-radius: 3px;
font-size: 16px;
padding: 4px 8px 4px 8px;
| 38,790
|
https://github.com/goyalshubhangi/practicals_3_year/blob/master/It/jsp_javascript/Prac9.java
|
Github Open Source
|
Open Source
|
MIT
| null |
practicals_3_year
|
goyalshubhangi
|
Java
|
Code
| 65
| 167
|
/*
* 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 P6;
import javax.servlet.jsp.tagext.SimpleTagSupport;
import javax.servlet.jsp.*;
import java.io.*;
import java.util.Calendar;
public class Prac9 extends SimpleTagSupport {
public void doTag() throws JspException, IOException
{
JspWriter out = getJspContext().getOut();
out.print("<br>Today's Date: ");
out.print(Calendar.getInstance().getTime());
}
}
| 43,606
|
https://github.com/moe1129peterson/node_express_api/blob/master/node_modules/pnpm/lib/node_modules/supi/lib/install/shrinkwrap.js
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
node_express_api
|
moe1129peterson
|
JavaScript
|
Code
| 60
| 218
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const encodeRegistry = require("encode-registry");
function absolutePathToRef(absolutePath, opts) {
if (opts.resolution.type)
return absolutePath;
const registryName = encodeRegistry(opts.standardRegistry);
if (absolutePath.startsWith(`${registryName}/`) && absolutePath.indexOf('/-/') === -1) {
if (opts.alias === opts.realName) {
const ref = absolutePath.replace(`${registryName}/${opts.realName}/`, '');
if (ref.indexOf('/') === -1)
return ref;
}
return absolutePath.replace(`${registryName}/`, '/');
}
return absolutePath;
}
exports.absolutePathToRef = absolutePathToRef;
//# sourceMappingURL=shrinkwrap.js.map
| 47,809
|
https://github.com/openvinotoolkit/openvino/blob/master/tools/mo/openvino/tools/mo/front/tf/reduce_ext.py
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,023
|
openvino
|
openvinotoolkit
|
Python
|
Code
| 175
| 791
|
# Copyright (C) 2018-2023 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
from openvino.tools.mo.ops.ReduceOps import ReduceProd, ReduceAnd, ReduceMax, ReduceMean, ReduceSum, ReduceL2, \
ReduceMin, ReduceLogicalOr
from openvino.tools.mo.front.extractor import FrontExtractorOp
from openvino.tools.mo.graph.graph import Node
class AllFrontExtractor(FrontExtractorOp):
op = 'All'
enabled = True
@classmethod
def extract(cls, node: Node):
keep_dims = node.pb.attr['keep_dims'].b
ReduceAnd.update_node_stat(node, {'keep_dims': keep_dims})
return cls.enabled
class AnyExtractor(FrontExtractorOp):
op = 'Any'
enabled = True
@classmethod
def extract(cls, node):
ReduceLogicalOr.update_node_stat(node, {'keep_dims': node.pb.attr['keep_dims'].b})
return cls.enabled
class MaxFrontExtractor(FrontExtractorOp):
op = 'Max'
enabled = True
@classmethod
def extract(cls, node: Node):
ReduceMax.update_node_stat(node, {'keep_dims': node.pb.attr['keep_dims'].b})
return cls.enabled
class MinFrontExtractor(FrontExtractorOp):
op = 'Min'
enabled = True
@classmethod
def extract(cls, node: Node):
ReduceMin.update_node_stat(node, {'keep_dims': node.pb.attr['keep_dims'].b})
return cls.enabled
class MeanExtractor(FrontExtractorOp):
op = 'Mean'
enabled = True
@classmethod
def extract(cls, node: Node):
ReduceMean.update_node_stat(node, {'keep_dims': node.pb.attr["keep_dims"].b})
return cls.enabled
class ProdFrontExtractor(FrontExtractorOp):
op = 'Prod'
enabled = True
@classmethod
def extract(cls, node: Node):
ReduceProd.update_node_stat(node, {'keep_dims': node.pb.attr["keep_dims"].b})
return cls.enabled
class SumFrontExtractor(FrontExtractorOp):
op = 'Sum'
enabled = True
@classmethod
def extract(cls, node: Node):
ReduceSum.update_node_stat(node, {'keep_dims': node.pb.attr["keep_dims"].b})
return cls.enabled
class EuclideanNormFrontExtractor(FrontExtractorOp):
op = 'EuclideanNorm'
enabled = True
@classmethod
def extract(cls, node: Node):
ReduceL2.update_node_stat(node, {'keep_dims': node.pb.attr["keep_dims"].b})
return cls.enabled
| 50,037
|
https://github.com/OpenAMEE/amee.platform.api/blob/master/amee-platform-domain/src/main/java/com/amee/domain/ValueType.java
|
Github Open Source
|
Open Source
|
MIT
| 2,015
|
amee.platform.api
|
OpenAMEE
|
Java
|
Code
| 274
| 782
|
package com.amee.domain;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import java.io.Serializable;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
public enum ValueType implements Serializable {
// The order of these values must not be changed!
// Hibernate has mapped them to ordinal values.
// Any new values must be appended to the list.
// TODO: We keep the old "DECIMAL" name and label for now so as not to break API compatibility. See: PL-1507
UNSPECIFIED("UNSPECIFIED", "Unspecified"),
TEXT("TEXT", "Text"),
DATE("DATE", "Date"),
BOOLEAN("BOOLEAN", "Boolean"),
INTEGER("INTEGER", "Integer"),
DOUBLE("DECIMAL", "Decimal");
private final String name;
private final String label;
ValueType(String name, String label) {
this.name = name;
this.label = label;
}
@Override
public String toString() {
return name;
}
public String getName() {
return name;
}
public String getLabel() {
return label;
}
public static Map<String, String> getChoices() {
Map<String, String> choices = new LinkedHashMap<String, String>();
for (ValueType valueType : ValueType.values()) {
choices.put(valueType.name, valueType.label);
}
return choices;
}
public static JSONObject getJSONObject() throws JSONException {
JSONObject obj = new JSONObject();
Map<String, String> choices = ValueType.getChoices();
for (Map.Entry<String, String> e : choices.entrySet()) {
obj.put(e.getKey(), e.getValue());
}
return obj;
}
public static Element getElement(Document document) {
Element element = document.createElement("ValueTypes");
Map<String, String> choices = ValueType.getChoices();
for (Map.Entry<String, String> e : choices.entrySet()) {
Element valueTypeElem = document.createElement("ValueType");
valueTypeElem.setAttribute("name", e.getKey());
valueTypeElem.setAttribute("label", e.getValue());
element.appendChild(valueTypeElem);
}
return element;
}
public static ValueType getValueType(Object object) {
if (object instanceof String) {
return ValueType.TEXT;
} else if (object instanceof Double) {
return ValueType.DOUBLE;
} else if (object instanceof Integer) {
return ValueType.INTEGER;
} else if (object instanceof Boolean) {
return ValueType.BOOLEAN;
} else if (object instanceof Date) {
return ValueType.DATE;
} else {
return ValueType.UNSPECIFIED;
}
}
}
| 18,332
|
https://github.com/jenifaelle/natural20-cp17/blob/master/src/sound/channel.py
|
Github Open Source
|
Open Source
|
MIT
| 2,017
|
natural20-cp17
|
jenifaelle
|
Python
|
Code
| 40
| 185
|
from typing import Dict
import pygame
from util.singleton import Singleton
class ChannelManager(metaclass=Singleton):
def __init__(self):
self.channels: Dict[str, pygame.mixer.ChannelType] = {'music': pygame.mixer.Channel(0),
'effect': pygame.mixer.Channel(1),
'extra': pygame.mixer.Channel(2)}
def play(self, channel: str, Sound: pygame.mixer.SoundType, volume: float, loops=0):
self.channels[channel].play(Sound, loops)
self.channels[channel].set_volume(volume)
def stop(self, channel):
self.channels[channel].stop()
| 49,008
|
https://github.com/nanobot248/extraterm/blob/master/build_scripts/node_modules-linux-x64/ptyw.js/vendor/winpty/agent/LargeConsoleRead.h
|
Github Open Source
|
Open Source
|
MIT
| null |
extraterm
|
nanobot248
|
C
|
Code
| 107
| 390
|
#ifndef LARGE_CONSOLE_READ_H
#define LARGE_CONSOLE_READ_H
#include <windows.h>
#include <stdlib.h>
#include <vector>
#include "SmallRect.h"
#include "../shared/DebugClient.h"
#include "../shared/WinptyAssert.h"
class Win32Console;
class LargeConsoleReadBuffer {
public:
LargeConsoleReadBuffer();
const SmallRect &rect() const { return m_rect; }
const CHAR_INFO *lineData(int line) const {
validateLineNumber(line);
return &m_data[(line - m_rect.Top) * m_rectWidth];
}
private:
CHAR_INFO *lineDataMut(int line) {
validateLineNumber(line);
return &m_data[(line - m_rect.Top) * m_rectWidth];
}
void validateLineNumber(int line) const {
if (line < m_rect.Top || line > m_rect.Bottom) {
trace("Fatal error: LargeConsoleReadBuffer: invalid line %d for "
"read rect %s", line, m_rect.toString().c_str());
abort();
}
}
SmallRect m_rect;
int m_rectWidth;
std::vector<CHAR_INFO> m_data;
friend void largeConsoleRead(LargeConsoleReadBuffer &out,
Win32Console &console,
const SmallRect &readArea);
};
#endif // LARGE_CONSOLE_READ_H
| 17,983
|
https://github.com/hsloan1a/midwaypython/blob/master/docs/006_Adding_a_Database/midway/alembic/versions/20190202_11f1e940695e.py
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,019
|
midwaypython
|
hsloan1a
|
Python
|
Code
| 116
| 488
|
"""init
Revision ID: 11f1e940695e
Revises:
Create Date: 2019-02-02 22:05:33.689016
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '11f1e940695e'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('horses',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(), nullable=False),
sa.Column('str', sa.Integer(), nullable=False),
sa.Column('active', sa.Integer(), nullable=False),
sa.PrimaryKeyConstraint('id', name=op.f('pk_horses')),
sa.UniqueConstraint('name', name=op.f('uq_horses_name'))
)
op.create_table('races',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('race_number', sa.Integer(), nullable=False),
sa.Column('score', sa.Integer(), nullable=False),
sa.Column('place', sa.Integer(), nullable=True),
sa.Column('horse_id', sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(['horse_id'], ['horses.id'], name=op.f('fk_races_horse_id_horses')),
sa.PrimaryKeyConstraint('id', name=op.f('pk_races'))
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('races')
op.drop_table('horses')
# ### end Alembic commands ###
| 24,832
|
https://github.com/yangxin0/waymo-open-dataset/blob/master/tf28/configure.sh
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
waymo-open-dataset
|
yangxin0
|
Shell
|
Code
| 300
| 1,030
|
#!/bin/bash
# Copyright 2019 The Waymo Open Dataset Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
# This file is modified from configure.sh in
# https://github.com/tensorflow/custom-op.
# This script writes to .bazelrc to tensorflow libs.
export PIP_MANYLINUX2010="${PIP_MANYLINUX2010:-0}"
export PYTHON_VERSION='3'
export PYTHON_MINOR_VERSION='9'
export TF_VERSION='2.8.0'
PYTHON="python3.9"
PIP="$PYTHON -m pip"
function write_to_bazelrc() {
echo "$1" >> .bazelrc
}
function write_action_env_to_bazelrc() {
write_to_bazelrc "build --action_env $1=\"$2\""
}
# Remove .bazelrc if it already exist
[ -e .bazelrc ] && rm .bazelrc
write_to_bazelrc "build -c opt"
write_to_bazelrc 'build --cxxopt="-std=c++14"'
write_to_bazelrc 'build --auto_output_filter=subpackages'
write_to_bazelrc 'build --copt="-Wall" --copt="-Wno-sign-compare"'
# Check if it's installed
if ${PIP} list | grep "tensorflow-macos" >/dev/null ; then
echo 'Using installed tensorflow-macos'
DETECT_TF_VERSION=$(${PYTHON} -c 'import tensorflow as tf; print(tf.__version__)')
if [ $TF_VERSION != $DETECT_TF_VERSION ]; then
echo "Only tensorflow 2.8.0 is supproted"
exit 255
fi
else
echo "Follow the guide bellow to install tensorflow-macos"
echo "https://developer.apple.com/metal/tensorflow-plugin/"
exit 255
fi
TF_CFLAGS=$(${PYTHON} -c 'import tensorflow as tf; print(" ".join(tf.sysconfig.get_compile_flags()))')
TF_LFLAGS=$(${PYTHON} -c 'import tensorflow as tf; print(" ".join(tf.sysconfig.get_link_flags()))')
write_action_env_to_bazelrc "TF_HEADER_DIR" $(${PYTHON} -c 'import tensorflow as tf; print(tf.sysconfig.get_compile_flags()[0][2:])')
write_action_env_to_bazelrc "TF_SHARED_LIBRARY_DIR" $(${PYTHON} -c 'import tensorflow as tf; print(tf.sysconfig.get_link_flags()[0][2:])')
write_action_env_to_bazelrc "TF_SHARED_LIBRARY_NAME" "libtensorflow_framework.dylib"
export TF_VERSION_UNDERSCORE=$(echo $TF_VERSION | sed 's/\./_/g')
export TF_VERSION_DASH=$(echo $TF_VERSION | sed 's/\./-/g')
cat tf28/WORKSPACE.in | sed "s/TF_VERSION/${TF_VERSION_UNDERSCORE}/" > WORKSPACE
cat tf28/setup.py.in | sed "s/TF_VERSION/${TF_VERSION_DASH}/" > tf28/setup.py
write_to_bazelrc 'build --cxxopt="-D_GLIBCXX_USE_CXX11_ABI=0"'
| 23,464
|
https://github.com/mishrakeshav/Competitive-Programming/blob/master/Google Kickstart/2018/Round C/planet_distance.py
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
Competitive-Programming
|
mishrakeshav
|
Python
|
Code
| 185
| 695
|
from collections import OrderedDict,deque
class Vertex:
def __init__(self,val):
self.val = val
self.isVisited = False
self.connections = dict()
self.parent = None
self.distance = None
def addConnection(self,val):
self.connections[val] = True
class Graph:
def __init__(self):
self.vertices = OrderedDict()
def addVertex(self,val):
self.vertices[val] = Vertex(val)
return self.vertices[val]
def getVertex(self,val):
if val in self.vertices:
return self.vertices[val]
return None
def addEdge(self,src,dst):
if src not in self:
self.addVertex(src)
if dst not in self:
self.addVertex(dst)
self.vertices[src].addConnection(dst)
def __contains__(self,val):
return val in self.vertices
def __iter__(self):
return iter(self.vertices.keys())
def resetDistances(self):
for node in self:
self.vertices[node].distance = None
def dfs(g):
visitedNodes = []
for node in g:
if node.isVisited and node != visitedNodes[-1]:
return node
v = dfsHelper(node,g,visitedNodes)
def dfsHelper(startNode,g,visitedNodes):
visitedNodes.append(startNode)
for node in g.vertices[startNode].connections:
if g.vertices[node] and visitedNodes[-1] != node:
return node
g.vertices[node].parent = startNode
d = dfsHelper(node,g,visitedNodes)
g.vertices[startNode].isVisited = True
return d
def bfs(start,g):
queue = deque()
queue.appendleft(start)
while len(queue):
currVertex = queue.popleft()
for nbr in g.vertices[currVertex].connections:
pass
for t in range(int(input())):
n = int(input())
g = Graph()
for i in range(n):
x,y = map(int,input().split())
g.addVertex(x,y)
node_in_cycle = dfs(g)
start = node_in_cycle
while g.vertices[start].parent != node_in_cycle:
g.vertices[start].distance = 0
start = g.vertices[start].parent
g.vertices[start].distance = 0
| 46,932
|
https://github.com/sportradar/UnifiedOddsSdkJava/blob/master/sdk-core/src/main/java/com/sportradar/unifiedodds/sdk/entities/CoveredFrom.java
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,021
|
UnifiedOddsSdkJava
|
sportradar
|
Java
|
Code
| 40
| 93
|
/*
* Copyright (C) Sportradar AG. See LICENSE for full license governing this code
*/
package com.sportradar.unifiedodds.sdk.entities;
/**
* Possible coverage locations
*/
@SuppressWarnings("java:S115") // Constant names should comply with a naming convention
public enum CoveredFrom {
Tv,
Venue
}
| 39,694
|
https://github.com/Anonymity94/cube.js/blob/master/examples/data-warehouse-performance-benchmarks/bigquery/cube-api.js
|
Github Open Source
|
Open Source
|
MIT, Apache-2.0, Cube
| 2,021
|
cube.js
|
Anonymity94
|
JavaScript
|
Code
| 86
| 390
|
import cubejs from '@cubejs-client/core';
const cubejsApi = cubejs.default(
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE2Mjc5ODkxODh9.toFTRcl7fdfZN-4fm9XSNu4qfpCZ2X8423Jbju8WyYY',
{ apiUrl: 'https://irish-idalia.gcp-us-central1.cubecloudapp.dev/cubejs-api/v1' }
);
const query = `
{
"measures": [
"Events.count"
],
"timeDimensions": [],
"order": {
"Events.count": "desc"
},
"dimensions": [
"Events.repositoryName",
"Events.type"
],
"filters": [
{
"member": "Events.type",
"operator": "equals",
"values": [
"WatchEvent"
]
}
],
"limit": 20,
"segments": []
}
`;
async function queryCube() {
await cubejsApi.load(query);
}
import * as http from "http";
const requestListener = async (req, res) => {
await queryCube();
res.writeHead(200);
res.end('Query Done!');
}
const server = http.createServer(requestListener);
server.listen(9090);
| 45,623
|
https://github.com/blackrian/vueoldman/blob/master/src/vuex/modules/dropDown.js
|
Github Open Source
|
Open Source
|
MIT
| 2,016
|
vueoldman
|
blackrian
|
JavaScript
|
Code
| 46
| 193
|
/**
* Created by Administrator on 2016/9/11.
*/
import { GET_DROP_VAL } from '../mutation-types'
const state={
//分组值
dropGroup:'1',
// 分组项
dropGroupItem:[
{
key:1,
value:'学习型'
},{
key:2,
value:'休闲型'
},{
key:3,
value:'养老型'
},{
key:4,
value:'娱乐型'
}
]
}
const mutations={
[GET_DROP_VAL](state,dropGroup){
state.dropGroupItem
}
}
export default{
state,mutations
}
| 42,775
|
https://github.com/treff7es/dagster/blob/master/examples/dagster_examples/intro_tutorial/tutorial_repository.py
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,019
|
dagster
|
treff7es
|
Python
|
Code
| 52
| 235
|
from dagster import RepositoryDefinition
from .hello_world import hello_world_pipeline
from .hello_dag import hello_dag_pipeline
from .actual_dag import actual_dag_pipeline
from .config import hello_with_config_pipeline
from .execution_context import execution_context_pipeline
from .resources_full import resources_pipeline
from .reusing_solids import reusing_solids_pipeline
from .configuration_schemas import configuration_schema_pipeline
def define_repository():
return RepositoryDefinition(
name='tutorial_repository',
pipeline_defs=[
configuration_schema_pipeline,
hello_world_pipeline,
hello_dag_pipeline,
actual_dag_pipeline,
hello_with_config_pipeline,
execution_context_pipeline,
resources_pipeline,
reusing_solids_pipeline,
],
)
| 35,857
|
https://github.com/gophertrain/training/blob/master/monmetlog/solutions/raft/store/store_test.go
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
training
|
gophertrain
|
Go
|
Code
| 7
| 14
|
package store_test
// TODO: write some tests
| 9,440
|
https://github.com/mpoozd/newNm/blob/master/application/views/admin/faq/update_faq.php
|
Github Open Source
|
Open Source
|
MIT, LicenseRef-scancode-unknown-license-reference
| 2,017
|
newNm
|
mpoozd
|
PHP
|
Code
| 215
| 1,073
|
<div class="row ">
<div class="col-md-12">
<?php if(validation_errors() != false) {?>
<div class="alert alert-danger alert-dismissable">
<button class="close" aria-hidden="true" data-dismiss="alert" type="button"></button>
<?php echo validation_errors(); ?>
</div>
<?php
} ?>
<!-- BEGIN SAMPLE FORM PORTLET-->
<div class="portlet light bordered">
<div class="portlet-title">
<div class="caption">
<span class="caption-subject font-dark bold uppercase"><?php echo $table_title ?></span>
</div>
</div>
<div class="portlet-body">
<form role="form" class="form-horizontal" method="post" action="">
<div class="form-group">
<label class="col-md-2 control-label">Name</label>
<div class="col-md-6">
<select class="form-control" name="ftype_name">
<option value="">Select Question Type</option>
<?php $selected = "selected"; foreach ($ftype_name as $ftype_name_row) { ?>
<option value="<?php echo $ftype_name_row['ftype_id'] ?>"<?php if ($this->input->post('ftype_name') == $ftype_name_row['ftype_id']) {echo $selected;} else if ($faq['faq_type_id'] == $ftype_name_row['ftype_id']){ echo $selected; } ?> ><?php echo $ftype_name_row['ftype_name'] ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="form-group">
<label class="col-md-2 control-label" for="">Question</label>
<div class="col-md-6">
<div class="input-icon right">
<input type="text" name="question" value="<?php if($this->input->post("question") != ""){ echo $this->input->post("question"); } else { echo $faq['question']; } ?>" placeholder="Question" class="form-control"> </div>
</div>
</div>
<div class="form-group">
<label class="col-md-2 control-label">Answer</label>
<div class="col-md-6">
<textarea id="page_content" name="answer" placeholder="Answer" rows="3" class="form-control"><?php if($this->input->post("answer") != ""){ echo $this->input->post("answer"); } else { echo $faq['answer']; }?></textarea>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<button class="btn green" type="submit">Update</button>
</div>
</div>
</form>
</div>
</div>
<!-- END SAMPLE FORM PORTLET-->
</div>
</div>
<script type="text/javascript">
CKEDITOR.replace( 'page_content',
{
filebrowserBrowseUrl : '<?=base_url()?>ckfinder/ckfinder.html',
filebrowserImageBrowseUrl : '<?=base_url()?>ckfinder/ckfinder.html?Type=Images',
filebrowserFlashBrowseUrl : '<?=base_url()?>ckfinder/ckfinder.html?Type=Flash',
filebrowserUploadUrl : '<?=base_url()?>ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Files',
filebrowserImageUploadUrl : '<?=base_url()?>ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Images',
filebrowserFlashUploadUrl : '<?=base_url()?>ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Flash'
});
</script>
| 857
|
https://github.com/Rockdell/dempy/blob/master/dempy/acquisitions/subject.py
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
dempy
|
Rockdell
|
Python
|
Code
| 218
| 778
|
from typing import List, Dict, Any
from dempy._base import Entity
from dempy._protofiles import SubjectMessage
class Subject(Entity):
"""Subject class"""
def __init__(self, type: str, id: str, tags: List[str], metadata: Dict[str, str], birthdate_timestamp: int, description: str,
first_name: str, last_name: str):
super().__init__(type, id, tags, metadata)
self.birthdate_timestamp = birthdate_timestamp
self.description = description
self.first_name = first_name
self.last_name = last_name
@staticmethod
def to_protobuf(obj: "Subject") -> SubjectMessage:
"""Encode an subject to a Protobuf message
Arguments:
obj {Subject} -- subject to be encoded
Returns:
SubjectMessage -- encoded subject
"""
subject_message = SubjectMessage()
subject_message.entity.CopyFrom(Entity.to_protobuf(obj))
subject_message.birthdate_timestamp = obj.birthdate_timestamp
if obj.description is not None:
subject_message.description = obj.description
if obj.first_name is not None:
subject_message.first_name = obj.first_name
if obj.last_name is not None:
subject_message.last_name = obj.last_name
return subject_message
@staticmethod
def from_protobuf(subject_message: SubjectMessage) -> "Subject":
"""Decode a Protobuf message to {Subject}
Arguments:
obj {SubjectMessage} -- message to be decoded
Returns:
Subject -- decoded subject
"""
return Subject(
type=subject_message.entity.type,
id=subject_message.entity.id,
tags=subject_message.entity.tags,
metadata=subject_message.entity.metadata,
birthdate_timestamp=subject_message.birthdate_timestamp if subject_message.HasField("birthdate_timestamp") else None,
description=subject_message.description if subject_message.HasField("description") else None,
first_name=subject_message.first_name if subject_message.HasField("first_name") else None,
last_name=subject_message.last_name if subject_message.HasField("last_name") else None,
)
@staticmethod
def from_json(obj: Dict[str, str]) -> Any:
"""Parse a JSON dictionary to {Subject}
Arguments:
obj {Dict[str, str]} -- JSON object
Returns:
Any -- parsed object and sub-objects
"""
if "type" in obj and obj["type"].endswith("Subject"):
return Subject(
type=obj["type"],
id=obj["id"],
metadata=obj["metadata"],
tags=obj["tags"],
birthdate_timestamp=obj["birthdateTimestamp"],
description=obj["description"],
first_name=obj["firstName"],
last_name=obj["lastName"]
)
return obj
__all__ = [
"Subject"
]
| 16,009
|
https://github.com/mavn-alliance/MAVN.Service.Referral/blob/master/client/MAVN.Service.Referral.Client/ReferralClient.cs
|
Github Open Source
|
Open Source
|
MIT
| null |
MAVN.Service.Referral
|
mavn-alliance
|
C#
|
Code
| 97
| 339
|
using Lykke.HttpClientGenerator;
namespace MAVN.Service.Referral.Client
{
/// <summary>
/// Referral API aggregating interface.
/// </summary>
public class ReferralClient : IReferralClient
{
// Note: Add similar ReferralApi properties for each new service controller
/// <summary>Interface to Referral ReferralApi.</summary>
public IReferralApi ReferralApi { get; private set; }
/// <summary>Interface to Referral ReferralHotelsApi.</summary>
public IReferralHotelsApi ReferralHotelsApi { get; }
/// <summary>Application ReferralFriendsApi interface</summary>
public IReferralFriendsApi ReferralFriendsApi { get; }
/// <summary> Application CommonReferralApi interface</summary>
public ICommonReferralApi CommonReferralApi { get; }
/// <summary>C-tor</summary>
public ReferralClient(IHttpClientGenerator httpClientGenerator)
{
ReferralApi = httpClientGenerator.Generate<IReferralApi>();
ReferralHotelsApi = httpClientGenerator.Generate<IReferralHotelsApi>();
ReferralFriendsApi = httpClientGenerator.Generate<IReferralFriendsApi>();
CommonReferralApi = httpClientGenerator.Generate<ICommonReferralApi>();
}
}
}
| 6,884
|
https://github.com/jasonsum/behavior_mapping/blob/master/setup.py
|
Github Open Source
|
Open Source
|
MIT
| null |
behavior_mapping
|
jasonsum
|
Python
|
Code
| 73
| 287
|
import setuptools
with open("README.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
setuptools.setup(
name="behavior_mapper",
version="1.2.1.dev1",
author="Jason Summer",
author_email="jasummer92@gmail.com",
description="Clusters channel activities or steps according to the transactions offered within a given organization's channel",
long_description=long_description,
long_description_content_type="text/markdown",
url="https://github.com/jasonsum/behavior_mapping",
classifiers=[
"Development Status :: 3 - Alpha",
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Topic :: Text Processing"
],
packages=['behavior_mapper'],
python_requires='>=3.8',
license='MIT',
install_requires=['pandas','nltk','gensim','numpy','scikit-learn', 'unittest', 'glob']
#project_urls={'':'',},
)
| 7,101
|
https://github.com/pradeep-charism/prad-concurrency/blob/master/src/main/java/practices/visitors/UnsafeWebsite.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
prad-concurrency
|
pradeep-charism
|
Java
|
Code
| 86
| 228
|
package practices.visitors;
import java.util.HashSet;
import java.util.Set;
public class UnsafeWebsite implements Website{
public static int visitors = 0;
// public int visitors = 0;
// public Set<Integer> allVisitors = new HashSet<>();
public static Set<Integer> allVisitors = new HashSet<>();
@Override
public int registerVisitors(String country) {
int id = visitors++;
if (allVisitors.contains(id)) {
System.out.println("Duplicate visitor registration..."+ id+ " from: "+ country);
System.exit(1);
} else {
allVisitors.add(id);
}
return id;
}
@Override
public void get(String country, int id) {
}
@Override
public void put(String country, int id) {
}
}
| 13,699
|
https://github.com/sofianeOuafir/SupplyChainAppEthereum/blob/master/contracts/Item.sol
|
Github Open Source
|
Open Source
|
MIT
| null |
SupplyChainAppEthereum
|
sofianeOuafir
|
Solidity
|
Code
| 77
| 231
|
pragma solidity ^0.6.4;
import "./ItemManager.sol";
contract Item {
uint public index;
uint public priceWei;
uint public paidWei;
ItemManager parentContract;
constructor(ItemManager _parentContract, uint _priceWei, uint _index) public {
parentContract = _parentContract;
index = _index;
priceWei = _priceWei;
}
receive() external payable {
require(msg.value >= priceWei, "We don't support partial payments");
require(paidWei == 0, "Item is already paid!");
paidWei += msg.value;
(bool success, ) = address(parentContract).call{value:msg.value}(abi.encodeWithSignature("triggerPayment(uint256)", index));
require(success, "Transaction wasn't successful, cancelling");
}
fallback () external {
}
}
| 5,095
|
https://github.com/doitian/dotfiles-public/blob/master/nvim/pack/local/opt/iy-bm.vim/plugin/iy-bm.vim
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,023
|
dotfiles-public
|
doitian
|
Vim Script
|
Code
| 16
| 62
|
if exists('g:loaded_iy_bm')
finish
endif
let g:loaded_iy_bm = 1
if !exists(':Bm')
command -nargs=* Bm call iy#bm#line(<q-args>)
endif
| 20,254
|
https://github.com/xuejiaomeng/vue-simple-tree/blob/master/src/components/VueTree.vue
|
Github Open Source
|
Open Source
|
MIT
| 2,018
|
vue-simple-tree
|
xuejiaomeng
|
Vue
|
Code
| 204
| 778
|
<template>
<ul class="vue-tree">
<tree-item
v-for="item in treeData"
:ids="ids"
:ids-with-parent="idsWithParent"
:model="item"
:options="termOptions"
:depth="0"
@add-a-child="addAChild"
@item-click="itemClick"
@item-edit="itemEdit"
@item-delete="itemDelete"
:key="item.id">
</tree-item>
</ul>
</template>
<script>
import Item from './Item.vue'
import '../vue-tree.css'
export default {
model: {
prop: 'ids',
event: 'change'
},
props: {
treeData: {
type: Array,
default: function () {
return []
}
},
options: {
type: Object,
default: function () {
return {}
}
},
ids: {
type: Array,
default: function () {
return []
}
}
},
data () {
return {
defaultOptions: {
itemName: 'name',
checkbox: true,
checkedOpen: true,
folderBold: true,
idsWithParent: true,
depthOpen: 0,
showAdd: true,
showEdit: true,
showDelete: true,
addClass: 'fa fa-plus-square-o',
editClass: 'fa fa-edit',
deleteClass: 'fa fa-trash-o',
openClass: 'fa fa-angle-right',
closeClass: 'fa fa-angle-down',
halfCheckedClass: 'fa fa-minus-square-o fa-fw',
checkedClass: 'fa fa-check-square-o fa-fw',
unCheckedClass: 'fa fa-square-o fa-fw'
},
termOptions: {},
idsWithParent: []
}
},
created () {
this.initOptions()
},
methods:{
addAChild(id){
this.$emit('add-a-child', id)
},
itemClick(id){
this.$emit('item-click', id)
},
itemEdit(id) {
this.$emit('item-edit', id)
},
itemDelete(id) {
this.$emit('item-delete', id)
},
initOptions () {
this.termOptions = Object.assign({}, this.defaultOptions, this.options);
this.idsWithParent = this.ids.slice(0)
}
},
components: {'tree-item': Item},
watch: {
options: {
handler: function (val) {
this.initOptions()
},
deep: true
},
ids: {
handler: function (val) {
this.idsWithParent = val.slice(0)
},
deep: true
}
}
}
</script>
| 4,421
|
https://github.com/JackSilence/mrt/blob/master/src/main/java/ninja/task/Task.java
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
mrt
|
JackSilence
|
Java
|
Code
| 46
| 141
|
package ninja.task;
import org.springframework.beans.factory.annotation.Value;
import magic.service.IService;
import net.gpedro.integrations.slack.SlackMessage;
import ninja.util.Utils;
public abstract class Task implements IService {
protected static final String COMMAND = "scheduled-task";
@Value( "${slack.webhook.url:}" )
protected String url;
protected void call( String text ) {
Utils.call( url, new SlackMessage( text ) );
}
}
| 2,422
|
https://github.com/rezam28/SPK-FAHP/blob/master/resources/views/layout/main.blade.php
|
Github Open Source
|
Open Source
|
MIT
| null |
SPK-FAHP
|
rezam28
|
PHP
|
Code
| 137
| 882
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>@yield('title')</title>
<link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,400i,700" rel="stylesheet">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="css/style.css">
@yield('css')
</head>
<body>
<div class="main-content container">
<!--navbar-->
<!-- Image and text -->
<nav class="navbar">
<a class="logo navbar-brand" href="/">
<img src="{{('../img/untag.png')}}" width="30" height="30" class="title" alt="" loading="lazy">
Sistem Pendukung Kepustusan
</a>
@if (Route::has('login'))
<a href="{{route('logout')}}" class="logout">Logout</a>
@endif
@auth('admin')
<a href="{{route('logout')}}" class="logout">Logout</a>
@endauth
<div class="toggle" onclick="ToggleMenu()"></div>
</nav>
<!--Sidebar-->
<div class="navigation" id="navigation">
<nav>
<ul>
<li>
<a href="{{route('hasil')}}">
<span class="icon"><i class="fa fa-calculator" aria-hidden="true"></i></span>
<span class="title">Hasil</span>
</a>
</li>
<li>
<a href="{{route('peta')}}">
<span class="icon"><i class="fa fa-map-marker" aria-hidden="true"></i></span>
<span class="title">Peta</span>
</a>
</li>
</ul>
</nav>
</div>
<div class="content">
@yield('content')
</div>
</div>
<script type="text/javascript">
function ToggleMenu(){
// document.getElementById("navigation").classList.toggle('active');
let navigation = document.querySelector('.navigation');
let toggle = document.querySelector('.toggle');
let content = document.querySelector('.content');
navigation.classList.toggle('active');
toggle.classList.toggle('active');
content.classList.toggle('active');
}
</script>
@yield('javascript')
</body>
</html>
| 12,324
|
https://github.com/MarceLlanos/BingoWebGame/blob/master/module/Application/src/Form/RegisterForm.php
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| null |
BingoWebGame
|
MarceLlanos
|
PHP
|
Code
| 98
| 369
|
<?php
namespace Application\Form;
use Zend\Form\Element;
use Zend\Form\Form;
class RegisterForm extends Form
{
public function __construct($name = null, $options = [])
{
parent::__construct($name, $options);
$name = new Element\Text('name');
$name->setLabel('User name')->setLabelAttributes(['class' => 'control-form']);
$name->setAttributes(['class' => 'form-control', 'placeholder' => 'Introduce your name. Ex.: John Doe']);
$this->add($name);
$email = new Element\Email('email');
$email->setLabel('Email')->setLabelAttributes(['class' => 'control-form']);
$email->setAttributes(['class' => 'form-control', 'placeholder' => 'Introduce you email. Ex.: example@gmail.com']);
$this->add($email);
$password = new Element\Password('password');
$password->setLabel('Password')->setAttributes(['class' => 'control-form']);
$password->setAttributes(['class' => 'form-control', 'placeholder' => 'Introduce a password.']);
$this->add($password);
$button = new Element\Button('send');
$button->setAttributes(['class' => "btn btn-primary btn-lg", 'style' => 'width: 100%','value' => 'Register', 'type' => 'submit']);
$this->add($button);
}
}
| 18,586
|
https://github.com/ashishdotme/ansu-bot/blob/master/Ansu.Bot/Config/Database/MongoSettings.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
ansu-bot
|
ashishdotme
|
C#
|
Code
| 36
| 86
|
using System;
using Ansu.MongoDB.Client.Interfaces;
namespace Ansu.Bot.Config.Models
{
public class MongoSettings : IMongoSettings
{
public string Database { get; set; }
public string Collection { get; set; }
public string ConnectionString { get; set; }
}
}
| 8,212
|
https://github.com/dancergraham/advent_of_code_2021/blob/master/day02/day02.py
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
advent_of_code_2021
|
dancergraham
|
Python
|
Code
| 140
| 367
|
from collections import Counter
from pathlib import Path
test_input = """forward 5
down 5
forward 8
up 3
down 8
forward 2"""
def part_1(puzzle_input: str) -> float:
parsed = [line for line in puzzle_input.splitlines()]
counter = Counter()
for line in parsed:
direction, distance = line.split()
counter[direction] += int(distance)
return counter["forward"] * (counter["down"] - counter["up"])
def part_2(puzzle_input: str) -> float:
parsed = [line for line in puzzle_input.splitlines()]
horizontal = 0
depth = 0
aim = 0
for line in parsed:
direction, distance = line.split()
distance = int(distance)
if direction == "forward":
horizontal += distance
depth += aim * distance
elif direction == "up":
aim -= distance
elif direction == "down":
aim += distance
return abs(horizontal * depth)
def test_part_1():
assert part_1(test_input) == 150
def test_part_2():
assert part_2(test_input) == 900
def main():
puzzle_input = Path("input.txt").read_text()
print(part_1(puzzle_input))
print(part_2(puzzle_input))
if __name__ == "__main__":
main()
| 43,384
|
https://github.com/open-toontown/open-toontown/blob/master/toontown/estate/DistributedPhoneAI.py
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,023
|
open-toontown
|
open-toontown
|
Python
|
Code
| 13
| 63
|
from direct.directnotify import DirectNotifyGlobal
from direct.distributed.DistributedObjectAI import DistributedObjectAI
class DistributedPhoneAI(DistributedObjectAI):
notify = DirectNotifyGlobal.directNotify.newCategory('DistributedPhoneAI')
| 49,385
|
https://github.com/bitwize/rscheme/blob/master/packages/threads/manager/pipe.scm
|
Github Open Source
|
Open Source
|
TCL
| 2,022
|
rscheme
|
bitwize
|
Scheme
|
Code
| 162
| 617
|
(define-class <internal-pipe-input> (<buffered-input-port>)
mbox)
(define-method provide-more-input ((self <internal-pipe-input>))
(if (mbox self)
(let ((m (receive-message! (mbox self))))
(cond
((pair? m) ; it's markup... ignore it
(provide-more-input self))
((string? m) m)
(else ; it's a close
(set-mbox! self #f)
#f)))
#f))
(define (flush-internal-pipe (self <internal-pipe-input>))
(let ((q (make-dequeue)))
(let loop ()
(if (mailbox-has-data? (mbox self))
(begin
(dequeue-push-back! q (receive-message! (mbox self)))
(loop))
(dequeue-state q)))))
(define-method more-input-ready? ((self <internal-pipe-input>))
;; XXX this fails if the only available data is markup
(mailbox-has-data? (mbox self)))
;;;
(define-class <internal-pipe-output> (<output-port>)
mbox)
(define-method write-markup ((self <internal-pipe-output>) markup)
(send-message! (mbox self) (cons 'markup markup)))
(define-method close-output-port ((self <internal-pipe-output>))
(send-message! (mbox self) #f))
(define-method write-string ((self <internal-pipe-output>) str)
(if (not (string=? str ""))
(send-message! (mbox self) str)))
(define-method output-port-write-char ((self <internal-pipe-output>) ch)
(send-message! (mbox self) (string ch)))
;;;
(define (make-internal-pipe #optional name)
(let ((mbox (make-mailbox (or name 'internal-pipe))))
(values (make <internal-pipe-input> mbox: mbox)
(make <internal-pipe-output> mbox: mbox))))
(define (is-waiting-for-internal-pipe? (t <thread>) (p <internal-pipe-output>))
(and (thread-blocked? t)
(eq? (thread-blocked-on t) (mbox p))))
| 12,014
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.