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/lyandy/EyeSight_iOS/blob/master/EyeSight/Classes/Past/PastDetail/Model/AndyPastDetailListModel.m
|
Github Open Source
|
Open Source
|
MIT
| 2,017
|
EyeSight_iOS
|
lyandy
|
Objective-C
|
Code
| 40
| 149
|
//
// AndyPastDetailListModel.m
// EyeSight
//
// Created by 李扬 on 15/11/12.
// Copyright © 2015年 andyli. All rights reserved.
//
#import "AndyPastDetailListModel.h"
#import "MJExtension.h"
#import "AndyPastDetailVideoListModel.h"
@implementation AndyPastDetailListModel
- (NSDictionary *)objectClassInArray
{
return @{@"videoList" : [AndyPastDetailVideoListModel class]};
}
@end
| 36,747
|
https://github.com/ietf-tools/ietf-guides/blob/master/guides/models.py
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,023
|
ietf-guides
|
ietf-tools
|
Python
|
Code
| 625
| 2,255
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import User
ATTEND_NONE = 'None'
ATTEND_ONE = 'One'
ATTEND_TWO = 'Two'
ATTEND_THREE = 'Three'
ATTEND_CHOICES = (
(ATTEND_NONE,'This is my first IETF meeting'),
(ATTEND_ONE, 'This is my second IETF meeting'),
(ATTEND_TWO, 'This is my third IETF meeting'),
(ATTEND_THREE, 'This is my fourth IETF meeting')
)
GEND_NOPREF = 'NoPref'
GEND_MALE = 'Male'
GEND_FEMALE = 'Female'
GEND_NONBINARY = 'Non-Binary'
GEND_CHOICES = (
(GEND_NOPREF, "I don't have a preference"),
(GEND_MALE, "I would prefer to work with a male guide"),
(GEND_FEMALE, "I would prefer to work with a female guide"),
)
GEND_TYPE_FEMALE = "Female"
GEND_TYPE_MALE = "Male"
GEND_TYPE_NONBINARY = "Non-Binary"
GEND_TYPES = (
(GEND_TYPE_FEMALE, "Female"),
(GEND_TYPE_MALE, "Male"),
(GEND_TYPE_NONBINARY, "Non Binary"),
)
YEARS_LESSTHANFIVE = "LESSTHANFIVE"
YEARS_FIVETOTEN = "FIVETOTEN"
YEARS_MORETHANTEN = "MORETHANTEN"
YEARS_CHOICES = (
(YEARS_LESSTHANFIVE,"Less than 5 years"),
(YEARS_FIVETOTEN,"5 to 10 years"),
(YEARS_MORETHANTEN, "More than 10 years"),
)
YNM_YES = "YES"
YNM_NO = "NO"
YNM_MAYBE = "MAYBE"
YNM_CHOICES = (
(YNM_YES, "Yes"),
(YNM_NO, "No"),
(YNM_MAYBE, "Maybe"),
)
YN_CHOICES = (
(YNM_YES, "Yes"),
(YNM_NO, "No"),
)
AREA_ART = "ART"
AREA_INT = "INT"
AREA_OPS = "OPS"
AREA_RTG = "RTG"
AREA_SEC = "SEC"
AREA_TSG = "TSG"
AREA_UNKNOWN = "UNKNOWN"
IETF_AREAS = (
(AREA_ART, "Applications and Real-Time"),
(AREA_INT, "Internet"),
(AREA_OPS, "Operations and Management"),
(AREA_RTG, "Routing"),
(AREA_SEC, "Security"),
(AREA_TSG, "Transport"),
(AREA_UNKNOWN, "I don't know yet")
)
class Area(models.Model):
area = models.CharField(max_length=64)
short = models.CharField(max_length=12,default="")
def __str__(self):
return self.area
class Language(models.Model):
language = models.CharField(max_length=32)
def __str__(self):
return self.language
class Participant(models.Model):
email = models.EmailField(primary_key=True)
attending = models.CharField('Will you be attending the next IETF?',
max_length=32, choices=YN_CHOICES,
default=YNM_NO)
remote = models.CharField('Will you be attending remotely?', max_length=32, choices=YN_CHOICES, default=YNM_NO)
given_name = models.CharField(max_length=64)
surname = models.CharField(max_length=64)
affiliation = models.CharField(max_length=64)
country = models.CharField('Country of residence',max_length=64)
language = models.ForeignKey(Language,verbose_name='Preferred conversational language',max_length=32,default=1,on_delete=models.CASCADE)
attend = models.CharField('Number of IETFs attended',max_length=32, choices=ATTEND_CHOICES, default=ATTEND_NONE)
topics = models.TextField('What technical topics brought you to the IETF?')
areas = models.ManyToManyField(Area, verbose_name='What IETF area(s) most interest you?', help_text = 'Further information about IETF areas is available <a href="https://www.ietf.org/topics/areas/">here</a>.' )
groups = models.CharField('Which working groups are you most interested in?',help_text='see <a href="https://www.ietf.org/how/wgs">https://www.ietf.org/how/wgs</a>',max_length=256)
gender_pref = models.CharField('Guide gender preference', max_length=32, choices=GEND_CHOICES, default=GEND_NOPREF)
additional_info = models.TextField('Is there anything else you would like to share with us?', blank=True)
def __str__(self):
return "%s %s <%s>" % (self.given_name, self.surname, self.email)
def pretty_attend(self):
attendmap = {
ATTEND_NONE: "0",
ATTEND_ONE: "1",
ATTEND_TWO: "2",
ATTEND_THREE: "3",
}
return attendmap[self.attend]
class Guide(models.Model):
email = models.EmailField(primary_key=True)
given_name = models.CharField(max_length=64)
surname = models.CharField(max_length=64)
affiliation = models.CharField(max_length=64)
country = models.CharField('Country of residence',max_length=64)
gender = models.CharField("Gender", max_length=32, default="", blank=True)
language = models.ManyToManyField(Language,verbose_name='What languages can you communicate in fluently?')
ietf_years = models.CharField('How long have you been participating in the IETF?', max_length=32, choices=YEARS_CHOICES, default = YEARS_LESSTHANFIVE)
multiple_guided = models.CharField('Are you willing to work with more than one program participant?', max_length=32, choices=YNM_CHOICES, default=YNM_YES)
give_intro = models.CharField('Are you willing to give a general introduction of the IETF to a newcomer program participant?', max_length=32, choices=YNM_CHOICES, default=YNM_YES, help_text="<em>(Sometimes it is not possible to exactly match guides with participants and their preferred technical areas)</em>")
areas = models.ManyToManyField(Area, verbose_name='What IETF area(s) are you involved in?')
groups = models.CharField('Which working groups are you most able to help people with?', max_length=256, default="", blank=True)
arrival_date = models.CharField('What date are you arriving at the next IETF meeting (YYYY/MM/DD)?', max_length=64)
accept_remote = models.CharField('Are you willing to guide remote participants?',max_length=32, choices=YNM_CHOICES, default=YNM_YES)
additional_info = models.TextField('Is there anything else we should know?',
blank=True)
keep_for_nexttime = models.BooleanField("Should we keep your registration data around for future participation in the guides program?", default=False)
def __str__(self):
return "%s %s <%s>" % (self.given_name, self.surname, self.email)
def pretty_ietf_years(self):
yearmap = {
YEARS_LESSTHANFIVE : "<5",
YEARS_FIVETOTEN : "5-10",
YEARS_MORETHANTEN: ">10"
}
return yearmap[self.ietf_years]
class Match(models.Model):
participant = models.ForeignKey(Participant,on_delete=models.CASCADE)
guide = models.ForeignKey(Guide,on_delete=models.CASCADE)
by = models.ForeignKey(User,on_delete=models.CASCADE)
date = models.DateTimeField(auto_now=True)
def __str__(self):
return "%s is guiding %s (made by %s on %s)" % (self.guide, self.participant, self.by.email, self.date)
| 47,196
|
https://github.com/Rich2/openstrat/blob/master/Util/src/pParse/NatHexaToken.scala
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,022
|
openstrat
|
Rich2
|
Scala
|
Code
| 157
| 353
|
/* Copyright 2018-21 Richard Oliver. Licensed under Apache Licence version 2.0. */
package ostrat; package pParse
/** Common trait for all tokens that can be valid hexadecimal natural numbers. */
trait NatHexaToken extends NatToken
{
def asHexaInt: Int =
{ var acc = 0
implicit val chars: Chars = digitsStr.toChars
def loop(rem: CharsOff): Int = rem match
{ case CharsOff0() => acc
case CharsOff1Tail(HexaDigitChar(_, i), tail) => { acc = acc * 16 + i; loop(tail) }
case _ => excep("Case not implemented")
}
loop(chars.offsetter0)
}
}
trait NatRawHexaToken extends NatRawToken
object NatRawHexaToken
{
def unapply(input: Any): Option[(TextPosn, String)] = input match {
case nrht: NatRawHexaToken => Some((nrht.startPosn, nrht.digitsStr))
case _ => None
}
}
/** Raw hexadecimal natural number token, starting with a digit that includes one or more 'A' .. 'F' digits. */
case class RawHexaToken(startPosn: TextPosn, srcStr: String) extends NatRawHexaToken
{ override def subTypeStr: String = "HexaRaw"
override def digitsStr: String = srcStr
}
| 33,382
|
https://github.com/robertbtown/BtownToolkit/blob/master/Example/Pods/Target Support Files/Pods-BtownToolkit_Tests/Pods-BtownToolkit_Tests-dummy.m
|
Github Open Source
|
Open Source
|
MIT
| 2,018
|
BtownToolkit
|
robertbtown
|
Objective-C
|
Code
| 10
| 56
|
#import <Foundation/Foundation.h>
@interface PodsDummy_Pods_BtownToolkit_Tests : NSObject
@end
@implementation PodsDummy_Pods_BtownToolkit_Tests
@end
| 40,646
|
https://github.com/elhadji907/onfp/blob/master/resources/views/courriers/index.blade.php
|
Github Open Source
|
Open Source
|
MIT
| null |
onfp
|
elhadji907
|
PHP
|
Code
| 659
| 2,898
|
@extends('layout.default')
@section('title', 'Onfp | Home')
@section('content')
@hasrole('Administrateur|Courrier|Gestionnaire|Demandeur|ACourrier')
<div class="container-fluid">
<div class="row">
<div class="col-xl-3 col-md-6 mb-4">
<div class="card border-left-primary shadow h-100 py-2">
<a class="nav-link" href="{{ route('courriers.index') }}" target="_blank">
<div class="card-body">
<div class="row no-gutters align-items-center">
<div class="col mr-2">
<div class="text-xs font-weight-bold text-primary text-uppercase mb-1">{{ ('Courriers (ANNUELS)') }}</div>
<div class="h5 mb-0 font-weight-bold text-gray-800">{{ $courrier }}</div>
</div>
<div class="col-auto">
<span data-feather="mail"></span>
</div>
</div>
</div>
</a>
</div>
</div>
<div class="col-xl-3 col-md-6 mb-4">
<div class="card border-left-success shadow h-100 py-2">
<a class="nav-link" href="{{ route('recues.index') }}" target="_blank">
<div class="card-body">
<div class="row no-gutters align-items-center">
<div class="col mr-2">
<div class="text-xs font-weight-bold text-success text-uppercase mb-1">
{{ ('Courriers (ARRIVES)') }}
</div>
<div class="h5 mb-0 font-weight-bold text-gray-800">{{ $recues }}</div>
</div>
<div class="col-auto">
<span data-feather="mail"></span>
</div>
</div>
</div>
</a>
</div>
</div>
<div class="col-xl-3 col-md-6 mb-4">
<div class="card border-left-info shadow h-100 py-2">
<a class="nav-link" href="{{ route('departs.index') }}" target="_blank">
<div class="card-body">
<div class="row no-gutters align-items-center">
<div class="col mr-2">
<div class="text-xs font-weight-bold text-info text-uppercase mb-1">{{ ('Courriers (DEPARTS)') }}</div>
<div class="row no-gutters align-items-center">
<div class="col-auto">
<div class="h5 mb-0 mr-3 font-weight-bold text-gray-800">{{ $departs }}</div>
</div>
</div>
</div>
<div class="col-auto">
<span data-feather="mail"></span>
</div>
</div>
</div>
</a>
</div>
</div>
<div class="col-xl-3 col-md-6 mb-4">
<div class="card border-left-warning shadow h-100 py-2">
<a class="nav-link" href="{{ route('internes.index') }}" target="_blank" >
<div class="card-body">
<div class="row no-gutters align-items-center">
<div class="col mr-2">
<div class="text-xs font-weight-bold text-warning text-uppercase mb-1">{{ ('Courriers (INTERNES)') }}</div>
<div class="h5 mb-0 font-weight-bold text-gray-800">{{ $internes }}</div>
</div>
<div class="col-auto">
<span data-feather="mail"></span>
</div>
</div>
</div>
</a>
</div>
</div>
</div>
</div>
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<i class="fas fa-table"></i>
Liste des courriers
</div>
<div class="card-body">
<div class="table-responsive">
<div align="right">
<a href="{{ route('courriers.create') }}"><div class="btn btn-success btn-sm"><i class="fas fa-plus"></i> Ajouter</i></div></a>
</div>
<br />
<table class="table table-bordered table-striped" width="100%" cellspacing="0" id="table-courriers">
<thead class="table-dark">
<tr>
{{-- <th style="width:5%;">N°</th> --}}
<th style="width:8%;">N°</th>
<th>Objet</th>
<th style="width:10%;">Expediteur</th>
<th style="width:11%;">Email</th>
<th style="width:11%;">Telephone</th>
<th style="width:12%;">Type de courrier</th>
<th style="width:5%;"></th>
</tr>
</thead>
<tfoot class="table-dark">
<tr>
{{-- <th>N°</th> --}}
<th>N°</th>
<th>Objet</th>
<th>Expediteur</th>
<th>Email</th>
<th>Telephone</th>
<th>Type de courrier</th>
<th></th>
</tr>
</tfoot>
<tbody>
<?php $i = 1 ?>
@foreach ($courriers as $courrier)
<tr>
{{-- <td>{!! $i++ !!}</td> --}}
<td>
<a style="color: darkorange; text-decoration: none;"
href="{!! url('courriers/'.$courrier->id) !!}" class="view" title="voir" target="_blank">
<b>{!! $courrier->numero !!}</b>
</a>
</td>
<td>{!! $courrier->objet !!}</td>
<td>{!! $courrier->expediteur !!}</td>
<td>{!! $courrier->email !!}</td>
<td>{!! $courrier->telephone !!}</td>
<td>
<b>{!! $courrier->types_courrier->name !!}</b>
</td>
<td class="d-flex align-items-baseline align-content-center">
@can('courrier-edit')
<a href="{!! url('courriers/'.$courrier->id) !!}" class= 'btn btn-primary btn-sm' title="voir">
<i class="far fa-eye"></i>
</a>
@endcan
</td>
</tr>
@endforeach
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
<br />
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-header">
{{-- <i class="fas fa-table"></i> --}}
<img src="{{ asset("img/stats_15267.png") }}" class="w-5"/>
Statistiques des courriers
</div>
<div class="card-body">
{{-- {!! $chart->container() !!} --}}
{{-- <canvas id="bar-chart" width="800" height="450"></canvas> --}}
</div>
</div>
</div>
</div>
</div>
<br />
@else
@endhasrole
@endsection
@push('scripts')
<script type="text/javascript">
$(document).ready( function () {
$('#table-courriers').DataTable({
dom: 'lBfrtip',
buttons: [
{
extend: 'copyHtml5',
text: '<i class="fas fa-copy"></i> Copy',
titleAttr: 'Copy'
},
{
extend: 'excelHtml5',
text: '<i class="fas fa-file-excel"></i> Excel',
titleAttr: 'Excel'
},
{
extend: 'csvHtml5',
text: '<i class="fas fa-file-csv"></i> CSV',
titleAttr: 'CSV'
},
{
extend: 'pdfHtml5',
text: '<i class="fas fa-file-pdf"></i> PDF',
orientation : 'landscape',
pageSize : 'RA4',
titleAttr: 'PDF'
},
{
extend: 'print',
text: '<i class="fas fa-print"></i> Print',
titleAttr: 'Print'
}
],
"lengthMenu": [ [10, 25, 50, 100, -1], [10, 25, 50, 100, "Tout"] ],
"order": [
[ 0, 'asc' ]
],
language: {
"sProcessing": "Traitement en cours...",
"sSearch": "Rechercher :",
"sLengthMenu": "Afficher _MENU_ éléments",
"sInfo": "Affichage de l'élément _START_ à _END_ sur _TOTAL_ éléments",
"sInfoEmpty": "Affichage de l'élément 0 à 0 sur 0 élément",
"sInfoFiltered": "(filtré de _MAX_ éléments au total)",
"sInfoPostFix": "",
"sLoadingRecords": "Chargement en cours...",
"sZeroRecords": "Aucun élément à afficher",
"sEmptyTable": "Aucune donnée disponible dans le tableau",
"oPaginate": {
"sFirst": "Premier",
"sPrevious": "Précédent",
"sNext": "Suivant",
"sLast": "Dernier"
},
"oAria": {
"sSortAscending": ": activer pour trier la colonne par ordre croissant",
"sSortDescending": ": activer pour trier la colonne par ordre décroissant"
},
"select": {
"rows": {
_: "%d lignes séléctionnées",
0: "Aucune ligne séléctionnée",
1: "1 ligne séléctionnée"
}
}
}
});
} );
</script>
{{-- {!! $chart->script() !!} --}}
@endpush
| 5,265
|
https://github.com/NexusMax/yii2-ads/blob/master/backend/config/main.php
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,018
|
yii2-ads
|
NexusMax
|
PHP
|
Code
| 406
| 1,344
|
<?php
$params = array_merge(
require(__DIR__ . '/../../common/config/params.php'),
require(__DIR__ . '/../../common/config/params-local.php'),
require(__DIR__ . '/params.php'),
require(__DIR__ . '/params-local.php')
);
return [
'id' => 'app-backend',
'basePath' => dirname(__DIR__),
'controllerNamespace' => 'backend\controllers',
'language' => 'ru-RU',
'bootstrap' => [
'log',
'queue', // Компонент регистрирует свои консольные команды
],
'components' => [
'queue' => [
'class' => \yii\queue\file\Queue::class,
'as log' => \yii\queue\LogBehavior::class,
'ttr' => 2 * 60, // Максимальное время выполнения задания
'attempts' => 3, // Максимальное кол-во попыток
'path' => '@runtime/queue',
],
// 'view' => [
// 'theme' => [
// 'pathMap' => [
// '@app/views' => '@vendor/dmstr/yii2-adminlte-asset/example-views/yiisoft/yii2-app'
// ],
// ],
// ],
'user' => [
'class' => 'common\models\User', // extend User component
],
'cache' => [
'class' => 'yii\caching\FileCache',
],
'formatter' => [
'class' => 'yii\i18n\Formatter',
'dateFormat' => 'php:d.m.Y',
'datetimeFormat' => 'php:j F, H:i',
'timeFormat' => 'php:H:i:s',
'defaultTimeZone' => 'Europe/Moscow',
'locale' => 'ru-RU'
],
'request' => [
'csrfParam' => '_csrf-backend',
],
'user' => [
'identityClass' => 'common\models\User',
'enableAutoLogin' => true,
'identityCookie' => ['name' => '_identity-backend', 'httpOnly' => true],
],
'session' => [
// this is the name of the session cookie used for login on the backend
'name' => 'advanced-backend',
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'errorHandler' => [
'errorAction' => 'site/error',
],
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
// send all mails to a file by default. You have to set
// 'useFileTransport' to false and configure a transport
// for the mailer to send real emails.
// 'viewPath' => '@app/mail',
// 'htmlLayout' => 'layouts/main-html',
// 'textLayout' => 'layouts/main-text',
// 'messageConfig' => [
// 'charset' => 'UTF-8',
// 'from' => ['antonlitvinov14@gmail.com' => 'Site Name'],
// ],
'useFileTransport' => false, // false - real server
// 'transport' => [
// 'class' => 'Swift_SmtpTransport',
// 'host' => 'smtp.gmail.com',
// 'username' => 'antonlitvinov14@gmail.com',
// 'password' => 'password',
// 'port' => '465', //465
// 'encryption' => 'ssl', //ssl
// ],
],
'request' => [
'baseUrl' => '/admin',
],
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
'image' => 'yii2images/images/image-by-item-and-alias',
'' => 'site/index',
'<controller:\w+>/<action:\w+>/' => '<controller>/<action>',
'<module:admin>/<controller:catalog>/<action:category>' => '<module:admin>/<controller:categories>/<action:index>',
],
],
'assetManager' => [
'appendTimestamp' => true,
'bundles' => [
'/admin/assets/522ef28c/no.conflict.js' => false,
],
],
],
'controllerMap' => [
'elfinder' => [
'class' => 'mihaildev\elfinder\PathController',
'access' => ['@'],
'root' => [
'baseUrl' => '/web',
'basePath' => Yii::getAlias('@appWeb'),
'path' => 'images/',
'name' => 'Global'
],
]
],
'params' => $params,
];
| 26,352
|
https://github.com/ndq809/EPLUS/blob/master/SQL/master/popup/p003/SPC_P003_LST3.sql
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
EPLUS
|
ndq809
|
SQL
|
Code
| 200
| 874
|
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SPC_P003_LST3]') AND type IN (N'P', N'PC'))
/****** Object: StoredProcedure [dbo].[SPC_M001L_FND1] Script Date: 2017/11/23 16:46:46 ******/
DROP PROCEDURE [dbo].[SPC_P003_LST3]
GO
/****** Object: StoredProcedure [dbo].[SPC_M001L_FND1] Script Date: 2017/11/23 16:46:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[SPC_P003_LST3]
@P_vocabulary_list NVARCHAR(MAX) = ''
AS
BEGIN
SET NOCOUNT ON;
DECLARE
@w_tag_div INT
CREATE TABLE #P003(
vocabulary_code NVARCHAR(15)
, vocabulary_id NVARCHAR(15)
, vocabulary_dtl_id NVARCHAR(15)
, vocabulary_nm NVARCHAR(500)
, vocabulary_div INT
, vocabulary_div_nm NVARCHAR(50)
, specialized_div INT
, specialized_div_nm NVARCHAR(500)
, field_div INT
, field_div_nm NVARCHAR(500)
, spelling NVARCHAR(500)
, mean NVARCHAR(MAX)
, image NVARCHAR(500)
, audio NVARCHAR(500)
)
--
INSERT INTO #P003
SELECT
M006.id
, M006.Vocabulary_id
, M006.Vocabulary_dtl_id
, M006.Vocabulary_nm
, M999_1.number_id
, M999_1.content
, M999_2.number_id
, M999_2.content
, M999_3.number_id
, M999_3.content
, M006.spelling
, M006.mean
, M006.image
, M006.audio
FROM M006
LEFT JOIN M999 M999_1
ON M006.vocabulary_div = M999_1.number_id
AND M999_1.name_div = 8
LEFT JOIN M999 M999_2
ON M006.specialized = M999_2.number_id
AND M999_2.name_div = 23
LEFT JOIN M999 M999_3
ON M006.field = M999_3.number_id
AND M999_3.name_div = 24
INNER JOIN
(
SELECT
vocabulary_code AS vocabulary_code
FROM OPENJSON(@P_vocabulary_list) WITH(
vocabulary_code VARCHAR(10) '$.vocabulary_code'
)
)TEMP ON
TEMP.vocabulary_code = M006.id
SELECT * FROM #P003
--
END
| 12,708
|
https://github.com/equipe25-GetHub/frontend/blob/master/src/views/404.vue
|
Github Open Source
|
Open Source
|
BSD-Source-Code
| null |
frontend
|
equipe25-GetHub
|
Vue
|
Code
| 22
| 77
|
<template>
<div class="not-found flex row justify-center">
Desculpe, página não encontrada, <router-link to="/login">Login</router-link>
</div>
</template>
<script>
export default {
name: 'NotFound'
};
</script>
| 48,653
|
https://github.com/bcgov/sbc-common-components/blob/master/vue/sbc-common-components/src/components/SbcAuthMenu.vue
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,023
|
sbc-common-components
|
bcgov
|
Vue
|
Code
| 692
| 2,553
|
<template>
<!-- Login Menu -->
<v-card>
<div>
<v-card-title class="body-2 font-weight-bold">Select login method</v-card-title>
<v-divider></v-divider>
</div>
<v-list
tile
dense
>
<v-list-item
v-for="loginOption in loginOptions"
:key="loginOption.idpHint"
@click="login(loginOption.idpHint)"
class="pr-6"
>
<v-list-item-icon left>
<v-icon>{{loginOption.icon}}</v-icon>
</v-list-item-icon>
<v-list-item-title>{{loginOption.option}}</v-list-item-title>
</v-list-item>
</v-list>
</v-card>
</template>
<script lang="ts">
import { Component, Mixins, Prop, Watch } from 'vue-property-decorator'
import { LDClient } from 'launchdarkly-js-client-sdk'
import { Role, IdpHint, LoginSource, Pages } from '../util/constants'
import { mapState, mapActions, mapGetters } from 'vuex'
import { UserSettings } from '../models/userSettings'
import NavigationMixin from '../mixins/navigation-mixin'
import { getModule } from 'vuex-module-decorators'
import AccountModule from '../store/modules/account'
import AuthModule from '../store/modules/auth'
import { KCUserProfile } from '../models/KCUserProfile'
import KeyCloakService from '../services/keycloak.services'
declare module 'vuex' {
interface Store<S> {
isModuleRegistered(_: string[]): boolean
}
}
@Component({
beforeCreate () {
this.$store.isModuleRegistered = function (aPath: string[]) {
let m = (this as any)._modules.root
return aPath.every((p) => {
m = m._children[p]
return m
})
}
if (!this.$store.isModuleRegistered(['account'])) {
this.$store.registerModule('account', AccountModule)
}
if (!this.$store.isModuleRegistered(['auth'])) {
this.$store.registerModule('auth', AuthModule)
}
this.$options.computed = {
...(this.$options.computed || {}),
...mapGetters('auth', ['isAuthenticated', 'currentLoginSource'])
}
this.$options.methods = {
...(this.$options.methods || {}),
...mapActions('account', [
'loadUserInfo',
'syncAccount',
'syncCurrentAccount',
'syncUserProfile',
'getCurrentUserProfile',
'updateUserProfile']),
...mapActions('auth', ['syncWithSessionStorage'])
}
}
})
export default class SbcAuthMenu extends Mixins(NavigationMixin) {
private ldClient!: LDClient
private readonly currentAccount!: UserSettings | null
private readonly accountName!: string
private readonly currentLoginSource!: string
private readonly isAuthenticated!: boolean
private readonly loadUserInfo!: () => KCUserProfile
private readonly syncAccount!: () => Promise<void>
// private readonly syncCurrentAccount!: (userSettings: UserSettings) => Promise<UserSettings>
private readonly syncUserProfile!: () => Promise<void>
private readonly syncWithSessionStorage!: () => void
private readonly getCurrentUserProfile!: (isAuth: boolean) => Promise<any>
private readonly updateUserProfile!: () => Promise<void>
@Prop({ default: '' }) redirectOnLoginSuccess!: string;
@Prop({ default: '' }) redirectOnLoginFail!: string;
@Prop({ default: false }) inAuth!: boolean;
@Prop({ default: false }) fromLogin!: boolean;
private readonly loginOptions = [
{
idpHint: IdpHint.BCSC,
option: 'BC Services Card',
icon: 'mdi-account-card-details-outline'
},
{
idpHint: IdpHint.BCEID,
option: 'BCeID',
icon: 'mdi-two-factor-authentication'
},
{
idpHint: IdpHint.IDIR,
option: 'IDIR',
icon: 'mdi-account-group-outline'
}
]
get isIDIR (): boolean {
return this.currentLoginSource === LoginSource.IDIR
}
get isBceid (): boolean {
return this.currentLoginSource === LoginSource.BCEID
}
get isBcscOrBceid (): boolean {
return [LoginSource.BCSC.valueOf(), LoginSource.BCEID.valueOf()].indexOf(this.currentLoginSource) >= 0
}
private async mounted () {
getModule(AccountModule, this.$store)
getModule(AuthModule, this.$store)
this.syncWithSessionStorage()
if (this.isAuthenticated) {
await this.loadUserInfo()
await this.syncAccount()
await this.updateProfile()
// checking for account status
await this.checkAccountStatus()
}
}
@Watch('isAuthenticated')
private async onisAuthenticated (isAuthenitcated: string, oldVal: string) {
if (isAuthenitcated) {
await this.updateProfile()
}
}
private async updateProfile () {
if (this.isBceid) {
await this.syncUserProfile()
}
}
private goToCreateBCSCAccount () {
this.redirectToPath(this.inAuth, Pages.CREATE_ACCOUNT)
}
private checkAccountStatus () {
// redirect if account status is suspended
if (this.currentAccount?.accountStatus && this.currentAccount?.accountStatus === 'NSF_SUSPENDED') {
this.redirectToPath(this.inAuth, `${Pages.ACCOUNT_FREEZ}`)
} else if (this.currentAccount?.accountStatus === 'PENDING_AFFIDAVIT_REVIEW') {
this.redirectToPath(this.inAuth, `${Pages.PENDING_APPROVAL}/${this.accountName}/true`)
}
}
login (idpHint: string) {
if (!this.fromLogin) {
if (this.redirectOnLoginSuccess) {
let url = encodeURIComponent(this.redirectOnLoginSuccess)
url += this.redirectOnLoginFail ? `/${encodeURIComponent(this.redirectOnLoginFail)}` : ''
window.location.assign(`${this.getContextPath()}signin/${idpHint}/${url}`)
} else {
window.location.assign(`${this.getContextPath()}signin/${idpHint}`)
}
} else {
// Initialize keycloak session
const kcInit = KeyCloakService.initializeKeyCloak(idpHint, this.$store)
kcInit.then(async (authenticated: boolean) => {
if (authenticated) {
// eslint-disable-next-line no-console
console.info('[SignIn.vue]Logged in User. Init Session and Starting refreshTimer')
// Set values to session storage
await KeyCloakService.initSession()
// tell KeycloakServices to load the user info
const userInfo = await this.loadUserInfo()
// update user profile
await this.updateUserProfile()
// sync the account if there is one
await this.syncAccount()
// if not from the sbc-auth, do the checks and redirect to sbc-auth
if (!this.inAuth) {
console.log('[SignIn.vue]Not from sbc-auth. Checking account status')
// redirect to create account page if the user has no 'account holder' role
const isRedirectToCreateAccount = (userInfo.roles.includes(Role.PublicUser) && !userInfo.roles.includes(Role.AccountHolder))
const currentUser = await this.getCurrentUserProfile(this.inAuth)
if ((userInfo?.loginSource !== LoginSource.IDIR) && !(currentUser?.userTerms?.isTermsOfUseAccepted)) {
console.log('[SignIn.vue]Redirecting. TOS not accepted')
this.redirectToPath(this.inAuth, Pages.USER_PROFILE_TERMS)
} else if (isRedirectToCreateAccount) {
console.log('[SignIn.vue]Redirecting. No Valid Role')
switch (userInfo.loginSource) {
case LoginSource.BCSC:
this.redirectToPath(this.inAuth, Pages.CREATE_ACCOUNT)
break
case LoginSource.BCEID:
this.redirectToPath(this.inAuth, Pages.CHOOSE_AUTH_METHOD)
break
}
}
}
}
}).catch(() => {
if (this.redirectOnLoginFail) {
window.location.assign(decodeURIComponent(this.redirectOnLoginFail))
}
})
}
}
private getContextPath (): string {
let baseUrl = (this.$router && (this.$router as any)['history'] && (this.$router as any)['history'].base) || ''
baseUrl += (baseUrl.length && baseUrl[baseUrl.length - 1] !== '/') ? '/' : ''
return baseUrl
}
}
</script>
<style lang="scss" scoped>
@import "../assets/scss/theme.scss";
.v-list--dense .v-subheader,
.v-list-item {
padding-right: 1.25rem;
padding-left: 1.25rem;
}
.v-list--dense .v-subheader,
.v-list--dense .v-list-item__title,
.v-list--dense .v-list-item__subtitle {
font-size: 0.875rem !important;
}
</style>
| 14,902
|
https://github.com/hongframework/hamster/blob/master/basic/src/main/java/com/hframework/hamster/sec/domain/model/HfsecOrganize_Example.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,020
|
hamster
|
hongframework
|
Java
|
Code
| 2,321
| 8,713
|
package com.hframework.hamster.sec.domain.model;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class HfsecOrganize_Example {
protected String orderByClause;
protected boolean distinct;
protected List<Criteria> oredCriteria;
protected Integer limitStart;
protected Integer limitEnd;
public HfsecOrganize_Example() {
oredCriteria = new ArrayList<Criteria>();
}
public void setOrderByClause(String orderByClause) {
this.orderByClause = orderByClause;
}
public String getOrderByClause() {
return orderByClause;
}
public void setDistinct(boolean distinct) {
this.distinct = distinct;
}
public boolean isDistinct() {
return distinct;
}
public List<Criteria> getOredCriteria() {
return oredCriteria;
}
public void or(Criteria criteria) {
oredCriteria.add(criteria);
}
public Criteria or() {
Criteria criteria = createCriteriaInternal();
oredCriteria.add(criteria);
return criteria;
}
public Criteria createCriteria() {
Criteria criteria = createCriteriaInternal();
if (oredCriteria.size() == 0) {
oredCriteria.add(criteria);
}
return criteria;
}
protected Criteria createCriteriaInternal() {
Criteria criteria = new Criteria();
return criteria;
}
public void clear() {
oredCriteria.clear();
orderByClause = null;
distinct = false;
}
public void setLimitStart(Integer limitStart) {
this.limitStart=limitStart;
}
public Integer getLimitStart() {
return limitStart;
}
public void setLimitEnd(Integer limitEnd) {
this.limitEnd=limitEnd;
}
public Integer getLimitEnd() {
return limitEnd;
}
protected abstract static class GeneratedCriteria {
protected List<Criterion> criteria;
protected GeneratedCriteria() {
super();
criteria = new ArrayList<Criterion>();
}
public boolean isValid() {
return criteria.size() > 0;
}
public List<Criterion> getAllCriteria() {
return criteria;
}
public List<Criterion> getCriteria() {
return criteria;
}
protected void addCriterion(String condition) {
if (condition == null) {
throw new RuntimeException("Value for condition cannot be null");
}
criteria.add(new Criterion(condition));
}
protected void addCriterion(String condition, Object value, String property) {
if (value == null) {
throw new RuntimeException("Value for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value));
}
protected void addCriterion(String condition, Object value1, Object value2, String property) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value1, value2));
}
public Criteria andHfsecOrganizeIdIsNull() {
addCriterion("hfsec_organize_id is null");
return (Criteria) this;
}
public Criteria andHfsecOrganizeIdIsNotNull() {
addCriterion("hfsec_organize_id is not null");
return (Criteria) this;
}
public Criteria andHfsecOrganizeIdEqualTo(Long value) {
addCriterion("hfsec_organize_id =", value, "hfsecOrganizeId");
return (Criteria) this;
}
public Criteria andHfsecOrganizeIdNotEqualTo(Long value) {
addCriterion("hfsec_organize_id <>", value, "hfsecOrganizeId");
return (Criteria) this;
}
public Criteria andHfsecOrganizeIdGreaterThan(Long value) {
addCriterion("hfsec_organize_id >", value, "hfsecOrganizeId");
return (Criteria) this;
}
public Criteria andHfsecOrganizeIdGreaterThanOrEqualTo(Long value) {
addCriterion("hfsec_organize_id >=", value, "hfsecOrganizeId");
return (Criteria) this;
}
public Criteria andHfsecOrganizeIdLessThan(Long value) {
addCriterion("hfsec_organize_id <", value, "hfsecOrganizeId");
return (Criteria) this;
}
public Criteria andHfsecOrganizeIdLessThanOrEqualTo(Long value) {
addCriterion("hfsec_organize_id <=", value, "hfsecOrganizeId");
return (Criteria) this;
}
public Criteria andHfsecOrganizeIdIn(List<Long> values) {
addCriterion("hfsec_organize_id in", values, "hfsecOrganizeId");
return (Criteria) this;
}
public Criteria andHfsecOrganizeIdNotIn(List<Long> values) {
addCriterion("hfsec_organize_id not in", values, "hfsecOrganizeId");
return (Criteria) this;
}
public Criteria andHfsecOrganizeIdBetween(Long value1, Long value2) {
addCriterion("hfsec_organize_id between", value1, value2, "hfsecOrganizeId");
return (Criteria) this;
}
public Criteria andHfsecOrganizeIdNotBetween(Long value1, Long value2) {
addCriterion("hfsec_organize_id not between", value1, value2, "hfsecOrganizeId");
return (Criteria) this;
}
public Criteria andHfsecOrganizeCodeIsNull() {
addCriterion("hfsec_organize_code is null");
return (Criteria) this;
}
public Criteria andHfsecOrganizeCodeIsNotNull() {
addCriterion("hfsec_organize_code is not null");
return (Criteria) this;
}
public Criteria andHfsecOrganizeCodeEqualTo(String value) {
addCriterion("hfsec_organize_code =", value, "hfsecOrganizeCode");
return (Criteria) this;
}
public Criteria andHfsecOrganizeCodeNotEqualTo(String value) {
addCriterion("hfsec_organize_code <>", value, "hfsecOrganizeCode");
return (Criteria) this;
}
public Criteria andHfsecOrganizeCodeGreaterThan(String value) {
addCriterion("hfsec_organize_code >", value, "hfsecOrganizeCode");
return (Criteria) this;
}
public Criteria andHfsecOrganizeCodeGreaterThanOrEqualTo(String value) {
addCriterion("hfsec_organize_code >=", value, "hfsecOrganizeCode");
return (Criteria) this;
}
public Criteria andHfsecOrganizeCodeLessThan(String value) {
addCriterion("hfsec_organize_code <", value, "hfsecOrganizeCode");
return (Criteria) this;
}
public Criteria andHfsecOrganizeCodeLessThanOrEqualTo(String value) {
addCriterion("hfsec_organize_code <=", value, "hfsecOrganizeCode");
return (Criteria) this;
}
public Criteria andHfsecOrganizeCodeLike(String value) {
addCriterion("hfsec_organize_code like", value, "hfsecOrganizeCode");
return (Criteria) this;
}
public Criteria andHfsecOrganizeCodeNotLike(String value) {
addCriterion("hfsec_organize_code not like", value, "hfsecOrganizeCode");
return (Criteria) this;
}
public Criteria andHfsecOrganizeCodeIn(List<String> values) {
addCriterion("hfsec_organize_code in", values, "hfsecOrganizeCode");
return (Criteria) this;
}
public Criteria andHfsecOrganizeCodeNotIn(List<String> values) {
addCriterion("hfsec_organize_code not in", values, "hfsecOrganizeCode");
return (Criteria) this;
}
public Criteria andHfsecOrganizeCodeBetween(String value1, String value2) {
addCriterion("hfsec_organize_code between", value1, value2, "hfsecOrganizeCode");
return (Criteria) this;
}
public Criteria andHfsecOrganizeCodeNotBetween(String value1, String value2) {
addCriterion("hfsec_organize_code not between", value1, value2, "hfsecOrganizeCode");
return (Criteria) this;
}
public Criteria andHfsecOrganizeNameIsNull() {
addCriterion("hfsec_organize_name is null");
return (Criteria) this;
}
public Criteria andHfsecOrganizeNameIsNotNull() {
addCriterion("hfsec_organize_name is not null");
return (Criteria) this;
}
public Criteria andHfsecOrganizeNameEqualTo(String value) {
addCriterion("hfsec_organize_name =", value, "hfsecOrganizeName");
return (Criteria) this;
}
public Criteria andHfsecOrganizeNameNotEqualTo(String value) {
addCriterion("hfsec_organize_name <>", value, "hfsecOrganizeName");
return (Criteria) this;
}
public Criteria andHfsecOrganizeNameGreaterThan(String value) {
addCriterion("hfsec_organize_name >", value, "hfsecOrganizeName");
return (Criteria) this;
}
public Criteria andHfsecOrganizeNameGreaterThanOrEqualTo(String value) {
addCriterion("hfsec_organize_name >=", value, "hfsecOrganizeName");
return (Criteria) this;
}
public Criteria andHfsecOrganizeNameLessThan(String value) {
addCriterion("hfsec_organize_name <", value, "hfsecOrganizeName");
return (Criteria) this;
}
public Criteria andHfsecOrganizeNameLessThanOrEqualTo(String value) {
addCriterion("hfsec_organize_name <=", value, "hfsecOrganizeName");
return (Criteria) this;
}
public Criteria andHfsecOrganizeNameLike(String value) {
addCriterion("hfsec_organize_name like", value, "hfsecOrganizeName");
return (Criteria) this;
}
public Criteria andHfsecOrganizeNameNotLike(String value) {
addCriterion("hfsec_organize_name not like", value, "hfsecOrganizeName");
return (Criteria) this;
}
public Criteria andHfsecOrganizeNameIn(List<String> values) {
addCriterion("hfsec_organize_name in", values, "hfsecOrganizeName");
return (Criteria) this;
}
public Criteria andHfsecOrganizeNameNotIn(List<String> values) {
addCriterion("hfsec_organize_name not in", values, "hfsecOrganizeName");
return (Criteria) this;
}
public Criteria andHfsecOrganizeNameBetween(String value1, String value2) {
addCriterion("hfsec_organize_name between", value1, value2, "hfsecOrganizeName");
return (Criteria) this;
}
public Criteria andHfsecOrganizeNameNotBetween(String value1, String value2) {
addCriterion("hfsec_organize_name not between", value1, value2, "hfsecOrganizeName");
return (Criteria) this;
}
public Criteria andHfsecOrganizeTypeIsNull() {
addCriterion("hfsec_organize_type is null");
return (Criteria) this;
}
public Criteria andHfsecOrganizeTypeIsNotNull() {
addCriterion("hfsec_organize_type is not null");
return (Criteria) this;
}
public Criteria andHfsecOrganizeTypeEqualTo(Byte value) {
addCriterion("hfsec_organize_type =", value, "hfsecOrganizeType");
return (Criteria) this;
}
public Criteria andHfsecOrganizeTypeNotEqualTo(Byte value) {
addCriterion("hfsec_organize_type <>", value, "hfsecOrganizeType");
return (Criteria) this;
}
public Criteria andHfsecOrganizeTypeGreaterThan(Byte value) {
addCriterion("hfsec_organize_type >", value, "hfsecOrganizeType");
return (Criteria) this;
}
public Criteria andHfsecOrganizeTypeGreaterThanOrEqualTo(Byte value) {
addCriterion("hfsec_organize_type >=", value, "hfsecOrganizeType");
return (Criteria) this;
}
public Criteria andHfsecOrganizeTypeLessThan(Byte value) {
addCriterion("hfsec_organize_type <", value, "hfsecOrganizeType");
return (Criteria) this;
}
public Criteria andHfsecOrganizeTypeLessThanOrEqualTo(Byte value) {
addCriterion("hfsec_organize_type <=", value, "hfsecOrganizeType");
return (Criteria) this;
}
public Criteria andHfsecOrganizeTypeIn(List<Byte> values) {
addCriterion("hfsec_organize_type in", values, "hfsecOrganizeType");
return (Criteria) this;
}
public Criteria andHfsecOrganizeTypeNotIn(List<Byte> values) {
addCriterion("hfsec_organize_type not in", values, "hfsecOrganizeType");
return (Criteria) this;
}
public Criteria andHfsecOrganizeTypeBetween(Byte value1, Byte value2) {
addCriterion("hfsec_organize_type between", value1, value2, "hfsecOrganizeType");
return (Criteria) this;
}
public Criteria andHfsecOrganizeTypeNotBetween(Byte value1, Byte value2) {
addCriterion("hfsec_organize_type not between", value1, value2, "hfsecOrganizeType");
return (Criteria) this;
}
public Criteria andHfsecOrganizeLevelIsNull() {
addCriterion("hfsec_organize_level is null");
return (Criteria) this;
}
public Criteria andHfsecOrganizeLevelIsNotNull() {
addCriterion("hfsec_organize_level is not null");
return (Criteria) this;
}
public Criteria andHfsecOrganizeLevelEqualTo(Byte value) {
addCriterion("hfsec_organize_level =", value, "hfsecOrganizeLevel");
return (Criteria) this;
}
public Criteria andHfsecOrganizeLevelNotEqualTo(Byte value) {
addCriterion("hfsec_organize_level <>", value, "hfsecOrganizeLevel");
return (Criteria) this;
}
public Criteria andHfsecOrganizeLevelGreaterThan(Byte value) {
addCriterion("hfsec_organize_level >", value, "hfsecOrganizeLevel");
return (Criteria) this;
}
public Criteria andHfsecOrganizeLevelGreaterThanOrEqualTo(Byte value) {
addCriterion("hfsec_organize_level >=", value, "hfsecOrganizeLevel");
return (Criteria) this;
}
public Criteria andHfsecOrganizeLevelLessThan(Byte value) {
addCriterion("hfsec_organize_level <", value, "hfsecOrganizeLevel");
return (Criteria) this;
}
public Criteria andHfsecOrganizeLevelLessThanOrEqualTo(Byte value) {
addCriterion("hfsec_organize_level <=", value, "hfsecOrganizeLevel");
return (Criteria) this;
}
public Criteria andHfsecOrganizeLevelIn(List<Byte> values) {
addCriterion("hfsec_organize_level in", values, "hfsecOrganizeLevel");
return (Criteria) this;
}
public Criteria andHfsecOrganizeLevelNotIn(List<Byte> values) {
addCriterion("hfsec_organize_level not in", values, "hfsecOrganizeLevel");
return (Criteria) this;
}
public Criteria andHfsecOrganizeLevelBetween(Byte value1, Byte value2) {
addCriterion("hfsec_organize_level between", value1, value2, "hfsecOrganizeLevel");
return (Criteria) this;
}
public Criteria andHfsecOrganizeLevelNotBetween(Byte value1, Byte value2) {
addCriterion("hfsec_organize_level not between", value1, value2, "hfsecOrganizeLevel");
return (Criteria) this;
}
public Criteria andParentHfsecOrganizeIdIsNull() {
addCriterion("parent_hfsec_organize_id is null");
return (Criteria) this;
}
public Criteria andParentHfsecOrganizeIdIsNotNull() {
addCriterion("parent_hfsec_organize_id is not null");
return (Criteria) this;
}
public Criteria andParentHfsecOrganizeIdEqualTo(Long value) {
addCriterion("parent_hfsec_organize_id =", value, "parentHfsecOrganizeId");
return (Criteria) this;
}
public Criteria andParentHfsecOrganizeIdNotEqualTo(Long value) {
addCriterion("parent_hfsec_organize_id <>", value, "parentHfsecOrganizeId");
return (Criteria) this;
}
public Criteria andParentHfsecOrganizeIdGreaterThan(Long value) {
addCriterion("parent_hfsec_organize_id >", value, "parentHfsecOrganizeId");
return (Criteria) this;
}
public Criteria andParentHfsecOrganizeIdGreaterThanOrEqualTo(Long value) {
addCriterion("parent_hfsec_organize_id >=", value, "parentHfsecOrganizeId");
return (Criteria) this;
}
public Criteria andParentHfsecOrganizeIdLessThan(Long value) {
addCriterion("parent_hfsec_organize_id <", value, "parentHfsecOrganizeId");
return (Criteria) this;
}
public Criteria andParentHfsecOrganizeIdLessThanOrEqualTo(Long value) {
addCriterion("parent_hfsec_organize_id <=", value, "parentHfsecOrganizeId");
return (Criteria) this;
}
public Criteria andParentHfsecOrganizeIdIn(List<Long> values) {
addCriterion("parent_hfsec_organize_id in", values, "parentHfsecOrganizeId");
return (Criteria) this;
}
public Criteria andParentHfsecOrganizeIdNotIn(List<Long> values) {
addCriterion("parent_hfsec_organize_id not in", values, "parentHfsecOrganizeId");
return (Criteria) this;
}
public Criteria andParentHfsecOrganizeIdBetween(Long value1, Long value2) {
addCriterion("parent_hfsec_organize_id between", value1, value2, "parentHfsecOrganizeId");
return (Criteria) this;
}
public Criteria andParentHfsecOrganizeIdNotBetween(Long value1, Long value2) {
addCriterion("parent_hfsec_organize_id not between", value1, value2, "parentHfsecOrganizeId");
return (Criteria) this;
}
public Criteria andStatusIsNull() {
addCriterion("`status` is null");
return (Criteria) this;
}
public Criteria andStatusIsNotNull() {
addCriterion("`status` is not null");
return (Criteria) this;
}
public Criteria andStatusEqualTo(Byte value) {
addCriterion("`status` =", value, "status");
return (Criteria) this;
}
public Criteria andStatusNotEqualTo(Byte value) {
addCriterion("`status` <>", value, "status");
return (Criteria) this;
}
public Criteria andStatusGreaterThan(Byte value) {
addCriterion("`status` >", value, "status");
return (Criteria) this;
}
public Criteria andStatusGreaterThanOrEqualTo(Byte value) {
addCriterion("`status` >=", value, "status");
return (Criteria) this;
}
public Criteria andStatusLessThan(Byte value) {
addCriterion("`status` <", value, "status");
return (Criteria) this;
}
public Criteria andStatusLessThanOrEqualTo(Byte value) {
addCriterion("`status` <=", value, "status");
return (Criteria) this;
}
public Criteria andStatusIn(List<Byte> values) {
addCriterion("`status` in", values, "status");
return (Criteria) this;
}
public Criteria andStatusNotIn(List<Byte> values) {
addCriterion("`status` not in", values, "status");
return (Criteria) this;
}
public Criteria andStatusBetween(Byte value1, Byte value2) {
addCriterion("`status` between", value1, value2, "status");
return (Criteria) this;
}
public Criteria andStatusNotBetween(Byte value1, Byte value2) {
addCriterion("`status` not between", value1, value2, "status");
return (Criteria) this;
}
public Criteria andCreatorIdIsNull() {
addCriterion("creator_id is null");
return (Criteria) this;
}
public Criteria andCreatorIdIsNotNull() {
addCriterion("creator_id is not null");
return (Criteria) this;
}
public Criteria andCreatorIdEqualTo(Long value) {
addCriterion("creator_id =", value, "creatorId");
return (Criteria) this;
}
public Criteria andCreatorIdNotEqualTo(Long value) {
addCriterion("creator_id <>", value, "creatorId");
return (Criteria) this;
}
public Criteria andCreatorIdGreaterThan(Long value) {
addCriterion("creator_id >", value, "creatorId");
return (Criteria) this;
}
public Criteria andCreatorIdGreaterThanOrEqualTo(Long value) {
addCriterion("creator_id >=", value, "creatorId");
return (Criteria) this;
}
public Criteria andCreatorIdLessThan(Long value) {
addCriterion("creator_id <", value, "creatorId");
return (Criteria) this;
}
public Criteria andCreatorIdLessThanOrEqualTo(Long value) {
addCriterion("creator_id <=", value, "creatorId");
return (Criteria) this;
}
public Criteria andCreatorIdIn(List<Long> values) {
addCriterion("creator_id in", values, "creatorId");
return (Criteria) this;
}
public Criteria andCreatorIdNotIn(List<Long> values) {
addCriterion("creator_id not in", values, "creatorId");
return (Criteria) this;
}
public Criteria andCreatorIdBetween(Long value1, Long value2) {
addCriterion("creator_id between", value1, value2, "creatorId");
return (Criteria) this;
}
public Criteria andCreatorIdNotBetween(Long value1, Long value2) {
addCriterion("creator_id not between", value1, value2, "creatorId");
return (Criteria) this;
}
public Criteria andCreateTimeIsNull() {
addCriterion("create_time is null");
return (Criteria) this;
}
public Criteria andCreateTimeIsNotNull() {
addCriterion("create_time is not null");
return (Criteria) this;
}
public Criteria andCreateTimeEqualTo(Date value) {
addCriterion("create_time =", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeNotEqualTo(Date value) {
addCriterion("create_time <>", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeGreaterThan(Date value) {
addCriterion("create_time >", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeGreaterThanOrEqualTo(Date value) {
addCriterion("create_time >=", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeLessThan(Date value) {
addCriterion("create_time <", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeLessThanOrEqualTo(Date value) {
addCriterion("create_time <=", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeIn(List<Date> values) {
addCriterion("create_time in", values, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeNotIn(List<Date> values) {
addCriterion("create_time not in", values, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeBetween(Date value1, Date value2) {
addCriterion("create_time between", value1, value2, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeNotBetween(Date value1, Date value2) {
addCriterion("create_time not between", value1, value2, "createTime");
return (Criteria) this;
}
public Criteria andModifierIdIsNull() {
addCriterion("modifier_id is null");
return (Criteria) this;
}
public Criteria andModifierIdIsNotNull() {
addCriterion("modifier_id is not null");
return (Criteria) this;
}
public Criteria andModifierIdEqualTo(Long value) {
addCriterion("modifier_id =", value, "modifierId");
return (Criteria) this;
}
public Criteria andModifierIdNotEqualTo(Long value) {
addCriterion("modifier_id <>", value, "modifierId");
return (Criteria) this;
}
public Criteria andModifierIdGreaterThan(Long value) {
addCriterion("modifier_id >", value, "modifierId");
return (Criteria) this;
}
public Criteria andModifierIdGreaterThanOrEqualTo(Long value) {
addCriterion("modifier_id >=", value, "modifierId");
return (Criteria) this;
}
public Criteria andModifierIdLessThan(Long value) {
addCriterion("modifier_id <", value, "modifierId");
return (Criteria) this;
}
public Criteria andModifierIdLessThanOrEqualTo(Long value) {
addCriterion("modifier_id <=", value, "modifierId");
return (Criteria) this;
}
public Criteria andModifierIdIn(List<Long> values) {
addCriterion("modifier_id in", values, "modifierId");
return (Criteria) this;
}
public Criteria andModifierIdNotIn(List<Long> values) {
addCriterion("modifier_id not in", values, "modifierId");
return (Criteria) this;
}
public Criteria andModifierIdBetween(Long value1, Long value2) {
addCriterion("modifier_id between", value1, value2, "modifierId");
return (Criteria) this;
}
public Criteria andModifierIdNotBetween(Long value1, Long value2) {
addCriterion("modifier_id not between", value1, value2, "modifierId");
return (Criteria) this;
}
public Criteria andModifyTimeIsNull() {
addCriterion("modify_time is null");
return (Criteria) this;
}
public Criteria andModifyTimeIsNotNull() {
addCriterion("modify_time is not null");
return (Criteria) this;
}
public Criteria andModifyTimeEqualTo(Date value) {
addCriterion("modify_time =", value, "modifyTime");
return (Criteria) this;
}
public Criteria andModifyTimeNotEqualTo(Date value) {
addCriterion("modify_time <>", value, "modifyTime");
return (Criteria) this;
}
public Criteria andModifyTimeGreaterThan(Date value) {
addCriterion("modify_time >", value, "modifyTime");
return (Criteria) this;
}
public Criteria andModifyTimeGreaterThanOrEqualTo(Date value) {
addCriterion("modify_time >=", value, "modifyTime");
return (Criteria) this;
}
public Criteria andModifyTimeLessThan(Date value) {
addCriterion("modify_time <", value, "modifyTime");
return (Criteria) this;
}
public Criteria andModifyTimeLessThanOrEqualTo(Date value) {
addCriterion("modify_time <=", value, "modifyTime");
return (Criteria) this;
}
public Criteria andModifyTimeIn(List<Date> values) {
addCriterion("modify_time in", values, "modifyTime");
return (Criteria) this;
}
public Criteria andModifyTimeNotIn(List<Date> values) {
addCriterion("modify_time not in", values, "modifyTime");
return (Criteria) this;
}
public Criteria andModifyTimeBetween(Date value1, Date value2) {
addCriterion("modify_time between", value1, value2, "modifyTime");
return (Criteria) this;
}
public Criteria andModifyTimeNotBetween(Date value1, Date value2) {
addCriterion("modify_time not between", value1, value2, "modifyTime");
return (Criteria) this;
}
}
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
public static class Criterion {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() {
return singleValue;
}
public boolean isBetweenValue() {
return betweenValue;
}
public boolean isListValue() {
return listValue;
}
public String getTypeHandler() {
return typeHandler;
}
protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
}
| 2,288
|
https://github.com/franz1981/infinispan/blob/master/commons/all/src/main/java/org/infinispan/commons/dataconversion/EncodingException.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,022
|
infinispan
|
franz1981
|
Java
|
Code
| 31
| 102
|
package org.infinispan.commons.dataconversion;
import org.infinispan.commons.CacheException;
/**
* @since 9.1
*/
public class EncodingException extends CacheException {
public EncodingException(String message) {
super(message);
}
public EncodingException(String message, Throwable cause) {
super(message, cause);
}
}
| 4,285
|
https://github.com/sw5cc/Excel2MySQL/blob/master/Excel2MySQL/slave.py
|
Github Open Source
|
Open Source
|
MIT
| null |
Excel2MySQL
|
sw5cc
|
Python
|
Code
| 47
| 175
|
# -*- utf-8 -*-
from time import sleep
from .utils import pop_request, bytes_to_str
from .dumps import xls2db
class Slave(object):
def next_requests(self):
return pop_request()
def start_requests(self):
return self.next_requests()
def process(self):
while True:
req = self.next_requests()
if req:
file = bytes_to_str(req)
print("xls2db: {0}".format(file))
xls2db(file)
else:
print("Empty queue, waiting...")
sleep(1)
| 40,138
|
https://github.com/CompPhysics/ThesisProjects/blob/master/doc/MSc/msc_students/former/johannes/programs/seriefiler/complex-interaction.f90
|
Github Open Source
|
Open Source
|
CC0-1.0
| 2,023
|
ThesisProjects
|
CompPhysics
|
Fortran Free Form
|
Code
| 3,032
| 9,576
|
! Program block complex-interaction.f90
!
! Author: Gaute Hagen and Morten Hjorth-Jensen
! ADDRESS: Dept. Physics, Universities of Bergen and Oslo, Norway
! E-MAIL: gaute.hagen@ift.uib.no, morten.hjorth-jensen@fys.uio.no
! LANGUAGE: F90/F95
! LAST UPGRADE : February 2005
!
! This file sets up a complex two-body interaction in the CoM
! system in momentum space using complex scaling.
! It allows for the use of the free interaction and a similarity
! transformed interaction as well.
!
! setup the free interaction
!
SUBROUTINE g_channel(i)
USE relcm_gmatrix
USE partial_waves
USE constants
USE wave_functions
IMPLICIT NONE
INTEGER, INTENT(IN) :: i ! loop variable over NN channels
INTEGER :: ncoup, pq_confs, p_confs, mspace
COMPLEX(DPC), ALLOCATABLE :: vkk(:,:), heff(:,:)
ncoup=1
IF ( orb_lrel_max(i) == jang_rel(i) ) ncoup = 1
IF ( orb_lrel_max(i) /= jang_rel(i) ) ncoup = 2
ALLOCATE(vkk (ncoup*n_k,ncoup*n_k))
! setup the NN interaction
CALL potential_interface(ncoup,vkk,i)
! construct free V-matrix in k-space
WRITE(6,'(12H Channel Nr:,I3,7H l_min:,I3,7H l_max:,I3,3H J:,I3,3H S:,I3,4H Tz:,I3)') &
i, orb_lrel_min(i), orb_lrel_max(i), jang_rel(i), spin_rel(i), iso(i)
SELECT CASE(type_of_interaction)
CASE('free')
vfree(1:ncoup*n_k,1:ncoup*n_k,i) = vkk(1:ncoup*n_k,1:ncoup*n_k)
CASE('renorm')
ALLOCATE(heff (ncoup*n_k1,ncoup*n_k1))
CALL g_mtx(ncoup,vkk,heff,i)
vfree(1:ncoup*n_k1,1:ncoup*n_k1,i) = heff(1:ncoup*n_k1,1:ncoup*n_k1)
DEALLOCATE(heff)
END SELECT
DEALLOCATE(vkk)
END SUBROUTINE g_channel
!
! Compute the T(G)-mtx for the actual channel
!
SUBROUTINE g_mtx(ncoup,vzz,heff,ichan)
USE wave_functions
USE constants
USE partial_waves
IMPLICIT NONE
INTEGER, INTENT(IN) :: ncoup, ichan
COMPLEX(DPC), DIMENSION(ncoup*n_k,ncoup*n_k), INTENT(IN) :: vzz
COMPLEX(DPC), DIMENSION(ncoup*n_k1,ncoup*n_k1), INTENT(INOUT) :: heff
INTEGER :: i, j, ntot, i1, np, nq, j1,j2, tisoz, no_zero
COMPLEX(DPC), ALLOCATABLE, DIMENSION(:,:) :: ham, cvec, temp
COMPLEX(DPC), ALLOCATABLE, DIMENSION(:) :: ceig
COMPLEX(DPC) :: sum, input_energy
! dimension of vectors and matrices
ntot = ncoup*n_k
ALLOCATE( ham(ntot, ntot), cvec(ntot,ntot), ceig(ntot), temp(ntot,ntot))
! setup hamiltonian to be diagonalized
ham = DCMPLX(0.0_DP,0.0_DP)
cvec = dcmplx(0.0_dp, 0.0_dp)
ceig = dcmplx(0.0_dp, 0.0_dp)
CALL complex_hamiltonian(ham,vzz, ntot, ichan)
temp = ham
no_zero = 0
do i = 1, ntot
do j = 1, ntot
if ( abs(ham(i,j)) == 0 ) no_zero = no_zero + 1
end do
end do
if ( no_zero > ntot*ntot/2 ) then
call lapack_diag(temp, cvec, ceig, ntot )
else
CALL diag_exact( temp, cvec, ceig, ntot )
end if
! construct renormalized nn-interaction via the Lee-Suzuki sim. transform
!
! size of model space : np = n_k1*ncoup
! size of complement space: nq = n_k2*ncoup
np = n_k1*ncoup; nq = n_k2*ncoup
CALL effective_int( np, nq, ntot, ncoup, cvec, ceig, heff )
!
! subtract diagonal elements to obtain Veff,
! and compare exact with effective interactions:
!
tisoz = iso(ichan)
DO i = 1, np
i1 = i
IF ( i > n_k1 ) i1 = i-n_k1
heff(i,i) = heff(i,i) - ( krel(i1) * krel(i1) )/p_mass(tisoz)
DO j = 1, np
j1 = j
IF ( j > n_k1 ) j1 = j-n_k1
heff(i,j) = heff(i,j)/SQRT( wkrel(i1)*wkrel(j1) )/krel(i1)/krel(j1)
ENDDO
ENDDO
! do i = 1, np
! write(6,*) abs(krel(i)), dble(heff(i,i)), aimag(heff(i,i))
! end do
DEALLOCATE(ham, temp, cvec ); DEALLOCATE(ceig)
END SUBROUTINE g_mtx
!
! complex scaled hamiltonian in momentum representation
!
SUBROUTINE complex_hamiltonian(h,vzz,ntot,ichan)
USE wave_functions
USE constants
USE partial_waves
IMPLICIT NONE
REAL(DP) :: delta
INTEGER, INTENT(IN) :: ntot, ichan
COMPLEX(DPC), DIMENSION(ntot,ntot), INTENT(INOUT) :: h
COMPLEX(DPC), DIMENSION(ntot,ntot), INTENT(IN) :: vzz
INTEGER :: i, j, i1, i2, tisoz
COMPLEX(DPC) :: wi
tisoz = iso(ichan)
h = 0.
DO i = 1, ntot
i1 = i
IF ( i > n_k ) i1 = i-n_k
h(i,i) = ( krel(i1) * krel(i1) )/p_mass(tisoz) + &
(krel(i1)) * (krel(i1)) * wkrel(i1) * Vzz(i,i)
DO j = 1, ntot
i2 = j
IF ( j > n_k ) i2 = j-n_k
IF (i /= j ) THEN
h(i,j) = SQRT( wkrel(i2) * wkrel(i1) ) * krel(i1) * krel(i2) * Vzz(i,j)
ENDIF
ENDDO
ENDDO
END SUBROUTINE complex_hamiltonian
! setting up potential vkk for complex arguments z,z', used in
! diagonalization of hamiltonian
!
! This routine contains old-fashioned common blocks
! acting as interface between the effective interaction program
! and the potential routines of the Bonn type, Nijmegen or
! Argonne groups.
! vkk is in units of MeV^-2,
! rgkk are mesh points in rel coordinates,
! units of fm^-1
! in partial wave basis, v(6)
! means
! v(1)= singlet uncoupled
! V(2)= triplet uncoupled
! V(3)= triplet coupled, < J+1 | V | J+1>
! V(4)= triplet coupled, < J-1 | V | J-1>
! V(5)= triplet coupled, < J+1 | V | J-1>
! V(6)= triplet coupled, < J-1 | V | J+1>
!
SUBROUTINE potential_interface(ncoup,vzz,ichan)
USE wave_functions
USE constants
USE partial_waves
IMPLICIT NONE
INTEGER :: i,j, ncoup, k, n, jxx, ichan, inn, isospin_tz, spin, ix, iy
!COMPLEX(DPC) :: v, ymev, xmev
REAL(DP) :: v, ymev, xmev
CHARACTER (LEN=4) :: label
COMMON /cnn/ inn
COMMON /cpot/ v(6),xmev,ymev
COMMON /cstate/ jxx, heform, sing, trip, coup, endep, label
LOGICAL :: sing, trip, coup, heform, endep
COMPLEX(DPC), DIMENSION(ncoup*n_k,ncoup*n_k), INTENT(INOUT) :: vzz
heform=.FALSE.
jxx=jang_rel(ichan)
sing=spin_rel(ichan) == 0
trip=spin_rel(ichan) == 1
coup=(ncoup == 2)
isospin_tz=iso(ichan)
spin = spin_rel(ichan)
SELECT CASE ( isospin_tz)
CASE (-1)
inn = 1 ! pp case = 1
CASE (0)
inn = 2 ! pn case = 2 if all inn=2, no CSB or ISB
CASE ( 1)
inn = 3 ! nn case = 3 if pp == nn, only ISB
END SELECT
DO i=1,n_k
xmev = dble( krel(i) )
ix = i
IF (ncoup == 2) k=i+n_k
DO j=1,n_k
ymev= dble( krel(j) )
iy = j
IF (ncoup == 2) n=j+n_k
SELECT CASE (type_of_pot)
! CASE('CD-bonn')
! CALL cdbonn
! CASE('Idaho-A')
! CALL idaho
! CASE('Idaho-B')
! CALL idaho
! CASE ( 'reid93')
! CALL reid93
! CASE ( 'argonnev18')
! CALL argonp
! CASE ( 'nij-I-II')
! CALL nijm2
CASE ( 'n3lo')
! write(6,*) 'n3lo'
CALL n3lo
END SELECT
! SELECT CASE (type_of_pot)
! CASE('cmplx_cdonn')
! CALL cmplx_cdbonn
! END SELECT
IF (sing ) THEN
vzz(j,i)= dcmplx( v(1) )
ELSEIF ((trip).AND.(.NOT.coup ) ) THEN
vzz(j,i) = dcmplx( v(2) )
ELSEIF (coup ) THEN
vzz(j,i)= dcmplx( v(4) )
vzz(j,k)= dcmplx( v(5) )
vzz(n,i)= dcmplx( v(6) )
vzz(n,k)= dcmplx( v(3) )
ENDIF
ENDDO
ENDDO
END SUBROUTINE potential_interface
!
! calculate effective interaction for gamow shell model calcs
!
subroutine effective_int( np, nq, ntot, ncoup, cvec, ceig, heff )
use constants
USE wave_functions
implicit none
complex*16, dimension(ntot,ntot), intent(in) :: cvec
complex*16, dimension(ntot,ntot) :: cvec_temp
complex*16, dimension(ntot), intent(in) :: ceig
integer, intent(in) :: np, nq, ntot, ncoup
integer :: npp, k1, i1,i,k2,nqq,j
complex*16 :: cvec_pp(np,np), cvec_qp(nq,np), cvec_model(nq,np)
complex*16 :: ceig_p(np), ceig_model(np)
double precision, dimension(ntot) :: temp
integer :: model(np), orb, orbit_no(ntot)
double precision :: cvec_max, overlap(ntot)
complex*16 :: e_a, e_b
complex*16, dimension(np,np), intent(inout) :: heff
real*8 :: a1,a2,b1,b2
! calculate P-space overlap of all eigenvectors
! loop over all eigen vectors
do orb = 1, ntot
overlap(orb) = 0.
do i = 1, n_k1
if ( ncoup == 1 )then
overlap(orb) = overlap(orb) + abs( cvec(i,orb) )**2
elseif( ncoup == 2 ) then
overlap(orb) = overlap(orb) + abs( cvec(i,orb) )**2 + abs( cvec(n_k + i,orb) )**2
end if
end do
orbit_no(orb) = orb
end do
! sort all overlaps and corresponding orbit numbers
call eigenvalue_sort(overlap,orbit_no, ntot)
cvec_pp = 0.; cvec_qp = 0.
! Set up eigenvalues and eigenvectors for model space and excluded space
if ( ncoup == 1 ) then
DO i=1, np
! loop over all model space coefficients of exact eigenvectors |k>
!
k1 = orbit_no(i)
DO j = 1, n_k
IF ( j <= n_k1 ) THEN
cvec_pp(j,i) = cvec(j,k1)
ceig_p(i) = ceig(k1)
ELSEIF ( j > n_k1 ) THEN
cvec_qp(j-n_k1,i) = cvec(j,k1)
ENDIF
ENDDO
ENDDO
end if
if ( ncoup == 2 ) then
DO i=1, np
! loop over all model space coefficients of exact eigenvectors |k>
!
k1 = orbit_no(i)
ceig_p(i) = ceig(k1)
DO j = 1, n_k1
cvec_pp(j,i) = cvec(j,k1)
cvec_pp(j+n_k1,i) = cvec(j+n_k,k1)
ENDDO
ENDDO
DO i=1, np
k1 = orbit_no(i)
do j = 1, n_k2
cvec_qp(j,i) = cvec(n_k1+j,k1)
cvec_qp(j+n_k2,i) = cvec(n_k+n_k1+j,k1)
end do
end DO
end if
heff = 0.
call lee_suzuki2( cvec_pp, cvec_qp, ceig_p, np, nq, heff )
! ! subtract diagonal terms
end subroutine effective_int
!
! Lee Suzuki similarity transformation
!
subroutine lee_suzuki( cvec_pp, cvec_qp, ceig, np, nq, heff )
!use gms_constants
!use ang_mom_functions
!use gms_arrays
!use shell_model_ham
implicit none
integer, intent(in) :: np, nq
complex*16, dimension(np,np),intent(in) :: cvec_pp
complex*16, dimension(nq,np),intent(in) :: cvec_qp
complex*16, dimension(np), intent(in) :: ceig
complex*16, dimension(np,np) :: temp, omega2, sim1, sim2, omega_2inv, u, u_inv, &
cvec_pp_inv
complex*16, dimension(nq,np) :: omega
complex*16, dimension(np) :: ceig_p, omega2_eig, eigval2
complex*16, dimension(np,np) :: eigen_vec, vl, heff_rhs
complex*16, dimension(np,np), intent(out) :: heff
double precision, dimension(2*np) :: rwork
complex*16, dimension(10000) :: work1
complex*16 :: d, sum1, temp1(np,np), temp2(np,nq), norm, determinant
integer :: i_p,j_p, j_q, ii, jj, k, i_q , a_p, a_pp
INTEGER :: i, lda, ldb, ldvl, LDVR, info, lwork, ILO , IHI
CHARACTER*1 :: jobvl, JOBVR, BALANC, SENSE
DOUBLE PRECISION, DIMENSION(np) :: SCALE, RCONDE, RCONDV
DOUBLE PRECISION :: ABNRM
integer :: ipiv(np) ,j
real*8 :: a1, a2, b1, b2
BALANC = 'N'
JOBVL = 'N'
JOBVR = 'V'
SENSE = 'N'
LDA = np
LDVL = 1
LDVR = np
LWORK = 10000
open(13,file='specter.dat')
eigen_vec = 0.
cvec_pp_inv = cvec_pp
call cmplxmatinv(cvec_pp_inv, np, d)
!write(6,*) cvec_pp_inv
omega = matmul( cvec_qp, cvec_pp_inv )
! non-hermitian effective interaction
! setup 2-p effective interaction in P-space
!write(6,*) 'step1'
heff = 0.
do i_p = 1, np
do j_p = 1, np
heff(i_p,j_p) = sum( cvec_pp(i_p,:)*ceig(:)*cvec_pp(j_p,:) )
sum1 = 0.
do k = 1, np
do i_q = 1, nq
sum1 = sum1 + cvec_pp(i_p,k) * ceig(k) * cvec_qp(i_q,k) * omega(i_q,j_p)
end do
end do
heff(i_p,j_p) = heff(i_p,j_p) + sum1
!write(6,*) heff(i_p,j_p)
end do
end do
!write(6,*) 'step2'
!write(6,*) cvec_pp_inv
!
! ***** organizing matrix (P(1 + omega * omega)P)
!
temp = 0.; omega2 = 0.
omega2 = matmul(transpose(cvec_pp_inv),cvec_pp_inv)
temp = omega2
!
! calculate sqrt and inverse sqrt of matrix (P(1 + omega * omega)
!call sqrtmat_newton( omega2, U, U_inv ,np )
call sqrtmat_db( omega2, U, U_inv ,np )
do i = 1, np
do j = 1, np
!if ( abs(temp1(i,j)- u(i,j)) < 1.e-6 ) cycle
! write(6,*) u(i,j) !, temp1(i,j)
end do
end do
heff_rhs = matmul( U, matmul( heff,u_inv ) )
! check if heff is symmetrized:
heff = 0.
heff = heff_rhs
do i_p = 1, np
do j_p = 1, np
! make heff manifestly symmetric
if ( i_p /= j_p ) then
if ( abs(heff(i_p,j_p)- heff(j_p,i_p)) < 1.e-6 ) cycle
write(13,*) 'sym test', heff(i_p,j_p), heff(j_p,i_p)
end if
end do
end do
! diagonalize 2p-effective shell model hamiltonian
!CALL ZGEEV( JOBVL, JOBVR, np, heff_rhs, LDA, ceig_p, VL, LDVL, eigen_vec, LDVR, &
! WORK1, LWORK, RWORK, INFO )
!write(6,*) 'step3'
call diag_hpp(heff_rhs, eigen_vec, ceig_p, np, 0 )
!write(6,*) 'step4'
call eigenvalue_sort_cmplx(ceig_p, np)
call eigenvalue_sort_cmplx(ceig, np)
! compare spectrum from exact and P-space diagonalization
write(13,*)
write(13,*) 'Compare model space two-body spectrum with exact spectrum:'
do i_p = 1, np
a1 = real( ceig_p(i_p))
a2 = aimag( ceig_p(i_p))
b1 = real( ceig(i_p) )
b2 = aimag( ceig(i_p) )
write(6,*) a1, b1
end do
end subroutine lee_suzuki
subroutine diag_hpp(h_pp, cvec, ceig, n, option )
implicit none
integer, intent(in) :: n
complex*16, dimension(n,n), intent(in) :: h_pp
integer :: i,j, i1, kvec, lwork, option, il ,iu, info
real*8 :: Avec(n*(n+1))
real*8,allocatable,dimension(:) :: work
real*8 :: thresh
complex*16 :: cvl, cvu
logical :: flag(n)
complex*16, dimension(n), intent(out) :: ceig
complex*16, dimension(n,n), intent(out) :: cvec
real*8 vl,vu
i1 = 0
do i = 1, n
do j = 1, i
i1 = i1 + 1
avec(i1) = dble(h_pp(j,i))
avec(i1+n*(n+1)/2) = aimag(h_pp(j,i))
end do
end do
lwork = 300*n
thresh = 30.0
kvec = n
!option = 4
info = 1
allocate( work(lwork) )
!write(6,*) 'begynner diag'
call cs(n,avec,ceig,kvec,cvec,lwork,work,thresh, &
option,il,iu,cvl,cvu,flag,info)
deallocate( work )
!write(12,*) 'three-body resonant state energy:'
!write(6,*) 'ferdig diag'
end subroutine diag_hpp
!
! eigenvalue sort
! sort cmplx vector real(a(1))<real(a(2)) < ... < real(a(n))
!
SUBROUTINE eigenvalue_sort(A,B, n)
IMPLICIT NONE
INTEGER :: i, j, n
double precision, DIMENSION(n), INTENT(INOUT) :: A
integer, dimension(n), intent(inout) :: B
double precision :: temp, temp1
double precision, DIMENSION(n) :: temp2
integer :: orb
DO i = 1, n
DO j = 1, n
IF ( abs( A(i) ) > abs( A(j) ) ) THEN
temp = A(i)
A(i) = A(j)
A(j) = temp
orb = B(i)
B(i) = B(j)
B(j) = orb
END IF
END DO
END DO
END SUBROUTINE eigenvalue_sort
!
! Lee Suzuki similarity transformation
!
SUBROUTINE lee_suzuki2( cvec_pp, cvec_qp, ceig, np, nq, heff )
IMPLICIT NONE
INTEGER, INTENT(IN) :: np, nq
COMPLEX*16, DIMENSION(np,np), INTENT(IN) :: cvec_pp
COMPLEX*16, DIMENSION(nq,np), INTENT(IN) :: cvec_qp
COMPLEX*16, DIMENSION(np), INTENT(IN) :: ceig
COMPLEX*16, DIMENSION(np,np) :: temp, omega2, sim1, sim2, omega_2inv, u, u_inv, &
cvec_pp_inv
COMPLEX*16, DIMENSION(nq,np) :: omega
COMPLEX*16, DIMENSION(np) :: ceig_p, omega2_eig, eigval2
COMPLEX*16, DIMENSION(np,np) :: eigen_vec, vl, heff_rhs
COMPLEX*16, DIMENSION(np,np), INTENT(INOUT) :: heff
DOUBLE PRECISION, DIMENSION(2*np) :: rwork
COMPLEX*16, DIMENSION(10000) :: work1
COMPLEX*16 :: d, sum1, temp1(np,np), temp2(np,nq), norm, determinant
INTEGER :: i_p,j_p, j_q, ii, jj, k, i_q , a_p, a_pp
INTEGER :: i, lda, ldb, ldvl, ldvr, info, lwork, ilo , ihi
CHARACTER*1 :: jobvl, jobvr, balanc, sense
DOUBLE PRECISION, DIMENSION(np) :: scale, rconde, rcondv
DOUBLE PRECISION :: abnrm
INTEGER :: ipiv(np) ,j
DOUBLE PRECISION :: a1, a2, b1, b2
balanc = 'n'; jobvl = 'n' ; jobvr = 'v'; sense = 'n'; lda = np
ldvl = 1; ldvr = np; lwork = 10000
eigen_vec = 0.
temp1 = TRANSPOSE(cvec_pp)
CALL zgeev( jobvl, jobvr, np, temp1, lda, omega2_eig, vl, ldvl, eigen_vec, ldvr, &
work1, lwork, rwork, info )
determinant = PRODUCT(omega2_eig(:))
! write(6,*) 'check determinant', determinant
! the P->Q space transformation matrix, omega
cvec_pp_inv = cvec_pp
call cmplxmatinv(cvec_pp_inv, np, d)
DO i_p = 1, np
DO i_q = 1, nq
omega(i_q,i_p) = SUM( cvec_pp_inv(:,i_p)*cvec_qp(i_q,:) )
ENDDO
ENDDO
! non-hermitian effective interaction
! setup 2-p effective interaction in P-space
heff = 0.
DO i_p = 1, np
DO j_p = 1, np
heff(i_p,j_p) = SUM( cvec_pp(i_p,:)*ceig(:)*cvec_pp(j_p,:) )
sum1 = 0.
DO k = 1, np
DO i_q = 1, nq
sum1 = sum1 + cvec_pp(i_p,k) * ceig(k) * cvec_qp(i_q,k) * omega(i_q,j_p)
ENDDO
ENDDO
heff(i_p,j_p) = heff(i_p,j_p) + sum1
ENDDO
ENDDO
! organizing the matrix (P(1 + omega * omega)P)
omega2 = MATMUL(TRANSPOSE(cvec_pp_inv),cvec_pp_inv)
! calculate sqrt and inverse sqrt of matrix (P(1 + omega * omega)P)
CALL sqrtmat( omega2, U, U_inv ,np )
heff_rhs = matmul( U, matmul( heff,u_inv ) )
! check if heff is symmetrized:
heff = 0.
heff = heff_rhs
DO i_p = 1, np
DO j_p = 1, np
! make heff manifestly symmetric
IF ( i_p /= j_p ) THEN
IF ( ABS(heff(i_p,j_p)- heff(j_p,i_p)) < 1.E-6 ) CYCLE
! WRITE(6,*) 'sym test', heff(i_p,j_p), heff(j_p,i_p)
ENDIF
ENDDO
ENDDO
! diagonalize 2p-effective shell model hamiltonian
CALL zgeev( jobvl, jobvr, np, heff_rhs, lda, ceig_p, vl, ldvl, eigen_vec, ldvr, &
work1, lwork, rwork, info )
call eigenvalue_sort_cmplx(ceig_p, np)
call eigenvalue_sort_cmplx(ceig, np)
! compare spectrum from exact and P-space diagonalization
! WRITE(6,*) 'Compare model space two-body spectrum with exact spectrum:'
DO i_p = 1, np
a1 = REAL( ceig_p(i_p))
a2 = AIMAG( ceig_p(i_p))
b1 = REAL( ceig(i_p) )
b2 = AIMAG( ceig(i_p) )
if ( abs( ceig_p(i_p) - ceig(i_p) ) > 0.001 ) &
write(6,*) 'eigenvalues wrong', A1, a2, B1, b2
ENDDO
END SUBROUTINE lee_suzuki2
!
! routine for calculating the principal square root ( and inverse )
! of a general matrix AA, i.e. solving the matrix equation: AA - A = 0.
! The routine is built on the property :
!
! | 0 AA | | 0 A |
! sign(B) = (| |) = (| |)
! | 1 0 | | A^-1 0 |
!
! the sign of the matrix AA is calculated using Newtons iteration method,
! see Higham et. al. ref. Numerical Algorithms 15 (1997) 227-242
!
SUBROUTINE sqrtmat( aa, a, a_inv ,n )
IMPLICIT NONE
INTEGER, INTENT(IN) :: n
COMPLEX*16, DIMENSION(n,n), INTENT(IN) :: aa
COMPLEX*16, DIMENSION(n,n), INTENT(OUT) :: a, a_inv
COMPLEX*16, DIMENSION(2*n,2*n) :: x, x0, x1, x2
COMPLEX*16, DIMENSION(n,n) :: i_mat, temp
INTEGER :: i,j,k
COMPLEX*16 :: d
! setup identity matrix
i_mat = 0.
DO i = 1, n
i_mat(i,i) = 1.d0
ENDDO
!setup starting matrix x0
x0 = 0.
DO i = n+1, 2*n
DO j = 1, n
x0(j,i) = aa(j,i-n)
ENDDO
ENDDO
DO i = 1, n
DO j = n+1, 2*n
x0(j,i) = i_mat(j-n,i)
ENDDO
ENDDO
k = 0
temp = 0.
x1 = 0.; x2 = 0.; x = 0.
DO WHILE( MAXVAL(ABS(temp-aa)) > 1.E-14 .AND. k < 1000 )
x1 = x0
x2 = x0
CALL cmplxmatinv(x2,2*n,d)
x = 0.5d0 * ( x1 + x2 )
x0 = x
k = k + 1
DO i = 1, n
DO j =1, n
a(i,j) = x(i,j+n)
a_inv(i,j) = x(i+n,j)
ENDDO
ENDDO
temp = MATMUL( a,a )
ENDDO
!WRITE(6,*) 'number of iterations in sqrt_mat:', k
END SUBROUTINE sqrtmat
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!fast diagonalizing of complex symmetric matrices
subroutine diag_exact( h, cvec, ceig, n )
use constants
implicit none
integer, intent(in) :: n
complex(dpc), dimension(n,n), intent(in) :: h
integer :: k, np
integer :: p, i,j, i1, kvec, lwork, option, il ,iu, info
real(dp) :: A(n*(n+1)), work(300*n)
real(dp) :: thresh
complex(dpc) :: cvl, cvu
logical :: flag(n)
complex(dpc) :: ceig(n), sum1
complex(dpc) :: cvec(n,n)
real(dp) vl,vu
lwork = 300*n
thresh = 30.0
kvec = n
option = 4
info = 1
i1 = 0
do i = 1, n
do j = 1, i
i1 = i1 + 1
a(i1) = dble(h(j,i))
a(i1+n*(n+1)/2) = aimag(h(j,i))
end do
end do
call cs(n,a,ceig,kvec,cvec,lwork,work,thresh, option,il,iu,cvl,cvu,flag,info)
end subroutine diag_exact
! jobvl, jobvr, np, temp1, lda, omega2_eig, vl, ldvl, eigen_vec, ldvr, &
! work1, lwork, rwork, info
SUBROUTINE lapack_diag(h, cvec, ceig, n )
use constants
implicit none
integer, intent(in) :: n
complex*16, dimension(n,n), intent(in) :: h
COMPLEX*16, DIMENSION(n,n), intent(out) :: cvec
COMPLEX*16, DIMENSION(n,n) :: vl
COMPLEX*16, DIMENSION(n), intent(out) :: ceig
DOUBLE PRECISION, DIMENSION(2*n) :: rwork
COMPLEX*16, DIMENSION(3168) :: work1
INTEGER :: lda, ldb, ldvl, ldvr, info, lwork, ilo , ihi
CHARACTER*1 :: jobvl, jobvr
DOUBLE PRECISION, DIMENSION(n) :: scale, rconde, rcondv
complex*16 :: norm
integer :: i
jobvl = 'N' ; jobvr = 'V'; lda = n
ldvl = 1; ldvr = n; lwork = 3168
ceig = 0.; cvec = 0.
CALL zgeev( jobvl, jobvr, n, h, lda, ceig, vl, ldvl, cvec, ldvr, &
work1, lwork, rwork, info )
! write(6,*) 'info', info, work1(1)
! berggren normalization
do i = 1, n
norm = sum( cvec(:,i)*cvec(:,i) )
cvec(:,i) = cvec(:,i)/sqrt(norm)
end do
end SUBROUTINE lapack_diag
| 49,709
|
https://github.com/Zarbokk/HippoCampus_Tools/blob/master/new_pc_tools/tools_install.sh
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| null |
HippoCampus_Tools
|
Zarbokk
|
Shell
|
Code
| 186
| 545
|
#!/bin/bash
## Terminator htop system tools ( make git etc etc....)
sudo usermod -a -G dialout $USER
sudo apt-get update -y
sudo apt-get install git zip qtcreator cmake build-essential genromfs ninja-build exiftool astyle -y
# make sure xxd is installed, dedicated xxd package since Ubuntu 18.04 but was squashed into vim-common before
which xxd || sudo apt install xxd -y || sudo apt-get install vim-common --no-install-recommends -y
# Required python packages
sudo apt-get install python-argparse python-empy python-toml python-numpy python-dev python-pip -y
sudo -H pip install --upgrade pip
sudo -H pip install pandas jinja2 pyserial pyyaml
# optional python tools
sudo -H pip install pyulog
# jMAVSim simulator dependencies
echo "Installing jMAVSim simulator dependencies"
sudo apt-get install ant openjdk-8-jdk openjdk-8-jre -y
## Gazebo simulator dependencies
sudo apt-get install protobuf-compiler libeigen3-dev libopencv-dev -y
sudo apt-get update
## Get ROS/Gazebo
## Install rosinstall and other dependencies
sudo apt install python-rosinstall python-rosinstall-generator python-wstool build-essential -y
# MAVROS: https://dev.px4.io/en/ros/mavros_installation.html
## Install dependencies
sudo apt-get install python-catkin-tools python-rosinstall-generator -y
#Install geographiclib
sudo apt install geographiclib -y
echo "PS1='\[\033[1;36m\]\u\[\033[1;31m\]@\[\033[1;32m\]\h:\[\033[1;35m\]\w\[\033[1;31m\]\$\[\033[0m\] '">> ~/.bashrc
sudo apt install terminator -y
source .bashrc
sudo apt install libgstreamer1.0-dev
cd
| 46,787
|
https://github.com/shenguojun/thomasjungblut-common/blob/master/src/de/jungblut/math/minimize/ParticleSwarmOptimization.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,012
|
thomasjungblut-common
|
shenguojun
|
Java
|
Code
| 559
| 1,342
|
package de.jungblut.math.minimize;
import java.util.Arrays;
import java.util.Random;
import de.jungblut.math.DoubleVector;
import de.jungblut.math.dense.DenseDoubleVector;
/**
* Particle Swarm Optimization algorithm to minimize costfunctions. This works
* quite like {@link GradientDescent}, but for this to work we don't need to
* have a derivative, it is enough to provide the cost at a certain parameter
* position (theta). For additional information you can browse the wikipedia
* page: <a
* href="http://en.wikipedia.org/wiki/Particle_swarm_optimization">Particle
* swarm optimization article on Wikipedia</a>
*
* @author thomas.jungblut
*
*/
public final class ParticleSwarmOptimization implements Minimizer {
private final int numParticles;
private final double alpha;
private final double beta;
private final double phi;
public ParticleSwarmOptimization(int numParticles, double alpha, double beta,
double phi) {
this.numParticles = numParticles;
this.alpha = alpha;
this.beta = beta;
this.phi = phi;
}
@Override
public final DoubleVector minimize(CostFunction f, DoubleVector pInput,
int maxIterations, boolean verbose) {
// setup
Random random = new Random();
DoubleVector globalBestPosition = pInput;
DoubleVector[] particlePositions = new DoubleVector[numParticles];
double[] particlePersonalBestCost = new double[numParticles];
// we are going to spread the particles a bit
for (int i = 0; i < numParticles; i++) {
particlePositions[i] = new DenseDoubleVector(Arrays.copyOf(
pInput.toArray(), pInput.getLength()));
for (int j = 0; j < particlePositions[i].getLength(); j++) {
particlePositions[i].set(j, particlePositions[i].get(j)
+ particlePositions[i].get(j) * random.nextDouble());
}
particlePersonalBestCost[i] = f.evaluateCost(particlePositions[i])
.getFirst();
}
// everything else will be seeded to the start position
DoubleVector[] particlePersonalBestPositions = new DoubleVector[numParticles];
Arrays.fill(particlePersonalBestPositions, pInput);
double globalCost = f.evaluateCost(pInput).getFirst();
// loop as long as we haven't reached our max iterations
for (int iteration = 0; iteration < maxIterations; iteration++) {
// loop over all particles and calculate new positions
for (int particleIndex = 0; particleIndex < particlePositions.length; particleIndex++) {
DoubleVector currentPosition = particlePositions[particleIndex];
DoubleVector currentBest = particlePersonalBestPositions[particleIndex];
DenseDoubleVector vec = new DenseDoubleVector(pInput.getDimension());
for (int index = 0; index < vec.getDimension(); index++) {
double value = (phi * currentPosition.get(index)) // inertia
+ (alpha * random.nextDouble() * (currentBest.get(index) - currentPosition
.get(index))) // personal memory
+ (beta * random.nextDouble() * (globalBestPosition.get(index) - currentPosition
.get(index))); // group memory
vec.set(index, value);
}
particlePositions[particleIndex] = vec;
double cost = f.evaluateCost(vec).getFirst();
// check if we have a personal best
if (cost < particlePersonalBestCost[particleIndex]) {
particlePersonalBestCost[particleIndex] = cost;
particlePersonalBestPositions[particleIndex] = vec;
// if we had a personal best, do we have a better global?
if (cost < globalCost) {
globalCost = cost;
globalBestPosition = vec;
}
}
}
if (verbose) {
System.out.print("Iteration " + iteration + " | Cost: " + globalCost
+ "\r");
}
}
return globalBestPosition;
}
/**
* Minimize a function using particle swarm optimization.
*
* @param f the cost function to minimize. Note that the returned gradient
* will be ignored, because it is not needed in this algorithm.
* @param pInput the initial starting point of the algorithm / particles. This
* is very important to choose, since this is considered a fast
* algorithm you could try out multiple starting points.
* @param numParticles how many particles to use.
* @param alpha personal memory weighting.
* @param beta group memory weighting.
* @param phi own velocity weighting (inertia).
* @param maxIterations how many iterations this algorithm should perform.
* @param verbose if true prints progress to STDOUT.
* @return a optimized parameter set for the costfunction.
*/
public static DoubleVector minimizeFunction(CostFunction f,
DoubleVector pInput, final int numParticles, double alpha, double beta,
double phi, final int maxIterations, final boolean verbose) {
return new ParticleSwarmOptimization(numParticles, alpha, beta, phi)
.minimize(f, pInput, maxIterations, verbose);
}
}
| 1,963
|
https://github.com/commercetools/commercetools-dotnet-core-sdk-v2/blob/master/commercetools.Sdk/commercetools.Sdk.HistoryApi/Generated/Models/Changes/ChangeLocalizedEnumValueOrderChange.cs
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,023
|
commercetools-dotnet-core-sdk-v2
|
commercetools
|
C#
|
Code
| 87
| 262
|
using commercetools.Sdk.HistoryApi.Models.ChangeValues;
using System.Collections.Generic;
using System.Linq;
namespace commercetools.Sdk.HistoryApi.Models.Changes
{
public partial class ChangeLocalizedEnumValueOrderChange : IChangeLocalizedEnumValueOrderChange
{
public string Type { get; set; }
public string Change { get; set; }
public IList<ILocalizedEnumValue> PreviousValue { get; set; }
public IEnumerable<ILocalizedEnumValue> PreviousValueEnumerable { set => PreviousValue = value.ToList(); }
public IList<ILocalizedEnumValue> NextValue { get; set; }
public IEnumerable<ILocalizedEnumValue> NextValueEnumerable { set => NextValue = value.ToList(); }
public string FieldName { get; set; }
public string AttributeName { get; set; }
public ChangeLocalizedEnumValueOrderChange()
{
this.Type = "ChangeLocalizedEnumValueOrderChange";
}
}
}
| 36,776
|
https://github.com/Langqs/--/blob/master/src/views/product/Spu/index.vue
|
Github Open Source
|
Open Source
|
MIT
| null |
--
|
Langqs
|
Vue
|
Code
| 410
| 2,189
|
<template>
<div>
<el-table :data="skuList.records" border style="width: 100%">
<el-table-column type="index" label="序号" width="80">
</el-table-column>
<el-table-column prop="skuName" label="名称" width="width">
</el-table-column>
<el-table-column prop="skuDesc" label="描述" width="width">
</el-table-column>
<el-table-column label="默认图片" width="150">
<template slot-scope="{row}">
<img :src="row.skuDefaultImg" style="width:120px;height:120px" alt="">
</template>
</el-table-column>
<el-table-column prop="weight" label="重量" align="center" width="100">
</el-table-column>
<el-table-column prop="price" label="价格" align="center" width="100">
</el-table-column>
<el-table-column label="操作" width="width">
<template slot-scope="{row}">
<el-button v-if="row.isSale==0" type="info" size="mini" @click="onSku(row)">上架</el-button>
<el-button v-else type="success" size="mini" @click="offSku(row)">下架</el-button>
<el-button type="primary" size="mini" @click="edit">编辑</el-button>
<br>
<el-button type="warning" size="mini" @click="skuInfo(row)" style="margin-top:10px">详情</el-button>
<el-button type="danger" size="mini" @click="deleteSku(row)">删除</el-button>
</template>
</el-table-column>
</el-table>
<!-- 分页器 -->
<el-pagination
@current-change="currentChange"
@size-change="sizeChange"
style="margin-top: 20px; text-align: center"
:current-page="page"
:page-sizes="[5, 10, 20]"
:page-size="limit"
:pager-count="7"
layout="prev, pager, next, jumper, ->,sizes,total "
:total="total"
>
</el-pagination>
<!-- 抽屉 -->
<el-drawer :show-close="false" :visible.sync="drawer" size='50%' style="overflow-y:scroll">
<el-row>
<el-col :span="5" class="left-column">名称</el-col>
<el-col :span="16" class="right-column">{{skuInfoList.skuName}}</el-col>
</el-row>
<el-row>
<el-col :span="5" class="left-column">描述</el-col>
<el-col :span="16" class="right-column">{{skuInfoList.skuDesc}}</el-col>
</el-row>
<el-row>
<el-col :span="5" class="left-column">价格</el-col>
<el-col :span="16" class="right-column">{{skuInfoList.price}} 元</el-col>
</el-row>
<el-row>
<el-col :span="5" class="left-column">平台属性</el-col>
<el-col :span="16" class="right-column">
<el-tag type="success" v-for="item in skuInfoList.skuAttrValueList" :key="item.id" style="margin:5px">
{{item.attrName}}:{{item.valueName}}
</el-tag>
</el-col>
</el-row>
<el-row>
<el-col :span="5" class="left-column">商品图片</el-col>
<el-col :span="16" class="right-column">
<el-carousel height="400px">
<el-carousel-item v-for="item in skuInfoList.skuImageList" :key="item.id">
<img :src="item.imgUrl" alt="" style="width:100%;height:100%">
</el-carousel-item>
</el-carousel>
</el-col>
</el-row>
</el-drawer>
</div>
</template>
<script>
export default {
name:'Spu',
data() {
return {
page: 1, //当前页码
limit: 5, //展示条数
total: 0, //总数据条数
skuList:[],//列表数据
skuInfoList:{},// 详情
drawer: false,//抽屉的显示与隐藏
}
},
mounted() {
this.getSkuList()
},
methods: {
// 获取 Sku列表
async getSkuList(){
let result = await this.$API.spu.reqSkuList(this.page,this.limit)
if (result.code ==200) {
this.skuList = result.data
}
this.total = this.skuList.total
},
// 上架
async onSku(row){
let result = await this.$API.spu.reqOnSku(row.id)
if (result.code ==200) {
row.isSale =1
this.$message({
type:'success',
message:'上架成功'
})
}
},
// 下架
async offSku(row){
let result = await this.$API.spu.reqOffSku(row.id)
if (result.code ==200) {
row.isSale =0
this.$message({
type:'success',
message:'下架成功'
})
}
},
// 编辑
edit(){
this.$message('正在开发中')
},
// 详情
async skuInfo(row){
let result = await this.$API.spu.reqSkuInfo(row.id)
if (result.code==200) {
this.skuInfoList = result.data
}
this.drawer=true
},
//分页器切换页码
currentChange(pager) {
this.page = pager;
this.getSkuList();
},
//切换页面显示条数
sizeChange(limit) {
this.limit = limit;
this.page = 1
this.getSkuList();
},
// 删除
deleteSku(row){
this.$confirm('是否确认删除?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(async () => {
let result = await this.$API.spu.reqDeleteSku(row.id)
if (result.code == 200) {
this.$message({
type: 'success',
message: '删除成功!'
});
this.page =1
this.getSkuList()
}
}).catch(() => {});
}
},
}
</script>
<style>
.el-carousel__item h3 {
color: #475669;
font-size: 14px;
opacity: 0.75;
line-height: 150px;
margin: 0;
}
.el-carousel__item:nth-child(2n) {
background-color: #99a9bf;
}
.el-carousel__item:nth-child(2n+1) {
background-color: #d3dce6;
}
.el-carousel__button{
width: 10px;
height: 10px;
background: red;
border-radius: 100%;
}
.left-column{
font-size: 18px;
margin: 10px 10px;
text-align: right;
}
.right-column{
font-size: 18px;
margin: 10px 10px;
}
</style>
| 6,721
|
https://github.com/gregoryduckworth/sloot-ainoga/blob/master/resources/views/admin/index.blade.php
|
Github Open Source
|
Open Source
|
MIT
| null |
sloot-ainoga
|
gregoryduckworth
|
PHP
|
Code
| 34
| 160
|
@extends('standard')
@section('title', 'Welcome')
@section('content')
<div class="col">
<div class="text-center">
Welcome to Agonia Tools - Admin Section!
</div>
<div class="col mx-auto mh-100" style="padding-top: 20px;">
<li><a href="/admin/update-info">Update Info</a></li>
<li><a href="/admin/update-images">Update Images</a></li>
<li><a href="/admin/clear-cache">Clear Cache</a></li>
</div>
</div>
@endsection
| 2,796
|
https://github.com/bhuman/BHumanCodeRelease/blob/master/Src/Modules/Perception/Scanlines/ScanLineRegionizer.h
|
Github Open Source
|
Open Source
|
BSD-2-Clause
| 2,023
|
BHumanCodeRelease
|
bhuman
|
C++
|
Code
| 2,015
| 4,518
|
/**
* @file ScanLineRegionizer.h
*
* This file declares a module that segments the image horizontally and
* vertically by detecting edges and applying heuristics to classify
* the regions between them.
*
* @author Lukas Malte Monnerjahn
* @author Arne Hasselbring
*/
#pragma once
#include "Representations/Configuration/RelativeFieldColorsParameters.h"
#include "Representations/Infrastructure/CameraInfo.h"
#include "Representations/Infrastructure/FrameInfo.h"
#include "Representations/Perception/ImagePreprocessing/BodyContour.h"
#include "Representations/Perception/ImagePreprocessing/CameraMatrix.h"
#include "Representations/Perception/ImagePreprocessing/ColorScanLineRegions.h"
#include "Representations/Perception/ImagePreprocessing/ECImage.h"
#include "Representations/Perception/ImagePreprocessing/FieldBoundary.h"
#include "Representations/Perception/ImagePreprocessing/RelativeFieldColors.h"
#include "Representations/Perception/ImagePreprocessing/ScanGrid.h"
#include "ImageProcessing/PixelTypes.h"
#include "Framework/Module.h"
#include <limits>
MODULE(ScanLineRegionizer,
{,
REQUIRES(BodyContour),
REQUIRES(CameraInfo),
REQUIRES(CameraMatrix),
REQUIRES(ECImage),
REQUIRES(FieldBoundary),
REQUIRES(FrameInfo),
REQUIRES(RelativeFieldColors),
REQUIRES(RelativeFieldColorsParameters),
REQUIRES(ScanGrid),
PROVIDES(ColorScanLineRegionsHorizontal),
PROVIDES(ColorScanLineRegionsVerticalClipped),
DEFINES_PARAMETERS(
{,
(Vector2f)(1500.f, 0.f) additionalSmoothingPoint, /**< On field distance in mm up to which additional smoothing is applied */
(float)(13) edgeThreshold, /**< The edge threshold. */
(unsigned short)(12) minHorizontalScanLineDistance, /**< Minimal distance between horizontal scan lines in px */
(unsigned char)(20) luminanceSimilarityThreshold, /**< Maximum luminance difference for two regions to become united */
(unsigned char)(20) hueSimilarityThreshold, /**< Maximum hue difference for two regions to become united */
(unsigned char)(26) saturationSimilarityThreshold, /**< Maximum saturation difference for two regions to become united */
(int)(520) lowerMinRegionSize, /**< Minimal size in covered scanline pixels for initial field regions on the lower camera */
(int)(640) upperMinRegionSize, /**< Minimal size in covered scanline pixels for initial field regions on the upper camera */
(float)(0.9f) baseLuminanceReduction, /**< Rather underestimate the baseLuminance as it is used for noise filtering */
(short)(2) verticalGridScanMinStep, /**< Minimum distance between two vertical scan steps */
(bool)(true) prelabelAsWhite, /**< Label upper regions that are brighter than both neighbors as white during region building */
(short)(20) maxPrelabelRegionSize, /**< Maximum region size to prelabel as white */
(short)(12) maxRegionSizeForStitching, /**< Maximum size in pixels of a none region between field and white or field and field for stitching */
(int)(400) estimatedFieldColorInvalidationTime, /**< Time in ms until the EstimatedFieldColor is invalidated */
}),
});
class ScanLineRegionizer : public ScanLineRegionizerBase
{
struct EstimatedFieldColor
{
// no support for circular hue range here, field wont be on the zero crossing
unsigned char minHue; /**< Minimal field hue */
unsigned char maxHue; /**< Maximum field hue */
unsigned char minSaturation; /**< Minimal field saturation */
unsigned char maxLuminance; /**< Maximum field luminance */
unsigned int lastSet; /**< Timestamp of when the estimated field colors were last set */
};
struct InternalRegion : ScanLineRegion
{
InternalRegion(unsigned short from, unsigned short to, PixelTypes::GrayscaledPixel y, PixelTypes::HuePixel h, PixelTypes::GrayscaledPixel s) :
ScanLineRegion(from, to, PixelTypes::Color::black), // initialize as black for optimized classification into field/none/white in later steps
y(y),
h(h),
s(s),
parent(nullptr)
{
ASSERT(to > from);
regionSize = to - from;
}
PixelTypes::GrayscaledPixel y; /**< A representative Y value of this region. */
PixelTypes::HuePixel h; /**< A representative H value of this region. */
PixelTypes::GrayscaledPixel s; /**< A representative S value of this region. */
int regionSize; /**< Accumulated size over this and all child regions */
private:
InternalRegion* parent; /**< Parent for union-find. */
unsigned short rank = 0; /**< Rank for union-find. */
public:
/**
* Finds the representative region for this set and does path compression.
* @return This sets representative region.
*/
InternalRegion* findSet()
{
if(parent == nullptr)
return this;
parent = parent->findSet();
return parent;
}
/**
* Unites this region set this the other region set.
* @param other The other region to unite with.
*/
void unite(InternalRegion& other)
{
InternalRegion* a = findSet();
InternalRegion* b = other.findSet();
if(a == b)
return;
if(a->rank > b->rank)
{
b->parent = a;
a->updateValues(b);
}
else
{
a->parent = b;
b->updateValues(a);
if(a->rank == b->rank)
++b->rank;
}
}
private:
/**
* Updates values of a new parent region that represents the whole set.
* @param other New values to incorporate.
*/
void updateValues(const InternalRegion* const other)
{
const int regionSum = regionSize + other->regionSize;
y = static_cast<PixelTypes::GrayscaledPixel>((regionSize * y + other->regionSize * other->y) / regionSum);
s = static_cast<PixelTypes::GrayscaledPixel>((regionSize * s + other->regionSize * other->s) / regionSum);
// special handling for circular hue range
if(static_cast<int>(h) - static_cast<int>(other->h) > std::numeric_limits<signed char>::max()) // == std::numeric_limits<unsigned char>::max() / 2
h += static_cast<unsigned char>((static_cast<int>(other->h) - static_cast<int>(h) + std::numeric_limits<unsigned char>::max()) * other->regionSize / regionSum);
else if(static_cast<int>(other->h) - static_cast<int>(h) > std::numeric_limits<signed char>::max())
h -= static_cast<unsigned char>((static_cast<int>(h) - static_cast<int>(other->h) + std::numeric_limits<unsigned char>::max()) * other->regionSize / regionSum);
else if((static_cast<int>(other->h) - static_cast<int>(h) >= 0))
h += static_cast<unsigned char>((static_cast<int>(other->h) - static_cast<int>(h)) * other->regionSize / regionSum);
else
h -= static_cast<unsigned char>((static_cast<int>(h) - static_cast<int>(other->h)) * other->regionSize / regionSum);
regionSize = regionSum;
}
};
/**
* Updates the horizontal color scan line regions.
* @param colorScanLineRegionsHorizontal The provided representation.
*/
void update(ColorScanLineRegionsHorizontal& colorScanLineRegionsHorizontal) override;
/**
* Updates the vertical color scan line regions.
* @param colorScanLineRegionsVertical The provided representation.
*/
void update(ColorScanLineRegionsVerticalClipped& colorScanLineRegionsVerticalClipped) override;
/**
* Creates regions along a horizontal line.
* @param y The height of the scan line in the image.
* @param regions The regions to be filled.
*/
void scanHorizontalGrid(unsigned int y, std::vector<InternalRegion>& regions, const unsigned int leftmostX, const unsigned int rightmostX) const;
/**
* Creates regions along a horizontal line.
* @param y The height of the scan line in the image.
* @param regions The regions to be filled.
*/
void scanHorizontal(unsigned int y, std::vector<InternalRegion>& regions, const unsigned int leftmostX, const unsigned int rightmostX) const;
/**
* Creates regions along a horizontal line.
* @param y The height of the scan line in the image.
* @param regions The regions to be filled.
*/
void scanHorizontalGridAdditionalSmoothing(unsigned int y, std::vector<InternalRegion>& regions, const unsigned int leftmostX, const unsigned int rightmostX) const;
/**
* Creates regions along a horizontal line.
* @param y The height of the scan line in the image.
* @param regions The regions to be filled.
*/
void scanHorizontalAdditionalSmoothing(unsigned int y, std::vector<InternalRegion>& regions, const unsigned int leftmostX, const unsigned int rightmostX) const;
/**
* Determines the horizontal scan start, excluding areas outside the field boundary
* @param y The height of the scan line in the image.
* @return The x-coordinate of where to start the scan
*/
[[nodiscard]] int horizontalScanStart(int x, int y) const;
/**
* Determines the horizontal scan stop, excluding areas outside the field boundary
* @param y The height of the scan line in the image.
* @return The x-coordinate of where to stop the scan
*/
[[nodiscard]] int horizontalScanStop(int x, int y) const;
/**
* Creates regions along a vertical scan line.
* @param line The scan grid line on which the scan is performed.
* @param middle The y coordinate at which to switch between 5x5 and 3x3 filter
* @param top The y coordinate (inclusive) below which the useful part of the image is located.
* @param regions he regions to be filled.
*/
void scanVerticalGrid(const ScanGrid::Line& line, int middle, int top, std::vector<InternalRegion>& regions) const;
/**
* Creates regions along a vertical scan line.
* @param line The scan grid line on which the scan is performed.
* @param middle The y coordinate at which to switch between 5x5 and 3x3 filter
* @param top The y coordinate (inclusive) below which the useful part of the image is located.
* @param regions he regions to be filled.
*/
void scanVertical(const ScanGrid::Line& line, int middle, int top, std::vector<InternalRegion>& regions) const;
/**
* Unites similar horizontal scan line regions.
* @param x The x coordinates of the regions.
* @param regions The regions (grouped by scan line), scan lines sorted from bottom to top,
* regions in the scan lines sorted ascending by pixel number from left to right.
*/
void uniteHorizontalFieldRegions(const std::vector<unsigned short>& y, std::vector<std::vector<InternalRegion>>& regions) const;
/**
* Unite similar vertical scan line regions.
* @param x The x coordinates of the regions.
* @param regions The regions (grouped by scan line), scan lines sorted from left to right,
* regions in the scan lines sorted descending by pixel number from bottom to top.
*/
void uniteVerticalFieldRegions(const std::vector<unsigned short>& x, std::vector<std::vector<InternalRegion>>& regions) const;
/**
* Checks whether two regions are similar enough to unite them.
* @param a One region.
* @param b The other region.
* @return true, if the regions are similar enough to be united
*/
bool areSimilar(InternalRegion& a, InternalRegion& b) const;
/**
* Classifies united regions into field and not field.
* @param xy x or y positions of the scan lines.
* @param regions The regions to classify.
* @param horizontal Are the regions on horizontal (true) or vertical (false) scan lines
*/
void classifyFieldRegions(const std::vector<unsigned short>& xy, std::vector<std::vector<InternalRegion>>& regions, bool horizontal);
void classifyFieldHorizontal(const std::vector<unsigned short>& y, std::vector<std::vector<InternalRegion>>& regions) const;
void classifyFieldVertical(std::vector<std::vector<InternalRegion>>& regions) const;
/**
* Decides whether a region qualifies as field.
* @param region The region
* @return true, if the region is field
*/
[[nodiscard]] bool regionIsField(const InternalRegion* const region) const;
/**
* Classifies some regions as white.
* @param regions The regions (grouped by scan line).
*/
void classifyWhiteRegionsWithThreshold(std::vector<std::vector<InternalRegion>>& regions) const;
/**
* Checks if the region fulfills basic characteristics for being prelabeled as white
* @param checkedRegion The tested region
* @return True, if the region fulfills basic characteristics for being prelabeled as white
*/
[[nodiscard]] bool prelabelWhiteCheck(const InternalRegion& checkedRegion) const;
/**
* Checks if the region neighbor allows the checked region to be prelabeled as white
* @param checkedRegion The tested region
* @param neighborRegion The neighbor region
* @return True, if the region neighbor allows the checked region to be prelabeled as white
*/
[[nodiscard]] bool prelabelWhiteNeighborCheck(const InternalRegion& checkedRegion, const InternalRegion& neighborRegion) const;
/**
* Replaces small "none" regions in between "field" and "white" or "field" and "field".
* @param regions The regions.
* @param horizontal Whether the stitching is done on horizontal or vertical scan line regions.
*/
void stitchUpHoles(std::vector<std::vector<InternalRegion>>& regions, bool horizontal) const;
/**
* Checks by timestamp if the EstimatedFieldColor is still presumed valid.
* @return True, if the EstimatedFieldColor is valid.
*/
[[nodiscard]] bool isEstimatedFieldColorValid() const;
/**
* Gets an image grayscale value that is representative for a given horizontal region.
* @param image The image.
* @param from The leftmost x coordinate of the region (inclusive).
* @param to The rightmost x coordinate of the region (exclusive).
* @param y The y coordinate of the region.
*/
static PixelTypes::GrayscaledPixel getHorizontalRepresentativeValue(const Image<PixelTypes::GrayscaledPixel>& image, unsigned int from, unsigned int to, unsigned int y);
/**
* Gets an image hue value that is representative for a given horizontal region.
* @param image The image.
* @param from The leftmost x coordinate of the region (inclusive).
* @param to The rightmost x coordinate of the region (exclusive).
* @param y The y coordinate of the region.
*/
static PixelTypes::HuePixel getHorizontalRepresentativeHueValue(const Image<PixelTypes::HuePixel>& image, unsigned int from, unsigned int to, unsigned int y);
/**
* Gets an image grayscale value that is representative for a given vertical region.
* @param image The image.
* @param x The x coordinate of the region.
* @param from The topmost y coordinate of the region (inclusive).
* @param to The bottommost y coordinate of the region (exclusive).
*/
static PixelTypes::GrayscaledPixel getVerticalRepresentativeValue(const Image<PixelTypes::GrayscaledPixel>& image, unsigned int x, unsigned int from, unsigned int to);
/**
* Gets an image hue value that is representative for a given vertical region.
* @param image The image.
* @param x The x coordinate of the region.
* @param from The topmost y coordinate of the region (inclusive).
* @param to The bottommost y coordinate of the region (exclusive).
*/
static PixelTypes::HuePixel getVerticalRepresentativeHueValue(const Image<PixelTypes::HuePixel>& image, unsigned int x, unsigned int from, unsigned int to);
/**
* Approximates the images average luminance.
*/
void approximateBaseLuminance();
/**
* Approximates the images average saturation.
*/
void approximateBaseSaturation();
public:
/**
* Computes an average over hue values that correctly handles the circular hue range.
* The old average and the additional value are weighted (dataPoints - 1) : 1.
* @param hueValue Current hue average.
* @param hueAddition New data point, that shall be incorporated in the average.
* @param dataPoints Number of data points including the new one.
* @return New average value.
*/
static float hueAverage(float hueValue, float hueAddition, int dataPoints);
private:
PixelTypes::GrayscaledPixel baseLuminance; /**< heuristically approximated average luminance of the image.
* Used as a min luminance threshold for filtering out irrelevant edges and noise */
PixelTypes::GrayscaledPixel baseSaturation; /**< heuristically approximated average saturation of the image.
* Used as a min luminance threshold for filtering out irrelevant edges and noise */
EstimatedFieldColor estimatedFieldColor; /**< Field color range estimated for the current image */
};
| 28,527
|
https://github.com/Joshb888/dd/blob/master/dashboard/public/bower_components/ckeditor/plugins/bidi/lang/oc.js
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
dd
|
Joshb888
|
JavaScript
|
Code
| 21
| 70
|
CKEDITOR.plugins.setLang("bidi", "oc", {
ltr: "Direccion del tèxte d'esquèrra cap a dreita",
rtl: "Direccion del tèxte de dreita cap a esquèrra",
});
| 14,847
|
https://github.com/siddhant3030/djangoecommerce/blob/master/satchmo/satchmo/projects/simple/urls.py
|
Github Open Source
|
Open Source
|
BSD-2-Clause
| 2,019
|
djangoecommerce
|
siddhant3030
|
Python
|
Code
| 15
| 56
|
from django.conf.urls import url, include
from satchmo_store.urls import urlpatterns
urlpatterns += [
url(r'test/', include('simple.localsite.urls'))
]
| 2,458
|
https://github.com/AhmedSafwat1/I-learn-backend/blob/master/Modules/Learn/Database/Seeders/LearnDatabaseSeeder.php
|
Github Open Source
|
Open Source
|
MIT
| null |
I-learn-backend
|
AhmedSafwat1
|
PHP
|
Code
| 33
| 132
|
<?php
namespace Modules\Learn\Database\Seeders;
use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;
use Modules\Learn\Database\Seeders\SubjectTableSeeder;
class LearnDatabaseSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
Model::unguard();
$this->call(SubjectTableSeeder::class);
}
}
| 42,903
|
https://github.com/ArthurFerreira2/herve/blob/master/C-tests/2-main.s
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
herve
|
ArthurFerreira2
|
GAS
|
Code
| 71
| 316
|
.file "2-main.c"
.option nopic
.attribute arch, "rv32i2p0_m2p0"
.attribute unaligned_access, 0
.attribute stack_align, 16
.text
.section .rodata.str1.4,"aMS",@progbits,1
.align 2
.LC0:
.string "Hello World !\n"
.section .text.startup,"ax",@progbits
.align 2
.globl main
.type main, @function
main:
lui a5,%hi(.LC0)
addi a5,a5,%lo(.LC0)
li a4,72
li a3,234881024
.L2:
sb a4,0(a3)
lbu a4,1(a5)
addi a5,a5,1
bne a4,zero,.L2
#APP
# 9 "2-main.c" 1
ebreak
# 0 "" 2
#NO_APP
li a0,0
ret
.size main, .-main
.ident "GCC: (GNU) 11.1.0"
| 20,156
|
https://github.com/andyshep/OrigamiEngine/blob/master/Example/OSX/OrigamiEngine Example/AppDelegate.m
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
OrigamiEngine
|
andyshep
|
Objective-C
|
Code
| 44
| 155
|
//
// ORGMAppDelegate.m
// OrigamiEngine Example
//
// Created by Arthur Evstifeev on 9/02/13.
//
//
#import "AppDelegate.h"
#import "PlayerViewController.h"
@interface AppDelegate ()
@property (strong, nonatomic) PlayerViewController *playerViewController;
@end
@implementation AppDelegate
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
self.playerViewController = [[PlayerViewController alloc] init];
[_mainView addSubview:_playerViewController.view];
}
@end
| 32,954
|
https://github.com/Clever/wag/blob/master/tracing/go.mod
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,023
|
wag
|
Clever
|
Go Module
|
Code
| 35
| 298
|
module github.com/Clever/wag/tracing
go 1.16
require (
github.com/grpc-ecosystem/grpc-gateway/v2 v2.11.2 // indirect
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.35.0
go.opentelemetry.io/otel v1.10.0
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.10.0
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.10.0
go.opentelemetry.io/otel/sdk v1.10.0
go.opentelemetry.io/otel/trace v1.10.0
golang.org/x/net v0.0.0-20220809012201-f428fae20770 // indirect
golang.org/x/sys v0.0.0-20220808155132-1c4a2a72c664 // indirect
google.golang.org/genproto v0.0.0-20220808204814-fd01256a5276 // indirect
)
| 6,298
|
https://github.com/gii-is-DP2/DP2-1920-G1-08/blob/master/src/test/java/org/springframework/inmocasa/service/ViviendaServiceTests.java
|
Github Open Source
|
Open Source
|
LicenseRef-scancode-generic-cla, Apache-2.0
| 2,020
|
DP2-1920-G1-08
|
gii-is-DP2
|
Java
|
Code
| 384
| 2,236
|
package org.springframework.inmocasa.service;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertTrue;
import java.time.LocalDate;
import java.util.Collection;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.inmocasa.model.Cliente;
import org.springframework.inmocasa.model.Compra;
import org.springframework.inmocasa.model.Propietario;
import org.springframework.inmocasa.model.Vivienda;
import org.springframework.inmocasa.model.enums.Estado;
import org.springframework.inmocasa.model.enums.Genero;
import org.springframework.stereotype.Service;
import com.paypal.base.rest.APIContext;
@DataJpaTest(includeFilters = @ComponentScan.Filter(Service.class))
@AutoConfigureTestDatabase(replace = Replace.NONE)
public class ViviendaServiceTests {
@Autowired
protected ViviendaService viviendaService;
@Autowired
protected PropietarioService propService;
@MockBean
APIContext apiContext;
// La vivienda se crea y se guarda en el repositorio
@Test
void shouldCreateAndSaveVivienda() {
Propietario p = this.propService.findPropietarioById(1);
Vivienda vivienda = new Vivienda();
vivienda.setId(17);
vivienda.setTitulo("Piso en venta en ocho de marzo s/n");
vivienda.setDireccion("Calle Ocho de Marzo s/n");
vivienda.setZona("Cerro Amate");
vivienda.setFechaPublicacion(LocalDate.of(2020, 01, 20));
vivienda.setPrecio(2260);
vivienda.setAmueblado(true);
vivienda.setCaracteristicas("Caracteristicas");
vivienda.setHorarioVisita("Martes de 9:00 a 13:00");
vivienda.setPropietario(p);
this.viviendaService.save(vivienda);
Collection<Vivienda> viviendas = (Collection<Vivienda>) this.viviendaService.findAll();
assertTrue(viviendas.contains(vivienda));
}
// La vivienda no se guarda porque ya existe una con el mismo id
@Test
void shouldNotCreateAndSaveVivienda() {
Propietario p = this.propService.findPropietarioById(2);
Vivienda vivienda = new Vivienda();
vivienda.setId(17);
vivienda.setTitulo("Piso en venta en ocho de marzo s/n");
vivienda.setDireccion("Calle Ocho de Marzo s/n");
vivienda.setZona("Cerro Amate");
vivienda.setFechaPublicacion(LocalDate.of(2020, 01, 20));
vivienda.setPrecio(2260);
vivienda.setAmueblado(true);
vivienda.setCaracteristicas("Caracteristicas");
vivienda.setHorarioVisita("Martes de 9:00 a 13:00");
vivienda.setPropietario(p);
this.viviendaService.save(vivienda);
Collection<Vivienda> viviendas = (Collection<Vivienda>) this.viviendaService.findAll();
assertThat(!viviendas.contains(vivienda));
}
// Se encuentra la vivienda por el id y esta existe.
@Test
void shouldFindViviendaById() {
Collection<Vivienda> viviendas = (Collection<Vivienda>) this.viviendaService.findAll();
Vivienda v = this.viviendaService.findViviendaId(1);
assertTrue(viviendas.contains(v));
}
// No se encuentra la vivienda porque el id no existe.
@Test
void shouldNoFindViviendaByViviendaId() {
Vivienda v = this.viviendaService.findViviendaId(10);
assertTrue(v == null);
}
// La vivienda se borra sin problemas
@Test
void shouldDeleteVivienda() {
Collection<Vivienda> todas = this.viviendaService.findAllNewest();
Vivienda vivienda = new Vivienda();
vivienda.setId(1);
vivienda.setTitulo("Piso en venta en ocho de marzo s/n");
vivienda.setDireccion("Calle Ocho de Marzo s/n");
vivienda.setZona("Cerro Amate");
vivienda.setFechaPublicacion(LocalDate.of(2020, 01, 20));
vivienda.setPrecio(2260);
vivienda.setAmueblado(true);
Propietario prop = new Propietario();
prop.setId(1);
prop.setNombre("John");
prop.setApellidos("Doe");
prop.setDni("46900025N");
prop.setEsInmobiliaria(false);
prop.setGenero(Genero.MASCULINO);
prop.setFechaNacimiento(LocalDate.of(1976, 6, 12));
prop.setUsername("john123");
prop.setPassword("john123");
vivienda.setPropietario(prop);
this.viviendaService.delete(vivienda);
assertThat(!todas.contains(vivienda));
}
// La vivienda no se borra porque está comprada
@Test
void shoudNotDeleteVivienda() {
Collection<Vivienda> todas = this.viviendaService.findAllNewest();
Vivienda vivienda2 = new Vivienda();
vivienda2.setId(2);
vivienda2.setTitulo("Piso en venta en ocho de marzo s/n");
vivienda2.setDireccion("Calle Ocho de Marzo s/n");
vivienda2.setZona("Cerro Amate");
vivienda2.setFechaPublicacion(LocalDate.of(2020, 01, 20));
vivienda2.setPrecio(2260);
vivienda2.setAmueblado(true);
Compra compra = new Compra();
compra.setVivienda(vivienda2);
compra.setEstado(Estado.ACEPTADO);
compra.setPrecioFinal(200);
Propietario prop = new Propietario();
prop.setId(1);
prop.setNombre("John");
prop.setApellidos("Doe");
prop.setDni("46900025N");
prop.setEsInmobiliaria(false);
prop.setGenero(Genero.MASCULINO);
prop.setFechaNacimiento(LocalDate.of(1976, 6, 12));
prop.setUsername("john123");
prop.setPassword("john123");
Cliente clie = new Cliente();
clie.setId(8);
clie.setNombre("John");
clie.setApellidos("Doe");
clie.setDni("46900025N");
clie.setGenero(Genero.MASCULINO);
clie.setFechaNacimiento(LocalDate.of(1976, 6, 12));
clie.setUsername("john123");
clie.setPassword("john123");
vivienda2.setPropietario(prop);
compra.setCliente(clie);
this.viviendaService.delete(vivienda2);
assertThat(todas.contains(vivienda2));
}
}
| 28,812
|
https://github.com/kbr-ucl/Hands-On-Domain-Driven-Design-with-.NET-Core/blob/master/Chapter13/src/Marketplace.EventStore/EsCheckpointStore.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
Hands-On-Domain-Driven-Design-with-.NET-Core
|
kbr-ucl
|
C#
|
Code
| 145
| 528
|
using System;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using EventStore.ClientAPI;
using Marketplace.EventSourcing;
using Newtonsoft.Json;
namespace Marketplace.EventStore
{
public class EsCheckpointStore : ICheckpointStore
{
const string CheckpointStreamPrefix = "checkpoint:";
readonly IEventStoreConnection _connection;
readonly string _streamName;
public EsCheckpointStore(
IEventStoreConnection connection,
string subscriptionName)
{
_connection = connection;
_streamName = CheckpointStreamPrefix + subscriptionName;
}
public async Task<long?> GetCheckpoint()
{
var slice = await _connection
.ReadStreamEventsBackwardAsync(_streamName, -1, 1, false);
var eventData = slice.Events.FirstOrDefault();
if (eventData.Equals(default(ResolvedEvent)))
{
await StoreCheckpoint(AllCheckpoint.AllStart?.CommitPosition);
await SetStreamMaxCount();
return null;
}
return eventData.Deserialze<Checkpoint>()?.Position;
}
public Task StoreCheckpoint(long? checkpoint)
{
var @event = new Checkpoint {Position = checkpoint};
var preparedEvent =
new EventData(
Guid.NewGuid(),
"$checkpoint",
true,
Encoding.UTF8.GetBytes(
JsonConvert.SerializeObject(@event)
),
null
);
return _connection.AppendToStreamAsync(
_streamName,
ExpectedVersion.Any,
preparedEvent
);
}
async Task SetStreamMaxCount()
{
var metadata = await _connection.GetStreamMetadataAsync(_streamName);
if (!metadata.StreamMetadata.MaxCount.HasValue)
await _connection.SetStreamMetadataAsync(
_streamName, ExpectedVersion.Any,
StreamMetadata.Create(1)
);
}
class Checkpoint
{
public long? Position { get; set; }
}
}
}
| 37,269
|
https://github.com/maniero/SOpt/blob/master/Java/OOP/SetterInherited.java
|
Github Open Source
|
Open Source
|
MIT
| 2,023
|
SOpt
|
maniero
|
Java
|
Code
| 13
| 51
|
@Override
public void setA(int value) {
if (value > 0) super.setA(value);
}
//https://pt.stackoverflow.com/q/463283/101
| 35,387
|
https://github.com/w0shiliyang/Yuncai/blob/master/YBL365/Class/Profile/Section3/GoodManage/EditGood/GoodAllInfos/ViewModel/YBLGoodAllInfosViewModel.m
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
Yuncai
|
w0shiliyang
|
Objective-C
|
Code
| 56
| 204
|
//
// YBLGoodAllInfosViewModel.m
// YC168
//
// Created by 乔同新 on 2017/5/12.
// Copyright © 2017年 乔同新. All rights reserved.
//
#import "YBLGoodAllInfosViewModel.h"
#import "YBLGoodModel.h"
@implementation YBLGoodAllInfosViewModel
- (NSMutableArray *)companyTypeDataArray{
if (!_companyTypeDataArray) {
_companyTypeDataArray = [NSMutableArray array];
}
return _companyTypeDataArray;
}
- (NSMutableArray *)expressDataArray{
if (!_expressDataArray) {
_expressDataArray = [NSMutableArray array];
}
return _expressDataArray;
}
@end
| 32,767
|
https://github.com/Framstag/urlstr/blob/master/urlstr-backend/src/main/java/com/framstag/urlstr/Main.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,020
|
urlstr
|
Framstag
|
Java
|
Code
| 142
| 652
|
package com.framstag.urlstr;
import io.quarkus.runtime.Quarkus;
import io.quarkus.runtime.QuarkusApplication;
import io.quarkus.runtime.annotations.QuarkusMain;
import org.neo4j.configuration.GraphDatabaseSettings;
import org.neo4j.configuration.connectors.BoltConnector;
import org.neo4j.configuration.helpers.SocketAddress;
import org.neo4j.dbms.api.DatabaseManagementService;
import org.neo4j.dbms.api.DatabaseManagementServiceBuilder;
import org.neo4j.graphdb.GraphDatabaseService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.neo4j.configuration.GraphDatabaseSettings.DEFAULT_DATABASE_NAME;
import java.io.File;
@QuarkusMain
public class Main {
private static final String DB_DIRECTORY = "db";
private static final Logger log = LoggerFactory.getLogger(Main.class);
public static void main(String... args) {
Quarkus.run(URLStr.class, args);
}
private static DatabaseManagementService dbManagementService;
private static void startNeo4J() {
log.info("Starting NEO4J database...");
File dbDirectory = new File(DB_DIRECTORY);
dbManagementService = new DatabaseManagementServiceBuilder(dbDirectory)
//.setConfig(GraphDatabaseSettings.xxx,true)
.setConfig(BoltConnector.enabled, true)
.setConfig(BoltConnector.listen_address, new SocketAddress("localhost", 7687))
.build();
GraphDatabaseService db = dbManagementService.database(DEFAULT_DATABASE_NAME);
log.info("Waiting for the database starting...");
while (!db.isAvailable(100)) {
log.info("Waiting ...");
}
log.info("Waiting for the database starting...done");
log.info("Starting NEO4J database...done");
}
private static void stopNeo4J() {
dbManagementService.shutdown();
}
public static class URLStr implements QuarkusApplication {
@Override
public int run(String... args) {
log.info("Initialisation...");
startNeo4J();
log.info("Initialisation...done");
Quarkus.waitForExit();
log.info("Shutdown...");
stopNeo4J();
log.info("Shutdown...done");
return 0;
}
}
}
| 24,980
|
https://github.com/ilkrbk/Apartment-app/blob/master/front/components/main/main-about/_main-about.sass
|
Github Open Source
|
Open Source
|
BSD-2-Clause
| 2,021
|
Apartment-app
|
ilkrbk
|
Sass
|
Code
| 112
| 398
|
.main-about
padding: 100px 0
position: relative
&::after
content: ''
background: url('../../../public/img/bg-main-about.svg') 50% 50% no-repeat
width: 30%
height: 100%
position: absolute
left: 12%
top: 0
@include largeDevice
padding: 80px 0
&::after
background: none
@include smallDevice
padding: 50px 0
.main-about__info
width: 50%
margin-left: auto
@include largeDevice
width: 100%
.main-about__title
font-weight: 700
@include font ($basicFont, 2rem, $darkGrey)
.main-about__descr
margin-top: 30px
@include font ($basicFont, 1.2rem, $darkGrey)
.main-about__list
margin-top: 40px
display: flex
justify-content: space-between
@include smallDevice
flex-wrap: wrap
margin: 0
.main-about__item
display: flex
flex-direction: column
align-items: center
padding: 0 20px
i
border: solid 1px $black
padding: 10px
border-radius: 50%
font-size: 1.2rem
@include smallDevice
margin-top: 30px
width: 50%
.main-about__item-descr
text-align: center
@include font ($basicFont, 1rem, $darkGrey)
@include smallDevice
| 41,821
|
https://github.com/twopointzero/TJAPlayer3/blob/master/TJAPlayer3/Stages/07.Game/Taiko/CAct演奏Drums判定文字列.cs
|
Github Open Source
|
Open Source
|
MIT, LicenseRef-scancode-warranty-disclaimer, LicenseRef-scancode-proprietary-license, LicenseRef-scancode-unknown-license-reference
| 2,021
|
TJAPlayer3
|
twopointzero
|
C#
|
Code
| 447
| 1,763
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Runtime.InteropServices;
using SlimDX;
namespace TJAPlayer3
{
internal class CAct演奏Drums判定文字列 : CAct演奏判定文字列共通
{
// コンストラクタ
public CAct演奏Drums判定文字列()
{
this.stレーンサイズ = new STレーンサイズ[ 12 ];
base.b活性化してない = true;
}
// CActivity 実装(共通クラスからの差分のみ)
public override int On進行描画()
{
throw new InvalidOperationException( "t進行描画(C演奏判定ライン座標共通 演奏判定ライン共通 ) のほうを使用してください。" );
}
public override int t進行描画( C演奏判定ライン座標共通 演奏判定ライン座標 )
{
if( !base.b活性化してない )
{
for( int i = 0; i < 12; i++ )
{
if( !base.st状態[ i ].ct進行.b停止中 )
{
base.st状態[ i ].ct進行.t進行();
if( base.st状態[ i ].ct進行.b終了値に達した )
{
base.st状態[ i ].ct進行.t停止();
base.st状態[ i ].b使用中 = false;
}
int num2 = base.st状態[ i ].ct進行.n現在の値;
if( base.st状態[ i ].judge != E判定.Great )
{
base.st状態[ i ].n相対X座標 = 0;
base.st状態[ i ].n相対Y座標 = 15;
base.st状態[ i ].n透明度 = 0xff;
}
if( ( base.st状態[ i ].judge != E判定.Miss ) && ( base.st状態[ i ].judge != E判定.Bad ) )
{
if( num2 < 20 )
{
base.st状態[ i ].n相対X座標 = 0;
base.st状態[ i ].n相対Y座標 = 0;
base.st状態[ i ].n透明度 = 0xff;
}
else if( num2 < 40 )
{
base.st状態[ i ].n相対X座標 = 0;
base.st状態[ i ].n相対Y座標 = 5;
base.st状態[ i ].n透明度 = 0xff;
}
else if( num2 >= 60 )
{
base.st状態[ i ].n相対X座標 = 0;
base.st状態[ i ].n相対Y座標 = 10;
base.st状態[ i ].n透明度 = 0xff;
}
else
{
base.st状態[ i ].n相対X座標 = 0;
base.st状態[ i ].n相対Y座標 = 15;
base.st状態[ i ].n透明度 = 0xff;
}
}
if( num2 < 20 )
{
base.st状態[ i ].n相対X座標 = 0;
base.st状態[ i ].n相対Y座標 = 0;
base.st状態[ i ].n透明度 = 0xff;
}
else if( num2 < 40 )
{
base.st状態[ i ].n相対X座標 = 0;
base.st状態[ i ].n相対Y座標 = 5;
base.st状態[ i ].n透明度 = 0xff;
}
else if( num2 >= 60 )
{
base.st状態[ i ].n相対X座標 = 0;
base.st状態[ i ].n相対Y座標 = 10;
base.st状態[ i ].n透明度 = 0xff;
}
else
{
base.st状態[ i ].n相対X座標 = 0;
base.st状態[ i ].n相対Y座標 = 15;
base.st状態[ i ].n透明度 = 0xff;
}
}
}
for( int j = 0; j < 12; j++ )
{
if( !base.st状態[ j ].ct進行.b停止中 )
{
if( TJAPlayer3.Tx.Judge != null )
{
int baseX = 370;
//int baseY = 135;
int baseY = TJAPlayer3.Skin.Game_Lane_Field_Y[base.st状態[j].nPlayer] - 53;
int x = TJAPlayer3.Skin.Game_Lane_Field_X[ 0 ] - TJAPlayer3.Tx.Judge.szテクスチャサイズ.Width / 2;
int y = ( baseY + base.st状態[ j ].n相対Y座標 );
TJAPlayer3.Tx.Judge.t2D描画( TJAPlayer3.app.Device, x, y, base.st判定文字列[ (int) base.st状態[ j ].judge ].rc );
}
}
}
}
return 0;
}
// その他
#region [ private ]
//-----------------
[StructLayout( LayoutKind.Sequential )]
private struct STレーンサイズ
{
public int x;
public int w;
}
private readonly int[] n文字の縦表示位置 = new int[] { 1, 2, 0, 1, 3, 2, 1, 0, 0, 0, 1, 1 };
private STレーンサイズ[] stレーンサイズ;
//-----------------
#endregion
}
}
| 15,201
|
https://github.com/joaovitormarianocorreia/trabalho-compiladores/blob/master/T2.h
|
Github Open Source
|
Open Source
|
MIT
| null |
trabalho-compiladores
|
joaovitormarianocorreia
|
C
|
Code
| 164
| 485
|
#define MAX 50
void ERRO_SINTATICO(char tipo[MAX], int linha);
void PROX_TOKEN(FILE *input, char token[], int linha);
void PROGRAM(FILE *input, char token[], int linha);
void BLOCO(FILE *input, char token[], int linha);
void VARIAVEIS(FILE *input, char token[], int linha);
void VARIAVEIS2(FILE *input, char token[], int linha);
void LISTA_IDENTIFICADORES(FILE *input, char token[], int linha);
void DECLARACAO_SUBROTINAS(FILE *input, char token[], int linha);
void PROCEDURE(FILE *input, char token[], int linha);
void PARAM_FORMAIS(FILE *input, char token[], int linha);
void COMANDO_COMPOSTO(FILE *input, char token[], int linha);
void COMANDO(FILE *input, char token[], int linha);
void COMANDO_SEM_ROTULO(FILE *input, char token[], int linha);
void ATRIBUICAO(FILE *input, char token[], int linha);
void CHAMA_PROCEDURE(FILE *input, char token[], int linha);
void CONDICIONAL(FILE *input, char token[], int linha);
void COMANDO_REPETITIVO(FILE *input, char token[], int linha);
void LISTA_EXPRESSOES(FILE *input, char token[], int linha);
void EXPRESSAO(FILE *input, char token[], int linha);
int RELACAO(char token[]);
void EXPRESSAO_SIMPLES(FILE *input, char token[], int linha);
void TERMO(FILE *input, char token[], int linha);
void FATOR(FILE *input, char token[], int linha);
int NUMERICO(char token[]);
int IDENTIFICADOR(char token[]);
| 7,018
|
https://github.com/htpans/htpans/blob/master/ImageJ_Macros/Background_Subtraction.ijm
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
htpans
|
htpans
|
ImageJ Macro
|
Code
| 36
| 139
|
dir1 = getDirectory("Choose Source Directory ");
dir2 = getDirectory("Choose Destination Directory ");
list = getFileList(dir1);
setBatchMode(true);
for (k=0; k<list.length; k++) {
showProgress(k+1, list.length);
open(dir1+list[k]);
title = getTitle();
//print(title);
run("Subtract Background...", "rolling=40 stack");
saveAs("Tiff", dir2+title);
close();
}
| 25,758
|
https://github.com/Hiswe/concompte/blob/master/acount-helpers/src/filter-array-with-object.ts
|
Github Open Source
|
Open Source
|
MIT
| null |
concompte
|
Hiswe
|
TypeScript
|
Code
| 151
| 399
|
import merge from 'lodash.merge'
import isObject from 'lodash.isobject'
// {foo: `bar`} [{foo: `bar`}, {foo: `baz`}] => [{foo: `baz`}]
interface Params<T, K> {
defaultObject: T
array: Array<K>
}
export function filterArrayWithObject<T, K>({
defaultObject,
array,
}: Params<T, K>): K[] {
if (!Array.isArray(array)) return []
if (!isObject(defaultObject)) return array
const defaultEntries = Object.entries(defaultObject)
const result = array
// make sure that the object has the same keys as the comparison
.map(entry => merge({}, defaultObject, entry))
// To achieve equal comparisons, cast to the same type
.map(entry => {
defaultEntries.forEach(([refKey, refValue]) => {
const type = typeof refValue
switch (type) {
case 'number':
return (entry[refKey] = parseFloat(entry[refKey]))
case 'string':
return (entry[refKey] = `${entry[refKey]}`)
}
})
return entry
})
.filter(entry => {
// check strict equivalence over all the defaultKeys
const isSameAsDefault = defaultEntries
.map(([refKey, refValue]) => refValue === entry[refKey])
.reduce((acc, curr) => acc && curr, true)
return !isSameAsDefault
})
return result
}
export default filterArrayWithObject
| 39,067
|
https://github.com/kevinzhwl/ObjectARXCore/blob/master/2007/utils/Atil/Inc/RgbPaletteModel.h
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
ObjectARXCore
|
kevinzhwl
|
C
|
Code
| 583
| 1,289
|
///////////////////////////////////////////////////////////////////////////////
//
//
// (C) Copyright 2005 by Autodesk, Inc. All rights reserved.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//
///////////////////////////////////////////////////////////////////////////////
#ifndef RGBMODEL_H
#include "RgbModel.h"
#endif
#ifndef DATAMODELATTRIBUTES_H
#include "DataModelAttributes.h"
#endif
#ifndef RGBCOLOR_H
#include "RgbColor.h"
#endif
#ifndef ATILEXCEPTION_H
#include "ATILException.h"
#endif
#ifndef RGBPALETTEMODEL_H
#define RGBPALETTEMODEL_H
namespace Atil
{
// Represents an eight-bit indexed color space. It is used to construct eight-bit color
// images. The DataModel holds an array of colors, called a palette, such that the indexes of the
// data refer to the entries in the palette of colors. Each entry in the palette is an instance of
// the structure RgbColor.
// The pixel values in the image represent indexes into the palette array held by the RgbPaletteModel.
//
class RgbPaletteModel : public RgbModel
{
public:
RgbPaletteModel (int nPaletteEntries = 256);
RgbPaletteModel (int nEntries, const RgbColor* colors);
RgbPaletteModel (int nBitsUsedPerPixel, int nEntries, const RgbColor* colors);
virtual ~RgbPaletteModel ();
virtual DataModel* clone () const;
virtual DataModelAttributes::DataModelType dataModelType () const;
virtual DataModelAttributes::PixelType pixelType () const;
virtual bool canConvertTo (const ColorModelInterface* colorModel) const;
virtual RowProviderInterface* getModelConversionTo (
const ColorModelInterface* colorModel, RowProviderInterface* pConvert) const;
virtual bool canConvertFrom (const ColorModelInterface* colorModel) const;
virtual RowProviderInterface* getModelConversionFrom (
const ColorModelInterface* colorModel, RowProviderInterface* pConvert) const;
// Returns the number of colors in the palette.
virtual int numEntries () const;
// Sets the colors in the palette to those specified.
virtual void setEntries (int startAt, int numEntries, const RgbColor* colors);
// Copies the colors in the palette to the specified array.
virtual void getEntries (int startAt, int numEntries, RgbColor* colors) const;
// Tests whether the value at the specified index is set to transparent.
bool isTransparent (int index) const;
// Make the value at the specified index transparent.
void setTransparent (int index) const;
// Tests whether the value at the specified index is set to opaque (non-tranparent).
bool isOpaque (int index) const;
// Make the value at the specified index opaque (non-transparent).
void setOpaque (int index) const;
// Returns the the alpha value of the element at the specified index.
Data8 alpha (int index) const;
// Sets the alpha value of the element at the specified index.
void setAlpha (int index, Data8 alpha) const;
virtual bool operator==(const DataModel& rhs) const;
virtual bool operator!=(const DataModel& rhs) const;
Atil::UInt8 nearestColorIndex (Atil::RgbColor color ) const;
protected:
RgbPaletteModel (DataModelAttributes::DataModelType dm,
DataModelAttributes::BitsPerPixel bpp, int nEntries );
mutable RgbColor maPalette[256];
// From 1 through 256.
int mnEntries;
};
class RgbPaletteModelException : public ATILException
{
public:
enum ExceptionType { kInvalidPaletteIndex };
public:
RgbPaletteModelException (const StringBuffer& sbMessage,
ExceptionType eType = kInvalidPaletteIndex );
RgbPaletteModelException (const RgbPaletteModelException& x);
virtual ~RgbPaletteModelException ();
virtual ExceptionType getExceptionType ();
private:
ExceptionType eType;
};
} //end of namespace
#endif
//#ifndef RGBCOLOR_H
//#include <RgbColor.h>
//#endif
| 45,627
|
https://github.com/SALUD-AR/sigep/blob/master/aviso.php
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,020
|
sigep
|
SALUD-AR
|
PHP
|
Code
| 295
| 1,466
|
<?php
require_once("config.php");
//error_reporting(8);
include "modulos/tareas/funcion.php";
echo $html_header;
// Variables
$id=$_GET["id"] or $id=$_POST["id"];
$cmd=$_POST["cmd"];
// Funciones
function actualiza () {
$sql="select id_tarea,anuncio from tareas where
(asignado ilike '%|".$_ses_user["login"]."|%' or asignado='Todos') and anuncio is not NULL and activo=1 and estado != '3' order by anuncio ASC,privilegio DESC";
$rs=sql($sql) or die;
echo "<script>parent.tareas=new Array;\n";
while ($fila=$rs->fetchrow())
echo "parent.tareas['".$fila["id_tarea"]."']='".$fila["anuncio"]."';\n";
echo "</script>\n";
}
// Comandos
if ($id) {
if ($cmd=="Aceptar") {
$tipo=$_POST["tipo"];
$numero=$_POST["numero"];
if ($tipo=="dia")
$fecha="'".date("Y/m/d H:i:s",mktime(date("H"),date("i"),date("s"),date("m"),date("d")+$numero,date("Y")))."'";
if ($tipo=="hora")
$fecha="'".date("Y/m/d H:i:s",mktime(date("H")+$numero,date("i"),date("s"),date("m"),date("d"),date("Y")))."'";
if ($tipo=="minuto")
$fecha="'".date("Y/m/d H:i:s",mktime(date("H"),date("i")+$numero,date("s"),date("m"),date("d"),date("Y")))."'";
$sql="UPDATE tareas SET anuncio=$fecha where id_tarea=$id";
$db->execute($sql)or die($db->errormsg());
actualiza();
echo "<script>parent.document.all.aviso.style.visibility='hidden';</script>";
}
if ($cmd=="Realizada") {
$fecha=date("Y/m/d H:i:s");
$sql="UPDATE tareas SET estado='3', vencido='$fecha' where id_tarea=$id";
$db->execute($sql)or die($db->errormsg());
actualiza();
echo "<script>parent.document.all.aviso.style.visibility='hidden';</script>";
}
// sql
$sql="Select fecha,vencido,creadopor,descripcion,estado,privilegio,solucion from tareas where id_tarea=$id";
$rs=$db->execute($sql) or die($db->errormsg());
?>
<script language='javascript' src='/lib/popcalendar.js'></script>
<form action="aviso.php" method=post>
<input type='hidden' name=id value='<? echo $id; ?>'>
<table align=center border=1 cellspacing=0 cellpadding=3 bgcolor="#D5D5D5" width=100% height=100%>
<tr>
<td align=center colspan=2>
<h1>Tiene una tarea pendiente</h1>
</td>
</tr>
<tr>
<td style="border: none;">
Fecha y hora de inicio:
<?
$h=substr($rs->fields["fecha"],11,8);
echo fecha($rs->fields["fecha"])." $h\n";
?>
</td>
<td align=right style="border: none;">
Fecha y hora de vencimiento:
<?
$h=substr($rs->fields["vencido"],11,8);
echo fecha($rs->fields["vencido"])." $h\n";
?>
</td>
</tr>
<tr>
<td width=50%>
Prioridad: <b><? echo $prioridades[$rs->fields["privilegio"]]; ?></b>
</td>
<td width=50%>
Estado: <b><? echo $estados[$rs->fields["estado"]]; ?></b>
</td>
</tr>
<tr>
<td width=50%>
Enviada por: <b><? echo $rs->fields["creadopor"]; ?></b>
</td>
<td valign=top width=50% rowspan=3>
Descripcion: <br>
<div style="background-color: white;height: 90%;border: solid ;border-width: 1;overflow-y: auto; width: 100%;"><? echo html_out($rs->fields["descripcion"]); ?></div>
</td>
<tr>
<td>
Recordar en: <input type=text name=numero value=15 size=5>
<select name=tipo>
<option value=minuto selected>Minutos</option>
<option value=hora>Horas</option>
<option value=dia>Dias</option>
</select>
</td>
</tr>
</tr>
<tr>
<td align=center>
<input type=submit name=cmd value="Aceptar">
<input type=button value="Ver detalles" OnClick="parent.location.href='<? echo encode_link("index.php",array("menu" => "tareas_porhacer", "extra" => Array("modi" => "tareas_porhacer","cmd" => "modificar","id" => $id))); ?>';">
<input type=submit name=cmd value="Realizada">
</td>
</tr>
</table>
</form>
<?
}
?>
</body>
</html>
| 2,574
|
https://github.com/DataDog/integrations-core/blob/master/kafka_consumer/tests/docker/kerberos/kdc/start.sh
|
Github Open Source
|
Open Source
|
BSD-3-Clause, MIT, BSD-3-Clause-Modification, Unlicense, Apache-2.0, LGPL-3.0-only, LicenseRef-scancode-public-domain, BSD-2-Clause, CC0-1.0
| 2,023
|
integrations-core
|
DataDog
|
Shell
|
Code
| 129
| 502
|
#!/usr/bin/env bash
rm /var/lib/secret/*.key
# Kafka service principal:
kadmin.local -w password -q "add_principal -randkey kafka/broker.kerberos-demo.local@TEST.CONFLUENT.IO" > /dev/null
# Zookeeper service principal:
kadmin.local -w password -q "add_principal -randkey zookeeper/zookeeper.kerberos-demo.local@TEST.CONFLUENT.IO" > /dev/null
# Create a principal with which to connect to Zookeeper from brokers - NB use the same credential on all brokers!
kadmin.local -w password -q "add_principal -randkey zkclient@TEST.CONFLUENT.IO" > /dev/null
# Create client principals to connect in to the cluster:
kadmin.local -w password -q "add_principal -randkey kafka/localhost@TEST.CONFLUENT.IO" > /dev/null
kadmin.local -w password -q "ktadd -k /var/lib/secret/zookeeper.key -norandkey zookeeper/zookeeper.kerberos-demo.local@TEST.CONFLUENT.IO " > /dev/null
kadmin.local -w password -q "ktadd -k /var/lib/secret/zookeeper-client.key -norandkey zkclient@TEST.CONFLUENT.IO " > /dev/null
kadmin.local -w password -q "ktadd -k /var/lib/secret/localhost.key -norandkey kafka/localhost@TEST.CONFLUENT.IO " > /dev/null
chmod 777 /var/lib/secret/broker.key
chmod 777 /var/lib/secret/zookeeper.key
chmod 777 /var/lib/secret/zookeeper-client.key
chmod 777 /var/lib/secret/localhost.key
/usr/sbin/krb5kdc -n
| 8,541
|
https://github.com/Maqsim/stackoverflow-app/blob/master/src/models/index.ts
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
stackoverflow-app
|
Maqsim
|
TypeScript
|
Code
| 20
| 70
|
export * from './extensions/with-environment';
export * from './extensions/with-root-store';
export * from './root-store/root-store';
export * from './root-store/root-store-context';
export * from './root-store/setup-root-store';
| 17,695
|
https://github.com/vitaxa/telegramit/blob/master/telegramit-core/src/test/kotlin/org/botlaxy/telegramit/core/client/TelegramPollingClientTest.kt
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
telegramit
|
vitaxa
|
Kotlin
|
Code
| 94
| 500
|
package org.botlaxy.telegramit.core.client
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import io.mockk.*
import io.mockk.impl.annotations.MockK
import org.botlaxy.telegramit.core.TelegramBot
import org.botlaxy.telegramit.core.client.api.TelegramApi
import org.botlaxy.telegramit.core.client.model.TelegramResponse
import org.botlaxy.telegramit.core.client.model.TelegramUpdate
import kotlin.test.BeforeTest
import kotlin.test.Test
class TelegramPollingClientTest {
@MockK(relaxed = true)
lateinit var updateListener: UpdateListener
@MockK(relaxed = true)
lateinit var telegramApi: TelegramApi
@MockK(relaxed = true)
lateinit var clientConfig: TelegramBot.TelegramPoolingClientConfig
lateinit var telegramPollingClient: TelegramPollingUpdateClient
@BeforeTest
fun setUp() {
MockKAnnotations.init(this)
val updatesResponse = TelegramApiTest::class.java.getResource("/response/getUpdatesResponse.json").readText()
val telegramUpdates = jacksonObjectMapper().readValue<TelegramResponse<List<TelegramUpdate>>>(updatesResponse)
every { telegramApi.getUpdates(any(), any(), any()) } returns telegramUpdates.result!!
telegramPollingClient = TelegramPollingUpdateClient(telegramApi, updateListener, clientConfig)
}
@Test
fun testTelegramPollingClientHandle() {
telegramPollingClient.start()
verify(timeout = 5000, atLeast = 1) { updateListener.onUpdate(any()) }
telegramPollingClient.close()
}
}
| 27,063
|
https://github.com/NF-TopSky-Team/TopskyHotelManagerSystem/blob/master/SYS.FormUI/AppFunction/FrmAboutUs.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
TopskyHotelManagerSystem
|
NF-TopSky-Team
|
C#
|
Code
| 290
| 704
|
/*
* MIT License
*Copyright (c) 2021 咖啡与网络(java-and-net)
*Permission is hereby granted, free of charge, to any person obtaining a copy
*of this software and associated documentation files (the "Software"), to deal
*in the Software without restriction, including without limitation the rights
*to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
*copies of the Software, and to permit persons to whom the Software is
*furnished to do so, subject to the following conditions:
*The above copyright notice and this permission notice shall be included in all
*copies or substantial portions of the Software.
*THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
*IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
*FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
*AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
*LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
*OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
*SOFTWARE.
*
*/
using Newtonsoft.Json;
using Sunny.UI;
using System;
using System.Drawing;
using System.IO;
using System.Net;
using System.Text;
using System.Windows.Forms;
namespace SYS.FormUI
{
public partial class FrmAboutUs : UIForm
{
public FrmAboutUs()
{
InitializeComponent();
}
#region 记录鼠标和窗体坐标的方法
private Point mouseOld;//鼠标旧坐标
private Point formOld;//窗体旧坐标
#endregion
#region 记录移动的窗体坐标
private void FrmAboutUs_MouseDown(object sender, MouseEventArgs e)
{
formOld = this.Location;
mouseOld = MousePosition;
}
#endregion
#region 记录窗体移动的坐标
private void FrmAboutUs_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
Point mouseNew = MousePosition;
int moveX = mouseNew.X - mouseOld.X;
int moveY = mouseNew.Y - mouseOld.Y;
this.Location = new Point(formOld.X + moveX, formOld.Y + moveY);
}
}
#endregion
private void btnClose_Click(object sender, EventArgs e)
{
this.Close();
}
private void FrmAboutUs_Load(object sender, EventArgs e)
{
}
}
}
| 14,875
|
https://github.com/parakhnr/TestHarness/blob/master/CppCommWithFileXfer/Utilities/DirExplorer-Template/Application.h
|
Github Open Source
|
Open Source
|
MIT
| null |
TestHarness
|
parakhnr
|
C
|
Code
| 379
| 875
|
#pragma once
///////////////////////////////////////////////////////////////////////
// Application.h - provides demonstration methods doFile and doDir //
// ver 1.1 //
// Jim Fawcett, CSE687 - Object Oriented Design, Fall 2018 //
///////////////////////////////////////////////////////////////////////
/*
* Package Operations:
* -------------------
* This package represents an application that needs to navigate directories
* as part of its application. It uses DirExploreT, with no modification
* for the application's needs.
*
* Required Files:
* ---------------
* Application.h, application.cpp
* DirExplorerT.h, DirExplorerT.cpp // DirExplorerT.cpp just for testing
* FileSystem.h, ,FileSystem.cpp
*
* Maintenance History:
* --------------------
* ver 1.1 : 19 Aug 2018
* - Converted to inline methods declared below class declaration.
* - Added all the applications processing to main.
* ver 1.0 : 11 Aug 2018
* - first release
*/
#include <iostream>
#include <string>
class Application
{
public:
Application();
// Application defines how to handle files and dirs, when to
// quit, and how to display final results.
// None of this requires alteration of DirExplorerT's code.
void doFile(const std::string& filename);
void doDir(const std::string& dirname);
size_t fileCount();
size_t dirCount();
bool done();
void showStats();
// configure application options
void showAllInCurrDir(bool showAllFilesInCurrDir);
bool showAllInCurrDir();
void maxItems(size_t maxItems);
private:
size_t fileCount_ = 0; // number of files processed
size_t dirCount_ = 0; // number of directories processed
size_t maxItems_ = 0; // upper bound on number of files to process
bool showAll_ = false; // if true, show empty directories
};
inline Application::Application()
{
std::cout << "\n Using Application methods doFile and doDir\n";
}
inline void Application::doFile(const std::string& filename)
{
++fileCount_;
if(showAll_ || !done())
{
std::cout << "\n file--> " << filename;
}
}
inline void Application::doDir(const std::string& dirname)
{
++dirCount_;
std::cout << "\n dir---> " << dirname;
}
inline size_t Application::fileCount()
{
return fileCount_;
}
inline size_t Application::dirCount()
{
return dirCount_;
}
inline void Application::showAllInCurrDir(bool showAllFilesInCurrDir)
{
showAll_ = showAllFilesInCurrDir;
}
inline bool Application::showAllInCurrDir()
{
return showAll_;
}
inline void Application::maxItems(size_t maxItems)
{
maxItems_ = maxItems;
}
//----< show final counts for files and dirs >---------------------
inline void Application::showStats()
{
std::cout << "\n\n processed " << fileCount_ << " files in " << dirCount_ << " directories";
if(done())
{
std::cout << "\n stopped because max number of files exceeded";
}
}
inline bool Application::done()
{
return (0 < maxItems_ && maxItems_ < fileCount_);
}
| 47,227
|
https://github.com/osidufg/osibot/blob/master/commands/np.js
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
osibot
|
osidufg
|
JavaScript
|
Code
| 112
| 440
|
const { MessageEmbed } = require("discord.js");
const { splitBar } = require("string-progressbar");
module.exports = {
name: "np",
aliases: ["nowplaying"],
execute(message) {
const queue = message.client.queue.get(message.guild.id);
if (!queue) return message.channel.send("gada queueueu bg");
const song = queue.songs[0];
const seek = (queue.connection.dispatcher.streamTime - queue.connection.dispatcher.pausedTime) / 1000;
const left = song.duration - seek;
console.log(seek);
console.log(left);
let nowPlaying = new MessageEmbed()
.setTitle("**Now Playing**")
.setThumbnail(`https://i.ytimg.com/vi/${song.id}/hqdefault.jpg`)
.setDescription(`**[${song.title}](${song.url})**`)
.setColor("#F8AA2A")
if (song.duration > 0) {
nowPlaying.addField(
"\u200b",
"**" + new Date(seek * 1000).toISOString().substr(11, 8) + "** / **" +
(song.duration == 0 ? " ◉ LIVE" : new Date(song.duration * 1000).toISOString().substr(11, 8)) + "**",
false
);
nowPlaying.setFooter(
`Time Remaining: ${new Date(left * 1000).toISOString().substr(11, 8) }`
);
}
return message.channel.send(nowPlaying);
}
}
| 43,516
|
https://github.com/patrickwilmes/serenity/blob/master/Kernel/Graphics/Intel/NativeGraphicsAdapter.cpp
|
Github Open Source
|
Open Source
|
BSD-2-Clause
| null |
serenity
|
patrickwilmes
|
C++
|
Code
| 2,023
| 9,295
|
/*
* Copyright (c) 2021, Liav A. <liavalb@hotmail.co.il>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <Kernel/Arch/x86/IO.h>
#include <Kernel/Bus/PCI/API.h>
#include <Kernel/Graphics/Console/ContiguousFramebufferConsole.h>
#include <Kernel/Graphics/Definitions.h>
#include <Kernel/Graphics/GraphicsManagement.h>
#include <Kernel/Graphics/Intel/NativeGraphicsAdapter.h>
#include <Kernel/PhysicalAddress.h>
namespace Kernel {
static constexpr IntelNativeGraphicsAdapter::PLLMaxSettings G35Limits {
{ 20'000'000, 400'000'000 }, // values in Hz, dot_clock
{ 1'400'000'000, 2'800'000'000 }, // values in Hz, VCO
{ 3, 8 }, // n
{ 70, 120 }, // m
{ 10, 20 }, // m1
{ 5, 9 }, // m2
{ 5, 80 }, // p
{ 1, 8 }, // p1
{ 5, 10 } // p2
};
static constexpr u16 supported_models[] {
0x29c2, // Intel G35 Adapter
};
static bool is_supported_model(u16 device_id)
{
for (auto& id : supported_models) {
if (id == device_id)
return true;
}
return false;
}
#define DDC2_I2C_ADDRESS 0x50
RefPtr<IntelNativeGraphicsAdapter> IntelNativeGraphicsAdapter::initialize(PCI::DeviceIdentifier const& pci_device_identifier)
{
VERIFY(pci_device_identifier.hardware_id().vendor_id == 0x8086);
if (!is_supported_model(pci_device_identifier.hardware_id().device_id))
return {};
return adopt_ref(*new IntelNativeGraphicsAdapter(pci_device_identifier.address()));
}
static size_t compute_dac_multiplier(size_t pixel_clock_in_khz)
{
dbgln_if(INTEL_GRAPHICS_DEBUG, "Intel native graphics: Pixel clock is {} KHz", pixel_clock_in_khz);
VERIFY(pixel_clock_in_khz >= 25000);
if (pixel_clock_in_khz >= 100000) {
return 1;
} else if (pixel_clock_in_khz >= 50000) {
return 2;
} else {
return 4;
}
}
static Graphics::Modesetting calculate_modesetting_from_edid(EDID::Parser& edid, size_t index)
{
auto details = edid.detailed_timing(index).release_value();
Graphics::Modesetting mode;
VERIFY(details.pixel_clock_khz());
mode.pixel_clock_in_khz = details.pixel_clock_khz();
size_t horizontal_active = details.horizontal_addressable_pixels();
size_t horizontal_sync_offset = details.horizontal_front_porch_pixels();
mode.horizontal.active = horizontal_active;
mode.horizontal.sync_start = horizontal_active + horizontal_sync_offset;
mode.horizontal.sync_end = horizontal_active + horizontal_sync_offset + details.horizontal_sync_pulse_width_pixels();
mode.horizontal.total = horizontal_active + details.horizontal_blanking_pixels();
size_t vertical_active = details.vertical_addressable_lines();
size_t vertical_sync_offset = details.vertical_front_porch_lines();
mode.vertical.active = vertical_active;
mode.vertical.sync_start = vertical_active + vertical_sync_offset;
mode.vertical.sync_end = vertical_active + vertical_sync_offset + details.vertical_sync_pulse_width_lines();
mode.vertical.total = vertical_active + details.vertical_blanking_lines();
return mode;
}
static bool check_pll_settings(const IntelNativeGraphicsAdapter::PLLSettings& settings, size_t reference_clock, const IntelNativeGraphicsAdapter::PLLMaxSettings& limits)
{
if (settings.n < limits.n.min || settings.n > limits.n.max) {
dbgln_if(INTEL_GRAPHICS_DEBUG, "N is invalid {}", settings.n);
return false;
}
if (settings.m1 < limits.m1.min || settings.m1 > limits.m1.max) {
dbgln_if(INTEL_GRAPHICS_DEBUG, "m1 is invalid {}", settings.m1);
return false;
}
if (settings.m2 < limits.m2.min || settings.m2 > limits.m2.max) {
dbgln_if(INTEL_GRAPHICS_DEBUG, "m2 is invalid {}", settings.m2);
return false;
}
if (settings.p1 < limits.p1.min || settings.p1 > limits.p1.max) {
dbgln_if(INTEL_GRAPHICS_DEBUG, "p1 is invalid {}", settings.p1);
return false;
}
if (settings.m1 <= settings.m2) {
dbgln_if(INTEL_GRAPHICS_DEBUG, "m2 is invalid {} as it is bigger than m1 {}", settings.m2, settings.m1);
return false;
}
auto m = settings.compute_m();
auto p = settings.compute_p();
if (m < limits.m.min || m > limits.m.max) {
dbgln_if(INTEL_GRAPHICS_DEBUG, "m invalid {}", m);
return false;
}
if (p < limits.p.min || p > limits.p.max) {
dbgln_if(INTEL_GRAPHICS_DEBUG, "p invalid {}", p);
return false;
}
auto dot = settings.compute_dot_clock(reference_clock);
auto vco = settings.compute_vco(reference_clock);
if (dot < limits.dot_clock.min || dot > limits.dot_clock.max) {
dbgln_if(INTEL_GRAPHICS_DEBUG, "Dot clock invalid {}", dot);
return false;
}
if (vco < limits.vco.min || vco > limits.vco.max) {
dbgln_if(INTEL_GRAPHICS_DEBUG, "VCO clock invalid {}", vco);
return false;
}
return true;
}
static size_t find_absolute_difference(u64 target_frequency, u64 checked_frequency)
{
if (target_frequency >= checked_frequency)
return target_frequency - checked_frequency;
return checked_frequency - target_frequency;
}
Optional<IntelNativeGraphicsAdapter::PLLSettings> IntelNativeGraphicsAdapter::create_pll_settings(u64 target_frequency, u64 reference_clock, const PLLMaxSettings& limits)
{
IntelNativeGraphicsAdapter::PLLSettings settings;
IntelNativeGraphicsAdapter::PLLSettings best_settings;
// FIXME: Is this correct for all Intel Native graphics cards?
settings.p2 = 10;
dbgln_if(INTEL_GRAPHICS_DEBUG, "Check PLL settings for ref clock of {} Hz, for target of {} Hz", reference_clock, target_frequency);
u64 best_difference = 0xffffffff;
for (settings.n = limits.n.min; settings.n <= limits.n.max; ++settings.n) {
for (settings.m1 = limits.m1.max; settings.m1 >= limits.m1.min; --settings.m1) {
for (settings.m2 = limits.m2.max; settings.m2 >= limits.m2.min; --settings.m2) {
for (settings.p1 = limits.p1.max; settings.p1 >= limits.p1.min; --settings.p1) {
dbgln_if(INTEL_GRAPHICS_DEBUG, "Check PLL settings for {} {} {} {} {}", settings.n, settings.m1, settings.m2, settings.p1, settings.p2);
if (!check_pll_settings(settings, reference_clock, limits))
continue;
auto current_dot_clock = settings.compute_dot_clock(reference_clock);
if (current_dot_clock == target_frequency)
return settings;
auto difference = find_absolute_difference(target_frequency, current_dot_clock);
if (difference < best_difference && (current_dot_clock > target_frequency)) {
best_settings = settings;
best_difference = difference;
}
}
}
}
}
if (best_settings.is_valid())
return best_settings;
return {};
}
IntelNativeGraphicsAdapter::IntelNativeGraphicsAdapter(PCI::Address address)
: VGACompatibleAdapter(address)
, m_registers(PCI::get_BAR0(address) & 0xfffffffc)
, m_framebuffer_addr(PCI::get_BAR2(address) & 0xfffffffc)
{
dbgln_if(INTEL_GRAPHICS_DEBUG, "Intel Native Graphics Adapter @ {}", address);
auto bar0_space_size = PCI::get_BAR_space_size(address, 0);
VERIFY(bar0_space_size == 0x80000);
dmesgln("Intel Native Graphics Adapter @ {}, MMIO @ {}, space size is {:x} bytes", address, PhysicalAddress(PCI::get_BAR0(address)), bar0_space_size);
dmesgln("Intel Native Graphics Adapter @ {}, framebuffer @ {}", address, PhysicalAddress(PCI::get_BAR2(address)));
auto region_or_error = MM.allocate_kernel_region(PhysicalAddress(PCI::get_BAR0(address)).page_base(), bar0_space_size, "Intel Native Graphics Registers", Memory::Region::Access::ReadWrite);
if (region_or_error.is_error()) {
TODO();
}
m_registers_region = region_or_error.release_value();
PCI::enable_bus_mastering(address);
{
SpinlockLocker control_lock(m_control_lock);
set_gmbus_default_rate();
set_gmbus_pin_pair(GMBusPinPair::DedicatedAnalog);
}
gmbus_read_edid();
auto modesetting = calculate_modesetting_from_edid(m_crt_edid.value(), 0);
dmesgln("Intel Native Graphics Adapter @ {}, preferred resolution is {:d}x{:d}", pci_address(), modesetting.horizontal.active, modesetting.vertical.active);
set_crt_resolution(modesetting.horizontal.active, modesetting.vertical.active);
auto framebuffer_address = PhysicalAddress(PCI::get_BAR2(pci_address()) & 0xfffffff0);
VERIFY(!framebuffer_address.is_null());
VERIFY(m_framebuffer_pitch != 0);
VERIFY(m_framebuffer_height != 0);
VERIFY(m_framebuffer_width != 0);
m_framebuffer_console = Graphics::ContiguousFramebufferConsole::initialize(framebuffer_address, m_framebuffer_width, m_framebuffer_height, m_framebuffer_pitch);
// FIXME: This is a very wrong way to do this...
GraphicsManagement::the().m_console = m_framebuffer_console;
}
void IntelNativeGraphicsAdapter::enable_vga_plane()
{
VERIFY(m_control_lock.is_locked());
VERIFY(m_modeset_lock.is_locked());
}
[[maybe_unused]] static StringView convert_register_index_to_string(IntelGraphics::RegisterIndex index)
{
switch (index) {
case IntelGraphics::RegisterIndex::PipeAConf:
return "PipeAConf"sv;
case IntelGraphics::RegisterIndex::PipeBConf:
return "PipeBConf"sv;
case IntelGraphics::RegisterIndex::GMBusData:
return "GMBusData"sv;
case IntelGraphics::RegisterIndex::GMBusStatus:
return "GMBusStatus"sv;
case IntelGraphics::RegisterIndex::GMBusCommand:
return "GMBusCommand"sv;
case IntelGraphics::RegisterIndex::GMBusClock:
return "GMBusClock"sv;
case IntelGraphics::RegisterIndex::DisplayPlaneAControl:
return "DisplayPlaneAControl"sv;
case IntelGraphics::RegisterIndex::DisplayPlaneALinearOffset:
return "DisplayPlaneALinearOffset"sv;
case IntelGraphics::RegisterIndex::DisplayPlaneAStride:
return "DisplayPlaneAStride"sv;
case IntelGraphics::RegisterIndex::DisplayPlaneASurface:
return "DisplayPlaneASurface"sv;
case IntelGraphics::RegisterIndex::DPLLDivisorA0:
return "DPLLDivisorA0"sv;
case IntelGraphics::RegisterIndex::DPLLDivisorA1:
return "DPLLDivisorA1"sv;
case IntelGraphics::RegisterIndex::DPLLControlA:
return "DPLLControlA"sv;
case IntelGraphics::RegisterIndex::DPLLControlB:
return "DPLLControlB"sv;
case IntelGraphics::RegisterIndex::DPLLMultiplierA:
return "DPLLMultiplierA"sv;
case IntelGraphics::RegisterIndex::HTotalA:
return "HTotalA"sv;
case IntelGraphics::RegisterIndex::HBlankA:
return "HBlankA"sv;
case IntelGraphics::RegisterIndex::HSyncA:
return "HSyncA"sv;
case IntelGraphics::RegisterIndex::VTotalA:
return "VTotalA"sv;
case IntelGraphics::RegisterIndex::VBlankA:
return "VBlankA"sv;
case IntelGraphics::RegisterIndex::VSyncA:
return "VSyncA"sv;
case IntelGraphics::RegisterIndex::PipeASource:
return "PipeASource"sv;
case IntelGraphics::RegisterIndex::AnalogDisplayPort:
return "AnalogDisplayPort"sv;
case IntelGraphics::RegisterIndex::VGADisplayPlaneControl:
return "VGADisplayPlaneControl"sv;
default:
VERIFY_NOT_REACHED();
}
}
void IntelNativeGraphicsAdapter::write_to_register(IntelGraphics::RegisterIndex index, u32 value) const
{
VERIFY(m_control_lock.is_locked());
VERIFY(m_registers_region);
SpinlockLocker lock(m_registers_lock);
dbgln_if(INTEL_GRAPHICS_DEBUG, "Intel Graphics {}: Write to {} value of {:x}", pci_address(), convert_register_index_to_string(index), value);
auto* reg = (volatile u32*)m_registers_region->vaddr().offset(index).as_ptr();
*reg = value;
}
u32 IntelNativeGraphicsAdapter::read_from_register(IntelGraphics::RegisterIndex index) const
{
VERIFY(m_control_lock.is_locked());
VERIFY(m_registers_region);
SpinlockLocker lock(m_registers_lock);
auto* reg = (volatile u32*)m_registers_region->vaddr().offset(index).as_ptr();
u32 value = *reg;
dbgln_if(INTEL_GRAPHICS_DEBUG, "Intel Graphics {}: Read from {} value of {:x}", pci_address(), convert_register_index_to_string(index), value);
return value;
}
bool IntelNativeGraphicsAdapter::pipe_a_enabled() const
{
VERIFY(m_control_lock.is_locked());
return read_from_register(IntelGraphics::RegisterIndex::PipeAConf) & (1 << 30);
}
bool IntelNativeGraphicsAdapter::pipe_b_enabled() const
{
VERIFY(m_control_lock.is_locked());
return read_from_register(IntelGraphics::RegisterIndex::PipeBConf) & (1 << 30);
}
bool IntelNativeGraphicsAdapter::gmbus_wait_for(GMBusStatus desired_status, Optional<size_t> milliseconds_timeout)
{
VERIFY(m_control_lock.is_locked());
size_t milliseconds_passed = 0;
while (1) {
if (milliseconds_timeout.has_value() && milliseconds_timeout.value() < milliseconds_passed)
return false;
full_memory_barrier();
u32 status = read_from_register(IntelGraphics::RegisterIndex::GMBusStatus);
full_memory_barrier();
VERIFY(!(status & (1 << 10))); // error happened
switch (desired_status) {
case GMBusStatus::HardwareReady:
if (status & (1 << 11))
return true;
break;
case GMBusStatus::TransactionCompletion:
if (status & (1 << 14))
return true;
break;
default:
VERIFY_NOT_REACHED();
}
IO::delay(1000);
milliseconds_passed++;
}
}
void IntelNativeGraphicsAdapter::gmbus_write(unsigned address, u32 byte)
{
VERIFY(m_control_lock.is_locked());
VERIFY(address < 256);
full_memory_barrier();
write_to_register(IntelGraphics::RegisterIndex::GMBusData, byte);
full_memory_barrier();
write_to_register(IntelGraphics::RegisterIndex::GMBusCommand, ((address << 1) | (1 << 16) | (GMBusCycle::Wait << 25) | (1 << 30)));
full_memory_barrier();
gmbus_wait_for(GMBusStatus::TransactionCompletion, {});
}
void IntelNativeGraphicsAdapter::gmbus_read(unsigned address, u8* buf, size_t length)
{
VERIFY(address < 256);
VERIFY(m_control_lock.is_locked());
size_t nread = 0;
auto read_set = [&] {
full_memory_barrier();
u32 data = read_from_register(IntelGraphics::RegisterIndex::GMBusData);
full_memory_barrier();
for (size_t index = 0; index < 4; index++) {
if (nread == length)
break;
buf[nread] = (data >> (8 * index)) & 0xFF;
nread++;
}
};
full_memory_barrier();
write_to_register(IntelGraphics::RegisterIndex::GMBusCommand, (1 | (address << 1) | (length << 16) | (GMBusCycle::Wait << 25) | (1 << 30)));
full_memory_barrier();
while (nread < length) {
gmbus_wait_for(GMBusStatus::HardwareReady, {});
read_set();
}
gmbus_wait_for(GMBusStatus::TransactionCompletion, {});
}
void IntelNativeGraphicsAdapter::gmbus_read_edid()
{
{
SpinlockLocker control_lock(m_control_lock);
gmbus_write(DDC2_I2C_ADDRESS, 0);
gmbus_read(DDC2_I2C_ADDRESS, (u8*)&m_crt_edid_bytes, sizeof(m_crt_edid_bytes));
}
if (auto parsed_edid = EDID::Parser::from_bytes({ m_crt_edid_bytes, sizeof(m_crt_edid_bytes) }); !parsed_edid.is_error()) {
m_crt_edid = parsed_edid.release_value();
} else {
dbgln("IntelNativeGraphicsAdapter: Parsing EDID failed: {}", parsed_edid.error());
m_crt_edid = {};
}
}
bool IntelNativeGraphicsAdapter::is_resolution_valid(size_t, size_t)
{
VERIFY(m_control_lock.is_locked());
VERIFY(m_modeset_lock.is_locked());
// FIXME: Check that we are able to modeset to the requested resolution!
return true;
}
void IntelNativeGraphicsAdapter::disable_output()
{
VERIFY(m_control_lock.is_locked());
disable_dac_output();
disable_all_planes();
disable_pipe_a();
disable_pipe_b();
disable_vga_emulation();
disable_dpll();
}
void IntelNativeGraphicsAdapter::enable_output(PhysicalAddress fb_address, size_t width)
{
VERIFY(m_control_lock.is_locked());
VERIFY(!pipe_a_enabled());
enable_pipe_a();
enable_primary_plane(fb_address, width);
enable_dac_output();
}
bool IntelNativeGraphicsAdapter::set_crt_resolution(size_t width, size_t height)
{
SpinlockLocker control_lock(m_control_lock);
SpinlockLocker modeset_lock(m_modeset_lock);
if (!is_resolution_valid(width, height)) {
return false;
}
// FIXME: Get the requested resolution from the EDID!!
auto modesetting = calculate_modesetting_from_edid(m_crt_edid.value(), 0);
disable_output();
auto dac_multiplier = compute_dac_multiplier(modesetting.pixel_clock_in_khz);
auto pll_settings = create_pll_settings((1000 * modesetting.pixel_clock_in_khz * dac_multiplier), 96'000'000, G35Limits);
if (!pll_settings.has_value())
VERIFY_NOT_REACHED();
auto settings = pll_settings.value();
dbgln_if(INTEL_GRAPHICS_DEBUG, "PLL settings for {} {} {} {} {}", settings.n, settings.m1, settings.m2, settings.p1, settings.p2);
enable_dpll_without_vga(pll_settings.value(), dac_multiplier);
set_display_timings(modesetting);
auto address = PhysicalAddress(PCI::get_BAR2(pci_address()) & 0xfffffff0);
VERIFY(!address.is_null());
enable_output(address, width);
m_framebuffer_width = width;
m_framebuffer_height = height;
m_framebuffer_pitch = width * 4;
return true;
}
void IntelNativeGraphicsAdapter::set_display_timings(const Graphics::Modesetting& modesetting)
{
VERIFY(m_control_lock.is_locked());
VERIFY(m_modeset_lock.is_locked());
VERIFY(!(read_from_register(IntelGraphics::RegisterIndex::PipeAConf) & (1 << 31)));
VERIFY(!(read_from_register(IntelGraphics::RegisterIndex::PipeAConf) & (1 << 30)));
dbgln_if(INTEL_GRAPHICS_DEBUG, "htotal - {}, {}", (modesetting.horizontal.active - 1), (modesetting.horizontal.total - 1));
write_to_register(IntelGraphics::RegisterIndex::HTotalA, (modesetting.horizontal.active - 1) | (modesetting.horizontal.total - 1) << 16);
dbgln_if(INTEL_GRAPHICS_DEBUG, "hblank - {}, {}", (modesetting.horizontal.blanking_start() - 1), (modesetting.horizontal.blanking_end() - 1));
write_to_register(IntelGraphics::RegisterIndex::HBlankA, (modesetting.horizontal.blanking_start() - 1) | (modesetting.horizontal.blanking_end() - 1) << 16);
dbgln_if(INTEL_GRAPHICS_DEBUG, "hsync - {}, {}", (modesetting.horizontal.sync_start - 1), (modesetting.horizontal.sync_end - 1));
write_to_register(IntelGraphics::RegisterIndex::HSyncA, (modesetting.horizontal.sync_start - 1) | (modesetting.horizontal.sync_end - 1) << 16);
dbgln_if(INTEL_GRAPHICS_DEBUG, "vtotal - {}, {}", (modesetting.vertical.active - 1), (modesetting.vertical.total - 1));
write_to_register(IntelGraphics::RegisterIndex::VTotalA, (modesetting.vertical.active - 1) | (modesetting.vertical.total - 1) << 16);
dbgln_if(INTEL_GRAPHICS_DEBUG, "vblank - {}, {}", (modesetting.vertical.blanking_start() - 1), (modesetting.vertical.blanking_end() - 1));
write_to_register(IntelGraphics::RegisterIndex::VBlankA, (modesetting.vertical.blanking_start() - 1) | (modesetting.vertical.blanking_end() - 1) << 16);
dbgln_if(INTEL_GRAPHICS_DEBUG, "vsync - {}, {}", (modesetting.vertical.sync_start - 1), (modesetting.vertical.sync_end - 1));
write_to_register(IntelGraphics::RegisterIndex::VSyncA, (modesetting.vertical.sync_start - 1) | (modesetting.vertical.sync_end - 1) << 16);
dbgln_if(INTEL_GRAPHICS_DEBUG, "sourceSize - {}, {}", (modesetting.vertical.active - 1), (modesetting.horizontal.active - 1));
write_to_register(IntelGraphics::RegisterIndex::PipeASource, (modesetting.vertical.active - 1) | (modesetting.horizontal.active - 1) << 16);
IO::delay(200);
}
bool IntelNativeGraphicsAdapter::wait_for_enabled_pipe_a(size_t milliseconds_timeout) const
{
size_t current_time = 0;
while (current_time < milliseconds_timeout) {
if (pipe_a_enabled())
return true;
IO::delay(1000);
current_time++;
}
return false;
}
bool IntelNativeGraphicsAdapter::wait_for_disabled_pipe_a(size_t milliseconds_timeout) const
{
size_t current_time = 0;
while (current_time < milliseconds_timeout) {
if (!pipe_a_enabled())
return true;
IO::delay(1000);
current_time++;
}
return false;
}
bool IntelNativeGraphicsAdapter::wait_for_disabled_pipe_b(size_t milliseconds_timeout) const
{
size_t current_time = 0;
while (current_time < milliseconds_timeout) {
if (!pipe_b_enabled())
return true;
IO::delay(1000);
current_time++;
}
return false;
}
void IntelNativeGraphicsAdapter::disable_dpll()
{
VERIFY(m_control_lock.is_locked());
VERIFY(m_modeset_lock.is_locked());
write_to_register(IntelGraphics::RegisterIndex::DPLLControlA, read_from_register(IntelGraphics::RegisterIndex::DPLLControlA) & ~0x80000000);
write_to_register(IntelGraphics::RegisterIndex::DPLLControlB, read_from_register(IntelGraphics::RegisterIndex::DPLLControlB) & ~0x80000000);
}
void IntelNativeGraphicsAdapter::disable_pipe_a()
{
VERIFY(m_control_lock.is_locked());
VERIFY(m_modeset_lock.is_locked());
write_to_register(IntelGraphics::RegisterIndex::PipeAConf, read_from_register(IntelGraphics::RegisterIndex::PipeAConf) & ~0x80000000);
dbgln_if(INTEL_GRAPHICS_DEBUG, "Disabling Pipe A");
wait_for_disabled_pipe_a(100);
dbgln_if(INTEL_GRAPHICS_DEBUG, "Disabling Pipe A - done.");
}
void IntelNativeGraphicsAdapter::disable_pipe_b()
{
VERIFY(m_control_lock.is_locked());
VERIFY(m_modeset_lock.is_locked());
write_to_register(IntelGraphics::RegisterIndex::PipeAConf, read_from_register(IntelGraphics::RegisterIndex::PipeBConf) & ~0x80000000);
dbgln_if(INTEL_GRAPHICS_DEBUG, "Disabling Pipe B");
wait_for_disabled_pipe_b(100);
dbgln_if(INTEL_GRAPHICS_DEBUG, "Disabling Pipe B - done.");
}
void IntelNativeGraphicsAdapter::set_gmbus_default_rate()
{
// FIXME: Verify GMBUS Rate Select is set only when GMBUS is idle
VERIFY(m_control_lock.is_locked());
// Set the rate to 100KHz
write_to_register(IntelGraphics::RegisterIndex::GMBusClock, read_from_register(IntelGraphics::RegisterIndex::GMBusClock) & ~(0b111 << 8));
}
void IntelNativeGraphicsAdapter::enable_pipe_a()
{
VERIFY(m_control_lock.is_locked());
VERIFY(m_modeset_lock.is_locked());
VERIFY(!(read_from_register(IntelGraphics::RegisterIndex::PipeAConf) & (1 << 31)));
VERIFY(!(read_from_register(IntelGraphics::RegisterIndex::PipeAConf) & (1 << 30)));
write_to_register(IntelGraphics::RegisterIndex::PipeAConf, read_from_register(IntelGraphics::RegisterIndex::PipeAConf) | 0x80000000);
dbgln_if(INTEL_GRAPHICS_DEBUG, "enabling Pipe A");
// FIXME: Seems like my video card is buggy and doesn't set the enabled bit (bit 30)!!
wait_for_enabled_pipe_a(100);
dbgln_if(INTEL_GRAPHICS_DEBUG, "enabling Pipe A - done.");
}
void IntelNativeGraphicsAdapter::enable_primary_plane(PhysicalAddress fb_address, size_t width)
{
VERIFY(m_control_lock.is_locked());
VERIFY(m_modeset_lock.is_locked());
VERIFY(((width * 4) % 64 == 0));
write_to_register(IntelGraphics::RegisterIndex::DisplayPlaneAStride, width * 4);
write_to_register(IntelGraphics::RegisterIndex::DisplayPlaneALinearOffset, 0);
write_to_register(IntelGraphics::RegisterIndex::DisplayPlaneASurface, fb_address.get());
// FIXME: Serenity uses BGR 32 bit pixel format, but maybe we should try to determine it somehow!
write_to_register(IntelGraphics::RegisterIndex::DisplayPlaneAControl, (read_from_register(IntelGraphics::RegisterIndex::DisplayPlaneAControl) & (~(0b1111 << 26))) | (0b0110 << 26) | (1 << 31));
}
void IntelNativeGraphicsAdapter::set_dpll_registers(const PLLSettings& settings)
{
VERIFY(m_control_lock.is_locked());
VERIFY(m_modeset_lock.is_locked());
write_to_register(IntelGraphics::RegisterIndex::DPLLDivisorA0, (settings.m2 - 2) | ((settings.m1 - 2) << 8) | ((settings.n - 2) << 16));
write_to_register(IntelGraphics::RegisterIndex::DPLLDivisorA1, (settings.m2 - 2) | ((settings.m1 - 2) << 8) | ((settings.n - 2) << 16));
write_to_register(IntelGraphics::RegisterIndex::DPLLControlA, read_from_register(IntelGraphics::RegisterIndex::DPLLControlA) & ~0x80000000);
}
void IntelNativeGraphicsAdapter::enable_dpll_without_vga(const PLLSettings& settings, size_t dac_multiplier)
{
VERIFY(m_control_lock.is_locked());
VERIFY(m_modeset_lock.is_locked());
set_dpll_registers(settings);
IO::delay(200);
write_to_register(IntelGraphics::RegisterIndex::DPLLControlA, (6 << 9) | (settings.p1) << 16 | (1 << 26) | (1 << 28) | (1 << 31));
write_to_register(IntelGraphics::RegisterIndex::DPLLMultiplierA, (dac_multiplier - 1) | ((dac_multiplier - 1) << 8));
// The specification says we should wait (at least) about 150 microseconds
// after enabling the DPLL to allow the clock to stabilize
IO::delay(200);
VERIFY(read_from_register(IntelGraphics::RegisterIndex::DPLLControlA) & (1 << 31));
}
void IntelNativeGraphicsAdapter::set_gmbus_pin_pair(GMBusPinPair pin_pair)
{
// FIXME: Verify GMBUS is idle
VERIFY(m_control_lock.is_locked());
write_to_register(IntelGraphics::RegisterIndex::GMBusClock, (read_from_register(IntelGraphics::RegisterIndex::GMBusClock) & (~0b111)) | (pin_pair & 0b111));
}
void IntelNativeGraphicsAdapter::disable_dac_output()
{
VERIFY(m_control_lock.is_locked());
VERIFY(m_modeset_lock.is_locked());
write_to_register(IntelGraphics::RegisterIndex::AnalogDisplayPort, 0b11 << 10);
}
void IntelNativeGraphicsAdapter::enable_dac_output()
{
VERIFY(m_control_lock.is_locked());
VERIFY(m_modeset_lock.is_locked());
write_to_register(IntelGraphics::RegisterIndex::AnalogDisplayPort, (read_from_register(IntelGraphics::RegisterIndex::AnalogDisplayPort) & (~(0b11 << 10))) | 0x80000000);
}
void IntelNativeGraphicsAdapter::disable_vga_emulation()
{
VERIFY(m_control_lock.is_locked());
VERIFY(m_modeset_lock.is_locked());
write_to_register(IntelGraphics::RegisterIndex::VGADisplayPlaneControl, (read_from_register(IntelGraphics::RegisterIndex::VGADisplayPlaneControl) & (~(1 << 30))) | 0x80000000);
}
void IntelNativeGraphicsAdapter::disable_all_planes()
{
VERIFY(m_control_lock.is_locked());
VERIFY(m_modeset_lock.is_locked());
write_to_register(IntelGraphics::RegisterIndex::DisplayPlaneAControl, read_from_register(IntelGraphics::RegisterIndex::DisplayPlaneAControl) & ~(1 << 31));
}
void IntelNativeGraphicsAdapter::initialize_framebuffer_devices()
{
auto address = PhysicalAddress(PCI::get_BAR2(pci_address()) & 0xfffffff0);
VERIFY(!address.is_null());
VERIFY(m_framebuffer_pitch != 0);
VERIFY(m_framebuffer_height != 0);
VERIFY(m_framebuffer_width != 0);
m_framebuffer_device = FramebufferDevice::create(*this, address, m_framebuffer_width, m_framebuffer_height, m_framebuffer_pitch);
// FIXME: Would be nice to be able to return a ErrorOr<void> here.
auto framebuffer_result = m_framebuffer_device->try_to_initialize();
VERIFY(!framebuffer_result.is_error());
}
ErrorOr<ByteBuffer> IntelNativeGraphicsAdapter::get_edid(size_t output_port_index) const
{
if (output_port_index != 0) {
dbgln("IntelNativeGraphicsAdapter: get_edid: Only one output supported");
return Error::from_errno(ENODEV);
}
if (m_crt_edid.has_value())
return ByteBuffer::copy(m_crt_edid_bytes, sizeof(m_crt_edid_bytes));
return ByteBuffer {};
}
}
| 608
|
https://github.com/ddd-ruby/attr_validator/blob/master/lib/pure_validator/validation_errors.rb
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
attr_validator
|
ddd-ruby
|
Ruby
|
Code
| 1,019
| 2,377
|
class PureValidator::ValidationErrors
attr_reader :messages
def initialize
@messages = {}
end
# Clear the error messages.
#
# errors.full_messages # => ["name can not be nil"]
# errors.clear
# errors.full_messages # => []
def clear
messages.clear
end
# Returns +true+ if the error messages include an error for the given key
# +attribute+, +false+ otherwise.
#
# errors.messages # => {:name=>["can not be nil"]}
# errors.include?(:name) # => true
# errors.include?(:age) # => false
def include?(attribute)
(v = messages[attribute]) && v.any?
end
# aliases include?
alias :has_key? :include?
# Get messages for +key+.
#
# errors.messages # => {:name=>["can not be nil"]}
# errors.get(:name) # => ["can not be nil"]
# errors.get(:age) # => nil
def get(key)
messages[key]
end
# Set messages for +key+ to +value+.
#
# errors.get(:name) # => ["can not be nil"]
# errors.set(:name, ["can't be nil"])
# errors.get(:name) # => ["can't be nil"]
def set(key, value)
messages[key] = value
end
# Delete messages for +key+. Returns the deleted messages.
#
# errors.get(:name) # => ["can not be nil"]
# errors.delete(:name) # => ["can not be nil"]
# errors.get(:name) # => nil
def delete(key)
messages.delete(key)
end
# When passed a symbol or a name of a method, returns an array of errors
# for the method.
#
# errors[:name] # => ["can not be nil"]
# errors['name'] # => ["can not be nil"]
def [](attribute)
get(attribute.to_sym) || set(attribute.to_sym, [])
end
# Adds to the supplied attribute the supplied error message.
#
# errors[:name] = "must be set"
# errors[:name] # => ['must be set']
def []=(attribute, error)
self[attribute] << error
end
# Iterates through each error key, value pair in the error messages hash.
# Yields the attribute and the error for that attribute. If the attribute
# has more than one error message, yields once for each error message.
#
# errors.add(:name, "can't be blank")
# errors.each do |attribute, error|
# # Will yield :name and "can't be blank"
# end
#
# errors.add(:name, "must be specified")
# errors.each do |attribute, error|
# # Will yield :name and "can't be blank"
# # then yield :name and "must be specified"
# end
def each
messages.each_key do |attribute|
self[attribute].each { |error| yield attribute, error }
end
end
# Returns the number of error messages.
#
# errors.add(:name, "can't be blank")
# errors.size # => 1
# errors.add(:name, "must be specified")
# errors.size # => 2
def size
values.flatten.size
end
# Returns all message values.
#
# errors.messages # => {:name=>["can not be nil", "must be specified"]}
# errors.values # => [["can not be nil", "must be specified"]]
def values
messages.values
end
# Returns all message keys.
#
# errors.messages # => {:name=>["can not be nil", "must be specified"]}
# errors.keys # => [:name]
def keys
messages.keys
end
# Returns an array of error messages, with the attribute name included.
#
# errors.add(:name, "can't be blank")
# errors.add(:name, "must be specified")
# errors.to_a # => ["name can't be blank", "name must be specified"]
def to_a
full_messages
end
# Returns the number of error messages.
#
# errors.add(:name, "can't be blank")
# errors.count # => 1
# errors.add(:name, "must be specified")
# errors.count # => 2
def count
to_a.size
end
# Returns +true+ if no errors are found, +false+ otherwise.
# If the error message is a string it can be empty.
#
# errors.full_messages # => ["name can not be nil"]
# errors.empty? # => false
def empty?
messages.all? { |k, v| v && v.empty? && !v.is_a?(String) }
end
# aliases empty?
alias_method :blank?, :empty?
# Returns a Hash of attributes with their error messages. If +full_messages+
# is +true+, it will contain full messages (see +full_message+).
#
# errors.to_hash # => {:name=>["can not be nil"]}
# errors.to_hash(true) # => {:name=>["name can not be nil"]}
def to_hash(full_messages = false)
if full_messages
messages = {}
self.messages.each do |attribute, array|
messages[attribute] = array.map { |message| full_message(attribute, message) }
end
messages
else
self.messages.dup
end
end
# Adds +message+ to the error messages on +attribute+. More than one error
# can be added to the same +attribute+
#
# errors.add(:name, 'is invalid')
# # => ["is invalid"]
# errors.add(:name, 'must be implemented')
# # => ["is invalid", "must be implemented"]
#
# errors.messages
# # => {:name=>["must be implemented", "is invalid"]}
#
# If +message+ is a proc, it will be called, allowing for things like
# <tt>Time.now</tt> to be used within an error.
#
# errors.messages # => {}
def add(attribute, message)
self[attribute] << message
end
# Adds +messages+ to the error messages on +attribute+.
#
# errors.add(:name, ['is invalid', 'must present'])
# # => ["is invalid", "must present"]
def add_all(attribute, errors)
messages[attribute] ||= []
messages[attribute] += errors
end
# Returns +true+ if an error on the attribute with the given message is
# present, +false+ otherwise. +message+ is treated the same as for +add+.
#
# errors.add :name, :blank
# errors.added? :name, :blank # => true
def added?(attribute, message)
self[attribute].include? message
end
# Returns all the full error messages in an array.
#
# class PersonValidator
# validates :name, :address, :email, presence: true
# validates :name, length: { min: 5, max: 30 }
# end
#
# = create(address: '123 First St.')
# errors.full_messages
# # => ["Name is too short (minimum is 5 characters)", "Name can't be blank", "Email can't be blank"]
def full_messages
messages.map { |attribute, message| full_message(attribute, message) }
end
# Returns all the full error messages for a given attribute in an array.
#
# class PersonValidator
# validates :name, :address, :email, presence: true
# validates :name, length: { min: 5, max: 30 }
# end
#
# = create()
# errors.full_messages_for(:name)
# # => ["Name is too short (minimum is 5 characters)", "Name can't be blank"]
def full_messages_for(attribute)
(get(attribute) || []).map { |message| full_message(attribute, message) }
end
# Returns a full message for a given attribute.
#
# errors.full_message(:name, 'is invalid') # => "Name is invalid"
def full_message(attribute, message)
return message if attribute == :base
attr_name = humanize(attribute.to_s.tr('.', '_'))
# attr_name = @base.class.human_attribute_name(attribute, default: attr_name)
I18n.t(:"errors.format", {
default: "%{attribute} %{message}",
attribute: attr_name,
message: message
})
end
def humanize(value, options = {})
PureValidator::Humanize.humanize(value, options)
end
end
| 45,148
|
https://github.com/zhangjunfeng123/SwiftHttp/blob/master/HDPhone/HDPhone/HDViewController.swift
|
Github Open Source
|
Open Source
|
MIT
| 2,015
|
SwiftHttp
|
zhangjunfeng123
|
Swift
|
Code
| 163
| 540
|
//
// HDViewController.swift
// HDPhone
//
// Created by 张达棣 on 14-11-14.
// Copyright (c) 2014年 张达棣. All rights reserved.
//
import UIKit
import HDNetwork
class HDViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
var imageData = NSData(contentsOfFile: "1.png")
let paramDict = ["image": HDNetHTTPItem(data: imageData, fileName: "imageName.png")]
//POST请求
HDNetHTTPRequestManager().POST("http://www.v2ex.com/api/nodes/all.json", parameters: paramDict, completion: {
(data: NSData?, error: NSError?) -> Void in
if error != nil {
println("上传图片失败")
return
} else {
println("上传图片成功")
}
println("请求all成功")
var json = JSON(data: data!, options: nil, error: nil)
let mid = json[0]["id"].integerValue
// //GET请求
// //参数
// let paramDict = ["id": HDNetHTTPItem(value: mid!)]
// HDNetHTTPRequestManager().GET("http://www.v2ex.com/api/nodes/show.json", parameters: paramDict, completion: {
// (data: NSData?, error: NSError?) -> Void in
// if error != nil {
// println("请求show.json失败")
// } else {
// json = JSON(data: data!, options: nil, error: nil)
// println(json)
// var titel = json["title"].stringValue
// println("请求show.json成功,标题为=\(titel)")
// }
// })
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 8,051
|
https://github.com/ameerthehacker/letschat/blob/master/src/app/components/threads/thread-list/thread-list.component.ts
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,020
|
letschat
|
ameerthehacker
|
TypeScript
|
Code
| 58
| 198
|
import { Component,
OnInit,
Input,
EventEmitter,
Output } from '@angular/core';
import { Thread } from "../../../models/thread";
import { User } from '../../../models/user';
@Component({
selector: 'lc-thread-list',
templateUrl: './thread-list.component.html',
styleUrls: ['./thread-list.component.scss']
})
export class ThreadListComponent implements OnInit {
@Output()
public select: EventEmitter<User> = new EventEmitter<User>();
@Input()
public threads: Thread[];
constructor() { }
ngOnInit() {
}
onThreadClick(user) {
this.select.emit(user);
}
}
| 24,466
|
https://github.com/costrouc/matchpy/blob/master/matchpy/expressions/functions.py
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
matchpy
|
costrouc
|
Python
|
Code
| 501
| 1,594
|
from functools import singledispatch
from typing import Dict
from .expressions import (
Expression, Operation, Wildcard, AssociativeOperation, CommutativeOperation, SymbolWildcard, Pattern, OneIdentityOperation
)
__all__ = [
'is_constant', 'is_syntactic', 'get_head', 'match_head', 'preorder_iter', 'preorder_iter_with_position',
'is_anonymous', 'contains_variables_from_set', 'create_operation_expression',
'rename_variables', 'op_iter', 'op_len', 'get_variables'
]
def is_constant(expression):
"""Check if the given expression is constant, i.e. it does not contain Wildcards."""
if isinstance(expression, Wildcard):
return False
if isinstance(expression, Expression):
return expression.is_constant
if isinstance(expression, Operation):
return all(is_constant(o) for o in op_iter(expression))
return True
def is_syntactic(expression):
"""
Check if the given expression is syntactic, i.e. it does not contain sequence wildcards or
associative/commutative operations.
"""
if isinstance(expression, Wildcard):
return expression.fixed_size
if isinstance(expression, Expression):
return expression.is_syntactic
if isinstance(expression, (AssociativeOperation, CommutativeOperation)):
return False
if isinstance(expression, Operation):
return all(is_syntactic(o) for o in op_iter(expression))
return True
def get_head(expression):
"""Returns the given expression's head."""
if isinstance(expression, Wildcard):
if isinstance(expression, SymbolWildcard):
return expression.symbol_type
return None
return type(expression)
def match_head(subject, pattern):
"""Checks if the head of subject matches the pattern's head."""
if isinstance(pattern, Pattern):
pattern = pattern.expression
pattern_head = get_head(pattern)
if pattern_head is None:
return True
if issubclass(pattern_head, OneIdentityOperation):
return True
subject_head = get_head(subject)
assert subject_head is not None
return issubclass(subject_head, pattern_head)
def preorder_iter(expression):
"""Iterate over the expression in preorder."""
yield expression
if isinstance(expression, Operation):
for operand in op_iter(expression):
yield from preorder_iter(operand)
def preorder_iter_with_position(expression):
"""Iterate over the expression in preorder.
Also yields the position of each subexpression.
"""
yield expression, ()
if isinstance(expression, Operation):
for i, operand in enumerate(op_iter(expression)):
for child, pos in preorder_iter_with_position(operand):
yield child, (i, ) + pos
def is_anonymous(expression):
"""Returns True iff the expression does not contain any variables."""
if hasattr(expression, 'variable_name') and expression.variable_name:
return False
if isinstance(expression, Operation):
return all(is_anonymous(o) for o in op_iter(expression))
return True
def contains_variables_from_set(expression, variables):
"""Returns True iff the expression contains any of the variables from the given set."""
if hasattr(expression, 'variable_name') and expression.variable_name in variables:
return True
if isinstance(expression, Operation):
return any(contains_variables_from_set(o, variables) for o in op_iter(expression))
return False
def get_variables(expression, variables=None):
"""Returns the set of variable names in the given expression."""
if variables is None:
variables = set()
if hasattr(expression, 'variable_name') and expression.variable_name is not None:
variables.add(expression.variable_name)
if isinstance(expression, Operation):
for operand in op_iter(expression):
get_variables(operand, variables)
return variables
def rename_variables(expression: Expression, renaming: Dict[str, str]) -> Expression:
"""Rename the variables in the expression according to the given dictionary.
Args:
expression:
The expression in which the variables are renamed.
renaming:
The renaming dictionary. Maps old variable names to new ones.
Variable names not occuring in the dictionary are left unchanged.
Returns:
The expression with renamed variables.
"""
if isinstance(expression, Operation):
if hasattr(expression, 'variable_name'):
variable_name = renaming.get(expression.variable_name, expression.variable_name)
return create_operation_expression(
expression, [rename_variables(o, renaming) for o in op_iter(expression)], variable_name=variable_name
)
operands = [rename_variables(o, renaming) for o in op_iter(expression)]
return create_operation_expression(expression, operands)
elif isinstance(expression, Expression):
expression = expression.__copy__()
expression.variable_name = renaming.get(expression.variable_name, expression.variable_name)
return expression
@singledispatch
def create_operation_expression(old_operation, new_operands, variable_name=True):
if variable_name is True:
variable_name = getattr(old_operation, 'variable_name', None)
if variable_name is False:
return operation(*new_operands)
return type(old_operation)(*new_operands, variable_name=variable_name)
@create_operation_expression.register(list)
@create_operation_expression.register(tuple)
@create_operation_expression.register(set)
@create_operation_expression.register(frozenset)
@create_operation_expression.register(dict)
def _(old_operation, new_operands, variable_name=True):
return type(old_operation)(new_operands)
@singledispatch
def op_iter(operation):
return iter(operation)
@op_iter.register(dict)
def _(operation):
return iter(operation.items())
@singledispatch
def op_len(operation):
return len(operation)
| 27,037
|
https://github.com/Ferlab-Ste-Justine/ferload/blob/master/app/auth/UserRequest.scala
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
ferload
|
Ferlab-Ste-Justine
|
Scala
|
Code
| 24
| 93
|
package auth
import org.keycloak.representations.AccessToken
import play.api.mvc.{Request, WrappedRequest}
case class UserRequest[A](accessToken: AccessToken, token: String, request: Request[A]) extends WrappedRequest[A](request) {
val isRpt: Boolean = Option(accessToken.getAuthorization).isDefined
}
| 45,648
|
https://github.com/Folivi95/CleanArchitecture-2/blob/master/.gitignore
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
CleanArchitecture-2
|
Folivi95
|
Ignore List
|
Code
| 7
| 68
|
.vs/*
.vscode/*
/CleanArchitecture.Presentation/obj/
/CleanArchitecture.Core/obj/
/CleanArchitecture.Infrastructure/obj/
/CleanArchitecture.Tests/obj/
/CleanArchitecture.Tests/bin/
| 28,287
|
https://github.com/acidicMercury8/xray-1.0/blob/master/sdk/boost_1_30_0/libs/graph/example/undirected_dfs.cpp
|
Github Open Source
|
Open Source
|
Linux-OpenIB
| 2,020
|
xray-1.0
|
acidicMercury8
|
C++
|
Code
| 363
| 985
|
//=======================================================================
// Copyright 2002 Jeremy G. Siek, Andrew Lumsdaine, Lie-Quan Lee,
//
// This file is part of the Boost Graph Library
//
// You should have received a copy of the License Agreement for the
// Boost Graph Library along with the software; see the file LICENSE.
// If not, contact Office of Research, Indiana University,
// Bloomington, IN 47405.
//
// Permission to modify the code and to distribute the code is
// granted, provided the text of this NOTICE is retained, a notice if
// the code was modified is included with the above COPYRIGHT NOTICE
// and with the COPYRIGHT NOTICE in the LICENSE file, and that the
// LICENSE file is distributed with the modified code.
//
// LICENSOR MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.
// By way of example, but not limitation, Licensor MAKES NO
// REPRESENTATIONS OR WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY
// PARTICULAR PURPOSE OR THAT THE USE OF THE LICENSED SOFTWARE COMPONENTS
// OR DOCUMENTATION WILL NOT INFRINGE ANY PATENTS, COPYRIGHTS, TRADEMARKS
// OR OTHER RIGHTS.
//=======================================================================
#include <string>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/undirected_dfs.hpp>
#include <boost/cstdlib.hpp>
/*
Example graph from Tarjei Knapstad.
H15
|
H8 C2
\ / \
H9-C0-C1 C3-O7-H14
/ | |
H10 C6 C4
/ \ / \
H11 C5 H13
|
H12
*/
std::string name[] = { "C0", "C1", "C2", "C3", "C4", "C5", "C6", "O7",
"H8", "H9", "H10", "H11", "H12", "H13", "H14", "H15"};
struct detect_loops : public boost::dfs_visitor<>
{
template <class Edge, class Graph>
void back_edge(Edge e, const Graph& g) {
std::cout << name[source(e, g)]
<< " -- "
<< name[target(e, g)] << "\n";
}
};
int main(int, char*[])
{
using namespace boost;
typedef adjacency_list< vecS, vecS, undirectedS,
no_property,
property<edge_color_t, default_color_type> > graph_t;
typedef graph_traits<graph_t>::vertex_descriptor vertex_t;
const std::size_t N = sizeof(name)/sizeof(std::string);
graph_t g(N);
add_edge(0, 1, g);
add_edge(0, 8, g);
add_edge(0, 9, g);
add_edge(0, 10, g);
add_edge(1, 2, g);
add_edge(1, 6, g);
add_edge(2, 15, g);
add_edge(2, 3, g);
add_edge(3, 7, g);
add_edge(3, 4, g);
add_edge(4, 13, g);
add_edge(4, 5, g);
add_edge(5, 12, g);
add_edge(5, 6, g);
add_edge(6, 11, g);
add_edge(7, 14, g);
std::cout << "back edges:\n";
detect_loops vis;
undirected_dfs(g, root_vertex(vertex_t(0)).visitor(vis)
.edge_color_map(get(edge_color, g)));
std::cout << std::endl;
return boost::exit_success;
}
| 26,989
|
https://github.com/ryanliszewski/Roomy/blob/master/roomy/Pods/ParseLiveQuery/Sources/ParseLiveQuery/Internal/BoltsHelpers.swift
|
Github Open Source
|
Open Source
|
MIT
| null |
Roomy
|
ryanliszewski
|
Swift
|
Code
| 166
| 431
|
/**
* Copyright (c) 2016-present, Parse, LLC.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
import Bolts
import BoltsSwift
let unknownDomain = "unknown"
func objcTask<T>(_ task: Task<T>) -> BFTask<T> where T: AnyObject {
let taskCompletionSource = BFTaskCompletionSource<T>()
task.continueWith { task in
if task.cancelled {
taskCompletionSource.trySetCancelled()
} else if task.faulted {
let error = task.error as? NSError ?? NSError(domain: unknownDomain, code: -1, userInfo: nil)
taskCompletionSource.trySetError(error)
} else {
taskCompletionSource.trySetResult(task.result)
}
}
return taskCompletionSource.task
}
func swiftTask(_ task: BFTask<AnyObject>) -> Task<AnyObject> {
let taskCompletionSource = TaskCompletionSource<AnyObject>()
task.continue({ task in
if task.isCancelled {
taskCompletionSource.tryCancel()
} else if let error = task.error , task.isFaulted {
taskCompletionSource.trySet(error: error)
} else if let result = task.result {
taskCompletionSource.trySet(result: result)
} else {
fatalError("Unknown task state")
}
return nil
})
return taskCompletionSource.task
}
| 47,688
|
https://github.com/stokpop/spring-cloud-sleuth/blob/master/tests/brave/spring-cloud-sleuth-instrumentation-feign-tests/src/test/java/org/springframework/cloud/sleuth/brave/instrument/feign/issues/issue393/Issue393Tests.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
spring-cloud-sleuth
|
stokpop
|
Java
|
Code
| 357
| 1,317
|
/*
* Copyright 2013-2020 the original author or authors.
*
* 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
*
* https://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.springframework.cloud.sleuth.brave.instrument.feign.issues.issue393;
import java.util.stream.Collectors;
import brave.Tracing;
import brave.handler.SpanHandler;
import brave.sampler.Sampler;
import brave.test.TestSpanHandler;
import feign.okhttp.OkHttpClient;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.cloud.sleuth.instrument.web.TraceWebServletAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.TestPropertySource;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import static org.assertj.core.api.BDDAssertions.then;
@FeignClient(name = "no-name", url = "http://localhost:9978")
interface MyNameRemote {
@RequestMapping(value = "/name/{id}", method = RequestMethod.GET)
String getName(@PathVariable("id") String id);
}
/**
* @author Marcin Grzejszczak
*/
@SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
@TestPropertySource(properties = { "spring.application.name=demo-feign-uri", "server.port=9978" })
public class Issue393Tests {
RestTemplate template = new RestTemplate();
@Autowired
Tracing tracer;
@Autowired
TestSpanHandler spans;
@BeforeEach
public void open() {
this.spans.clear();
}
@Test
public void should_successfully_work_when_service_discovery_is_on_classpath_and_feign_uses_url() {
String url = "http://localhost:9978/hello/mikesarver";
ResponseEntity<String> response = this.template.getForEntity(url, String.class);
then(response.getBody()).isEqualTo("mikesarver foo");
// retries
then(this.spans).hasSize(2);
then(this.spans.spans().stream().map(span -> span.tags().get("http.path")).collect(Collectors.toList()))
.containsOnly("/name/mikesarver");
}
}
@Configuration(proxyBeanMethods = false)
@EnableAutoConfiguration(
// spring boot test will otherwise instrument the client and server with the
// same bean factory which isn't expected
exclude = TraceWebServletAutoConfiguration.class)
@EnableFeignClients
@EnableDiscoveryClient
class Application {
@Bean
public DemoController demoController(MyNameRemote myNameRemote) {
return new DemoController(myNameRemote);
}
// issue #513
@Bean
public OkHttpClient myOkHttpClient() {
return new OkHttpClient();
}
@Bean
public feign.Logger.Level feignLoggerLevel() {
return feign.Logger.Level.BASIC;
}
@Bean
public Sampler defaultSampler() {
return Sampler.ALWAYS_SAMPLE;
}
@Bean
public SpanHandler testSpanHandler() {
return new TestSpanHandler();
}
}
@RestController
class DemoController {
private final MyNameRemote myNameRemote;
DemoController(MyNameRemote myNameRemote) {
this.myNameRemote = myNameRemote;
}
@RequestMapping("/hello/{name}")
public String getHello(@PathVariable("name") String name) {
return this.myNameRemote.getName(name) + " foo";
}
@RequestMapping("/name/{name}")
public String getName(@PathVariable("name") String name) {
return name;
}
}
| 20,873
|
https://github.com/TheArijitSaha/MyMDb-RN-App/blob/master/Client/components/SeriesListItem/index.tsx
|
Github Open Source
|
Open Source
|
MIT
| null |
MyMDb-RN-App
|
TheArijitSaha
|
TypeScript
|
Code
| 188
| 676
|
import React, { PureComponent } from "react";
import {
ImageBackground,
StyleSheet,
Text,
View,
TouchableOpacity,
} from "react-native";
import { LinearGradient } from "expo-linear-gradient";
import SeriesProgress from "./SeriesProgress";
interface SeriesListItemProps {
series: Series;
navigation: any;
}
export default class SeriesListItem extends PureComponent<SeriesListItemProps> {
constructor(props: SeriesListItemProps) {
super(props);
}
render() {
const { series, navigation } = this.props;
const styles = StyleSheet.create({
container: {
flex: 1,
width: "50%",
height: 280,
display: "flex",
justifyContent: "center",
},
poster: {
flex: 1,
resizeMode: "cover",
backgroundColor: "#aaaaaa",
borderStyle: "solid",
borderWidth: 3,
},
label: {
position: "absolute",
bottom: 0,
justifyContent: "center",
width: "100%",
// backgroundColor: series.seen
// ? "rgba(94, 154, 115, 0.85)"
// : "rgba(164, 104, 115, 0.85)",
padding: 5,
},
linearGradient: {
width: "100%",
height: "100%",
},
title: {
textAlign: "center",
flex: 1,
color: "white",
},
releaseYear: {
textAlign: "center",
flex: 1,
color: "white",
},
});
return (
<View style={styles.container}>
<TouchableOpacity
style={styles.poster}
onPress={() =>
navigation.navigate("SeriesDetail", { series: series })
}
>
<ImageBackground
source={{ uri: series.poster }}
style={styles.poster}
>
<LinearGradient
// Background Linear Gradient
colors={["transparent", "transparent", "rgba(0,0,0,0.9)"]}
style={styles.linearGradient}
>
<View style={styles.label}>
<SeriesProgress
seasons={series.seasons}
seenEpisodes={series.seenEpisodes}
/>
<Text style={styles.title}>{series.title}</Text>
</View>
</LinearGradient>
</ImageBackground>
</TouchableOpacity>
</View>
);
}
}
| 25,805
|
https://github.com/aa2g/ReiEdit-AA2/blob/master/AA2Lib/Effects/BrightnessShiftEffect.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
ReiEdit-AA2
|
aa2g
|
C#
|
Code
| 113
| 384
|
// --------------------------------------------------
// AA2Lib - BrightnessShiftEffect.cs
// --------------------------------------------------
using System;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Effects;
namespace AA2Lib.Effects
{
public class BrightnessShiftEffect : ShaderEffect
{
public static readonly DependencyProperty HueShiftProperty = DependencyProperty.Register("Shift",
typeof(float),
typeof(BrightnessShiftEffect),
new UIPropertyMetadata(0.0f, PixelShaderConstantCallback(0)));
public static readonly DependencyProperty InputProperty =
RegisterPixelShaderSamplerProperty("Input", typeof(BrightnessShiftEffect), 0);
private static readonly PixelShader Shader = new PixelShader();
public Brush Input
{
get { return (Brush) GetValue(InputProperty); }
set { SetValue(InputProperty, value); }
}
public float Shift
{
get { return (float) GetValue(HueShiftProperty); }
set { SetValue(HueShiftProperty, value); }
}
static BrightnessShiftEffect()
{
// Associate _pixelShader with our compiled pixel shader
Shader.UriSource = new Uri(@"pack://application:,,,/AA2Lib;component/Effects/Bin/ValShift.ps");
}
public BrightnessShiftEffect()
{
PixelShader = Shader;
UpdateShaderValue(InputProperty);
UpdateShaderValue(HueShiftProperty);
}
}
}
| 16
|
https://github.com/NexusLinkTeam/WeNavi/blob/master/app/src/main/java-gen/com/nexuslink/wenavi/FriendVerifyDao.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
WeNavi
|
NexusLinkTeam
|
Java
|
Code
| 525
| 1,428
|
package com.nexuslink.wenavi;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import de.greenrobot.dao.AbstractDao;
import de.greenrobot.dao.Property;
import de.greenrobot.dao.internal.DaoConfig;
import com.nexuslink.wenavi.FriendVerify;
// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT.
/**
* DAO for table FRIEND_VERIFY.
*/
public class FriendVerifyDao extends AbstractDao<FriendVerify, Long> {
public static final String TABLENAME = "FRIEND_VERIFY";
/**
* Properties of entity FriendVerify.<br/>
* Can be used for QueryBuilder and for referencing column names.
*/
public static class Properties {
public final static Property Avatar = new Property(0, String.class, "avatar", false, "AVATAR");
public final static Property NickName = new Property(1, String.class, "nickName", false, "NICK_NAME");
public final static Property Hello = new Property(2, String.class, "hello", false, "HELLO");
public final static Property UserName = new Property(3, String.class, "userName", false, "USER_NAME");
public final static Property Id = new Property(4, Long.class, "id", true, "_id");
};
public FriendVerifyDao(DaoConfig config) {
super(config);
}
public FriendVerifyDao(DaoConfig config, DaoSession daoSession) {
super(config, daoSession);
}
/** Creates the underlying database table. */
public static void createTable(SQLiteDatabase db, boolean ifNotExists) {
String constraint = ifNotExists? "IF NOT EXISTS ": "";
db.execSQL("CREATE TABLE " + constraint + "'FRIEND_VERIFY' (" + //
"'AVATAR' TEXT," + // 0: avatar
"'NICK_NAME' TEXT," + // 1: nickName
"'HELLO' TEXT," + // 2: hello
"'USER_NAME' TEXT," + // 3: userName
"'_id' INTEGER PRIMARY KEY );"); // 4: id
}
/** Drops the underlying database table. */
public static void dropTable(SQLiteDatabase db, boolean ifExists) {
String sql = "DROP TABLE " + (ifExists ? "IF EXISTS " : "") + "'FRIEND_VERIFY'";
db.execSQL(sql);
}
/** @inheritdoc */
@Override
protected void bindValues(SQLiteStatement stmt, FriendVerify entity) {
stmt.clearBindings();
String avatar = entity.getAvatar();
if (avatar != null) {
stmt.bindString(1, avatar);
}
String nickName = entity.getNickName();
if (nickName != null) {
stmt.bindString(2, nickName);
}
String hello = entity.getHello();
if (hello != null) {
stmt.bindString(3, hello);
}
String userName = entity.getUserName();
if (userName != null) {
stmt.bindString(4, userName);
}
Long id = entity.getId();
if (id != null) {
stmt.bindLong(5, id);
}
}
/** @inheritdoc */
@Override
public Long readKey(Cursor cursor, int offset) {
return cursor.isNull(offset + 4) ? null : cursor.getLong(offset + 4);
}
/** @inheritdoc */
@Override
public FriendVerify readEntity(Cursor cursor, int offset) {
FriendVerify entity = new FriendVerify( //
cursor.isNull(offset + 0) ? null : cursor.getString(offset + 0), // avatar
cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1), // nickName
cursor.isNull(offset + 2) ? null : cursor.getString(offset + 2), // hello
cursor.isNull(offset + 3) ? null : cursor.getString(offset + 3), // userName
cursor.isNull(offset + 4) ? null : cursor.getLong(offset + 4) // id
);
return entity;
}
/** @inheritdoc */
@Override
public void readEntity(Cursor cursor, FriendVerify entity, int offset) {
entity.setAvatar(cursor.isNull(offset + 0) ? null : cursor.getString(offset + 0));
entity.setNickName(cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1));
entity.setHello(cursor.isNull(offset + 2) ? null : cursor.getString(offset + 2));
entity.setUserName(cursor.isNull(offset + 3) ? null : cursor.getString(offset + 3));
entity.setId(cursor.isNull(offset + 4) ? null : cursor.getLong(offset + 4));
}
/** @inheritdoc */
@Override
protected Long updateKeyAfterInsert(FriendVerify entity, long rowId) {
entity.setId(rowId);
return rowId;
}
/** @inheritdoc */
@Override
public Long getKey(FriendVerify entity) {
if(entity != null) {
return entity.getId();
} else {
return null;
}
}
/** @inheritdoc */
@Override
protected boolean isEntityUpdateable() {
return true;
}
}
| 1,191
|
https://github.com/koobitor/class-webpro/blob/master/lesson/week1/57090500414_Thanawat_HW1/login
|
Github Open Source
|
Open Source
|
MIT
| 2,016
|
class-webpro
|
koobitor
|
Shell
|
Code
| 28
| 126
|
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title> Ragnarok Online Login</title>
</head>
<body>
<center>
<form>
<fieldset>
<legend>Login:</legend>
Username: <input type="text"><br>
Password: <input type="text"><br>
</fieldset>
</form>
</center>
</body>
</html>
| 479
|
https://github.com/fossabot/desktop-2/blob/master/packages/desktop-core/src/session/iSessionService.ts
|
Github Open Source
|
Open Source
|
ISC
| null |
desktop-2
|
fossabot
|
TypeScript
|
Code
| 31
| 66
|
import { ISessionConfiguration } from "../configuration";
export interface ISessionService {
/**
* Configure the session based on the given configuration.
* @param configuration The session configuration
*/
configureSession(configuration: ISessionConfiguration): Promise<void>;
}
| 12,943
|
https://github.com/inishchith/DeepSpeech/blob/master/swig/Examples/test-suite/ocaml/inout_runme.ml
|
Github Open Source
|
Open Source
|
LicenseRef-scancode-swig, GPL-3.0-or-later, LicenseRef-scancode-unknown-license-reference, GPL-3.0-only, Apache-2.0
| 2,020
|
DeepSpeech
|
inishchith
|
OCaml
|
Code
| 30
| 75
|
open Swig
open Inout
let _ =
assert (_AddOne1 '(1.) as float = 2.);
assert (_AddOne3 '(1, 1, 1) = C_list ['2.;'2.;'2.]);
assert (_AddOne1r '(1.) as float = 2.);
;;
| 16,247
|
https://github.com/sadikovi/Pulsar/blob/master/demo/js/util.js
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
Pulsar
|
sadikovi
|
JavaScript
|
Code
| 1,290
| 3,888
|
var Util = function() {
return {
/* check for old IE versions */
isBadIE: function() {
if (window.attachEvent && !window.addEventListener) {
return true;
} else {
return false;
}
},
/* check if object is array */
isArray: function(obj) {
if( Object.prototype.toString.call(obj) === '[object Array]' ) {
return true;
} else {
return false;
}
},
/* add event listener and remove event listener */
addEventListener: function(elem, evnt, handler) {
if (elem.addEventListener)
elem.addEventListener(evnt, handler, false);
else if (elem.attachEvent) {
elem.attachEvent("on"+evnt, handler);
} else {
elem["on" + evnt] = null;
}
},
removeEventListener: function(elem, evnt, handler) {
if (elem.removeEventListener) {
elem.removeEventListener(evnt, handler, false);
} else if (elem.detachEvent) {
elem.detachEvent("on" + evnt, handler);
} else {
elem["on" + evnt] = null;
}
},
/* check if event occures on element or its children */
isEventForElement: function(event, element) {
if (!event || !element)
return false;
var c = element.children;
if (event.target == element) {
return true;
} else if (event.target != element && (!c || c.length == 0)) {
return false;
} else {
var bl = false;
for (var i=0; i<c.length; i++)
bl = bl || Util.isEventForElement(event, c[i]);
return bl;
}
},
/* add class to element and remove class from element */
addClass: function(elem, classname) {
if (!elem) {return;}
if (elem.className && !elem.className.baseVal) {
var a = elem.className.split(" ");
for (var i=0; i<a.length; i++)
if (a[i] == classname)
return;
elem.className += " " + classname;
} else {
elem.setAttribute("class", elem.getAttribute("class") + " " + classname);
}
},
removeClass: function(elem, classname) {
if (!elem) {return;}
var newclassname = "";
var isSvg = elem.className && elem.className.baseVal;
var a = ((!isSvg)?elem.className:elem.getAttribute("class")).split(" ");
for (var i=0; i<a.length; i++) {
if (a[i] != classname) { newclassname += " " + a[i]; }
}
if (!isSvg) {
elem.className = newclassname.replace(/^\s+|\s+$/gm,'');
} else {
elem.setAttribute("class", newclassname.replace(/^\s+|\s+$/gm,''));
}
},
hasClass: function(elem, classname) {
if (!elem) {return;}
if (elem.className && !elem.className.baseVal) {
var a = elem.className.split(" ");
for (var i=0; i<a.length; i++)
if (a[i] == classname)
return true;
return false;
} else {
return new RegExp('(\\s|^)' + classname + '(\\s|$)').test(elem.getAttribute("class"));
}
},
/* PHP special chars decode function */
htmlspecialchars_decode: function(string, quote_style) {
var optTemp = 0, i = 0, noquotes = false;
if (typeof quote_style === 'undefined')
quote_style = 2;
string = string.toString().replace(/</g, '<').replace(/>/g, '>');
var OPTS = {
'ENT_NOQUOTES': 0,
'ENT_HTML_QUOTE_SINGLE': 1,
'ENT_HTML_QUOTE_DOUBLE': 2,
'ENT_COMPAT': 2,
'ENT_QUOTES': 3,
'ENT_IGNORE': 4
};
if (quote_style === 0)
noquotes = true;
if (typeof quote_style !== 'number') {
quote_style = [].concat(quote_style);
for (i = 0; i < quote_style.length; i++) {
if (OPTS[quote_style[i]] === 0) {
noquotes = true;
} else if (OPTS[quote_style[i]]) {
optTemp = optTemp | OPTS[quote_style[i]];
}
}
quote_style = optTemp;
}
if (quote_style & OPTS.ENT_HTML_QUOTE_SINGLE) {
string = string.replace(/�*39;/g, "'");
}
if (!noquotes) {
string = string.replace(/"/g, '"');
}
string = string.replace(/&/g, '&');
return string;
},
/* PHP special chars escape function */
htmlspecialchars: function(string, quote_style, charset, double_encode) {
var optTemp = 0, i = 0, noquotes = false;
if (typeof quote_style === 'undefined' || quote_style === null)
quote_style = 2;
string = string.toString();
if (double_encode !== false)
string = string.replace(/&/g, '&');
string = string.replace(/</g, '<').replace(/>/g, '>');
var OPTS = {
'ENT_NOQUOTES': 0,
'ENT_HTML_QUOTE_SINGLE': 1,
'ENT_HTML_QUOTE_DOUBLE': 2,
'ENT_COMPAT': 2,
'ENT_QUOTES': 3,
'ENT_IGNORE': 4
};
if (quote_style === 0)
noquotes = true;
if (typeof quote_style !== 'number') {
quote_style = [].concat(quote_style);
for (i = 0; i < quote_style.length; i++) {
if (OPTS[quote_style[i]] === 0) {
noquotes = true;
} else if (OPTS[quote_style[i]]) {
optTemp = optTemp | OPTS[quote_style[i]];
}
}
quote_style = optTemp;
}
if (quote_style & OPTS.ENT_HTML_QUOTE_SINGLE) {
string = string.replace(/'/g, ''');
}
if (!noquotes) {
string = string.replace(/"/g, '"');
}
return string;
},
/* replace all occuriences in string */
replaceAll: function(str, find, replace) {
return str.replace(new RegExp(find, 'g'), replace);
},
/* replace json special characters */
replaceJSONSpecialChars: function(text) {
var r = Util.replaceAll(text, "\r", "\\r");
r = Util.replaceAll(r, "\n", "\\n");
r = Util.replaceAll(r, "\"", "\\"+"\"");
/* do not need to escape single quotes */
/*r = Util.replaceAll(r, "\'", "\\"+"\'");*/
return r;
},
/* generate random id value */
generateId: (function() {
function s4() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
return function() {
return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
s4() + '-' + s4() + s4() + s4();
};
})(),
/* return current date and time in format: dd/mm/yyyy hh:mi:ss */
getCurrentDateTime: function() {
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth()+1;
var day = now.getDate();
var hour = now.getHours();
var minute = now.getMinutes();
var second = now.getSeconds();
if(month.toString().length == 1)
var month = '0'+month;
if(day.toString().length == 1)
var day = '0'+day;
if(hour.toString().length == 1)
var hour = '0'+hour;
if(minute.toString().length == 1)
var minute = '0'+minute;
if(second.toString().length == 1)
var second = '0'+second;
var dateTime = day+"/"+month+"/"+year+" "+hour+":"+minute+":"+second;
return dateTime;
},
/* parse current url and return GET parameter by key */
parseGet: function(val, url) {
var link = (url) ? url : location.search;
var result = null, tmp = [];
var items = link.substr(1).split("&");
for (var index = 0; index < items.length; index++) {
tmp = items[index].split("=");
if (tmp[0] === val) result = decodeURIComponent(tmp[1]);
}
return result;
},
/********************************/
/* build html objects functions */
createElement: function(tagname, id, aClass, text, parent) {
var element = document.createElement(tagname);
if (aClass != null && aClass != "")
element.className = aClass;
if (id != null && id != "")
element.id = id;
if (text != null && text != "")
element.innerHTML = text;
if (parent)
parent.appendChild(element);
return element;
},
createImage: function(id, aClass, src, title, parent) {
var img = Util.createElement("img", id, aClass, null, parent);
img.src = src;
//img.title = title;
//img.alt = title;
return img;
},
createButton: function(id, isMini, aClass, text, parent, handler, img) {
var a = Util.createElement("a", id, ((isMini==false)?"button":"minibutton") + " " + aClass, null, parent);
// adding text
var s = Util.createElement("span", null, null, text, a);
// adding image
if (!isMini && img) {
var is = Util.createElement("span", null, null, null, a);
Util.createImage(null, "button_img hMargined_small", img, text, is);
}
// adding handler
if (handler)
Util.addEventListener(a, "click", handler);
// add event listeners for "selected" state
Util.addEventListener(a, "mousedown", function(e) {
if (e.button == 0)
Util.addClass(a, "selected");
});
Util.addEventListener(a, "mouseup", function(e) {
if (e.button == 0)
Util.removeClass(a, "selected");
});
Util.addEventListener(document.body, "mouseup", function(e) {
if (e.button == 0 && Util.hasClass(a, "selected") && e.target != a)
Util.removeClass(a, "selected");
});
return a;
},
createModalButton: function(id, isMini, aClass, text, parent, content) {
var a = Util.createElement("a", id, ((isMini==false)?"button":"minibutton")+" modal-view-parent "+aClass, null, parent);
var s = Util.createElement("span", null, null, text, a);
var is = Util.createElement("span", null, null, null, a);
Util.createImage(null, "button_img hMargined_small", Source.IMG_MB_DOWN, "", is);
a.isModalViewShown = false;
a.modalView = null;
Util.addEventListener(a, "click", function(e) {
if (!a.isModalViewShown) {
a.modalView = ModalView.showModalView(a, true, false, content);
a.isModalViewShown = true;
} else {
ModalView.removeModalView(a);
a.isModalViewShown = false;
a.modalView = null;
}
e.stopPropagation();
});
Util.addEventListener(a, "mousedown", function(e) {
if (e.button == 0)
Util.addClass(a, "selected");
e.stopPropagation();
});
Util.addEventListener(document.body, "mouseup", function(e) {
if (e.button == 0 && Util.hasClass(a, "selected") && e.target != a && a.isModalView == false)
Util.removeClass(a, "selected");
e.stopPropagation();
});
Util.addEventListener(document.body, "click", function(e) {
if (a.isModalViewShown && !Util.isEventForElement(e, a) && !Util.isEventForElement(e, a.modalView)) {
ModalView.removeModalView(a);
a.isModalViewShown = false;
a.modalView = null;
}
e.stopPropagation();
});
return a;
},
createLink: function(id, aClass, text, url, target, parent) {
var a = Util.createElement("a", id, aClass, text, parent);
a.href = url;
a.target = target;
a.setAttribute("tabindex", "-1");
return a;
},
createTextfield: function(id, aClass, placeholder, parent, isPassword) {
var t = Util.createElement("input", id, "gTextInput" + " " + ((aClass)?aClass:""), null, parent);
t.type = "text";
if (placeholder)
t.placeholder = placeholder;
if (isPassword == true) {
t.type = "password";
}
return t;
},
createTextarea: function(id, aClass, placeholder, parent) {
var t = Util.createElement("textarea", id, "gTextarea" + " " + ((aClass)?aClass:""), null, parent);
if (placeholder)
t.placeholder = placeholder;
return t;
}
}
}();
| 8,663
|
https://github.com/stevecaldwell77/Net-Amazon-DynamoDB-Marshaler/blob/master/t/basic.t
|
Github Open Source
|
Open Source
|
Artistic-1.0
| null |
Net-Amazon-DynamoDB-Marshaler
|
stevecaldwell77
|
Perl
|
Code
| 2,295
| 5,970
|
use strict;
use warnings;
use Test::More;
use Test::Deep;
use Test::Fatal;
use boolean;
use IO::Handle;
use Set::Object;
BEGIN { use_ok('Net::Amazon::DynamoDB::Marshaler'); }
# If the value is undef, use Null ('NULL')
sub test_undef() {
my $item = {
user_id => undef,
};
my $item_dynamodb = {
user_id => { NULL => '1' },
};
cmp_deeply(
dynamodb_marshal($item),
$item_dynamodb,
'undef marshalled to NULL',
);
cmp_deeply(
dynamodb_unmarshal($item_dynamodb),
$item,
'NULL unmarshalled to undef',
);
}
# If the value is an empty string, use Null ('NULL')
sub test_empty_string() {
my $item = {
user_id => '',
};
my $item_dynamodb = {
user_id => { NULL => '1' },
};
cmp_deeply(
dynamodb_marshal($item),
$item_dynamodb,
'empty string marshalled to NULL',
);
}
# If the value is a number, use Number ('N').
sub test_number() {
my $item = {
user_id => '1234',
pct_complete => 0.33,
};
my $item_dynamodb = {
user_id => { N => '1234' },
pct_complete => { N => '0.33' },
};
cmp_deeply(
dynamodb_marshal($item),
$item_dynamodb,
'numbers marshalled to N',
);
cmp_deeply(
dynamodb_unmarshal($item_dynamodb),
$item,
q|N's unmarshalled to numbers|,
);
}
# If it's a number, but is too large/precise for DynamoDB, use String('S').
sub test_out_of_range_number() {
my $item = {
ok_large => '1E+125',
ok_small => '1E-129',
ok_small_negative => '-1E-129',
ok_large_negative => '-1E+125',
ok_precise => 1x38,
too_large => '1E+126',
too_small => '1E-130',
too_small_negative => '-1E-130',
too_large_negative => '-1E+126',
too_precise => 1x39,
too_precise2 => '1.'.(1x38),
super_large => '6e3341866116', # this evaluates to 0
};
cmp_deeply(
dynamodb_marshal($item),
{
ok_large => {
N => '1E+125',
},
ok_small => {
N => '1E-129',
},
ok_small_negative => {
N => '-1E-129',
},
ok_large_negative => {
N => '-1E+125',
},
ok_precise => {
N => 1x38,
},
too_large => {
S => '1E+126',
},
too_small => {
S => '1E-130',
},
too_small_negative => {
S => '-1E-130',
},
too_large_negative => {
S => '-1E+126',
},
too_precise => {
S => 1x39,
},
too_precise2 => {
S => '1.'.(1x38),
},
super_large => {
S => '6e3341866116',
}
},
'out-of-bounds numbers marshalled to S',
);
}
# For any other non-reference, use String ('S').
sub test_scalar() {
my $item = {
first_name => 'John',
description => 'John is a very good boy',
};
my $item_dynamodb = {
first_name => { S => 'John' },
description => { S => 'John is a very good boy' },
};
cmp_deeply(
dynamodb_marshal($item),
$item_dynamodb,
'strings marshalled to S',
);
cmp_deeply(
dynamodb_unmarshal($item_dynamodb),
$item,
q|S's unmarshalled to strings|,
);
}
# If the value is an arrayref, use List ('L').
sub test_list() {
my $item = {
tags => [
'complete',
'development',
1234,
],
};
my $item_dynamodb = {
tags => {
L => [
{ S => 'complete' },
{ S => 'development' },
{ N => '1234' },
],
},
};
cmp_deeply(
dynamodb_marshal($item),
$item_dynamodb,
'arrayrefs marshalled to L',
);
cmp_deeply(
dynamodb_unmarshal($item_dynamodb),
$item,
'L unmarshalled to arrayref',
);
}
# If the value is a hashref, use Map ('M').
sub test_map() {
my $item = {
scores => {
math => 95,
english => 80,
},
};
my $item_dynamodb = {
scores => {
M => {
math => { N => '95'},
english => { N => '80'},
},
},
};
cmp_deeply(
dynamodb_marshal($item),
$item_dynamodb,
'hashref marshalled to M',
);
cmp_deeply(
dynamodb_unmarshal($item_dynamodb),
$item,
'M unmarshalled to hashref',
);
}
# If the value isa boolean, use Boolean ('BOOL').
sub test_boolean() {
my $item = {
active => true,
disabled => false,
};
my $item_dynamodb = {
active => { BOOL => '1' },
disabled => { BOOL => '0' },
};
cmp_deeply(
dynamodb_marshal($item),
$item_dynamodb,
'booleans marshalled to BOOL',
);
cmp_deeply(
dynamodb_unmarshal($item_dynamodb),
$item,
'BOOL unmarshalled to boolean',
);
}
# If the value isa Set::Object, use Number Set ('NS') if all members are
# numbers.
sub test_number_set() {
my $item = {
scores => Set::Object->new(5, 7, 25, 32.4),
};
my $item_dynamodb = {
scores => {
NS => [5, 7, 25, 32.4],
},
};
cmp_deeply(
dynamodb_marshal($item),
{
scores => {
NS => set(5, 7, 25, 32.4),
},
},
'Set::Object with numbers marshalled to NS',
);
my $unmarshalled = dynamodb_unmarshal($item_dynamodb);
cmp_deeply(
$unmarshalled,
{
scores => isa('Set::Object'),
},
'NS unmarshalled to Set::Object',
) or return;
cmp_deeply(
[ $unmarshalled->{scores}->elements ],
set(5, 7, 25, 32.4),
'unmarshalled NS has correct elements',
);
}
# If the value isa Set::Object, use String Set ('SS') if one member is not
# a number.
sub test_string_set() {
my $item = {
tags => Set::Object->new(54, 'clothing', 'female'),
};
my $item_dynamodb = {
tags => {
SS => ['54', 'clothing', 'female'],
},
};
cmp_deeply(
dynamodb_marshal($item),
{
tags => {
SS => set('54', 'clothing', 'female'),
},
},
'Set::Object with non-number marshalled to SS',
);
my $unmarshalled = dynamodb_unmarshal($item_dynamodb);
cmp_deeply(
$unmarshalled,
{
tags => isa('Set::Object'),
},
'SS unmarshalled to Set::Object',
) or return;
cmp_deeply(
[ $unmarshalled->{tags}->elements ],
set('54', 'clothing', 'female'),
'unmarshalled SS has correct elements',
);
}
# If the value isa Set::Object, and a member is a reference, throw an error.
sub test_set_error() {
like(
exception {
dynamodb_marshal({
tags => Set::Object->new('large', { foo => 'bar' }),
});
},
qr/Sets can only contain strings and numbers/,
'Error thrown trying to marshall a set with a reference',
);
}
# An un-convertable value value should throw an error.
sub test_other() {
like(
exception {
dynamodb_marshal({
filehandle => IO::Handle->new(),
});
},
qr/unable to marshal value: IO::Handle/,
'Error thrown trying to marshall an unknown value',
);
}
# Test nested data structure
sub test_complex() {
my @codes = (1234, 5678);
my @roles = ('user', 'student');
my $item = {
id => 25,
first_name => 'John',
last_name => 'Doe',
active => true,
admin => false,
codes => Set::Object->new(@codes),
roles => Set::Object->new(@roles),
delete_date => undef,
favorites => ['math', 'physics', 'chemistry'],
relationships => {
teachers => [12, 25],
employees => [],
students => {
past => [11, 45],
current => [6, 32],
}
},
events => [
{
type => 'login',
date => '2017-07-01',
},
{
type => 'purchase',
date => '2017-07-02',
},
],
};
my $item_dynamodb = {
id => { N => '25' },
first_name => { S => 'John' },
last_name => { S => 'Doe' },
active => { BOOL => 1 },
admin => { BOOL => 0 },
codes => { NS => \@codes },
roles => { SS => \@roles },
delete_date => { NULL => 1 },
favorites => {
L => [
{ S => 'math' },
{ S => 'physics' },
{ S => 'chemistry' },
],
},
relationships => {
M => {
students => {
M => {
past => {
L => [
{ N => '11' },
{ N => '45' },
]
},
current => {
L => [
{ N => '6' },
{ N => '32' },
],
},
},
},
teachers => {
L => [
{ N => '12' },
{ N => '25' },
],
},
employees => {
L => [],
},
},
},
events => {
L => [
{
M => {
type => { S => 'login' },
date => { S => '2017-07-01' },
},
},
{
M => {
type => { S => 'purchase' },
date => { S => '2017-07-02' },
},
},
],
},
};
cmp_deeply(
dynamodb_marshal($item),
{
%$item_dynamodb,
codes => { NS => set(@codes) },
roles => { SS => set(@roles) },
},
'nested data structure marshalled correctly',
);
cmp_deeply(
dynamodb_unmarshal($item_dynamodb),
{
%$item,
codes => isa('Set::Object'),
roles => isa('Set::Object'),
},
'nested data structure unmarshalled correctly',
);
}
sub test_force_type_string() {
my $item = {
username => '1234',
email_address => 'john@example.com',
age => 24,
family => undef,
nickname => '',
active => true,
disabled => false,
};
cmp_deeply(
dynamodb_marshal($item),
{
username => { N => '1234' },
email_address => { S => 'john@example.com' },
age => { N => 24 },
family => { NULL => 1 },
nickname => { NULL => 1 },
active => { BOOL => 1 },
disabled => { BOOL => 0 },
},
'attribute marshalled to derived types with no force_type',
);
my $force_type = {
username => 'S',
family => 'S',
nickname => 'S',
active => 'S',
disabled => 'S',
};
cmp_deeply(
dynamodb_marshal($item, force_type => $force_type),
{
username => { S => '1234' },
email_address => { S => 'john@example.com' },
age => { N => 24 },
active => { S => '1' },
disabled => { S => '0' },
},
'attributes marshalled to S via force_type, undefs dropped',
);
}
sub test_force_type_number() {
my $item = {
user_id => '1234',
rank => undef,
age => 'twenty-five',
active => true,
disabled => false,
};
cmp_deeply(
dynamodb_marshal($item),
{
user_id => { N => '1234' },
rank => { NULL => 1 },
age => { S => 'twenty-five' },
active => { BOOL => 1 },
disabled => { BOOL => 0 },
},
'attribute marshalled to derived types with no force_type',
);
my $force_type = {
user_id => 'N',
rank => 'N',
age => 'N',
active => 'N',
disabled => 'N',
};
cmp_deeply(
dynamodb_marshal($item, force_type => $force_type),
{
user_id => { N => '1234' },
active => { N => '1' },
disabled => { N => '0' },
},
'attributes marshalled to N via force_type, undefs dropped',
);
}
sub test_force_type_errors() {
my $item = {
zip_code => '01453',
colors => Set::Object->new(qw(red yellow green)),
ages => Set::Object->new(qw(23 54 42)),
};
cmp_deeply(
dynamodb_marshal($item, force_type => {}),
{
zip_code => { N => '01453' },
colors => { SS => set(qw(red yellow green)) },
ages => { NS => set(qw(23 54 42)) },
},
'attributes look OK without force_type',
);
like(
exception {
dynamodb_marshal($item, force_type => { colors => 'S' });
},
qr/force_type not supported for sets yet/,
'Error thrown trying to apply force_type to string set',
);
like(
exception {
dynamodb_marshal($item, force_type => { ages => 'S' });
},
qr/force_type not supported for sets yet/,
'Error thrown trying to apply force_type to number set',
);
cmp_deeply(
dynamodb_marshal($item, force_type => { zip_code => 'S' }),
{
zip_code => { S => '01453' },
colors => { SS => set(qw(red yellow green)) },
ages => { NS => set(qw(23 54 42)) },
},
'applying force_type to non-set values in item with sets works',
);
like(
exception {
dynamodb_marshal($item, force_type => { ages => 'L' });
},
qr/invalid force_type value for "ages"/,
'Error thrown trying to force_type to an L',
);
}
sub test_force_type_list() {
my $zip_vals = [
'11510',
undef,
'60185',
'01902',
'one-three-six-five-two',
];
my $item = {
zip_codes => $zip_vals,
zip_code_strings => $zip_vals,
zip_code_numbers => $zip_vals,
};
my $force_type = {
zip_code_strings => 'S',
zip_code_numbers => 'N',
};
cmp_deeply(
dynamodb_marshal($item, force_type => $force_type),
{
zip_codes => {
L => [
{ N => '11510' },
{ NULL => 1 },
{ N => '60185' },
{ N => '01902' },
{ S => 'one-three-six-five-two' },
],
},
zip_code_strings => {
L => [
{ S => '11510' },
{ S => '60185' },
{ S => '01902' },
{ S => 'one-three-six-five-two' },
],
},
zip_code_numbers => {
L => [
{ N => '11510' },
{ N => '60185' },
{ N => '01902' },
],
},
},
'force_type applied correctly to list',
);
}
sub test_force_type_map() {
my $item = {
address => {
street => '1234 Main',
apt => '',
zip => '01234',
},
external_ids => {
database1 => '5246',
database2 => {
person_id => 165034,
person_code => 'a23cds5',
}
},
};
my $force_type = {
address => 'S',
external_ids => 'N',
};
cmp_deeply(
dynamodb_marshal($item, force_type => $force_type),
{
address => {
M => {
street => { S => '1234 Main' },
zip => { S => '01234' },
},
},
external_ids => {
M => {
database1 => { N => '5246' },
database2 => {
M => {
person_id => { N => 165034 },
},
},
},
},
},
'force_type applied correctly to map',
);
}
sub test_force_type_complex() {
my $item = {
username => 'jsmith',
details => {
first_name => 'John',
age => 34,
suffix => undef,
roles => [qw(author editor)],
address => {
number => 1234,
street => 'Main St.',
city => 'Los Angeles',
state => 'CA',
},
favorites => [
{
name => '1984',
author => 'George Orwell',
},
{
name => 'Our Mutual Friend',
author => 'Charles Dickens',
},
],
},
};
my $force_type = {
details => 'S',
};
cmp_deeply(
dynamodb_marshal($item, force_type => $force_type),
{
username => { S => 'jsmith' },
details => {
M => {
first_name => { S => 'John' },
age => { S => '34' },
roles => {
L => [
{ S => 'author' },
{ S => 'editor' },
],
},
address => {
M => {
number => { S => '1234' },
street => { S => 'Main St.' },
city => { S => => 'Los Angeles' },
state => { S => 'CA' },
},
},
favorites => {
L => [
{
M => {
name => { S => '1984' },
author => { S => 'George Orwell' },
},
},
{
M => {
name => { S => 'Our Mutual Friend' },
author => { S => 'Charles Dickens' },
},
},
],
},
},
},
},
'force_type applied correctly to map',
);
}
# Workaround for https://github.com/pplu/aws-sdk-perl/issues/79
# Apparently Paws sometimes returns an empty list alongside a scalar value.
# Bug reported in https://github.com/stevecaldwell77/Net-Amazon-DynamoDB-Marshaler/issues/1
sub test_empty_list_bug() {
my $item = {
email_address => 'foo@bar.com',
age => 42,
active => true,
};
my $item_dynamodb = {
email_address => { S => 'foo@bar.com', L => [] },
age => { N => '42', L => [] },
active => { BOOL => '1', L => [] },
};
cmp_deeply(
dynamodb_unmarshal($item_dynamodb),
$item,
'Extra empty lists are ignored',
);
}
test_undef();
test_empty_string();
test_number();
test_out_of_range_number();
test_scalar();
test_list();
test_map();
test_boolean();
test_number_set();
test_string_set();
test_set_error();
test_other();
test_complex();
test_force_type_string();
test_force_type_number();
test_force_type_errors();
test_force_type_list();
test_force_type_map();
test_force_type_complex();
test_empty_list_bug();
done_testing;
| 35,528
|
https://github.com/FutaGuard/python-adguardhome/blob/master/adguardhome/types/filtering/__init__.py
|
Github Open Source
|
Open Source
|
MIT
| null |
python-adguardhome
|
FutaGuard
|
Python
|
Code
| 8
| 17
|
from .check_host import Check_Host
from .status import Status
| 1,247
|
https://github.com/trofi/re2c/blob/master/examples/rust/eof/03_eof_rule.rs
|
Github Open Source
|
Open Source
|
LicenseRef-scancode-warranty-disclaimer, LicenseRef-scancode-public-domain
| 2,022
|
re2c
|
trofi
|
Rust
|
Code
| 385
| 1,090
|
/* Generated by re2c */
// re2rust $INPUT -o $OUTPUT
// Expect a null-terminated string.
fn lex(s: &[u8]) -> isize {
let (mut cur, mut mar) = (0, 0);
let lim = s.len() - 1; // null-terminator not included
let mut count = 0;
'lex: loop {
{
#[allow(unused_assignments)]
let mut yych : u8 = 0;
let mut yystate : usize = 0;
'yyl: loop {
match yystate {
0 => {
yych = unsafe {*s.get_unchecked(cur)};
match yych {
0x20 => {
cur += 1;
yystate = 3;
continue 'yyl;
}
0x27 => {
cur += 1;
yystate = 5;
continue 'yyl;
}
_ => {
if cur >= lim {
yystate = 10;
continue 'yyl;
}
cur += 1;
yystate = 1;
continue 'yyl;
}
}
}
1 => {
yystate = 2;
continue 'yyl;
}
2 => { return -1; }
3 => {
yych = unsafe {*s.get_unchecked(cur)};
match yych {
0x20 => {
cur += 1;
yystate = 3;
continue 'yyl;
}
_ => {
yystate = 4;
continue 'yyl;
}
}
}
4 => { continue 'lex; }
5 => {
mar = cur;
yych = unsafe {*s.get_unchecked(cur)};
if yych >= 0x01 {
yystate = 7;
continue 'yyl;
}
if cur >= lim {
yystate = 2;
continue 'yyl;
}
cur += 1;
yystate = 6;
continue 'yyl;
}
6 => {
yych = unsafe {*s.get_unchecked(cur)};
yystate = 7;
continue 'yyl;
}
7 => {
match yych {
0x27 => {
cur += 1;
yystate = 8;
continue 'yyl;
}
0x5C => {
cur += 1;
yystate = 9;
continue 'yyl;
}
_ => {
if cur >= lim {
yystate = 11;
continue 'yyl;
}
cur += 1;
yystate = 6;
continue 'yyl;
}
}
}
8 => { count += 1; continue 'lex; }
9 => {
yych = unsafe {*s.get_unchecked(cur)};
if yych <= 0x00 {
if cur >= lim {
yystate = 11;
continue 'yyl;
}
cur += 1;
yystate = 6;
continue 'yyl;
}
cur += 1;
yystate = 6;
continue 'yyl;
}
10 => { return count; }
11 => {
cur = mar;
yystate = 2;
continue 'yyl;
}
_ => {
panic!("internal lexer error")
}
}
}
}
}
}
fn main() {
assert_eq!(lex(b"\0"), 0);
assert_eq!(lex(b"'qu\0tes' 'are' 'fine: \\'' \0"), 3);
assert_eq!(lex(b"'unterminated\\'\0"), -1);
}
| 7,534
|
https://github.com/lalilaloe/carbon-ds/blob/master/components/file-uploader.ds.js
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
carbon-ds
|
lalilaloe
|
JavaScript
|
Code
| 614
| 3,820
|
export default {
displayName: "file-uploader",
name: "file-uploader",
homepage: "https://www.carbondesignsystem.com/components/file-uploader"
}
export const variants = [
{
displayName:"file-uploader",
picture:{
src:"./pictures/file-uploader/file-uploader.png",
width:281,
height:172},
snippet:{
html:`
<div class="bx--form-item">
<strong class="bx--file--label">Account
photo</strong>
<p class="bx--label-description">Only .jpg and .png files. 500kb max file size.</p>
<div class="bx--file" data-file data-file-demo-state-manager>
<label for="file-uploader" class="bx--file-browse-btn" role="button" tabindex="0">
<div data-file-drop-container class="bx--file__drop-container">
Drag and drop files here or
upload
<input type="file" class="bx--file-input" id="file-uploader" data-file-uploader
data-target="[data-file-container]" multiple />
</div>
</label>
<div data-file-container class="bx--file-container">
</div>
</div>
</div>
`}},
{
displayName:"example-upload-states",
picture:{
src:"./pictures/file-uploader/example-upload-states.png",
width:320,
height:409},
snippet:{
html:`
<div class="bx--form-item">
<strong class="bx--file--label">Account
photo</strong>
<p class="bx--label-description">Only .jpg and .png files. 500kb max file size.</p>
<div class="bx--file" data-file data-file-demo-state-manager>
<label for="prepopulated-file-uploader" class="bx--file-browse-btn" role="button" tabindex="0">
<div data-file-drop-container class="bx--file__drop-container">
Drag and drop files here or
upload
<input type="file" class="bx--file-input" id="prepopulated-file-uploader" data-file-uploader
data-target="[data-file-container]" multiple />
</div>
</label>
<div data-file-container class="bx--file-container">
<div class="bx--file__selected-file">
<p class="bx--file-filename">Lorem ipsum dolor sit amet consectetur adipisicing elit. Libero vero
sapiente illum reprehenderit molestiae perferendis voluptatem temporibus laudantium ducimus magni voluptatum
veniam, odit nesciunt corporis numquam maxime sunt excepturi sint!</p>
<span data-for="prepopulated-file-uploader" class="bx--file__state-container">
<svg focusable="false" preserveAspectRatio="xMidYMid meet" xmlns="http://www.w3.org/2000/svg" fill="currentColor" class="bx--file-complete" width="16" height="16" viewBox="0 0 16 16" aria-hidden="true"><path d="M8,1C4.1,1,1,4.1,1,8c0,3.9,3.1,7,7,7s7-3.1,7-7C15,4.1,11.9,1,8,1z M7,11L4.3,8.3l0.9-0.8L7,9.3l4-3.9l0.9,0.8L7,11z"></path><path d="M7,11L4.3,8.3l0.9-0.8L7,9.3l4-3.9l0.9,0.8L7,11z" data-icon-path="inner-path" opacity="0"></path></svg>
</span>
</div>
<div class="bx--file__selected-file bx--file__selected-file--invalid" data-invalid>
<p class="bx--file-filename">color.jpeg</p>
<span data-for="prepopulated-file-uploader" class="bx--file__state-container">
<svg focusable="false" preserveAspectRatio="xMidYMid meet" xmlns="http://www.w3.org/2000/svg" fill="currentColor" class="bx--file--invalid" width="16" height="16" viewBox="0 0 16 16" aria-hidden="true"><path d="M8,1C4.2,1,1,4.2,1,8s3.2,7,7,7s7-3.1,7-7S11.9,1,8,1z M7.5,4h1v5h-1C7.5,9,7.5,4,7.5,4z M8,12.2 c-0.4,0-0.8-0.4-0.8-0.8s0.3-0.8,0.8-0.8c0.4,0,0.8,0.4,0.8,0.8S8.4,12.2,8,12.2z"></path><path d="M7.5,4h1v5h-1C7.5,9,7.5,4,7.5,4z M8,12.2c-0.4,0-0.8-0.4-0.8-0.8s0.3-0.8,0.8-0.8 c0.4,0,0.8,0.4,0.8,0.8S8.4,12.2,8,12.2z" data-icon-path="inner-path" opacity="0"></path></svg>
<svg focusable="true" preserveAspectRatio="xMidYMid meet" xmlns="http://www.w3.org/2000/svg" fill="currentColor" aria-label="Remove uploaded file" class="bx--file-close" width="16" height="16" viewBox="0 0 32 32" role="img" tabindex="0"><path d="M24 9.4L22.6 8 16 14.6 9.4 8 8 9.4 14.6 16 8 22.6 9.4 24 16 17.4 22.6 24 24 22.6 17.4 16 24 9.4z"></path></svg>
</span>
<div class="bx--form-requirement">
<div class="bx--form-requirement__title">File size exceeds limit.</div>
<p class="bx--form-requirement__supplement">500 kb max file size. Select a new file and try
again.</p>
</div>
</div>
<div class="bx--file__selected-file">
<p class="bx--file-filename">color.jpeg</p>
<span data-for="prepopulated-file-uploader" class="bx--file__state-container">
<div class="bx--inline-loading__animation">
<div data-inline-loading-spinner="" class="bx--loading bx--loading--small">
<svg class="bx--loading__svg" viewBox="-75 -75 150 150">
<circle class="bx--loading__background" cx="0" cy="0" r="26.8125"></circle>
<circle class="bx--loading__stroke" cx="0" cy="0" r="26.8125"></circle>
</svg>
</div>
</div>
</span>
</div>
</div>
</div>
</div>
`}},
{
displayName:"legacy",
picture:{
src:"./pictures/file-uploader/legacy.png",
width:281,
height:116},
snippet:{
html:`
<div class="bx--form-item">
<strong class="bx--file--label">Account
photo</strong>
<p class="bx--label-description">Only .jpg and .png files. 500kb max file size.</p>
<div class="bx--file" data-file data-file-demo-state-manager>
<label for="legacy-file-uploader" class="bx--file-btn bx--btn bx--btn--primary"
role="button" tabindex="0">Add file</label>
<input type="file" class="bx--file-input" id="legacy-file-uploader" data-file-uploader
data-target="[data-file-container]" multiple />
<div data-file-container data-file-drop-container class="bx--file-container">
</div>
</div>
</div>
`}},
{
displayName:"legacy-with-example-upload-states",
picture:{
src:"./pictures/file-uploader/legacy-with-example-upload-states.png",
width:320,
height:353},
snippet:{
html:`
<div class="bx--form-item">
<strong class="bx--file--label">Account
photo</strong>
<p class="bx--label-description">Only .jpg and .png files. 500kb max file size.</p>
<div class="bx--file" data-file data-file-demo-state-manager>
<label for="legacy-file-uploader" class="bx--file-btn bx--btn bx--btn--primary"
role="button" tabindex="0">Add file</label>
<input type="file" class="bx--file-input" id="legacy-file-uploader" data-file-uploader
data-target="[data-file-container]" multiple />
<div data-file-container data-file-drop-container class="bx--file-container">
<div class="bx--file__selected-file">
<p class="bx--file-filename">Lorem ipsum dolor sit amet consectetur adipisicing elit. Libero vero
sapiente illum reprehenderit molestiae perferendis voluptatem temporibus laudantium ducimus magni voluptatum
veniam, odit nesciunt corporis numquam maxime sunt excepturi sint!</p>
<span data-for="legacy-file-uploader-states" class="bx--file__state-container">
<svg focusable="false" preserveAspectRatio="xMidYMid meet" xmlns="http://www.w3.org/2000/svg" fill="currentColor" class="bx--file-complete" width="16" height="16" viewBox="0 0 16 16" aria-hidden="true"><path d="M8,1C4.1,1,1,4.1,1,8c0,3.9,3.1,7,7,7s7-3.1,7-7C15,4.1,11.9,1,8,1z M7,11L4.3,8.3l0.9-0.8L7,9.3l4-3.9l0.9,0.8L7,11z"></path><path d="M7,11L4.3,8.3l0.9-0.8L7,9.3l4-3.9l0.9,0.8L7,11z" data-icon-path="inner-path" opacity="0"></path></svg>
</span>
</div>
<div class="bx--file__selected-file bx--file__selected-file--invalid" data-invalid>
<p class="bx--file-filename">color.jpeg</p>
<span data-for="legacy-file-uploader-states" class="bx--file__state-container">
<svg focusable="false" preserveAspectRatio="xMidYMid meet" xmlns="http://www.w3.org/2000/svg" fill="currentColor" class="bx--file--invalid" width="16" height="16" viewBox="0 0 16 16" aria-hidden="true"><path d="M8,1C4.2,1,1,4.2,1,8s3.2,7,7,7s7-3.1,7-7S11.9,1,8,1z M7.5,4h1v5h-1C7.5,9,7.5,4,7.5,4z M8,12.2 c-0.4,0-0.8-0.4-0.8-0.8s0.3-0.8,0.8-0.8c0.4,0,0.8,0.4,0.8,0.8S8.4,12.2,8,12.2z"></path><path d="M7.5,4h1v5h-1C7.5,9,7.5,4,7.5,4z M8,12.2c-0.4,0-0.8-0.4-0.8-0.8s0.3-0.8,0.8-0.8 c0.4,0,0.8,0.4,0.8,0.8S8.4,12.2,8,12.2z" data-icon-path="inner-path" opacity="0"></path></svg>
<svg focusable="true" preserveAspectRatio="xMidYMid meet" xmlns="http://www.w3.org/2000/svg" fill="currentColor" aria-label="Remove uploaded file" class="bx--file-close" width="16" height="16" viewBox="0 0 32 32" role="img" tabindex="0"><path d="M24 9.4L22.6 8 16 14.6 9.4 8 8 9.4 14.6 16 8 22.6 9.4 24 16 17.4 22.6 24 24 22.6 17.4 16 24 9.4z"></path></svg>
</span>
<div class="bx--form-requirement">
<div class="bx--form-requirement__title">File size exceeds limit.</div>
<p class="bx--form-requirement__supplement">500 kb max file size. Select a new file and try
again.</p>
</div>
</div>
<div class="bx--file__selected-file">
<p class="bx--file-filename">color.jpeg</p>
<span data-for="legacy-file-uploader-states" class="bx--file__state-container">
<div class="bx--inline-loading__animation">
<div data-inline-loading-spinner="" class="bx--loading bx--loading--small">
<svg class="bx--loading__svg" viewBox="-75 -75 150 150">
<circle class="bx--loading__background" cx="0" cy="0" r="26.8125"></circle>
<circle class="bx--loading__stroke" cx="0" cy="0" r="26.8125"></circle>
</svg>
</div>
</div>
</span>
</div>
</div>
</div>
</div>
`}}
]
| 18,735
|
https://github.com/jagp2097/bb3d/blob/master/app/Policies/CompraPolicy.php
|
Github Open Source
|
Open Source
|
MIT
| null |
bb3d
|
jagp2097
|
PHP
|
Code
| 35
| 119
|
<?php
namespace bagrap\Policies;
use bagrap\User;
use bagrap\Compra;
use bagrap\Pedido;
use Illuminate\Support\Facades\Auth;
use Illuminate\Auth\Access\HandlesAuthorization;
class CompraPolicy
{
use HandlesAuthorization;
public function index(User $user)
{
return Auth::check() && $user->role_id == 2 ? true : false;
}
}
| 26,294
|
https://github.com/ChristopherAsakiewicz/ASKquestions/blob/master/questions-with-classifier-ega-test/src/it/java/com/ibm/watson/app/qaclassifier/selenium/WelcomePageIT.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,019
|
ASKquestions
|
ChristopherAsakiewicz
|
Java
|
Code
| 253
| 762
|
/* Copyright IBM Corp. 2015
*
* 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.ibm.watson.app.qaclassifier.selenium;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import com.ibm.watson.app.qaclassifier.selenium.drivers.Multiplatform;
import com.ibm.watson.app.qaclassifier.selenium.drivers.Multiplatform.InjectDriver;
import com.ibm.watson.app.qaclassifier.selenium.drivers.SeleniumConfig;
@RunWith(Multiplatform.class)
@SeleniumConfig(skipWelcomeScreen = false)
/*
* Test ordering is important because pressingNextButtonDynamic will dismiss the welcome screen.
*/
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class WelcomePageIT {
@InjectDriver
public WebDriver driver;
@Test
public void pageLoadsSuccessfully() throws Exception {
assertEquals("The page title should be correct on load.",
"Showcase App for NL Classifier",
driver.getTitle());
assertTrue("The welcome screen is visible", driver.findElement(By.tagName("welcome")).isDisplayed());
}
@Test
public void pressingNextButtonDynamic() throws InterruptedException {
WebElement screenText = driver.findElement(By.id("screenText"));
WebElement trainMeText = driver.findElement(By.id("trainMeText"));
WebElement actionButton = driver.findElement(By.id("actionButton"));
assertEquals("Proper welcome text is displayed.",
"Hello! I'm Watson. I'm learning to answer questions about the Natural Language Classifier.",
screenText.getText().replaceAll("\\s+", " "));
assertEquals("Proper train me text is displayed.",
"Train me. Let me know whether I provide good answers.",
trainMeText.getText().replaceAll("\\s+", " "));
actionButton.click();
assertTrue("Home page loads after pressing next button second time",
driver.findElements(By.className("home")).size() > 0);
}
}
| 96
|
https://github.com/laddushashavali123/Selenified_Java_Framework/blob/master/src/main/java/com/coveros/selenified/OutputFile.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
Selenified_Java_Framework
|
laddushashavali123
|
Java
|
Code
| 3,240
| 9,020
|
/*
* Copyright 2018 Coveros, Inc.
*
* This file is part of Selenified.
*
* Selenified is 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.coveros.selenified;
import com.coveros.selenified.Browser.BrowserName;
import com.coveros.selenified.application.App;
import com.coveros.selenified.services.Request;
import com.coveros.selenified.services.Response;
import com.coveros.selenified.utilities.TestCase;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.testng.log4testng.Logger;
import java.io.*;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* A custom output file, recording all details of every step performed, both
* actions and app. Actions, expected results, and actual results are captured.
* All asserts have a screenshot taken for traceability, while all failing
* actions also have a screenshot taken to assist with debugging purposes
*
* @author Max Saperstone
* @version 3.0.4
* @lastupdate 1/12/2019
*/
public class OutputFile {
private static final Logger log = Logger.getLogger(OutputFile.class);
public static final String PASSORFAIL = "PASSORFAIL";
private App app = null;
private final String url;
private final String suite;
private final String group;
private final String version;
private final String author;
private final String objectives;
private final String test;
private final String directory;
private final File file;
private final String filename;
private Capabilities capabilities;
private final List<String> screenshots = new ArrayList<>();
// timing of the test
private long startTime;
private long lastTime = 0;
// this will track the step numbers
private int stepNum = 0;
// this will keep track of the errors
private int errors = 0;
// constants
private static final String START_ROW = " <tr>\n";
private static final String START_CELL = " <td>";
private static final String END_CELL = "</td>\n";
private static final String END_ROW = " </tr>\n";
private static final String END_IDIV = "</i></div>";
// the image width for reporting
private static final int EMBEDDED_IMAGE_WIDTH = 300;
/**
* Creates a new instance of the OutputFile, which will serve as the
* detailed log
*
* @param directory - a string of the directory holding the files
* @param test - a string value of the test name, typically the method name
* @param capabilities - the capabilities of the tests that are running
* @param url - the url all of the tests are running against
* @param suite - the test suite associated with the particular test
* @param group - any testng groups associated with the particular test
* @param author - the author associated with the particular test
* @param version - the version of the test suite associated with the particular
* test
* @param objectives - the test objectives, taken from the testng description
*/
@SuppressWarnings("squid:S00107")
public OutputFile(String directory, String test, Capabilities capabilities, String url, String suite, String group,
String author, String version, String objectives) {
this.directory = directory;
this.test = test;
this.capabilities = capabilities;
this.url = url;
this.suite = suite;
this.group = group;
this.author = author;
this.version = version;
this.objectives = objectives;
filename = generateFilename();
file = new File(directory, filename);
setupFile();
setStartTime();
createOutputHeader();
}
/**
* Retrieves the directory in string form of the output files
*
* @return String: filename
*/
public String getDirectory() {
return directory;
}
/**
* Retrieves the filename in string form of the output file
*
* @return String: filename
*/
public String getFileName() {
return filename;
}
/**
* Retrieves the current error count of the test
*
* @return Integer: the number of errors current encountered on the current
* test
*/
public int getErrors() {
return errors;
}
/**
* Increments the current error count of the test by one
*/
public void addError() {
errors++;
}
/**
* Increments the current error count of the test by the provided amount
*
* @param errorsToAdd - the number of errors to add
*/
public void addErrors(int errorsToAdd) {
errors += errorsToAdd;
}
/**
* Determines if a 'real' browser is being used. If the browser is NONE or
* HTMLUNIT it is not considered a real browser
*
* @return Boolean: is the browser a 'real' browser
*/
private boolean isRealBrowser() {
Browser browser = capabilities.getBrowser();
return browser.getName() != BrowserName.NONE && browser.getName() != BrowserName.HTMLUNIT;
}
/**
* Sets the App class which controls all actions within the browser
*
* @param app - the application to be tested, contains all control elements
*/
public void setApp(App app) {
this.app = app;
}
/**
* Generates a unique filename, based on the package, class, method name, and invocation count
*
* @return String: the filename
*/
private String generateFilename() {
String counter = "";
if (capabilities.getInstance() > 0) {
counter = "_" + capabilities.getInstance();
}
return test + counter + ".html";
}
/**
* Creates the directory and file to hold the test output file
*/
private void setupFile() {
if (!new File(directory).exists() && !new File(directory).mkdirs()) {
try {
throw new IOException("Unable to create output directory");
} catch (IOException e) {
log.error(e);
}
}
if (!file.exists()) {
try {
if (!file.createNewFile()) {
throw new IOException("Unable to create output file");
}
} catch (IOException e) {
log.error(e);
}
}
}
/**
* Counts the number of occurrence of a string within a file
*
* @param textToFind - the text to count
* @return Integer: the number of times the text was found in the file
* provided
*/
private int countInstancesOf(String textToFind) {
int count = 0;
try (FileReader fr = new FileReader(file); BufferedReader reader = new BufferedReader(fr)) {
String line;
while ((line = reader.readLine()) != null) {
if (line.contains(textToFind)) {
count++;
}
}
} catch (IOException ioe) {
log.error(ioe);
}
return count;
}
/**
* Replaces an occurrence of a string within a file
*
* @param oldText - the text to be replaced
* @param newText - the text to be replaced with
*/
private void replaceInFile(String oldText, String newText) {
StringBuilder oldContent = new StringBuilder();
try (FileReader fr = new FileReader(file); BufferedReader reader = new BufferedReader(fr)) {
String line;
while ((line = reader.readLine()) != null) {
oldContent.append(line);
oldContent.append("\r\n");
}
} catch (IOException e) {
log.error(e);
}
// replace a word in a file
String newContent = oldContent.toString().replaceAll(oldText, newText);
try (FileWriter writer = new FileWriter(file)) {
writer.write(newContent);
} catch (IOException ioe) {
log.error(ioe);
}
}
/**
* Captures the entire page screen shot, and created an HTML file friendly
* link to place in the output file
*
* @return String: the image link string
*/
public String captureEntirePageScreenshot() {
String imageName = generateImageName();
String imageLink = generateImageLink(imageName);
try {
app.takeScreenshot(imageName);
screenshots.add(imageName);
} catch (Exception e) {
log.error(e);
imageLink = "<br/><b><font class='fail'>No Screenshot Available</font></b>";
}
return imageLink;
}
/**
* Writes an action that was performed out to the output file. If the action
* is considered a failure, and a 'real' browser is being used (not NONE or
* HTMLUNIT), then a screenshot will automatically be taken
*
* @param action - the step that was performed
* @param expectedResult - the result that was expected to occur
* @param actualResult - the result that actually occurred
* @param result - the result of the action
*/
public void recordAction(String action, String expectedResult, String actualResult, Result result) {
stepNum++;
String success = "Check";
String imageLink = "";
if (result == Result.SUCCESS) {
success = "Pass";
}
if (result == Result.FAILURE) {
success = "Fail";
}
if (!"Pass".equals(success) && isRealBrowser()) {
// get a screen shot of the action
imageLink = captureEntirePageScreenshot();
}
// determine time differences
Date currentTime = new Date();
long dTime = currentTime.getTime() - lastTime;
long tTime = currentTime.getTime() - startTime;
lastTime = currentTime.getTime();
try (
// Reopen file
FileWriter fw = new FileWriter(file, true); BufferedWriter out = new BufferedWriter(fw)) {
// record the action
out.write(START_ROW);
out.write(" <td align='center'>" + stepNum + ".</td>\n");
out.write(START_CELL + action + END_CELL);
out.write(START_CELL + expectedResult + END_CELL);
out.write(" <td class='" + result.toString().toLowerCase() + "'>" + actualResult + imageLink + END_CELL);
out.write(START_CELL + dTime + "ms / " + tTime + "ms</td>\n");
out.write(" <td class='" + success.toLowerCase() + "'>" + success + END_CELL);
out.write(END_ROW);
} catch (IOException e) {
log.error(e);
}
}
/**
* Writes to the output file the actual outcome of an event. A screenshot is
* automatically taken to provide tracability for and proof of success or
* failure. This method should only be used after first writing the expected
* result, using the recordExpected method.
*
* @param actualOutcome - what the actual outcome was
* @param result - whether this result is a pass or a failure
*/
public void recordActual(String actualOutcome, Success result) {
try (
// reopen the log file
FileWriter fw = new FileWriter(file, true); BufferedWriter out = new BufferedWriter(fw)) {
// get a screen shot of the action
String imageLink = "";
if (isRealBrowser()) {
imageLink = captureEntirePageScreenshot();
}
// determine time differences
Date currentTime = new Date();
long dTime = currentTime.getTime() - lastTime;
long tTime = currentTime.getTime() - startTime;
lastTime = currentTime.getTime();
// write out the actual outcome
out.write(START_CELL + actualOutcome + imageLink + END_CELL);
out.write(START_CELL + dTime + "ms / " + tTime + "ms</td>\n");
// write out the pass or fail result
if (result == Success.PASS) {
out.write(" <td class='pass'>Pass</td>\n");
} else {
out.write(" <td class='fail'>Fail</td>\n");
}
// end the row
out.write(END_ROW);
} catch (IOException e) {
log.error(e);
}
}
/**
* Writes to the output file the expected outcome of an event. This method
* should always be followed the recordActual method to record what actually
* happened.
*
* @param expectedOutcome - what the expected outcome is
*/
public void recordExpected(String expectedOutcome) {
stepNum++;
try (
// reopen the log file
FileWriter fw = new FileWriter(file, true); BufferedWriter out = new BufferedWriter(fw)) {
// start the row
out.write(START_ROW);
// log the step number
out.write(" <td align='center'>" + stepNum + ".</td>\n");
// leave the step blank as this is simply a check
out.write(" <td> </td>\n");
// write out the expected outcome
out.write(START_CELL + expectedOutcome + END_CELL);
} catch (IOException e) {
log.error(e);
}
}
/**
* Creates the specially formatted output header for the particular test
* case
*/
private void createOutputHeader() {
// setup some constants
String endBracket3 = " }\n";
String endBracket4 = " }\n";
String boldFont = " font-weight:bold;\n";
String swapRow = " </tr><tr>\n";
// Open file
SimpleDateFormat sdf = new SimpleDateFormat("EEEE, MMMM d, yyyy");
SimpleDateFormat stf = new SimpleDateFormat("HH:mm:ss");
String datePart = sdf.format(new Date());
String sTime = stf.format(startTime);
try (FileWriter fw = new FileWriter(file); BufferedWriter out = new BufferedWriter(fw)) {
out.write("<html>\n");
out.write(" <head>\n");
out.write(" <title>" + test + "</title>\n");
out.write(" <style type='text/css'>\n");
out.write(" table {\n");
out.write(" margin-left:auto;margin-right:auto;\n");
out.write(" width:90%;\n");
out.write(" border-collapse:collapse;\n");
out.write(endBracket3);
out.write(" table, td, th {\n");
out.write(" border:1px solid black;\n");
out.write(" padding:0px 10px;\n");
out.write(endBracket3);
out.write(" th {\n");
out.write(" text-align:right;\n");
out.write(endBracket3);
out.write(" td {\n");
out.write(" word-wrap: break-word;\n");
out.write(endBracket3);
out.write(" .warning {\n");
out.write(" color:orange;\n");
out.write(endBracket3);
out.write(" .check {\n");
out.write(" color:orange;\n");
out.write(boldFont);
out.write(endBracket3);
out.write(" .fail {\n");
out.write(" color:red;\n");
out.write(boldFont);
out.write(endBracket3);
out.write(" .pass {\n");
out.write(" color:green;\n");
out.write(boldFont);
out.write(endBracket3);
out.write(" </style>\n");
out.write(" <script type='text/javascript'>\n");
out.write(" function toggleImage( imageName ) {\n");
out.write(" var element = document.getElementById( imageName );\n");
out.write(" element.src = location.href.match(/^.*\\//) + imageName;\n");
out.write(" element.style.display = (element.style.display != 'none' ? 'none' : '' );\n");
out.write(endBracket3);
out.write(" function displayImage( imageName ) {\n");
out.write(" window.open( location.href.match(/^.*\\//) + imageName )\n");
out.write(endBracket3);
out.write(" function toggleVis(col_no, do_show) {\n");
out.write(" var stl;\n");
out.write(" if (do_show) stl = ''\n");
out.write(" else stl = 'none';\n");
out.write(" var tbl = document.getElementById('all_results');\n");
out.write(" var rows = tbl.getElementsByTagName('tr');\n");
out.write(" var cels = rows[0].getElementsByTagName('th')\n");
out.write(" cels[col_no].style.display=stl;\n");
out.write(" for (var row=1; row<rows.length;row++) {\n");
out.write(" var cels = rows[row].getElementsByTagName('td')\n");
out.write(" cels[col_no].style.display=stl;\n");
out.write(endBracket4);
out.write(endBracket3);
out.write(" function getElementsByClassName(oElm, strTagName, strClassName){\n");
out.write(
" var arrElements = (strTagName == '*' && document.all)? document.all : oElm.getElementsByTagName(strTagName);\n");
out.write(" var arrReturnElements = new Array();\n");
out.write(" strClassName = strClassName.replace(/\\-/g, '\\\\-');\n");
out.write(" var oRegExp = new RegExp('(^|\\s)' + strClassName + '(\\s|$)');\n");
out.write(" var oElement;\n");
out.write(" for(var i=0; i<arrElements.length; i++){\n");
out.write(" oElement = arrElements[i];\n");
out.write(" if(oRegExp.test(oElement.className)){\n");
out.write(" arrReturnElements.push(oElement);\n");
out.write(" }\n");
out.write(endBracket4);
out.write(" return (arrReturnElements)\n");
out.write(endBracket3);
out.write(" function fixImages( imageName ) {\n");
out.write(" top.document.title = document.title;\n");
out.write(" allImgIcons = getElementsByClassName( document, 'img', 'imgIcon' );\n");
out.write(" for( var element in allImgIcons ) {\n");
out.write(" element.src = location.href.match(/^.*\\//) + element.src;\n");
out.write(endBracket4);
out.write(endBracket3);
out.write(" </script>\n");
out.write(" </head>\n");
out.write(" <body onLoad='fixImages()'>\n");
out.write(" <table>\n");
out.write(START_ROW);
out.write(" <th bgcolor='lightblue'><font size='5'>Test</font></th>\n");
out.write(" <td bgcolor='lightblue' colspan=3><font size='5'>" + test + " </font></td>\n");
out.write(swapRow);
out.write(" <th>Tester</th>\n");
out.write(" <td>Automated</td>\n");
out.write(" <th>Version</th>\n");
out.write(START_CELL + this.version + END_CELL);
out.write(swapRow);
out.write(" <th>Author</th>\n");
out.write(START_CELL + this.author + END_CELL);
out.write(" <th rowspan='2'>Test Run Time</th>\n");
out.write(" <td rowspan='2'>\n");
out.write(" Start:\t" + sTime + " <br/>\n");
out.write(" End:\tTIMEFINISHED <br/>\n");
out.write(" Run Time:\tRUNTIME \n");
out.write(" </td>\n ");
out.write(swapRow);
out.write(" <th>Date Tested</th>\n");
out.write(START_CELL + datePart + END_CELL);
out.write(swapRow);
out.write(" <th>URL Under Test</th>\n");
out.write(START_CELL + "<a href='" + url + "'>" + url + "</a>" + END_CELL);
out.write(" <th>Browser</th>\n");
out.write(START_CELL + capabilities.getBrowser().getDetails() + END_CELL);
out.write(swapRow);
out.write(" <th>Testing Group</th>\n");
out.write(START_CELL + group + END_CELL);
out.write(" <th>Testing Suite</th>\n");
out.write(START_CELL + suite + END_CELL);
out.write(swapRow);
out.write(" <th>Test Objectives</th>\n");
out.write(" <td colspan=3>" + objectives + END_CELL);
out.write(swapRow);
out.write(" <th>Overall Results</th>\n");
out.write(" <td colspan=3 style='padding: 0px;'>\n");
out.write(" <table style='width: 100%;'><tr>\n");
out.write(" <td font-size='big' rowspan=2>PASSORFAIL</td>\n");
out.write(" <td><b>Steps Performed</b></td><td><b>Steps Passed</b></td>" +
"<td><b>Steps Failed</b></td>\n");
out.write(" </tr><tr>\n");
out.write(" <td>STEPSPERFORMED</td><td>STEPSPASSED</td><td>STEPSFAILED</td>\n");
out.write(" </tr></table>\n");
out.write(" </td>\n");
out.write(swapRow);
out.write(" <th>View Results</th>\n");
out.write(" <td colspan=3>\n");
out.write(" <input type=checkbox name='step' onclick='toggleVis(0,this.checked)' checked>Step\n");
out.write(" <input type=checkbox name='action' onclick='toggleVis(1,this.checked)' checked>Action \n");
out.write(
" <input type=checkbox name='expected' onclick='toggleVis(2,this.checked)' checked>Expected Results \n");
out.write(
" <input type=checkbox name='actual' onclick='toggleVis(3,this.checked)' checked>Actual Results \n");
out.write(
" <input type=checkbox name='times' onclick='toggleVis(4,this.checked)' checked>Step Times \n");
out.write(" <input type=checkbox name='result' onclick='toggleVis(5,this.checked)' checked>Results\n");
out.write(" </td>\n");
out.write(END_ROW);
out.write(" </table>\n");
out.write(" <table id='all_results'>\n");
out.write(START_ROW);
out.write(" <th align='center'>Step</th><th style='text-align:center'>Action</th>" +
"<th style='text-align:center'>Expected Result</th>" +
"<th style='text-align:center'>Actual Result</th>" +
"<th style='text-align:center'>Step Times</th><th style='text-align:center'>Pass/Fail</th>\n");
out.write(END_ROW);
} catch (IOException e) {
log.error(e);
}
}
/**
* Ends and closes the output test file. The HTML is properly ended, and the
* file is analyzed to determine if the test passed or failed, and that
* information is updated, along with the overall timing of the test
*/
public void finalizeOutputFile(int testStatus) {
// reopen the file
try (FileWriter fw = new FileWriter(file, true); BufferedWriter out = new BufferedWriter(fw)) {
out.write(" </table>\n");
out.write(" </body>\n");
out.write("</html>\n");
} catch (IOException e) {
log.error(e);
}
// Record the metrics
int passes = countInstancesOf("<td class='pass'>Pass</td>");
int fails = countInstancesOf("<td class='fail'>Fail</td>");
replaceInFile("STEPSPERFORMED", Integer.toString(fails + passes));
replaceInFile("STEPSPASSED", Integer.toString(passes));
replaceInFile("STEPSFAILED", Integer.toString(fails));
if (fails == 0 && errors == 0 && testStatus == 1) {
replaceInFile(PASSORFAIL, "<font size='+2' class='pass'><b>SUCCESS</b></font>");
} else if (fails == 0 && errors == 0) {
replaceInFile(PASSORFAIL, "<font size='+2' class='warning'><b>" + Result.values()[testStatus] + "</b></font>");
} else {
replaceInFile(PASSORFAIL, "<font size='+2' class='fail'><b>FAILURE</b></font>");
}
// record the time
SimpleDateFormat stf = new SimpleDateFormat("HH:mm:ss");
String timeNow = stf.format(new Date());
long totalTime = (new Date()).getTime() - startTime;
long time = totalTime / 1000;
StringBuilder seconds = new StringBuilder(Integer.toString((int) (time % 60)));
StringBuilder minutes = new StringBuilder(Integer.toString((int) ((time % 3600) / 60)));
StringBuilder hours = new StringBuilder(Integer.toString((int) (time / 3600)));
for (int i = 0; i < 2; i++) {
if (seconds.length() < 2) {
seconds.insert(0, "0");
}
if (minutes.length() < 2) {
minutes.insert(0, "0");
}
if (hours.length() < 2) {
hours.insert(0, "0");
}
}
replaceInFile("RUNTIME", hours + ":" + minutes + ":" + seconds);
replaceInFile("TIMEFINISHED", timeNow);
if (System.getProperty("packageResults") != null && "true".equals(System.getProperty("packageResults"))) {
packageTestResults();
}
}
/**
* Packages the test result file along with screenshots into a zip file
*/
private void packageTestResults() {
File f = new File(directory, filename + "_RESULTS.zip");
try (ZipOutputStream out = new ZipOutputStream(new FileOutputStream(f))) {
// Add html results to zip file
ZipEntry e = new ZipEntry(filename);
out.putNextEntry(e);
Path path = FileSystems.getDefault().getPath(directory, filename);
byte[] data = Files.readAllBytes(path);
out.write(data, 0, data.length);
out.closeEntry();
// Add screenshots to zip file
for (String screenshot : screenshots) {
ZipEntry s = new ZipEntry(screenshot.replaceAll(".*\\/", ""));
out.putNextEntry(s);
Path screenPath = FileSystems.getDefault().getPath(screenshot);
byte[] screenData = Files.readAllBytes(screenPath);
out.write(screenData, 0, screenData.length);
out.closeEntry();
}
} catch (IOException e) {
log.error(e);
}
}
/**
* Generates the HTML friendly link for the image
*
* @param imageName the name of the image being embedded
* @return String: the link for the image which can be written out to the
* html file
*/
private String generateImageLink(String imageName) {
String imageLink = "<br/>";
if (imageName.length() >= directory.length() + 1) {
imageLink += "<a href='javascript:void(0)' onclick='toggleImage(\"" +
imageName.substring(directory.length() + 1) + "\")'>Toggle Screenshot Thumbnail</a>";
imageLink += " <a href='javascript:void(0)' onclick='displayImage(\"" +
imageName.substring(directory.length() + 1) + "\")'>View Screenshot Fullscreen</a>";
imageLink += "<br/><img id='" + imageName.substring(directory.length() + 1) + "' border='1px' src='" +
imageName.substring(directory.length() + 1) + "' width='" + EMBEDDED_IMAGE_WIDTH +
"px' style='display:none;'>";
} else {
imageLink += "<b><font class='fail'>No Image Preview</font></b>";
}
return imageLink;
}
/**
* Generates a unique image name
*
* @return String: the name of the image file as a PNG
*/
private String generateImageName() {
long timeInSeconds = new Date().getTime();
String randomChars = TestCase.getRandomString(10);
return directory + "/" + timeInSeconds + "_" + randomChars + ".png";
}
/**
* Determines the current time and sets the 'last time' to the current time
*/
private void setStartTime() {
startTime = (new Date()).getTime();
lastTime = startTime;
}
///////////////////////////////////////////////////////////////////
// some comparisons for our services
///////////////////////////////////////////////////////////////////
/**
* Formats the request parameters to be 'prettily' printed out in HTML
*
* @param params - the parameters to be formatted. Either a JSON object, or a
* hashmap
* @return String: a 'prettily' formatted string that is HTML safe to output
*/
public String outputRequestProperties(Request params, File file) {
StringBuilder output = new StringBuilder();
if (params != null && params.isPayload()) {
output.append("<br/> with parameters: ");
output.append("<div><i>");
if (params.getJsonPayload() != null) {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
output.append(gson.toJson(params.getJsonPayload()));
}
if (params.getMultipartData() != null) {
for (Map.Entry<String, Object> entry : params.getMultipartData().entrySet()) {
output.append("<div>");
output.append(String.valueOf(entry.getKey()));
output.append(" : ");
output.append(String.valueOf(entry.getValue()));
output.append("</div>");
}
}
output.append(END_IDIV);
}
if (file != null) {
output.append("<div> with file: <i>").append(file.getAbsoluteFile()).append(END_IDIV);
}
return formatHTML(output.toString());
}
/**
* Formats the response parameters to be 'prettily' printed out in HTML
*
* @param response - the http response to be formatted.
* @return String: a 'prettily' formatted string that is HTML safe to output
*/
public String formatResponse(Response response) {
if (response == null) {
return "";
}
StringBuilder output = new StringBuilder();
if (response.isData()) {
output.append("<div><i>");
Gson gson = new GsonBuilder().setPrettyPrinting().create();
if (response.getArrayData() != null) {
output.append(gson.toJson(response.getArrayData()));
}
if (response.getObjectData() != null) {
output.append(gson.toJson(response.getObjectData()));
}
output.append(END_IDIV);
}
return formatHTML(output.toString());
}
/**
* Takes a generic string and replaces spaces and new lines with HTML
* friendly pieces for display purposes
*
* @param string : the regular string to be formatted into an HTML pretty
* rendering string
* @return String : the replaced result
*/
public String formatHTML(String string) {
if (string == null) {
return "";
}
return string.replaceAll(" ", " ").replaceAll("\n", "<br/>");
}
///////////////////////////////////////////////////////////////////
// this enum will be for a pass/fail
///////////////////////////////////////////////////////////////////
/**
* Determines if the tests pass or fail
*
* @author Max Saperstone
*/
public enum Success {
PASS, FAIL;
int errors;
static {
PASS.errors = 0;
FAIL.errors = 1;
}
/**
* Retrieves the errors associated with the enumeration
*
* @return Integer: the errors associated with the enumeration
*/
public int getErrors() {
return this.errors;
}
}
/**
* Gives status for each test step
*
* @author Max Saperstone
*/
public enum Result {
WARNING, SUCCESS, FAILURE, SKIPPED
}
}
| 50,513
|
https://github.com/nagaseshadri/puppet-vagrant-oc11.1/blob/master/modules/custom/sqldeveloper/lib/facter/sqldeveloper_installed.rb
|
Github Open Source
|
Open Source
|
MIT
| 2,018
|
puppet-vagrant-oc11.1
|
nagaseshadri
|
Ruby
|
Code
| 16
| 73
|
require 'facter'
Facter.add(:sqldeveloper_installed) do
setcode do
if File.exist?Facter.value(:root_install_directory) + '/sqldeveloper/sqldeveloper.sh'
true
else
false
end
end
end
| 18,536
|
https://github.com/jscalvo16/Php-Project-Up/blob/master/resources/views/autenticacion/cambiarContrasena.blade.php
|
Github Open Source
|
Open Source
|
MIT
| null |
Php-Project-Up
|
jscalvo16
|
PHP
|
Code
| 211
| 971
|
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="utf-8">
<title>ProjectUp</title>
<meta content="width=device-width, initial-scale=1.0" name="viewport">
<meta content="" name="keywords">
<meta content="" name="description">
<meta content="Author" name="SENA">
<!-- Favicons -->
<link href=" {{ asset('assets/img/iconP.png') }} " rel="icon">
<!-- Google Fonts -->
<link href="https://fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,700,700i|Raleway:300,400,500,700,800|Montserrat:300,400,700" rel="stylesheet">
<!-- Libraries CSS Files -->
<link rel="stylesheet" href=" {{ asset('lib/font-awesome/css/font-awesome.min.css') }} ">
<link rel="stylesheet" href=" {{ asset('lib/animate/animate.min.css') }} ">
<link rel="stylesheet" href=" {{ asset('lib/ionicons/css/ionicons.min.css') }} ">
<link rel="stylesheet" href=" {{ asset('lib/owlcarousel/assets/owl.carousel.min.css') }} ">
<link rel="stylesheet" href=" {{ asset('lib/magnific-popup/magnific-popup.css') }} ">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.1/css/all.min.css">
<!-- Main Stylesheet File -->
<link href=" {{ asset('css/login2.css') }} " rel="stylesheet">
<style>
.div strong {
color: red;
position: relative;
top: 53px;
float: left;
}
</style>
</head>
<body>
<div class="container">
<div class="login-content" style="margin-left: 425px">
<form action="{{url('cambiarContrasena/'. $usuario->IdUsua)}}" method="POST" >
@csrf
<p style="text-align: center">
<img class="loginImg" src=" {{ asset('assets/img/Logo_login.png') }} " alt="Logo PROJECTUP">
</p>
<br>
<h3 class="title">Cambio de password</h3>
<br>
<!-- Input contraseña -->
<div class="input-div one">
<div class="i">
<i class="fas fa-unlock-alt"></i>
</div>
<div class="div">
<h5>Contraseña</h5>
<input type="password" class="input" id="usuario" name="password" value="{{old('password')}}">
<strong> {{$errors->first('password')}} </strong>
</div>
</div>
<!-- Input confirmar contraseña -->
<div class="input-div one">
<div class="i">
<i class="fas fa-unlock-alt"></i>
</div>
<div class="div">
<h5>Confirmar contraseña</h5>
<input type="password" class="input" id="usuario" name="password_confirmation">
<strong> {{$errors->first('password')}} </strong>
</div>
</div>
<br>
<input type="submit" class="btn" value="Cambiar">
</form>
</div>
</div>
<script src=" {{ asset('js/formLogin.js') }} "></script>
</body>
</html>
| 5,476
|
https://github.com/gdelfiol/ClinicalKnowledgeSummary/blob/master/CKSapplication/src/app/clickTracker.directive.ts
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
ClinicalKnowledgeSummary
|
gdelfiol
|
TypeScript
|
Code
| 79
| 245
|
import { Directive, ElementRef, HostListener } from '@angular/core';
import {DataService} from './services/data.service';
@Directive({
selector: '[clickTracker]'
})
export class ClickTrackerDirective {
constructor(public element: ElementRef, public dataService: DataService) { }
@HostListener('click', ['$event'])
elemClicked() {
const pathID = sessionStorage.getItem('pathId');
const sessId = sessionStorage.getItem('uuid');
const name = this.element.nativeElement;
let value;
if (name.id) {
value = name.id;
} else {
value = name.className;
}
const now = Date.now();
this.dataService.postFreq({ 'clickedItem': value, 'path': pathID, 'app': 'CKS', 'sessId': sessId, 'time': now})
.subscribe(res => res);
}
}
| 40,743
|
https://github.com/EduCordova/phpApiRest/blob/master/database/factories/TransactionFactory.php
|
Github Open Source
|
Open Source
|
MIT
| 2,018
|
phpApiRest
|
EduCordova
|
PHP
|
Code
| 38
| 164
|
<?php
use App\Transaction;
use App\Seller;
use App\User;
use Faker\Generator as Faker;
$factory->define(Transaction::class, function (Faker $faker) {
$vendedor = Seller::has('products')->get()->random();
$comprador = User::all()->except($vendedor->id)->random();
return [
// 'name' => $faker->word,
'quality' => $faker->numberBetween(1,3),
'buyer_id' => $comprador->id,
'product_id' =>$vendedor->products->random()->id,
];
});
| 25,226
|
https://github.com/GrigoryTsuryev/getpack/blob/master/src/schemas/delivery.ts
|
Github Open Source
|
Open Source
|
MIT
| null |
getpack
|
GrigoryTsuryev
|
TypeScript
|
Code
| 56
| 164
|
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';
export type DeliveryDocument = Delivery & Document;
@Schema()
export class Delivery {
@Prop()
id: number;
@Prop()
packageSize: number;
@Prop()
cost: number;
@Prop()
description: string;
@Prop()
date: string;
@Prop()
courier: string;
@Prop()
sender: string;
@Prop()
assigned: boolean;
}
export const DeliverySchema = SchemaFactory.createForClass(Delivery);
| 24,601
|
https://github.com/BearerPipelineTest/botbuilder-dotnet/blob/master/libraries/Microsoft.Bot.Builder.AI.QnA/Models/KnowledgeBaseAnswerSpan.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
botbuilder-dotnet
|
BearerPipelineTest
|
C#
|
Code
| 172
| 366
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using Newtonsoft.Json;
namespace Microsoft.Bot.Builder.AI.QnA.Models
{
/// <summary>
/// Gets or sets precise answer of query from Knowledge Base.
/// </summary>
internal class KnowledgeBaseAnswerSpan
{
/// <summary>
/// Gets or sets the precise answer text.
/// </summary>
/// <value>
/// The precise answer text.
/// </value>
[JsonProperty("text")]
public string Text { get; set; }
/// <summary>
/// Gets or sets the confidence in precise answer.
/// </summary>
/// <value>
/// The confidence in precise answer.
/// </value>
[JsonProperty("confidenceScore")]
public float ConfidenceScore { get; set; }
/// <summary>
/// Gets or sets the precise answer startIndex in long answer.
/// </summary>
/// <value>
/// The precise answer startIndex in long answer.
/// </value>
[JsonProperty("offset")]
public int Offset { get; set; }
/// <summary>
/// Gets or sets the precise answer length in long answer.
/// </summary>
/// <value>
/// The precise answer length in long answer.
/// </value>
[JsonProperty("length")]
public int Length { get; set; }
}
}
| 17,304
|
https://github.com/colombod/corefxlab/blob/master/src/ALCProxy.Communication/ALCClient.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
corefxlab
|
colombod
|
C#
|
Code
| 959
| 2,197
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.Loader;
namespace ALCProxy.Communication
{
internal delegate object ServerCall(MethodInfo info, IList<object> args, IList<Type> types);
/// <summary>
/// This currently is designed to only work in-process
/// </summary>
public abstract class ALCClient : IProxyClient
{
protected object _server; // Can't make this an IServerObject directly due to the type-loading barrier
protected string _serverTypeName;
protected Type _intType;
internal ServerCall _serverDelegate;
protected Type _serverType;
#if DEBUG
private StackTrace _stackTrace; // Holds information for debugging purposes
#endif
/// <summary>
/// ALCClient gets the information that is needed to set up the ALCServer in the target ALC
/// </summary>
/// <exception cref="ArgumentNullException">Throws if missing an interface type/server type to work with or a server name</exception>
public ALCClient(Type interfaceType, string serverName, Type serverType)
{
if ((interfaceType ?? serverType) == null || serverName == null)
throw new ArgumentNullException();
_serverType = serverType;
_intType = interfaceType;
_serverTypeName = serverName;
#if DEBUG
_stackTrace = new StackTrace(true);
#endif
}
private Type FindTypeInAssembly(string typeName, Assembly a)
{
//find the type we're looking for
Type t = a.GetType(typeName);
if (t == null)
{
t = a.GetType(a.GetName().Name + "." + typeName);
if (t == null)
{
throw new TypeLoadException("Proxy creation exception: No valid type while searching for the given type: " + typeName + " || " + a.GetName().Name + "." + typeName);
}
}
return t;
}
/// <summary>
/// Creates the link between the client and the server, while also passing in all the information to the server for setup
/// </summary>
/// <param name="alc">The target AssemblyLoadContext</param>
/// <param name="typeName">Name of the proxied type</param>
/// <param name="assemblyName">path of the assembly to the type</param>
/// <param name="genericTypes">any generics that we need the proxy to work with</param>
/// <exception cref="ArgumentNullException">Throws if we're missing either the given ALC, the AssemblyName to load, or the type to load from the assembly</exception>
public void SetUpServer(AssemblyLoadContext alc, string typeName, AssemblyName assemblyName, object[] constructorParams, Type[] genericTypes)
{
if (alc == null || typeName == null || assemblyName == null)
throw new ArgumentNullException();
if (genericTypes == null)
genericTypes = new Type[] { };
if (constructorParams == null)
constructorParams = new object[] { };
Assembly a = alc.LoadFromAssemblyName(assemblyName);
// Find the type we're going to proxy inside the loaded assembly
Type objType = FindTypeInAssembly(typeName, a);
// Get the interface of the object so we can set it as the server's generic type
Type interfaceType = FindInterfaceType(_intType.Name, objType);
if (interfaceType.IsGenericType)
{
interfaceType = interfaceType.MakeGenericType(genericTypes.Select(x => ConvertType(x, alc)).ToArray());
}
// Load *this* (ALCProxy.Communication) assembly into the ALC so we can get the server into the ALC
Assembly serverAssembly = alc.LoadFromAssemblyName(Assembly.GetAssembly(_serverType).GetName());
// Get the server type, then make it generic with the interface we're using
Type serverType = FindTypeInAssembly(_serverTypeName, serverAssembly).MakeGenericType(interfaceType);
// Give the client its reference to the server
SerializeParameters(constructorParams, out IList<object> serializedConstArgs, out IList<Type> argTypes);
ConstructorInfo ci = serverType.GetConstructor(
new Type[] { typeof(Type), typeof(Type[]), typeof(IList<object>), typeof(IList<Type>) });
_server = ci.Invoke(new object[] { objType, genericTypes, serializedConstArgs.ToList(), argTypes });
_serverDelegate = (ServerCall)Delegate.CreateDelegate(typeof(ServerCall), _server, serverType.GetMethod("CallObject"));
// Attach to the unloading event
alc.Unloading += UnloadClient;
}
/// <summary>
/// Takes a Type that's been passed from the user ALC, and loads it into the current ALC for use.
/// </summary>
private Type ConvertType(Type toConvert, AssemblyLoadContext currentLoadContext)
{
AssemblyName assemblyName = Assembly.GetAssembly(toConvert).GetName();
return currentLoadContext.LoadFromAssemblyName(assemblyName).GetType(toConvert.FullName);
}
private Type FindInterfaceType(string interfaceName, Type objType)
{
Type[] interfaces;
if (objType.IsGenericType)
interfaces = objType.GetGenericTypeDefinition().GetInterfaces();
else
interfaces = objType.GetInterfaces();
// Type[] interfaces = objType.GetInterfaces();
foreach(Type t in interfaces)
{
if (t.Name.Equals(interfaceName))
return GetModType(t.Name, t.Module);
}
throw new Exception("Interface not found, error");
}
private Type GetModType(string name, Module m)
{
foreach (Type t in m.GetTypes())
{
if (t.Name.Equals(name))
return t;
}
throw new Exception("Type not found in module");
}
private void UnloadClient(object sender)
{
_server = null; // Unload only removes the reference to the proxy, doesn't do anything else, since the ALCs need to be cleaned up by the users before the GC can collect.
_serverDelegate = null;
}
/// <summary>
/// Converts each argument into a serialized version of the object so it can be sent over in a call-by-value fashion
/// </summary>
/// <param name="method">the methodInfo of the target method</param>
/// <param name="args">the current objects assigned as arguments to send</param>
/// <exception cref="ArgumentNullException">Throws if we're missing a method to call</exception>
/// <exception cref="InvalidOperationException">Throws if the client doesn't have a link to a server, usually due to the ALC being unloaded</exception>
/// <returns>the Deserialized return object to give back to the proxy</returns>
public object SendMethod(MethodInfo method, object[] args)
{
if (method == null)
throw new ArgumentNullException();
if (_serverDelegate == null) //We've called the ALC unload, so the proxy has been cut off
throw new InvalidOperationException("Error in ALCClient: Proxy has been unloaded, or communication server was never set up correctly");
if (args == null)
args = new object[] { };
SerializeParameters(args, out IList<object> streams, out IList<Type> argTypes);
object encryptedReturn = _serverDelegate( method, streams, argTypes );
return DeserializeReturnType(encryptedReturn, method.ReturnType);
}
protected void SerializeParameters(object[] arguments, out IList<object> serializedArgs, out IList<Type> argTypes)
{
argTypes = new List<Type>();
serializedArgs = new List<object>();
for (int i = 0; i < arguments.Length; i++)
{
object arg = arguments[i];
Type t = arg.GetType();
//Serialize the argument
object serialArg = SerializeParameter(arg, t);
serializedArgs.Add(serialArg);
argTypes.Add(t);
}
}
/// <summary>
/// Serializes an object that's being used as a parameter for a method call. Will be sent to the ALCServer to be deserialized and used in the method call.
/// </summary>
protected abstract object SerializeParameter(object param, Type paramType);
/// <summary>
/// Deserializes the object that is returned from the ALCServer once a method call is finished.
/// </summary>
protected abstract object DeserializeReturnType(object returnedObject, Type returnType);
}
}
| 310
|
https://github.com/bhenriq-souza/GraphQL-Booking-App-API/blob/master/database/mongo/index.js
|
Github Open Source
|
Open Source
|
MIT
| null |
GraphQL-Booking-App-API
|
bhenriq-souza
|
JavaScript
|
Code
| 92
| 285
|
const { Logger } = require('../../utils');
class MongooseConnection {
/**
* Initializes the Mongoose Connection Class
*
* @param {*} mongoose
* @param {*} config
*/
constructor(mongoose, config) {
this.mongoose = mongoose;
this.config = config;
this.logger = Logger.createLogger('info');
}
/**
* Creates a Mongoose Connection
*
*/
async connect() {
try {
const {
user,
password,
host,
database,
config,
} = this.config;
const connectionString = `mongodb://${user}:${password}@${host}/${database}${config}`;
const ret = await this.mongoose.connect(connectionString, { useNewUrlParser: true });
this.logger.info(`Connected to database ${ret.connection.db.databaseName}`);
} catch (err) {
this.logger.warn(err);
throw err;
}
}
}
module.exports = MongooseConnection;
| 24,757
|
https://github.com/IgnoredAmbience/test262/blob/master/implementation-contributed/javascriptcore/stress/scoped-arguments-test.js
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| null |
test262
|
IgnoredAmbience
|
JavaScript
|
Code
| 54
| 136
|
function foo(a)
{
(function() { return a; })();
return [arguments[0], arguments];
}
noInline(foo);
for (var i = 0; i < 10000; ++i) {
var result = foo(42);
if (result[0] != 42)
throw new Error("result[0] is not 42: " + result[0]);
if (result[1][0] != 42)
throw new Error("result[1][0] is not 42: " + result[1][0]);
}
| 37,748
|
https://github.com/suryajayantara/InternCompetitionElectro/blob/master/app/InstalasiPenerangan.php
|
Github Open Source
|
Open Source
|
MIT
| null |
InternCompetitionElectro
|
suryajayantara
|
PHP
|
Code
| 15
| 77
|
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class InstalasiPenerangan extends Model
{
protected $fillable = ['nama','nim','kelas','no_telpon','konsumsi','prodi','semester','id_line','status_bayar'];
}
| 18,419
|
https://github.com/openforis/calc/blob/master/calc-core/src/main/java/org/openforis/calc/chain/export/BaseUnitWeightROutputScript.java
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
calc
|
openforis
|
Java
|
Code
| 106
| 439
|
package org.openforis.calc.chain.export;
import org.apache.commons.lang3.StringUtils;
import org.openforis.calc.engine.Workspace;
import org.openforis.calc.metadata.Entity;
import org.openforis.calc.metadata.SamplingDesign;
import org.openforis.calc.r.RScript;
import org.openforis.calc.r.RVariable;
import org.openforis.calc.r.SetValue;
import org.openforis.calc.schema.FactTable;
/**
*
* @author M. Togna
*
*/
public class BaseUnitWeightROutputScript extends ROutputScript {
public BaseUnitWeightROutputScript(int index , Workspace workspace) {
super( "base-unit-weight.R", createScript(workspace), Type.USER , index );
}
private static RScript createScript(Workspace workspace) {
RScript r = r();
if( workspace.hasSamplingDesign() ){
SamplingDesign samplingDesign = workspace.getSamplingDesign();
String weightScript = samplingDesign.getSamplingUnitWeightScript();
if( StringUtils.isBlank(weightScript) ){
Entity entity = samplingDesign.getSamplingUnit();
RVariable weightVar = r().variable( entity.getName(), FactTable.WEIGHT_COLUMN );
SetValue setWeight = r().setValue( weightVar, r().rScript("NA") );
r.addScript( setWeight );
} else {
r.addScript( r().rScript( weightScript ) );
}
}
return r;
}
}
| 25,054
|
https://github.com/ima-tech/pristine-ts/blob/master/packages/common/src/interfaces/dynamic-configuration-resolver.interface.ts
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
pristine-ts
|
ima-tech
|
TypeScript
|
Code
| 118
| 190
|
import {InjectionToken} from "tsyringe";
/**
* This interface specifies what a DynamicConfigurationResolver should look like.
* A DynamicConfigurationResolver is used in configurations when you need an initialized instance of a service to resolve the value of the configuration.
* Beware that the service resolved by the injectionToken needs to be registered in the dependency container before.
*/
export interface DynamicConfigurationResolverInterface<T> {
/**
* The injection token for the service that needs to be resolved
*/
injectionToken?: InjectionToken;
/**
* The function that needs to be executed to resolve the value for the configuration.
* @param injectedInstance The initialized instance of the service resolved with the injection token.
*/
dynamicResolve: (injectedInstance?: T) => Promise<string | number | boolean>;
}
| 42,635
|
https://github.com/jcmnunes/phd-calculation-routines/blob/master/peclet.m
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
phd-calculation-routines
|
jcmnunes
|
MATLAB
|
Code
| 99
| 191
|
function Pe = peclet(rp, Kd, Kc, Jv, D, Lp)
% PECLET Compute Pe number
% PE = PECLET(RP, KD, KC, JV, D, LP) evalutes
% the Peclet number (PE). Input arguments are:
% * RP - Membrane pore radius [m]
% * KD - Hindrance diffusion coefficient
% * KC - Hindrance convection coefficient
% * JV - Filtration flux [m/s]
% * D - Diffusion coefficient
% * LP - Hydraulic permeability [m]
% Use consistent units (Peclet number must be
% adimensional).
Pe = Kc .* rp.^2 .* Jv ./ (8 .* Kd .* D .* Lp);
| 35,484
|
https://github.com/boris-guzeev/test_news/blob/master/module/Application/src/Controller/IndexController.php
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,020
|
test_news
|
boris-guzeev
|
PHP
|
Code
| 172
| 641
|
<?php
/**
* @link http://github.com/zendframework/ZendSkeletonApplication for the canonical source repository
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Application\Controller;
use Application\Model\NewsTable;
use Zend\Mvc\Controller\AbstractActionController;
class IndexController extends AbstractActionController
{
private $table;
public function __construct(NewsTable $table)
{
$this->table = $table;
}
public function indexAction()
{
// находим год и месяц
$monthYear = $this->table->fetchMonthYear();
$paginationUrl = [];
if (!empty($this->params()->fromQuery('theme')))
{
$value = $this->params()->fromQuery('theme');
$data = $this->table->fetchAll(
'theme',
$value,
$this->params()->fromQuery('page')
);
$paginationUrl['theme'] = $value;
} elseif (!empty($this->params()->fromQuery('ym')))
{
$value = $this->params()->fromQuery('ym');
$data = $this->table->fetchAll(
'ym',
$value,
$this->params()->fromQuery('page')
);
$paginationUrl['ym'] = $value;
} else {
$data = $this->table->fetchAll(
null,
null,
$this->params()->fromQuery('page')
);
}
$themes = $this->table->getThemesList();
foreach ($data['news'] as &$one) {
$length = strlen($one['text']);
if ($length >= 255) {
$one['text'] = mb_substr($one['text'], 0, 255) . '...';
}
}
return [
'monthYear' => $monthYear,
'news' => $data['news'],
'pagination' => $data['pagination'],
'paginationUrl' => $paginationUrl,
'themes' => $themes
];
}
public function showAction()
{
$id = (int) $this->params()->fromRoute('id', 0);
$news = $this->table->fetchOne($id);
return [
'news' => $news
];
}
}
| 13,271
|
https://github.com/masroore/CTEX/blob/master/resources/lang/ja/notifications.php
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
CTEX
|
masroore
|
PHP
|
Code
| 19
| 87
|
<?php
return [
'title' => '通知',
'page_title' => '通知',
'page_title_desc' => '取引所サービスからの通知',
'tag' => '通知',
'no_content_msg' => '内容がありません'
];
| 28,289
|
https://github.com/Cadris/roslyn/blob/master/src/VisualStudio/Core/Def/EditorConfigSettings/ISettingsEditorView.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
roslyn
|
Cadris
|
C#
|
Code
| 68
| 163
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading.Tasks;
using System.Windows.Controls;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Shell.TableControl;
namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings
{
internal interface ISettingsEditorView
{
UserControl SettingControl { get; }
IWpfTableControl TableControl { get; }
Task<SourceText> UpdateEditorConfigAsync(SourceText sourceText);
void OnClose();
}
}
| 38,144
|
https://github.com/pllemon/tyyMusic/blob/master/src/layout/components/Navbar.vue
|
Github Open Source
|
Open Source
|
MIT
| null |
tyyMusic
|
pllemon
|
Vue
|
Code
| 97
| 438
|
<template>
<div class="navbar fx-cb">
<div class="fx-cs">
<hamburger :is-active="sidebar.opened" class="hamburger-container" @toggleClick="toggleSideBar" />
<p class="page-title">{{$route.meta.title}}</p>
</div>
<div>
<el-button type="text" @click="back" v-show="$route.meta.inlinePage"><i class="el-icon-back"></i>返回</el-button>
<el-button type="text" @click="refresh" ><i class="el-icon-refresh-left"></i>刷新</el-button>
</div>
</div>
</template>
<script>
import { mapGetters } from 'vuex'
import Hamburger from '@/components/Hamburger'
export default {
components: {
Hamburger
},
computed: {
...mapGetters([
'sidebar'
])
},
methods: {
toggleSideBar() {
this.$store.dispatch('app/toggleSideBar')
},
back() {
this.$router.go(-1)
},
refresh() {
window.location.reload()
}
}
}
</script>
<style lang="scss" scoped>
.page-title{
font-size: 18px;
font-weight: bold;
}
.navbar {
height: 50px;
overflow: hidden;
position: relative;
background: #fff;
box-shadow: 0 1px 4px rgba(0,21,41,.08);
padding-right: 10px;
}
</style>
| 200
|
https://github.com/AkcayHasan/KotlinApp/blob/master/app/src/main/java/com/hasanakcay/kotlinapp/viewmodel/AlbumsPageViewModel.kt
|
Github Open Source
|
Open Source
|
MIT
| null |
KotlinApp
|
AkcayHasan
|
Kotlin
|
Code
| 66
| 323
|
package com.hasanakcay.kotlinapp.viewmodel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.hasanakcay.kotlinapp.model.Album
import com.hasanakcay.kotlinapp.service.AlbumsAPIService
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.observers.DisposableSingleObserver
import io.reactivex.schedulers.Schedulers
class AlbumsPageViewModel : ViewModel() {
val albums = MutableLiveData<List<Album>>()
private val albumsApiService = AlbumsAPIService()
private val disposable = CompositeDisposable()
fun dataFromJson(){
disposable.add(
albumsApiService.getData()
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribeWith(object : DisposableSingleObserver<List<Album>>(){
override fun onSuccess(t: List<Album>) {
albums.value = t
}
override fun onError(e: Throwable) {
e.printStackTrace()
}
})
)
}
}
| 24,192
|
https://github.com/mingdaocom/pd-openweb/blob/master/src/components/common/function.js
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,023
|
pd-openweb
|
mingdaocom
|
JavaScript
|
Code
| 1,263
| 4,372
|
import { AT_ALL_TEXT } from 'src/components/comment/config';
import { upgradeVersionDialog, htmlEncodeReg } from 'src/util';
import Emotion from 'src/components/emotion/emotion';
import weixin from 'src/api/weixin';
import { index as dialog } from 'src/components/mdDialog/dialog';
import projectAjax from 'src/api/project';
import userController from 'src/api/user';
const replaceMessageCustomTag = function (message, tagName, replaceHtmlFunc, filterCustom) {
var startTag, endTag, customReplaceStr;
if (!message) return message;
if (typeof tagName === 'string') {
startTag = '[' + tagName + ']';
endTag = '[/' + tagName + ']';
} else if (Array.isArray(tagName)) {
startTag = tagName[0];
endTag = tagName[1];
} else {
return message;
}
if (message.indexOf(startTag) > -1) {
var customRegExp = new RegExp(
'(' +
startTag.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&') +
')([0-9a-zA-Z-]*\\|?.*?)' +
endTag.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&'),
'gi',
);
if (filterCustom) {
message = message.replace(customRegExp, '');
} else {
message = message.replace(customRegExp, function ($0, $1, $2) {
var customStr = $2;
var splitterIndex = customStr.indexOf('|');
if (splitterIndex === -1) {
return replaceHtmlFunc ? replaceHtmlFunc(customStr, '无法解析' + tagName) : '';
}
var customId = customStr.substr(0, splitterIndex);
var customName = customStr.substr(splitterIndex + 1);
return replaceHtmlFunc ? replaceHtmlFunc(customId, customName) : customName;
});
}
}
return message;
};
const getUserStatus = function (user) {
if (user) {
switch (user.status) {
case 2:
return _l('(被拒绝加入,需从后台恢复权限)');
break;
case 3:
return _l('(待审批)');
break;
case 4:
return _l('(被暂停权限,需从后台恢复权限)');
break;
}
}
return '';
};
const inviteNoticeMessage = function (title, accounts) {
if (!accounts.length) return '';
var noticeMessage = title + ':<br/>';
$.each(accounts, function (i, item) {
var message = '';
if (item.account) {
// 不存在的用户
message = item.account;
} else {
// 已存在的用户
var accountArr = [];
if (item.email) {
accountArr.push(item.email);
}
if (item.mobilePhone) {
accountArr.push(item.mobilePhone);
}
var desc = accountArr.join(' / ') + getUserStatus(item.user);
message = item.fullname + (desc.length ? ':' + desc : '');
}
noticeMessage += '<div class="Font12 Gray_c LineHeight25">' + message + '</div>';
});
return noticeMessage;
};
/**
* 替换动态/任务等内容中的链接
* @param {string} args.message 替换前的 html
* @param {object[]} args.rUserList @ 到的帐号列表
* @param {object[]} args.rGroupList @ 到的群组列表
* @param {object[]} args.categories 打的话题
* @param {boolean} args.noLink 只生成文本,不生成链接
* @param {boolean} args.filterFace 不显示表情
* @return {string} 替换后的 html
*/
export const createLinksForMessage = function (args) {
var message = args.message.replace(/\n/g, '<br>');
var rUserList = args.rUserList;
var rGroupList = args.rGroupList;
var categories = args.categories;
var noLink = args.noLink;
var filterFace = args.filterFace;
var sourceType = args.sourceType;
var replaceStr = '';
var j;
message = message.replace(/\[all\]atAll\[\/all\]/gi, '<a>@' + AT_ALL_TEXT[sourceType] + '</a>');
if (rUserList && rUserList.length > 0) {
for (j = 0; j < rUserList.length; j++) {
var rUser = rUserList[j];
replaceStr = '';
var name = htmlEncodeReg(rUser.name || rUser.fullname);
var aid = rUser.aid || rUser.accountId;
if (name) {
if (noLink) {
replaceStr += ' @' + name + ' ';
} else {
if (md.global.Account.isPortal || (aid || '').indexOf('a#') > -1) {
// 外部门户
replaceStr += ' <a>@' + name + '</a> ';
} else {
replaceStr += ' <a data-accountid="' + aid + '" target="_blank" href="/user_' + aid + '">@' + name + '</a> ';
}
}
}
var userRegExp = new RegExp('\\[aid]' + aid + '\\[/aid]', 'gi');
message = message.replace(userRegExp, replaceStr);
}
}
if (rGroupList && rGroupList.length > 0) {
for (j = 0; j < rGroupList.length; j++) {
var rGroup = rGroupList[j];
replaceStr = '';
if (rGroup.groupName) {
if (noLink) {
replaceStr += '@' + htmlEncodeReg(rGroup.groupName);
} else {
if (rGroup.isDelete) {
replaceStr +=
' <span class="DisabledColor" title="群组已删除">@' + htmlEncodeReg(rGroup.groupName) + '</span> ';
} else {
replaceStr +=
' <a target="_blank" data-groupid="' +
rGroup.groupID +
'" href="/group/groupValidate?gID=' +
rGroup.groupID +
'">@' +
htmlEncodeReg(rGroup.groupName) +
'</a> ';
}
}
}
var groupRegExp = new RegExp('\\[gid]' + rGroup.groupID + '\\[/gid]', 'gi');
message = message.replace(groupRegExp, replaceStr);
}
}
var getReplaceHtmlFunc = function (getLink, getPlain) {
return function (customId, customName) {
if (noLink) {
return getPlain ? getPlain(customId) : customName;
}
return getLink(customId, customName);
};
};
// TODO: 了解此处各字符串是否已由后台encode
// 话题
var findCategory = function (id) {
if (categories) {
for (var i = 0, l = categories.length; i < l; i++) {
if (categories[i].catID === id) {
return categories[i];
}
}
}
};
message = replaceMessageCustomTag(
message,
'cid',
getReplaceHtmlFunc(
function (id, name) {
var category = findCategory(id);
name = category ? category.catName : '未知话题';
return '<a target="_blank" href="/feed?catId=' + id + '">#' + htmlEncodeReg(name) + '#</a>';
},
function (id, name) {
var category = findCategory(id);
name = category ? category.catName : '未知话题';
return '#' + htmlEncodeReg(name) + '#';
},
),
);
// 任务
message = replaceMessageCustomTag(
message,
'tid',
getReplaceHtmlFunc(function (id, name) {
return '<a target="_blank" href="/apps/task/task_' + id + '">' + htmlEncodeReg(name) + '</a>';
}),
);
// 项目
message = replaceMessageCustomTag(
message,
'fid',
getReplaceHtmlFunc(function (id, name) {
return '<a target="_blank" href="/apps/task/folder_' + id + '">' + htmlEncodeReg(name) + '</a>';
}),
);
// 日程
message = replaceMessageCustomTag(
message,
['[CALENDAR]', '[CALENDAR]'],
getReplaceHtmlFunc(function (id, name) {
return '<a target="_blank" href="/apps/calendar/detail_' + id + '">' + htmlEncodeReg(name) + '</a>';
}),
);
// 问答中心
message = replaceMessageCustomTag(
message,
['[STARTANSWER]', '[ENDANSWER]'],
getReplaceHtmlFunc(function (id, name) {
return '<a target="_blank" href="/feeddetail?itemID=' + id + '">' + htmlEncodeReg(name) + '</a>';
}),
);
// 文档版本
message = replaceMessageCustomTag(
message,
['[docversion]', '[docversion]'],
getReplaceHtmlFunc(function (id, name) {
return (
'<a href="/feeddetail?itemID=' +
id +
'" target="_blank">' +
(htmlEncodeReg(name.split('|')[0]) || '文件') +
'</a>'
);
}),
);
if ((typeof filterFace === 'undefined' || !filterFace) && !noLink) {
message = Emotion.parse(message);
}
message = message.replace(/<br( \/)?>/g, '\n'); // .replace(/<[^>]+>/g, '');
if (!noLink) {
message = message.replace(/\n/g, '<br>');
var urlReg = /http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=])?[^ <>\[\]*(){},\u4E00-\u9FA5]+/gi;
message = message.replace(urlReg, function (m) {
return '<a target="_blank" href="' + m + '">' + m + '</a>';
});
}
// 外部用户
if ((args.accountId || '').indexOf('a#') > -1) {
message = message.replace(new RegExp(`\\[aid\\]${args.accountId}\\[\\/aid\\]`, 'g'), args.accountName);
}
return message;
};
// 发送提醒通知 未填写手机号码
export const sendNoticeInvite = function (id, object, projectId, type) {
if (object) {
object.removeAttr('onclick').css('cursor', 'none').text(_l('已发送提醒'));
}
if ($.isArray(id) ? id.length <= 0 : !id) {
alert(_l('没有要提醒的人'), 4);
}
if (!$.isArray(id)) {
id = [id];
}
userController
.sendNotice({
accountIds: id,
projectId: projectId,
type: type,
})
.done(function (result) {
alert('已成功发送提醒', 1);
});
};
export const showFollowWeixinDialog = function () {
var html = `
<div class='pAll10 mLeft30 pBottom30'>
<div class='followWeixinQrCode Left'>
${LoadDiv()}
</div>
<div class='left mTop20 mLeft15'>
<span class='InlineBlock LineHeight30 Font14'>${_l('用微信【扫一扫】二维码')}</span>
</div>
<div class='Clear'></div>
</div>
`;
dialog({
dialogBoxID: 'followWeixinDialog',
container: {
header: _l('关注服务号'),
content: html,
yesText: null,
noText: null,
},
width: 398,
});
weixin.getWeiXinServiceNumberQRCode().then(function (data) {
var content = '加载失败';
if (data) {
content = "<img src='" + data + "' width='98' height='98'/>";
}
$('#followWeixinDialog .followWeixinQrCode').html(content);
});
};
// 验证网络是否到期异步
export const expireDialogAsync = function (projectId, text) {
var def = $.Deferred();
def.resolve();
return def.promise();
};
// 提示邀请结果
export const existAccountHint = function (result, chooseInviteCallback, limitHint, failedHint) {
var SendMessageResult = {
Failed: 0,
Success: 1,
Limit: 2,
};
if ($.isFunction(chooseInviteCallback)) {
chooseInviteCallback({
status: result.sendMessageResult === SendMessageResult.Success ? 1 : 0,
});
}
if (result.sendMessageResult === SendMessageResult.Failed) {
alert(failedHint || _l('邀请失败'), 2);
return;
}
var accountInfos = []; // 成功
var existAccountInfos = []; // 已存在
var failedAccountInfos = []; // 失败
var limitAccountInfos = []; // 邀请限制
var forbidAccountInfos = []; // 账号来源类型受限
// result type array
$.each(result.results, function (index, singleResult) {
// 成功
if (singleResult.accountInfos) {
accountInfos = accountInfos.concat(singleResult.accountInfos);
}
// 已存在
if (singleResult.existAccountInfos) {
existAccountInfos = existAccountInfos.concat(singleResult.existAccountInfos);
}
// 失败
if (singleResult.failedAccountInfos) {
failedAccountInfos = failedAccountInfos.concat(singleResult.failedAccountInfos);
}
// 限制
if (singleResult.limitAccountInfos) {
limitAccountInfos = limitAccountInfos.concat(singleResult.limitAccountInfos);
}
// 账号来源类型受限
if (singleResult.forbidAccountInfos) {
forbidAccountInfos = forbidAccountInfos.concat(singleResult.forbidAccountInfos);
}
});
var message = _l('邀请成功');
var isNotice =
existAccountInfos.length || // 详细提醒
failedAccountInfos.length ||
limitAccountInfos.length ||
forbidAccountInfos.length;
if (isNotice) {
message = inviteNoticeMessage(_l('以下用户邀请成功'), accountInfos);
message += inviteNoticeMessage(_l('以下用户已存在,不能重复邀请'), existAccountInfos);
message += inviteNoticeMessage(_l('以下用户超过邀请数量限制,无法邀请'), limitAccountInfos);
message += inviteNoticeMessage(_l('以下用户邀请失败'), failedAccountInfos);
message += inviteNoticeMessage(_l('以下用户账号来源类型受限'), forbidAccountInfos);
}
if (isNotice) {
alert(message, 3);
} else {
alert(message);
}
return {
accountInfos: accountInfos,
existAccountInfos: existAccountInfos,
};
};
| 31,514
|
https://github.com/chimera-linux/cports/blob/master/main/base-cbuild-host/template.py
|
Github Open Source
|
Open Source
|
BSD-2-Clause
| 2,023
|
cports
|
chimera-linux
|
Python
|
Code
| 42
| 139
|
pkgname = "base-cbuild-host"
pkgver = "0.1"
pkgrel = 1
build_style = "meta"
depends = [
"apk-tools",
"openssl",
"git",
"bubblewrap",
"chimerautils",
"python",
]
pkgdesc = "Everything one needs to use cbuild and cports"
maintainer = "q66 <q66@chimera-linux.org>"
license = "custom:meta"
url = "https://chimera-linux.org"
| 43,320
|
https://github.com/RogerioTostes/AnalisedeRepositorioGitHub/blob/master/IC2020/Models/Repos.cs
|
Github Open Source
|
Open Source
|
MIT
| null |
AnalisedeRepositorioGitHub
|
RogerioTostes
|
C#
|
Code
| 111
| 225
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace IC2020.Models
{
public class Item
{
public string url { get; set; }
public string tag_name { get; set; }
public DateTime published_at { get; set; }
public Author author { get; set; }
}
public class Author
{
public string login { get; set; }
}
public class RepoInfo
{
public string id { get; set; }
public string full_name { get; set; }
public string language { get; set; }
public string default_branch { get; set; }
public int watchers_count { get; set; }
public int open_issues_count { get; set; }
public int forks { get; set; }
}
}
| 18,518
|
https://github.com/liulq315/auto_parcel/blob/master/Compiler/build.gradle
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,020
|
auto_parcel
|
liulq315
|
Gradle
|
Code
| 52
| 266
|
apply plugin: 'java'
apply plugin: 'com.novoda.bintray-release'
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.google.auto.service:auto-service:1.0-rc6'
annotationProcessor 'com.google.auto.service:auto-service:1.0-rc6'
}
// 新增
publish {
userOrg = 'lqos' //bintray.com用户名
groupId = 'com.zxn.parcel' //jcenter上的路径
artifactId = 'auto_parcel' //项目名称
publishVersion = '0.1.0'//版本号
desc = '自动实现序列化'//描述,自由填写
website = 'https://github.com/bug2048/auto_parcel' // 网址,自由填写
}
sourceCompatibility = 1.7
targetCompatibility = 1.7
| 43,097
|
https://github.com/Werdenruhm/CommonLib/blob/master/src/CommonLib/XmlSettingsBase.java
|
Github Open Source
|
Open Source
|
MIT
| null |
CommonLib
|
Werdenruhm
|
Java
|
Code
| 461
| 1,358
|
package CommonLib;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Properties;
/**
*
*
* @param <E>
*/
public class XmlSettingsBase<E extends Enum<E>> {
final Properties props = new Properties();
final String fileName;
final boolean autoStore;
final String[] requiredProperties;
public XmlSettingsBase(String ExecutingJarWarEarFileName, String settingsFileName, boolean ConfigFileIsRequiredForStart, String[] RequiredProperties)
{
String fileName_ = settingsFileName;
String roap;
try {
roap = Common.getJarRelativeOrAbsolutePath(ExecutingJarWarEarFileName);
} catch (Throwable ex) {
fileName = fileName_;
writeTmpSysProps();
throw ex;
}
if (roap.length() > 0)
fileName_ = roap + fileName_;
fileName = fileName_;
autoStore = true;
requiredProperties = RequiredProperties;
try {
loadFromXML();
} catch (Exception ex) {
if (ConfigFileIsRequiredForStart)
throw ex;
}
}
public XmlSettingsBase(String ExecutingJarWarEarFileName, String settingsFileName, boolean ConfigFileIsRequiredForStart, Class<E> requiredPropertiesEnum)
{
this(ExecutingJarWarEarFileName, settingsFileName, ConfigFileIsRequiredForStart, Common.arrayTransform(requiredPropertiesEnum.getEnumConstants(), String[].class, ee -> ee.toString()));
}
public String getProperty(String key) {
return props.getProperty(key);
}
public String getProperty(E key) {
return props.getProperty(key.toString());
}
public synchronized void storeToXML()
{
try (FileOutputStream fos = new FileOutputStream(new File(fileName))) {
props.storeToXML(fos, "");
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
public synchronized void setProperty(String key, String value) {
props.setProperty(key, value);
if (autoStore)
storeToXML();
}
public final synchronized void loadFromXML()
{
try (FileInputStream fis = new FileInputStream(new File(fileName))) {
props.loadFromXML(fis);
} catch (IOException ex) {
String tmpFileName = Common.getTmpdir() + (fileName.contains(Common.getFileSeparator()) ? fileName.substring(1 + fileName.lastIndexOf(Common.getFileSeparator())) : fileName);
try (FileOutputStream fos = new FileOutputStream(new File(tmpFileName))) {
Properties props2 = new Properties();
if (requiredProperties != null && requiredProperties.length > 0)
{
for (String prp : requiredProperties)
{
props2.setProperty(prp, "value of " + prp);
}
}
props2.storeToXML(fos, "");
} catch (IOException ex2) { tmpFileName = null; }
writeTmpSysProps();
throw new Common.ArtificialError("Error reading properties from (" + fileName + "): " + ex.getMessage() + "\r\n"
+ "An example properties file created in '" + tmpFileName + "'.");
}
if (requiredProperties != null && requiredProperties.length > 0)
{
String errmsg = null;
for (String prp : requiredProperties)
{
if (getProperty(prp) == null)
{
if (errmsg == null)
errmsg = "A properties file (" + fileName + ") does not have required properties: ";
else
errmsg += ", ";
errmsg += "[" + prp + "]";
}
}
if (errmsg != null)
{
errmsg += "! Add it into a properties file and restart.";
throw new Common.ArtificialError(errmsg);
}
}
}
final void writeTmpSysProps()
{
String tmpFileName = "";
try {
tmpFileName = Common.getTmpdir() + (fileName.contains(Common.getFileSeparator()) ? fileName.substring(1 + fileName.lastIndexOf(Common.getFileSeparator())) : fileName);
Properties prprts = System.getProperties();
String prprtsS = "";
for (String k : prprts.stringPropertyNames())
prprtsS += k + "=[" + prprts.getProperty(k) + "]\r\n";
prprtsS += "\r\n\r\n" + "InputArguments:" + "\r\n";
for (String k : java.lang.management.ManagementFactory.getRuntimeMXBean().getInputArguments())
prprtsS += k + "\r\n";
Files.write(Paths.get(tmpFileName + "_SystemProperties_" + new java.text.SimpleDateFormat("yyyyMMddHHmmss").format(new java.util.Date()) + ".txt"), prprtsS.getBytes("utf-8"));
} catch (Exception exx) { throw new Error("writeTmpSysProps Error(tmpFileName = " + tmpFileName + "):" + exx.getMessage());}
}
}
| 346
|
https://github.com/michaeljb/18xx.games/blob/master/lib/engine/game/g_1840/step/special_track.rb
|
Github Open Source
|
Open Source
|
MIT
| null |
18xx.games
|
michaeljb
|
Ruby
|
Code
| 272
| 1,005
|
# frozen_string_literal: true
require_relative '../../../step/track'
module Engine
module Game
module G1840
module Step
class SpecialTrack < Engine::Step::Track
ACTIONS_WITH_PASS = %w[lay_tile pass].freeze
def actions(entity)
return [] unless entity == pending_entity
ACTIONS_WITH_PASS
end
def round_state
super.merge(
{
pending_tile_lays: [],
}
)
end
def active?
pending_entity
end
def current_entity
pending_entity
end
def pending_entity
pending_tile_lay[:entity]
end
def color
pending_tile_lay[:color]
end
def pending_tile_lay
@round.pending_tile_lays&.first || {}
end
def available_hex(entity, hex)
return false if @game.orange_framed?(hex.tile)
connected = @game.graph_for_entity(entity).connected_hexes(entity)[hex]
return false unless connected
return hex.tile.color == :white if color == :yellow
return hex.tile.color == :yellow if color == :green
return @game.class::RED_TILES.include?(hex.coordinates) if color == :red &&
hex.tile == hex.original_tile
return hex.tile.color == color if hex.tile == hex.original_tile
end
def potential_tiles(_entity, hex)
if color == :red
return @game.tiles
.select { |tile| color == tile.color }
end
if color == :purple
if (tiles = @game.class::PURPLE_SPECIAL_TILES[hex.coordinates])
return @game.tiles.select { |tile| tiles.include?(tile.name) }
end
return @game.tiles.select do |tile|
color == tile.color && !@game.class::TILES_FIXED_ROTATION.include?(tile.name)
end
end
tiles = super
return tiles.select { |tile| @game.orange_framed?(tile) } if @game.orange_framed?(hex.tile)
tiles.reject { |tile| @game.orange_framed?(tile) }
end
def process_lay_tile(action)
lay_tile(action)
@round.laid_hexes << action.hex
@round.pending_tile_lays.shift
end
def process_pass(action)
super
@round.pending_tile_lays.shift
end
def hex_neighbors(entity, hex)
@game.graph_for_entity(entity).connected_hexes(entity)[hex]
end
def legal_tile_rotation?(entity, hex, tile)
return tile.rotation.zero? if color == :purple && @game.class::TILES_FIXED_ROTATION.include?(tile.name)
return true if color == :purple
if color == :red
return tile.exits.all? { |edge| hex.neighbors[edge] } &&
!(tile.exits & hex_neighbors(entity, hex)).empty?
end
super
end
def show_other
@game.owning_major_corporation(current_entity)
end
def upgradeable_tiles(entity, hex)
potential_tiles(entity, hex).map do |tile|
tile.rotate!(0) # reset tile to no rotation since calculations are absolute
tile.legal_rotations = legal_tile_rotations(entity, hex, tile)
next if tile.legal_rotations.empty?
tile.rotate! # rotate it to the first legal rotation
tile
end.compact
end
end
end
end
end
end
| 15,729
|
https://github.com/sailfish009/unpythonic/blob/master/unpythonic/syntax/util.py
|
Github Open Source
|
Open Source
|
BSD-3-Clause, BSD-2-Clause
| 2,020
|
unpythonic
|
sailfish009
|
Python
|
Code
| 2,781
| 6,609
|
# -*- coding: utf-8 -*-
"""Utilities for working with syntax."""
from functools import partial
from copy import deepcopy
import re
from ast import (Call, Name, Attribute, Lambda, FunctionDef,
If, Num, NameConstant, For, While, With, Try, ClassDef,
withitem)
from .astcompat import AsyncFunctionDef, AsyncFor, AsyncWith
from macropy.core import Captured
from macropy.core.walkers import Walker
from .letdoutil import isdo, ExpandedDoView
from ..regutil import all_decorators, tco_decorators, decorator_registry
def isx(tree, x, accept_attr=True):
"""Test whether tree is a reference to the name ``x`` (str).
Alternatively, ``x`` may be a predicate that accepts a ``str``
and returns whether it matches, to support more complex matching
(e.g. ``lambda s: s.startswith("foo")``).
Both bare names and attributes can be recognized, to support
both from-imports and regular imports of ``somemodule.x``.
We support:
- bare name ``x``
- ``x`` inside a ``macropy.core.Captured`` node, which may be inserted
during macro expansion
- ``x`` as an attribute (if ``accept_attr=True``)
"""
# WTF, so sometimes there **is** a Captured node, while sometimes there isn't (letdoutil.islet)? At which point are these removed?
# Captured nodes only come from unpythonic.syntax, and we use from-imports
# and bare names for anything hq[]'d; but any references that appear
# explicitly in the user code may use either bare names or somemodule.f.
ismatch = x if callable(x) else lambda s: s == x
return ((type(tree) is Name and ismatch(tree.id)) or
(type(tree) is Captured and ismatch(tree.name)) or
(accept_attr and type(tree) is Attribute and ismatch(tree.attr)))
def make_isxpred(x):
"""Make a predicate for isx.
Here ``x`` is an ``str``; the resulting function will match the names
x, x1, x2, ..., so that it works also with captured identifiers renamed
by MacroPy's ``hq[]``.
"""
rematch = re.match
pat = re.compile(r"^{}\d*$".format(x))
return lambda s: rematch(pat, s)
def getname(tree, accept_attr=True):
"""The cousin of ``isx``.
From the same types of trees, extract the name as str.
If no match on ``tree``, return ``None``.
"""
if type(tree) is Name:
return tree.id
if type(tree) is Captured:
return tree.name
if accept_attr and type(tree) is Attribute:
return tree.attr
return None
def isec(tree, known_ecs):
"""Test whether tree is a call to a function known to be an escape continuation.
known_ecs: list of ``str``, names of known escape continuations.
**CAUTION**: Only bare-name references are supported.
"""
return type(tree) is Call and getname(tree.func, accept_attr=False) in known_ecs
def detect_callec(tree):
"""Collect names of escape continuations from call_ec invocations in tree.
Currently supported and unsupported cases::
# use as decorator, supported
@call_ec
def result(ec): # <-- we grab name "ec" from here
...
# use directly on a literal lambda, supported
result = call_ec(lambda ec: ...) # <-- we grab name "ec" from here
# use as a function, **NOT supported**
def g(ec): # <-- should grab from here
...
...
result = call_ec(g) # <-- but this is here; g could be in another module
Additionally, the literal names `ec`, `brk`, `throw` are always interpreted
as invoking an escape continuation (whether they actually do or not).
So if you need the third pattern above, use **exactly** the name `ec`
for the escape continuation parameter, and it will work.
(The name `brk` covers the use of `unpythonic.fploop.breakably_looped`,
and `throw` covers the use of `unpythonic.ec.throw`.)
"""
fallbacks = ["ec", "brk", "throw"]
iscallec = partial(isx, x=make_isxpred("call_ec"))
@Walker
def detect(tree, *, collect, **kw):
# TODO: add support for general use of call_ec as a function (difficult)
if type(tree) in (FunctionDef, AsyncFunctionDef) and any(iscallec(deco) for deco in tree.decorator_list):
fdef = tree
collect(fdef.args.args[0].arg) # FunctionDef.arguments.(list of arg objects).arg
elif is_decorated_lambda(tree, mode="any"):
decorator_list, thelambda = destructure_decorated_lambda(tree)
if any(iscallec(decocall.func) for decocall in decorator_list):
collect(thelambda.args.args[0].arg) # we assume it's the first arg, as that's what call_ec expects.
return tree
return fallbacks + detect.collect(tree)
@Walker
def detect_lambda(tree, *, collect, stop, **kw):
"""Find lambdas in tree. Helper for block macros.
Run ``detect_lambda.collect(tree)`` in the first pass, before allowing any
nested macros to expand. (Those may generate more lambdas that your block
macro is not interested in).
The return value from ``.collect`` is a ``list``of ``id(lam)``, where ``lam``
is a Lambda node that appears in ``tree``. This list is suitable as
``userlambdas`` for the TCO macros.
This ignores any "lambda e: ..." added by an already expanded ``do[]``,
to allow other block macros to better work together with ``with multilambda``
(which expands in the first pass, to eliminate semantic surprises).
"""
if isdo(tree):
stop()
thebody = ExpandedDoView(tree).body
for thelambda in thebody: # lambda e: ...
# NOTE: If a collecting Walker recurses further to collect in a
# branch that has already called `stop()`, the results must be
# propagated manually.
for theid in detect_lambda.collect(thelambda.body):
collect(theid)
if type(tree) is Lambda:
collect(id(tree))
return tree
def is_decorator(tree, fname):
"""Test tree whether it is the decorator ``fname``.
``fname`` may be ``str`` or a predicate, see ``isx``.
References of the forms ``f``, ``foo.f`` and ``hq[f]`` are supported.
We detect:
- ``Name``, ``Attribute`` or ``Captured`` matching the given ``fname``
(non-parametric decorator), and
- ``Call`` whose ``.func`` matches the above rule (parametric decorator).
"""
return ((isx(tree, fname)) or
(type(tree) is Call and isx(tree.func, fname)))
def is_lambda_decorator(tree, fname=None):
"""Test tree whether it decorates a lambda with ``fname``.
A node is detected as a lambda decorator if it is a ``Call`` that supplies
exactly one positional argument, and its ``.func`` is the decorator ``fname``
(``is_decorator(tree.func, fname)`` returns ``True``).
This function does not know or care whether a chain of ``Call`` nodes
terminates in a ``Lambda`` node. See ``is_decorated_lambda``.
``fname`` is optional; if ``None``, do not check the name.
Examples::
trampolined(arg) # --> non-parametric decorator
looped_over(range(10), acc=0)(arg) # --> parametric decorator
"""
return ((type(tree) is Call and len(tree.args) == 1) and
(fname is None or is_decorator(tree.func, fname)))
def is_decorated_lambda(tree, mode):
"""Detect a tree of the form f(g(h(lambda ...: ...)))
mode: str, "known" or "any":
"known": match a chain containing known decorators only.
See ``unpythonic.regutil``.
"any": match any chain of one-argument ``Call`` nodes terminating
in a ``Lambda`` node.
Note this works also for parametric decorators; for them, the ``func``
of the ``Call`` is another ``Call`` (that specifies the parameters).
"""
assert mode in ("known", "any")
if mode == "known":
detectors = [partial(is_lambda_decorator, fname=x) for x in all_decorators]
else: # mode == "any":
detectors = [is_lambda_decorator]
def detect(tree):
if type(tree) is not Call:
return False
if not any(f(tree) for f in detectors):
return False
if type(tree.args[0]) is Lambda:
return True
return detect(tree.args[0])
return detect(tree)
def destructure_decorated_lambda(tree):
"""Get the AST nodes for ([f, g, h], lambda) in f(g(h(lambda ...: ...)))
Input must be a tree for which ``is_decorated_lambda`` returns ``True``.
This returns **the original AST nodes**, to allow in-place transformations.
"""
def get(tree, lst):
if type(tree) is Call:
# collect tree itself, not tree.func, because sort_lambda_decorators needs to reorder the funcs.
return get(tree.args[0], lst + [tree])
elif type(tree) is Lambda:
return lst, tree
assert False, "Expected a chain of Call nodes terminating in a Lambda node" # pragma: no cover
return get(tree, [])
def has_tco(tree, userlambdas=[]):
"""Return whether a FunctionDef or a decorated lambda has TCO applied.
userlambdas: list of ``id(some_tree)``; when detecting a lambda,
only consider it if its id matches one of those in the list.
Return value is ``True`` or ``False`` (depending on test result) if the
test was applicable, and ``None`` if it was not applicable (no match on tree).
"""
return has_deco(tco_decorators, tree, userlambdas)
def has_curry(tree, userlambdas=[]):
"""Return whether a FunctionDef or a decorated lambda has curry applied.
userlambdas: list of ``id(some_tree)``; when detecting a lambda,
only consider it if its id matches one of those in the list.
Return value is ``True`` or ``False`` (depending on test result) if the
test was applicable, and ``None`` if it was not applicable (no match on tree).
"""
return has_deco(["curry"], tree, userlambdas)
def has_deco(deconames, tree, userlambdas=[]):
"""Return whether a FunctionDef or a decorated lambda has any given deco applied.
deconames: list of decorator names to test.
userlambdas: list of ``id(some_tree)``; when detecting a lambda,
only consider it if its id matches one of those in the list.
Return value is ``True`` or ``False`` (depending on test result) if the
test was applicable, and ``None`` if it was not applicable (no match on tree).
"""
if type(tree) in (FunctionDef, AsyncFunctionDef):
return any(is_decorator(x, fname) for fname in deconames for x in tree.decorator_list)
elif is_decorated_lambda(tree, mode="any"):
decorator_list, thelambda = destructure_decorated_lambda(tree)
if (not userlambdas) or (id(thelambda) in userlambdas):
return any(is_lambda_decorator(x, fname) for fname in deconames for x in decorator_list)
return None # not applicable
def sort_lambda_decorators(tree):
"""Fix ordering of known lambda decorators (recursively) in ``tree``.
Strictly, lambdas have no decorator_list, but can be decorated by explicitly
surrounding them with calls to decorator functions.
Examples::
call_ec(trampolined(lambda ...: ...))
--> trampolined(call_ec(lambda ...: ...))
call_ec(curry(trampolined(lambda ...: ...)))
--> trampolined(call_ec(curry(lambda ...: ...)))
"""
def prioritize(tree): # sort key for Call nodes invoking known decorators
for k, (pri, fname) in enumerate(decorator_registry):
if is_lambda_decorator(tree, fname):
return k
# Only happens if called for a `tree` containing unknown (not registered) decorators.
x = getname(tree.func) if type(tree) is Call else "<unknown>" # pragma: no cover
assert False, "Only registered decorators can be auto-sorted, '{:s}' is not; see unpythonic.regutil".format(x) # pragma: no cover
@Walker
def fixit(tree, *, stop, **kw):
# we can robustly sort only decorators for which we know the correct ordering.
if is_decorated_lambda(tree, mode="known"):
decorator_list, thelambda = destructure_decorated_lambda(tree)
# We can just swap the func attributes of the nodes.
ordered_decorator_list = sorted(decorator_list, key=prioritize)
ordered_funcs = [x.func for x in ordered_decorator_list]
for thecall, newfunc in zip(decorator_list, ordered_funcs):
thecall.func = newfunc
# don't recurse on the tail of the "decorator list" (call chain),
# but recurse into the lambda body.
stop()
fixit.recurse(thelambda.body)
return tree
return fixit.recurse(tree)
# TODO: should we just sort the decorators here, like we do for lambdas?
# (The current solution is less magic, but less uniform.)
def suggest_decorator_index(deco_name, decorator_list):
"""Suggest insertion index for decorator deco_name in given decorator_list.
``decorator_list`` is the eponymous attribute of a ``FunctionDef``
or ``AsyncFunctionDef`` AST node.
The return value ``k`` is intended to be used like this::
if k is not None:
decorator_list.insert(k, mydeco)
else:
decorator_list.append(mydeco) # or do something else
If ``deco_name`` is not in the registry (see ``unpythonic.regutil``),
or if an approprite index could not be determined, the return value
is ``None``.
"""
if deco_name not in all_decorators:
return None # unknown decorator, don't know where it should go # pragma: no cover
names = [getname(tree) for tree in decorator_list]
pri_by_name = {dname: pri for pri, dname in decorator_registry}
# sanity check that existing known decorators are ordered correctly
# (otherwise there is no unique insert position)
knownnames = [x for x in names if x in pri_by_name]
knownpris = [pri_by_name[x] for x in knownnames]
def isascending(lst):
maxes = cummax(lst)
return all(b >= a for a, b in zip(maxes, maxes[1:]))
def cummax(lst):
m = float("-inf")
out = []
for x in lst:
m = max(x, m)
out.append(m)
return out
if not (knownpris and isascending(knownpris)):
return None
# when deciding the index, only care about known decorators (hence "suggest")
targetpri = pri_by_name[deco_name]
if targetpri < knownpris[0]:
return 0
if targetpri > knownpris[-1]:
return len(decorator_list)
assert knownpris[0] <= targetpri <= knownpris[-1]
for pri, dname in zip(knownpris, knownnames):
if pri >= targetpri:
break
else:
assert False # pragma: no cover
return names.index(dname)
def eliminate_ifones(body):
"""Eliminate ``if 1`` by splicing the contents into the surrounding body.
We also support "if True", "if 0", "if False" and "if None". The *then* or
*else* branch is spliced accordingly.
Here ``body`` is a ``list`` of statements.
**NOTE**: The Python compiler already performs this optimization, but the
``call_cc`` macro must be placed at the top level of a function body, and
``let_syntax`` (and its cousin ``abbrev``) generates these ``if 1`` blocks.
So to be able to use ``let_syntax`` in block mode, when the RHS happens to
include a ``call_cc`` (see the example in test_conts_gen.py)...
"""
def isifone(tree):
if type(tree) is If:
if type(tree.test) is Num: # TODO: Python 3.8+: ast.Constant, no ast.Num
if tree.test.n == 1:
return "then"
elif tree.test.n == 0:
return "else"
elif type(tree.test) is NameConstant: # TODO: Python 3.8+: ast.Constant, no ast.NameConstant
if tree.test.value is True:
return "then"
elif tree.test.value in (False, None):
return "else"
return False
def optimize(tree): # stmt -> list of stmts
t = isifone(tree)
if t:
branch = tree.body if t == "then" else tree.orelse
return branch
return [tree]
return transform_statements(optimize, body)
def transform_statements(f, body):
"""Recurse over statement positions and apply the syntax transformer ``f``.
This function understands statements such as ``def``, ``with``, ``if`` and
``for``, and calls ``f`` for each statement in their bodies, recursively.
For example, for an ``if``, statements in all branches are processed through
the transformation ``f``.
``f`` is a one-argument function that takes an AST representing a single
statement, and that **must** return a ``list`` of ASTs representing statements.
The output ``list`` will be spliced to replace the input statement. This
allows ``f`` to drop a statement (1->0) or to replace one statement with
several (1->n), beside making one-to-one (1->1) transformations.
(Transformations requiring n input statements are currently not supported.)
``body`` may be an AST representing a single statement, or a ``list`` of
such ASTs (e.g. the ``body`` of an ``ast.With``).
The input is modified in-place, provided ``f`` does so. In any case, the
original lists inside the ASTs containing the statements are in-place
replaced with the transformed ones.
The return value is the transformed ``body``. It is always a ``list`` of ASTs.
"""
def rec(tree):
# TODO: brittle, may need changes as the Python AST evolves. Better ways to do this?
if type(tree) in (FunctionDef, AsyncFunctionDef, ClassDef, With, AsyncWith):
tree.body = rec(tree.body)
elif type(tree) in (If, For, While, AsyncFor):
tree.body = rec(tree.body)
tree.orelse = rec(tree.orelse)
elif type(tree) is Try:
tree.body = rec(tree.body)
tree.orelse = rec(tree.orelse)
tree.finalbody = rec(tree.finalbody)
for handler in tree.handlers:
handler.body = rec(handler.body)
elif type(tree) is list: # multiple-statement body in AST
return [output_stmt for input_stmt in tree for output_stmt in rec(input_stmt)]
# A single statement. Transform it.
replacement = f(tree)
if not isinstance(replacement, list):
raise TypeError("`f` must return a list of statements, got {} with value '{}'".format(type(replacement), replacement)) # pragma: no cover
return replacement
return rec(body)
def splice(tree, rep, tag):
"""Splice in a tree into another tree.
Walk ``tree``, replacing all occurrences of a ``Name(id=tag)`` with
the tree ``rep``.
This is convenient for first building a skeleton with a marker such as
``q[name["_here_"]]``, and then splicing in ``rep`` later. See ``forall``
and ``envify`` for usage examples.
"""
@Walker
def doit(tree, *, stop, **kw):
if type(tree) is Name and tree.id == tag:
stop()
# Copy just to be on the safe side. Different instances may be
# edited differently by other macros expanded later.
return deepcopy(rep)
return tree
return doit.recurse(tree)
def wrapwith(item, body, locref=None):
"""Wrap ``body`` with a single-item ``with`` block, using ``item``.
``item`` must be an expr, used as ``context_expr`` of the ``withitem`` node.
``body`` must be a ``list`` of AST nodes.
``locref`` is an optional AST node to copy source location info from.
If not supplied, ``body[0]`` is used.
Syntax transformer. Returns the wrapped body.
"""
locref = locref or body[0]
wrapped = With(items=[withitem(context_expr=item, optional_vars=None)],
body=body,
lineno=locref.lineno, col_offset=locref.col_offset)
return [wrapped]
def ismarker(typename, tree):
"""Return whether tree is a specific AST marker. Used by block macros.
That is, whether ``tree`` is a ``with`` block with a single context manager,
which is represented by a ``Name`` whose ``id`` matches the given ``typename``.
Example. If ``tree`` is the AST for the following code::
with ContinuationsMarker:
...
then ``ismarker("ContinuationsMarker", tree)`` returns ``True``.
"""
if type(tree) is not With or len(tree.items) != 1:
return False
ctxmanager = tree.items[0].context_expr
return type(ctxmanager) is Name and ctxmanager.id == typename
# We use a custom metaclass to make __enter__ and __exit__ callable on the class
# instead of requiring an instance.
#
# Note ``thing.dostuff(...)`` means ``Thing.dostuff(thing, ...)``; the method
# is looked up *on the class* of the instance ``thing``, not on the instance
# itself. Hence, to make method lookup succeed when we have no instance, the
# method should be defined on the class of the class, i.e. *on the metaclass*.
# https://stackoverflow.com/questions/20247841/using-delitem-with-a-class-object-rather-than-an-instance-in-python
class ASTMarker(type):
"""Metaclass for AST markers used by block macros.
This can be used by block macros to tell other block macros that a section
of the AST is an already-expanded block of a given kind (so that others can
tune their processing or skip it, as appropriate). At run time a marker
does nothing.
Usage::
with SomeMarker:
... # expanded code goes here
We provide a custom metaclass so that there is no need to instantiate
``SomeMarker``; suitable no-op ``__enter__`` and ``__exit__`` methods
are defined on the metaclass, so e.g. ``SomeMarker.__enter__`` is valid.
"""
def __enter__(cls):
pass
def __exit__(cls, exctype, excvalue, traceback):
pass
class ContinuationsMarker(metaclass=ASTMarker):
"""AST marker for an expanded "with continuations" block."""
pass
# must be "instantiated" because we need to pass information at macro expansion time using the ctor call syntax.
class AutorefMarker(metaclass=ASTMarker):
"""AST marker for an expanded "with autoref(o)" block."""
def __init__(self, varname):
pass
def __enter__(cls):
pass
def __exit__(cls, exctype, excvalue, traceback):
pass
| 3,997
|
https://github.com/leha-bot/eve/blob/master/test/unit/module/real/core/bit_shl.cpp
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
eve
|
leha-bot
|
C++
|
Code
| 362
| 1,486
|
/**
EVE - Expressive Vector Engine
Copyright : EVE Contributors & Maintainers
SPDX-License-Identifier: MIT
**/
//==================================================================================================
#include "test.hpp"
#include <eve/constant/valmax.hpp>
#include <eve/constant/valmin.hpp>
#include <eve/function/bit_cast.hpp>
#include <eve/function/bit_shl.hpp>
//==================================================================================================
// Types tests
//==================================================================================================
EVE_TEST_TYPES( "Check return types of bit_shl"
, eve::test::simd::unsigned_types
)
<typename T>(eve::as<T>)
{
using v_t = eve::element_type_t<T>;
using i_t = eve::as_integer_t<T, signed>;
using u_t = eve::as_integer_t<T, unsigned>;
using vi_t = eve::as_integer_t<v_t, signed>;
using vu_t = eve::as_integer_t<v_t, unsigned>;
//regular
TTS_EXPR_IS( eve::bit_shl(T(), T() ) , T);
TTS_EXPR_IS( eve::bit_shl(T(), v_t()) , T);
TTS_EXPR_IS( eve::bit_shl(v_t(), T()) , T);
TTS_EXPR_IS( eve::bit_shl(v_t(), v_t()) , v_t);
TTS_EXPR_IS( eve::bit_shl(T(), i_t() ) , T);
TTS_EXPR_IS( eve::bit_shl(T(), u_t()) , T);
TTS_EXPR_IS( eve::bit_shl(v_t(), i_t()) , T);
TTS_EXPR_IS( eve::bit_shl(v_t(), u_t()) , T);
TTS_EXPR_IS( eve::bit_shl(T(), vi_t() ) , T);
TTS_EXPR_IS( eve::bit_shl(T(), vu_t()) , T);
TTS_EXPR_IS( eve::bit_shl(v_t(), vi_t()) , v_t);
TTS_EXPR_IS( eve::bit_shl(v_t(), vu_t()) , v_t);
};
//================================================================================================
// random size values
//================================================================================================
inline auto const random_bits = []<typename T>(eve::as<T>, auto& gen)
{
using i_t = eve::as_integer_t<eve::element_type_t<T>>;
eve::prng<i_t> dist(0,8*sizeof(i_t)-1);
std::array<i_t,eve::test::amount<T>()> d;
std::for_each(d.begin(), d.end(), [&](auto& e) { e = dist(gen); });
return d;
};
//==================================================================================================
// wide tests
//==================================================================================================
EVE_TEST( "Check behavior of bit_shl(wide, wide)"
, eve::test::simd::integers
, eve::test::generate(eve::test::randoms(-50,50)
, random_bits
, eve::test::logicals(0, 3))
)
<typename T, typename I, typename L>(T a0, I a1, L test)
{
using eve::bit_shl;
using eve::detail::map;
using v_t = typename T::value_type;
TTS_EQUAL( bit_shl(a0, a1), map([](auto e, auto s) ->v_t { return e << s; }, a0, a1));
TTS_EQUAL( bit_shl[test](a0, a1), eve::if_else(test, eve::bit_shl(a0, a1), a0));
};
EVE_TEST( "Check behavior of bit_shl(wide, scalar)"
, eve::test::simd::integers
, eve::test::generate(eve::test::randoms(-50,50)
, random_bits
, eve::test::logicals(0, 3))
)
<typename T, typename I, typename L>(T a0, I s, L test)
{
using eve::bit_shl;
using eve::detail::map;
auto val = s.get(0);
using v_t = typename T::value_type;
TTS_EQUAL( bit_shl(a0, val), map([&](auto e) ->v_t{ return e << val; }, a0) );
TTS_EQUAL( bit_shl[test](a0, val), eve::if_else(test, eve::bit_shl(a0, val), a0));
};
//==================================================================================================
// Scalar tests
//==================================================================================================
EVE_TEST( "Check behavior of bitshl(scalar, scalar)"
, eve::test::scalar::integers
, eve::test::generate(eve::test::randoms(-50,50)
, random_bits
, eve::test::logicals(0, 3))
)
<typename T, typename I, typename L>(T a0, I a1, L test)
{
using eve::bit_shl;
using v_t = typename T::value_type;
for(std::size_t i = 0; i < a0.size(); ++i)
{
TTS_EQUAL( bit_shl(a0[i], a1[i]), v_t(a0[i] << a1[i]));
TTS_EQUAL( bit_shl[test[i]](a0[i], a1[i]), (test[i] ? bit_shl(a0[i], a1[i]) : a0[i]));
}
};
| 9,848
|
https://github.com/mherde/modAL/blob/master/modAL/utils/parzen_window_classifier.py
|
Github Open Source
|
Open Source
|
MIT
| null |
modAL
|
mherde
|
Python
|
Code
| 871
| 2,413
|
import numpy as np
from sklearn.base import BaseEstimator, ClassifierMixin
from sklearn.metrics.pairwise import pairwise_kernels
from sklearn.utils import check_random_state, check_array
class PWC(BaseEstimator, ClassifierMixin):
"""PWC
The Parzen window classifier (PWC) is a simple and probabilistic classifier. This classifier is based on a
non-parametric density estimation obtained by applying a kernel function.
Parameters
----------
n_classes: int,
This parameter indicates the number of available classes.
metric: str,
The metric must a be a valid kernel defined by the function sklearn.metrics.pairwise.pairwise_kernels.
n_neighbors: int,
Number of nearest neighbours. Default is None, which means all available samples are considered.
kwargs: str,
Any further parameters are passed directly to the kernel function.
Attributes
----------
n_classes: int,
This parameters indicates the number of available classes.
metric: str,
The metric must a be a valid kernel defined by the function sklearn.metrics.pairwise.pairwise_kernels.
n_neighbors: int,
Number of nearest neighbours. Default is None, which means all available samples are considered.
kwargs: str,
Any further parameters are passed directly to the kernel function.
X: array-like, shape (n_samples, n_features)
The sample matrix X is the feature matrix representing the samples.
y: array-like, shape (n_samples) or (n_samples, n_outputs)
It contains the class labels of the training samples.
The number of class labels may be variable for the samples.
Z: array-like, shape (n_samples, n_classes)
The class labels are represented by counting vectors. An entry Z[i,j] indicates how many class labels of class j
were provided for training sample i.
References
----------
O. Chapelle, "Active Learning for Parzen Window Classifier",
Proceedings of the Tenth International Workshop Artificial Intelligence and Statistics, 2005.
"""
# see https://scikit-learn.org/stable/modules/generated/sklearn.metrics.pairwise.pairwise_kernels.html for
# more information
KERNEL_PARAMS = {
"additive_chi2": (),
"chi2": frozenset(["gamma"]),
"cosine": (),
"linear": (),
"poly": frozenset(["gamma", "degree", "coef0"]),
"polynomial": frozenset(["gamma", "degree", "coef0"]),
"rbf": frozenset(["gamma"]),
"laplacian": frozenset(["gamma"]),
"sigmoid": frozenset(["gamma", "coef0"]),
"precomputed": frozenset([])
}
def __init__(self, n_classes, metric='rbf', n_neighbors=None, gamma=None, random_state=42, **kwargs):
self.n_classes = int(n_classes)
if self.n_classes <= 0:
raise ValueError("The parameter 'n_classes' must be a positive integer.")
self.metric = str(metric)
if self.metric not in self.KERNEL_PARAMS.keys():
raise ValueError("The parameter 'metric' must be a in {}".format(self.KERNEL_PARAMS.keys()))
self.n_neighbors = int(n_neighbors) if n_neighbors is not None else n_neighbors
if self.n_neighbors is not None and self.n_neighbors <= 0:
raise ValueError("The parameter 'n_neighbors' must be a positive integer.")
self.random_state = check_random_state(random_state)
self.kwargs = kwargs
self.X = None
self.y = None
self.Z = None
self.gamma = gamma
def fit(self, X, y):
"""
Fit the model using X as training data and y as class labels.
Parameters
----------
X: matrix-like, shape (n_samples, n_features)
The sample matrix X is the feature matrix representing the samples.
y: array-like, shape (n_samples) or (n_samples, n_outputs)
It contains the class labels of the training samples.
The number of class labels may be variable for the samples, where missing labels are
represented by np.nan.
Returns
-------
self: PWC,
The PWC is fitted on the training data.
"""
if np.size(X) > 0:
self.X = check_array(X)
self.y = check_array(y, ensure_2d=False, force_all_finite=False).astype(int)
# convert labels to count vectors
self.Z = np.zeros((np.size(X, 0), self.n_classes))
for i in range(np.size(self.Z, 0)):
self.Z[i, self.y[i]] += 1
return self
def predict_proba(self, X, **kwargs):
"""
Return probability estimates for the test data X.
Parameters
----------
X: array-like, shape (n_samples, n_features) or shape (n_samples, m_samples) if metric == 'precomputed'
Test samples.
C: array-like, shape (n_classes, n_classes)
Classification cost matrix.
Returns
-------
P: array-like, shape (t_samples, n_classes)
The class probabilities of the input samples. Classes are ordered by lexicographic order.
"""
# if normalize is false, the probabilities are frequency estimates
normalize = kwargs.pop('normalize', True)
# no training data -> random prediction
if self.X is None or np.size(self.X, 0) == 0:
if normalize:
return np.full((np.size(X, 0), self.n_classes), 1. / self.n_classes)
else:
return np.zeros((np.size(X, 0), self.n_classes))
# calculating metric matrix
if self.metric == 'linear':
K = pairwise_kernels(X, self.X, metric=self.metric, **self.kwargs)
else:
K = pairwise_kernels(X, self.X, metric=self.metric, gamma=self.gamma, **self.kwargs)
if self.n_neighbors is None:
# calculating labeling frequency estimates
P = K @ self.Z
else:
if np.size(self.X, 0) < self.n_neighbors:
n_neighbors = np.size(self.X, 0)
else:
n_neighbors = self.n_neighbors
indices = np.argpartition(K, -n_neighbors, axis=1)[:, -n_neighbors:]
P = np.empty((np.size(X, 0), self.n_classes))
for i in range(np.size(X, 0)):
P[i, :] = K[i, indices[i]] @ self.Z[indices[i], :]
if normalize:
# normalizing probabilities of each sample
normalizer = np.sum(P, axis=1)
P[normalizer > 0] /= normalizer[normalizer > 0, np.newaxis]
P[normalizer == 0, :] = [1 / self.n_classes] * self.n_classes
# normalizer[normalizer == 0.0] = 1.0
# for y_idx in range(self.n_classes):
# P[:, y_idx] /= normalizer
return P
def predict(self, X, **kwargs):
"""
Return class label predictions for the test data X.
Parameters
----------
X: array-like, shape (n_samples, n_features) or shape (n_samples, m_samples) if metric == 'precomputed'
Test samples.
Returns
-------
y: array-like, shape = [n_samples]
Predicted class labels class.
"""
C = kwargs.pop('C', None)
if C is None:
C = np.ones((self.n_classes, self.n_classes))
np.fill_diagonal(C, 0)
P = self.predict_proba(X, normalize=True)
return self._rand_arg_min(np.dot(P, C), axis=1)
def reset(self):
"""
Reset fitted parameters.
"""
self.X = None
self.y = None
self.Z = None
self.random_state = self.random_state
def _rand_arg_min(self, arr, axis=1):
"""
Returns index of minimal element per given axis. In case of a tie, the index is chosen randomly.
Parameters
----------
arr: array-like
Array whose minimal elements' indices are determined.
axis: int
Indices of minimal elements are determined along this axis.
Returns
-------
min_indices: array-like
Indices of minimal elements.
"""
arr_min = arr.min(axis, keepdims=True)
tmp = self.random_state.uniform(low=1, high=2, size=arr.shape) * (arr == arr_min)
return tmp.argmax(axis)
| 15,996
|
https://github.com/reislerjul/HoloIoT/blob/master/UnityProject/HoloIoT/Assets/MeshChart/Script/BarChart.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,017
|
HoloIoT
|
reislerjul
|
C#
|
Code
| 521
| 2,146
|
using UnityEngine;
using System.Collections;
public class BarChart : Chart {
public float mBarWidth = 0.2f;
public Color[] mBaseColor;
public float MaxValue = 1.0f, MinValue = 0.0f;
public bool AutoRange = true;
public float alpha = 1.0f;
public bool Stacked = true;
public float mDepthPitch = 0.001f;
private float mWidth = 1.0f, mHeight = 1.0f;
private Mesh mesh;
private MeshFilter meshFilter;
private Vector3[] vertices;
private int[] triangles;
private Vector2[] uvs;
private Color[] mColor;
BarChart() {
int length = 8;
mData = new float[2][];
mData[0] = new float[length];
for(int j=0;j<mData[0].Length;j++) {
mData[0][j] = mData[0].Length / (float)(j + 2.0f);
}
mData[1] = new float[length];
for(int j=0;j<mData[1].Length;j++) {
mData[1][j] = (float)j / (float)mData[1].Length;
}
mBaseColor = new Color[]{Color.blue, Color.red, Color.green,
Color.yellow, Color.magenta, Color.cyan, Color.gray};
}
protected override void CreateChartData() {
meshFilter = (MeshFilter)GetComponent("MeshFilter");
mesh = meshFilter.sharedMesh;//new Mesh();
if(mesh == null) {
mesh = new Mesh();
}
mesh.Clear();
vertices = new Vector3[mData.Length * mData[0].Length * 4];
mColor = new Color[mData.Length * mData[0].Length * 4];
uvs = new Vector2[mData.Length * mData[0].Length * 4];
triangles = new int[3* 2 * mData.Length * (mData[0].Length)];
if(AutoRange) {
MaxValue=0;
MinValue=0;
if(mData.Length > 0) {
if(mData[0].Length > 0) {
MaxValue = MinValue = mData[0][0];
}
}
for(int i=0;i<mData.Length;i++) {
for(int j=0;j<mData[i].Length;j++) {
if(MaxValue < mData[i][j]) {
MaxValue = mData[i][j];
}
if(MinValue > mData[i][j]) {
MinValue = mData[i][j];
}
}
}
float dur = MaxValue - MinValue;
}
for(int j=0;j<mData[0].Length;j++) {
float sum = MinValue;
for(int i=0;i<mData.Length;i++) {
float bw2 = (float)mWidth / (float)mData[i].Length * mBarWidth * 0.5f;
float t = (float)mWidth * (float)(j + 1) / (float)mData[i].Length;
float v;
float vb;
float xoffset = 0.0f;
if(Stacked) {
v = (mData[i][j] + sum - MinValue) / (MaxValue - MinValue) * mHeight;
vb = (sum - MinValue) / (MaxValue - MinValue) * mHeight;
} else {
v = (mData[i][j] - MinValue) / (MaxValue - MinValue) * mHeight;
vb = 0.0f;
xoffset = i * bw2*2.0f;
}
vertices[(i*mData[i].Length+j)*4+0] = new Vector3( xoffset + t - bw2, vb, mDepthPitch * (-i-1) );
vertices[(i*mData[i].Length+j)*4+1] = new Vector3( xoffset + t + bw2, vb, mDepthPitch * (-i-1) );
vertices[(i*mData[i].Length+j)*4+2] = new Vector3( xoffset + t - bw2, v, mDepthPitch * (-i-1) );
vertices[(i*mData[i].Length+j)*4+3] = new Vector3( xoffset + t + bw2, v, mDepthPitch * (-i-1) );
for(int k=0;k<4;k++) {
mColor[(i*mData[i].Length+j)*4+k] = mBaseColor[i];
mColor[(i*mData[i].Length+j)*4+k].a = alpha;
}
uvs[(i*mData[i].Length+j)*4+0] = new Vector2(0.0f, 0.0f);
uvs[(i*mData[i].Length+j)*4+1] = new Vector2(1.0f, 0.0f);
uvs[(i*mData[i].Length+j)*4+2] = new Vector2(0.0f, 1.0f);
uvs[(i*mData[i].Length+j)*4+3] = new Vector2(1.0f, 1.0f);
if(v > vb) {
triangles[(i*(mData[i].Length)+j)*6+0] = 0 + (i*mData[i].Length+j)*4;
triangles[(i*(mData[i].Length)+j)*6+1] = 2 + (i*mData[i].Length+j)*4;
triangles[(i*(mData[i].Length)+j)*6+2] = 1 + (i*mData[i].Length+j)*4;
triangles[(i*(mData[i].Length)+j)*6+3] = 1 + (i*mData[i].Length+j)*4;
triangles[(i*(mData[i].Length)+j)*6+4] = 2 + (i*mData[i].Length+j)*4;
triangles[(i*(mData[i].Length)+j)*6+5] = 3 + (i*mData[i].Length+j)*4;
} else {
triangles[(i*(mData[i].Length)+j)*6+0] = 0 + (i*mData[i].Length+j)*4;
triangles[(i*(mData[i].Length)+j)*6+1] = 1 + (i*mData[i].Length+j)*4;
triangles[(i*(mData[i].Length)+j)*6+2] = 2 + (i*mData[i].Length+j)*4;
triangles[(i*(mData[i].Length)+j)*6+3] = 1 + (i*mData[i].Length+j)*4;
triangles[(i*(mData[i].Length)+j)*6+4] = 3 + (i*mData[i].Length+j)*4;
triangles[(i*(mData[i].Length)+j)*6+5] = 2 + (i*mData[i].Length+j)*4;
}
sum += mData[i][j];
}
}
if(mesh.vertices.Length != vertices.Length) {
mesh.triangles = null;
}
mesh.vertices = vertices;
mesh.triangles = triangles;
mesh.uv = uvs;
mesh.colors = mColor;
mesh.RecalculateNormals();
mesh.RecalculateBounds();
//mesh.Optimize();
meshFilter.sharedMesh = mesh;
meshFilter.sharedMesh.name = "BarChartMesh";
vertices = null;
mColor = null;
uvs = null;
triangles = null;
mesh = null;
meshFilter = null;
}
}
| 14,011
|
https://github.com/eduardordm/enginevib/blob/master/test/soft_ticker_test.rb
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
enginevib
|
eduardordm
|
Ruby
|
Code
| 14
| 78
|
require 'test_helper'
class SofTickerTest < Minitest::Test
def test_must_comply_with_contract
Enginevib::SoftTicker.respond_to? :preempt_rt
Enginevib::SoftTicker.respond_to? :delay_rt
end
end
| 46,528
|
https://github.com/VisionGameOrg/enjin-csharp-sdk/blob/master/EnjinCSharpSDK/Models/Asset.cs
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,022
|
enjin-csharp-sdk
|
VisionGameOrg
|
C#
|
Code
| 347
| 757
|
/* Copyright 2021 Enjin Pte. 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.
*/
using System.Collections.Generic;
using JetBrains.Annotations;
using Newtonsoft.Json;
namespace Enjin.SDK.Models
{
/// <summary>
/// Models a asset on the platform.
/// </summary>
[PublicAPI]
public class Asset
{
/// <summary>
/// Represents the base ID of this asset.
/// </summary>
/// <value>The ID.</value>
[JsonProperty("id")]
public string? Id { get; private set; }
/// <summary>
/// Represents the name of this asset.
/// </summary>
/// <value>The name.</value>
[JsonProperty("name")]
public string? Name { get; private set; }
/// <summary>
/// Represents the state data of this asset.
/// </summary>
/// <value>The data.</value>
[JsonProperty("stateData")]
public AssetStateData? StateData { get; private set; }
/// <summary>
/// Represents the configuration data of this asset.
/// </summary>
/// <value>The data.</value>
[JsonProperty("configData")]
public AssetConfigData? ConfigData { get; private set; }
/// <summary>
/// Represents the variant mode of this asset.
/// </summary>
/// <value>The variant mode.</value>
[JsonProperty("variantMode")]
public AssetVariantMode? VariantMode { get; private set; }
/// <summary>
/// Represents variants of this asset.
/// </summary>
/// <value>The variants.</value>
[JsonProperty("variants")]
public List<AssetVariant>? Variants { get; private set; }
/// <summary>
/// Represents the datetime when this asset was created.
/// </summary>
/// <value>The datetime.</value>
/// <remarks>
/// The datetime is formatted using the ISO 8601 date format.
/// </remarks>
[JsonProperty("createdAt")]
public string? CreatedAt { get; private set; }
/// <summary>
/// Represents the datetime when this asset was last updated.
/// </summary>
/// <value>The datetime.</value>
/// <remarks>
/// The datetime is formatted using the ISO 8601 date format.
/// </remarks>
[JsonProperty("updatedAt")]
public string? UpdatedAt { get; private set; }
}
}
| 35,953
|
https://github.com/zxfrdas/ZTLib/blob/master/source/test/src/com/example/test/SourceController.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,015
|
ZTLib
|
zxfrdas
|
Java
|
Code
| 166
| 533
|
package com.example.test;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
public class SourceController {
private List<String> mOrderSources;
private SourceMap mSpecificVideoSources;
private static final class SourceMap extends HashMap<String, Collection<String>> {
private static final long serialVersionUID = -962874052035416446L;
public Collection<String> put(String key, String value) {
Collection<String> realValue = new HashSet<String>();
realValue.add(value);
return put(key, realValue);
}
@Override
public Collection<String> put(String key, Collection<String> value) {
if (containsKey(key)) {
value.addAll(get(key));
}
return super.put(key, value);
}
}
private static final class InstanceHolder {
private static SourceController sInstance = new SourceController();
}
public static SourceController getInstance() {
return InstanceHolder.sInstance;
}
private SourceController() {
mSpecificVideoSources = new SourceMap();
mOrderSources = new ArrayList<String>();
mOrderSources.add(2 + "");
mOrderSources.add(0 + "");
mOrderSources.add(1 + "");
}
public void put(String name, String value) {
mSpecificVideoSources.put(name, value);
}
public void remove(String name) {
mSpecificVideoSources.remove(name);
}
public String getSuitableSource(String name) {
Collection<String> sources = mSpecificVideoSources.get(name);
for (String s : mOrderSources) {
for (String source : sources) {
if (s.equals(source)) {
return s;
}
}
}
return null;
}
}
| 17,620
|
https://github.com/MikeIceman/tg-php/blob/master/WebService/Library/iniparser.class.php
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
tg-php
|
MikeIceman
|
PHP
|
Code
| 304
| 1,016
|
<?php
// INI Parser Class File V.1 By ArioWeb Tech Media Inc.
// Author : NIMIX3 ( www.NIMIX3.com )
// Under GPL3 License
function write_ini_file($array, $file)
{
$res = array();
foreach($array as $key => $val)
{
if(is_array($val))
{
$res[] = "[$key]";
foreach($val as $skey => $sval) $res[] = "$skey = ".(is_numeric($sval) ? $sval : '"'.$sval.'"');
}
else $res[] = "$key = ".(is_numeric($val) ? $val : '"'.$val.'"');
}
safefilerewrite($file, implode("\r\n", $res));
}
function safefilerewrite($fileName, $dataToSave)
{ if ($fp = fopen($fileName, 'w'))
{
$startTime = microtime();
do
{ $canWrite = flock($fp, LOCK_EX);
if(!$canWrite) usleep(round(rand(0, 100)*1000));
} while ((!$canWrite)and((microtime()-$startTime) < 1000));
if ($canWrite)
{ fwrite($fp, $dataToSave);
flock($fp, LOCK_UN);
}
fclose($fp);
}
}
function read_ini_file($file)
{
return parse_ini_file($file);
}
function parse_ini_advanced($array) {
$returnArray = array();
if (is_array($array)) {
foreach ($array as $key => $value) {
$e = explode(':', $key);
if (!empty($e[1])) {
$x = array();
foreach ($e as $tk => $tv) {
$x[$tk] = trim($tv);
}
$x = array_reverse($x, true);
foreach ($x as $k => $v) {
$c = $x[0];
if (empty($returnArray[$c])) {
$returnArray[$c] = array();
}
if (isset($returnArray[$x[1]])) {
$returnArray[$c] = array_merge($returnArray[$c], $returnArray[$x[1]]);
}
if ($k === 0) {
$returnArray[$c] = array_merge($returnArray[$c], $array[$key]);
}
}
} else {
$returnArray[$key] = $array[$key];
}
}
}
return $returnArray;
}
function recursive_parse($array)
{
$returnArray = array();
if (is_array($array)) {
foreach ($array as $key => $value) {
if (is_array($value)) {
$array[$key] = recursive_parse($value);
}
$x = explode('.', $key);
if (!empty($x[1])) {
$x = array_reverse($x, true);
if (isset($returnArray[$key])) {
unset($returnArray[$key]);
}
if (!isset($returnArray[$x[0]])) {
$returnArray[$x[0]] = array();
}
$first = true;
foreach ($x as $k => $v) {
if ($first === true) {
$b = $array[$key];
$first = false;
}
$b = array($v => $b);
}
$returnArray[$x[0]] = array_merge_recursive($returnArray[$x[0]], $b[$x[0]]);
} else {
$returnArray[$key] = $array[$key];
}
}
}
return $returnArray;
}
// example
//$array = parse_ini_file('test.ini', true);
//$array = recursive_parse(parse_ini_advanced($array));
?>
| 10,413
|
https://github.com/USDA-FSA/fsa-design-system/blob/master/js/components/ds-page-toggle.js
|
Github Open Source
|
Open Source
|
CC0-1.0
| 2,022
|
fsa-design-system
|
USDA-FSA
|
JavaScript
|
Code
| 168
| 431
|
var Storage = require('../utilities/storage');
var PageToggle = function () {
var key, toggle, toggleState, toggleId, bodyClass, useStorage;
// Toggle ON setter
var setOn = function(){
document.body.classList.add(bodyClass);
setState(true);
}
// Toggle OFF setter
var setOff = function(){
document.body.classList.remove(bodyClass);
setState(false);
}
// State setter
var setState = function(bool){
toggle.checked = toggleState = bool;
if(useStorage) Storage.setToggleState(key, bool);
}
// Set initial state of page/show code checkbox
var setInitialState = function(){ toggleState ? setOn() : setOff() }
var init = function( obj ){
key = obj.key;
toggleId = obj.toggleId;
bodyClass = obj.bodyClass;
useStorage = obj.useStorage == false ? false : true;
toggleState = false;
// Grab Toggle checkbox on page
toggle = document.getElementById(toggleId);
// check to make sure toggle exists on page, then set change handler
if(toggle){
if(useStorage) toggleState = Storage.getToggleState(key)
// delay initialize code so that is runs last on page
setTimeout( setInitialState, 200);
toggle.addEventListener('change', function(e){
toggleState ? setOff() : setOn()
}, false);
}
}
//Object Literal Return
return {
init: init // expects an Object
};
};
module.exports = PageToggle;
| 29,762
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.