hexsha
stringlengths 40
40
| size
int64 5
1.05M
| ext
stringclasses 98
values | lang
stringclasses 21
values | max_stars_repo_path
stringlengths 3
945
| max_stars_repo_name
stringlengths 4
118
| max_stars_repo_head_hexsha
stringlengths 40
78
| max_stars_repo_licenses
sequencelengths 1
10
| max_stars_count
int64 1
368k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 3
945
| max_issues_repo_name
stringlengths 4
118
| max_issues_repo_head_hexsha
stringlengths 40
78
| max_issues_repo_licenses
sequencelengths 1
10
| max_issues_count
int64 1
134k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 3
945
| max_forks_repo_name
stringlengths 4
135
| max_forks_repo_head_hexsha
stringlengths 40
78
| max_forks_repo_licenses
sequencelengths 1
10
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 5
1.05M
| avg_line_length
float64 1
1.03M
| max_line_length
int64 2
1.03M
| alphanum_fraction
float64 0
1
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
525440de8f0b4fa7b5286d76ef215b00230b8ae6 | 542 | rb | Ruby | app/controllers/api/v1/accounts/agent_histories_controller.rb | proficientDev/TextyOmni | 954cbd8c4d4aefdb7a71f3e18e0c7e2791b0c9f8 | [
"MIT"
] | null | null | null | app/controllers/api/v1/accounts/agent_histories_controller.rb | proficientDev/TextyOmni | 954cbd8c4d4aefdb7a71f3e18e0c7e2791b0c9f8 | [
"MIT"
] | null | null | null | app/controllers/api/v1/accounts/agent_histories_controller.rb | proficientDev/TextyOmni | 954cbd8c4d4aefdb7a71f3e18e0c7e2791b0c9f8 | [
"MIT"
] | null | null | null | class Api::V1::Accounts::AgentHistoriesController < ApplicationController
before_action :fetch_agent_histories, only: [:show]
def index
@agent_histories = agent_histories
end
def show
Rails.logger.info "--------------USER: #{@agent_histories}"
# return @agent_histories
render partial: 'api/v1/models/agent_histories.json.jbuilder', locals: { resource: @agent_histories }
end
private
def fetch_agent_histories
@agent_histories = Current.account.users.find(params[:id]).availability_statuses
end
end
| 28.526316 | 105 | 0.728782 |
79db8e48d42ead5650e6ac8c620b95402188f211 | 847 | php | PHP | src/test/php/com/handlebarsjs/unittest/LookupHelperTest.class.php | xp-forge/handlebars | c7129cbba082b68710751f7d26dc6dbd3223ad72 | [
"RSA-MD"
] | null | null | null | src/test/php/com/handlebarsjs/unittest/LookupHelperTest.class.php | xp-forge/handlebars | c7129cbba082b68710751f7d26dc6dbd3223ad72 | [
"RSA-MD"
] | 12 | 2015-01-10T19:50:40.000Z | 2021-05-09T14:14:37.000Z | src/test/php/com/handlebarsjs/unittest/LookupHelperTest.class.php | xp-forge/handlebars | c7129cbba082b68710751f7d26dc6dbd3223ad72 | [
"RSA-MD"
] | null | null | null | <?php namespace com\handlebarsjs\unittest;
use unittest\Assert;
use unittest\{Test, Values};
class LookupHelperTest extends HelperTest {
#[Test]
public function should_lookup_arbitrary_content() {
Assert::equals('ZeroOne', $this->evaluate('{{#each goodbyes}}{{lookup ../data .}}{{/each}}', [
'goodbyes' => [0, 1],
'data' => ['Zero', 'One']
]));
}
#[Test]
public function should_not_fail_on_undefined_value() {
Assert::equals('', $this->evaluate('{{#each goodbyes}}{{lookup ../bar .}}{{/each}}', [
'goodbyes' => [0, 1],
'data' => ['Zero', 'One']
]));
}
#[Test, Values(['{{lookup map key}}', '{{lookup map key.name}}', '{{lookup map.sub key}}', '{{lookup map.sub key.name}}'])]
public function lookup_non_existant($expr) {
Assert::equals('', $this->evaluate($expr, []));
}
} | 30.25 | 125 | 0.586777 |
dd7094cdf5465e626696af6846d14eb1be0d4caa | 3,885 | java | Java | src/main/java/io/xjar/XEncryption.java | ilaotan/xjar | 7dc76e81f3c6eea0a50889f877baf682e6aa91aa | [
"Apache-2.0"
] | 1,054 | 2018-11-29T06:56:40.000Z | 2022-03-31T09:17:48.000Z | src/main/java/io/xjar/XEncryption.java | codeya1024/xjar | f54488ce450835bf2ae88e23de3d78552a043608 | [
"Apache-2.0"
] | 96 | 2018-12-02T06:48:07.000Z | 2022-03-30T15:01:02.000Z | src/main/java/io/xjar/XEncryption.java | codeya1024/xjar | f54488ce450835bf2ae88e23de3d78552a043608 | [
"Apache-2.0"
] | 323 | 2018-11-30T17:02:36.000Z | 2022-03-24T03:56:16.000Z | package io.xjar;
import io.xjar.filter.XAllEntryFilter;
import io.xjar.filter.XAnyEntryFilter;
import io.xjar.filter.XMixEntryFilter;
import io.xjar.key.XKey;
import org.apache.commons.compress.archivers.jar.JarArchiveEntry;
import java.io.File;
import java.security.NoSuchAlgorithmException;
import java.util.regex.Pattern;
import static io.xjar.XFilters.*;
/**
* 加密
*
* @author Payne [email protected]
* 2020/4/30 17:05
*/
public class XEncryption {
private File jar;
private XKey key;
private XAnyEntryFilter<JarArchiveEntry> includes = XKit.any();
private XAllEntryFilter<JarArchiveEntry> excludes = XKit.all();
/**
* 指定原文包路径
*
* @param jar 原文包路径
* @return {@code this}
*/
public XEncryption from(String jar) {
return from(new File(jar));
}
/**
* 指定原文包文件
*
* @param jar 原文包文件
* @return {@code this}
*/
public XEncryption from(File jar) {
this.jar = jar;
return this;
}
/**
* 指定密码
*
* @param password 密码
* @return {@code this}
*/
public XEncryption use(String password) {
try {
this.key = XKit.key(password);
return this;
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException(e);
}
}
/**
* 指定高级密码
*
* @param algorithm 算法名称
* @param keysize 密钥长度
* @param ivsize 向量长度
* @param password 加密密码
* @return {@code this}
*/
public XEncryption use(String algorithm, int keysize, int ivsize, String password) {
try {
this.key = XKit.key(algorithm, keysize, ivsize, password);
return this;
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException(e);
}
}
/**
* 指定包含资源的ANT表达式, 可指定多个.
*
* @param ant 包含资源的ANT表达式
* @return {@code this}
*/
public XEncryption include(String ant) {
includes.mix(ant(ant));
return this;
}
/**
* 指定包含资源的正则表达式, 可指定多个.
*
* @param regex 包含资源的正则表达式
* @return {@code this}
*/
public XEncryption include(Pattern regex) {
includes.mix(regex(regex.pattern()));
return this;
}
/**
* 指定排除资源的ANT表达式, 可指定多个.
*
* @param ant 排除资源的ANT表达式
* @return {@code this}
*/
public XEncryption exclude(String ant) {
excludes.mix(not(ant(ant)));
return this;
}
/**
* 指定排除资源的正则表达式, 可指定多个.
*
* @param regex 排除资源的正则表达式
* @return {@code this}
*/
public XEncryption exclude(Pattern regex) {
excludes.mix(not(regex(regex.pattern())));
return this;
}
/**
* 指定密文包路径, 并执行加密.
*
* @param xJar 密文包路径
* @throws Exception 加密异常
*/
public void to(String xJar) throws Exception {
to(new File(xJar));
}
/**
* 指定密文包文件, 并执行加密.
*
* @param xJar 密文包文件
* @throws Exception 加密异常
*/
public void to(File xJar) throws Exception {
if (jar == null) {
throw new IllegalArgumentException("jar to encrypt is null. [please call from(String jar) or from(File jar) before]");
}
if (key == null) {
throw new IllegalArgumentException("key to encrypt is null. [please call use(String password) or use(String algorithm, int keysize, int ivsize, String password) before]");
}
XMixEntryFilter<JarArchiveEntry> filter;
if (includes.size() == 0 && excludes.size() == 0) {
filter = null;
} else {
filter = XKit.all();
if (includes.size() > 0) {
filter.mix(includes);
}
if (excludes.size() > 0) {
filter.mix(excludes);
}
}
XCryptos.encrypt(jar, xJar, key, filter);
}
}
| 23.834356 | 183 | 0.559588 |
4f4aa31273982e21e564dc92cdc3fc60eff0d2bc | 1,300 | php | PHP | resources/views/programar_cirugia/form.blade.php | rikardote/cirugias | 3f582bb3977c69564798828af65013bcdfc59eb5 | [
"MIT"
] | null | null | null | resources/views/programar_cirugia/form.blade.php | rikardote/cirugias | 3f582bb3977c69564798828af65013bcdfc59eb5 | [
"MIT"
] | null | null | null | resources/views/programar_cirugia/form.blade.php | rikardote/cirugias | 3f582bb3977c69564798828af65013bcdfc59eb5 | [
"MIT"
] | null | null | null | <div class="form-group">
{!! Form::label('fecha', 'Fecha') !!}
{!! Form::text('fecha', fecha_dmy($date), [
'class' => 'form-control',
'placeholder' => 'Selecciona la fecha',
'readonly'
]) !!}
</div>
<div class="form-group">
{!! Form::select('ubicacion', ['HOSP' => 'HOSP', 'EXT' => 'EXT'], null, [
'class' => 'form-control',
'placeholder' => 'Selecciona una ubicacion',
'required'])
!!}
</div>
<div class="form-group">
{!! Form::label('edad', 'Edad del paciente') !!}
{!! Form::number('edad', null, [
'class' => 'form-control',
'placeholder' => 'Ingrese edad del paciente',
'min' => '1',
'required'
]) !!}
</div>
<div class="form-group">
{!! Form::label('medico_id', 'Medico') !!}
{!! Form::select('medico_id', $medicos, null, [
'class' => 'form-control',
'placeholder' => 'Selecciona un Medico',
'required'
]) !!}
</div>
<div class="form-group">
{!! Form::label('cirugia_id', 'Cirugia') !!}
{!! Form::select('cirugia_id', $cirugias, null, [
'class' => 'form-control',
'placeholder' => 'Selecciona un procedimiento',
'required'
]) !!}
</div>
<div class="form-group">
{!! Form::label('urgencias', 'Urgencia?') !!}
{!!Form::checkbox('urgencias', 1); !!}
</div>
{{ Form::hidden('paciente_id', $paciente->id) }} | 26 | 74 | 0.555385 |
4af994b1f5e9c8c76d19bcb98edc30e566cda5f8 | 1,757 | dart | Dart | lib/main.dart | BenjaminEarley/flutter_chat_app | 050b0ed85784e14c94f418310f1f74ac91f725bd | [
"MIT"
] | 2 | 2019-08-09T20:54:32.000Z | 2019-08-23T17:18:21.000Z | lib/main.dart | BenjaminEarley/flutter_chat_app | 050b0ed85784e14c94f418310f1f74ac91f725bd | [
"MIT"
] | 1 | 2019-08-23T19:19:58.000Z | 2019-08-23T19:19:58.000Z | lib/main.dart | BenjaminEarley/flutter_chat_app | 050b0ed85784e14c94f418310f1f74ac91f725bd | [
"MIT"
] | 1 | 2019-08-23T17:18:31.000Z | 2019-08-23T17:18:31.000Z | import 'package:chat/blocs/auth/auth_bloc.dart';
import 'package:chat/pages/chat/chat.dart';
import 'package:chat/pages/profile/profile.dart';
import 'package:chat/pages/registration/registration.dart';
import 'package:chat/pages/splash.dart';
import 'package:firebase_analytics/firebase_analytics.dart';
import 'package:firebase_analytics/observer.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
void main() => runApp(ChatApp());
class ChatApp extends StatelessWidget {
static FirebaseAnalytics analytics = FirebaseAnalytics();
static FirebaseAnalyticsObserver observer =
FirebaseAnalyticsObserver(analytics: analytics);
@override
Widget build(BuildContext context) {
return Provider<AuthBloc>(
builder: (context) => AuthBloc(),
dispose: (context, bloc) => bloc.dispose(),
child: MaterialApp(
title: "Cool Chat",
theme: defaultTheme,
navigatorObservers: <NavigatorObserver>[ChatApp.observer],
initialRoute: splashPage,
routes: {
splashPage: (context) => SplashPage(),
registrationPage: (context) => RegistrationPage(),
chatPage: (context) => ChatPage(),
profilePage: (context) => ProfilePage(),
},
),
);
}
}
final ThemeData iOSTheme = new ThemeData(
primarySwatch: Colors.orange,
primaryColor: Colors.grey[100],
primaryColorBrightness: Brightness.light,
);
final ThemeData defaultTheme = new ThemeData(
primarySwatch: Colors.purple,
accentColor: Colors.orangeAccent[400],
brightness: Brightness.light,
);
final ThemeData defaultDarkTheme = new ThemeData(
primarySwatch: Colors.purple,
accentColor: Colors.orangeAccent[700],
brightness: Brightness.dark,
);
| 31.375 | 66 | 0.716562 |
7983a15205a1f11a498d968bb063734d8fc4e3ea | 262 | php | PHP | cathpci_import_ajax.php | vanderbilt-redcap/VHVI_PCI | aa910801661ab7c387e911196f0fb11978022459 | [
"MIT"
] | null | null | null | cathpci_import_ajax.php | vanderbilt-redcap/VHVI_PCI | aa910801661ab7c387e911196f0fb11978022459 | [
"MIT"
] | null | null | null | cathpci_import_ajax.php | vanderbilt-redcap/VHVI_PCI | aa910801661ab7c387e911196f0fb11978022459 | [
"MIT"
] | null | null | null | <?php
header('Content-Type: application/json;charset=utf-8');
$module->llog('receieved cathpci_import_ajax reqeust: ' . date('c'));
$response = new \stdClass();
list($response->success, $response->msg) = $module->importChunk();
exit(json_encode($response));
?> | 29.111111 | 69 | 0.706107 |
a17833c6d8b87486807f59a4f3a59053aca4e920 | 133 | tsx | TypeScript | src/components/JaegerIntegration/JaegerResults/index.tsx | jadeyliu939/kiali-ui | f0fd35c6e8ca8a5b3c648db86251845e8db48e8f | [
"Apache-2.0"
] | null | null | null | src/components/JaegerIntegration/JaegerResults/index.tsx | jadeyliu939/kiali-ui | f0fd35c6e8ca8a5b3c648db86251845e8db48e8f | [
"Apache-2.0"
] | 3 | 2018-12-06T08:50:51.000Z | 2020-08-04T09:09:51.000Z | src/components/JaegerIntegration/JaegerResults/index.tsx | SmithXiong/kiali-ui-i18n | 3ff8ddef922d5dfe502d9d5da58089bbc44e7cb2 | [
"Apache-2.0"
] | null | null | null | import { JaegerItem } from './JaegerItem';
import transformTraceData from './transform';
export { JaegerItem, transformTraceData };
| 26.6 | 45 | 0.759398 |
cd15d2f4328f66c0913908292cd4152a19c8900e | 1,968 | cs | C# | test/Shared/FunctionalTests/Migrations/LoggingScenarios.cs | mariloutb/EntityFramework-Classic | b52a43d8e72b3a9afe553d4949197c1cace51d68 | [
"Apache-2.0"
] | 96 | 2018-07-08T16:32:23.000Z | 2022-03-31T20:46:21.000Z | test/Shared/FunctionalTests/Migrations/LoggingScenarios.cs | mariloutb/EntityFramework-Classic | b52a43d8e72b3a9afe553d4949197c1cace51d68 | [
"Apache-2.0"
] | 48 | 2018-08-12T19:39:31.000Z | 2021-12-29T01:06:43.000Z | test/Shared/FunctionalTests/Migrations/LoggingScenarios.cs | mariloutb/EntityFramework-Classic | b52a43d8e72b3a9afe553d4949197c1cace51d68 | [
"Apache-2.0"
] | 39 | 2018-08-02T13:00:49.000Z | 2022-02-20T06:25:35.000Z | // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
namespace System.Data.Entity.Migrations
{
using Moq;
using System.Data.Entity.Migrations.Infrastructure;
using System.Data.Entity.TestHelpers;
[Variant(DatabaseProvider.SqlClient, ProgrammingLanguage.CSharp)]
public class LoggingScenarios : DbTestCase
{
private class WarningMigration : DbMigration
{
public override void Up()
{
CreateTable(
"PkTooLong",
t => new
{
Id = t.String(maxLength: 451)
})
.PrimaryKey(t => t.Id);
}
}
[MigrationsTheory]
public void Can_log_provider_execution_warnings()
{
ResetDatabase();
var migrator = CreateMigrator<ShopContext_v1>();
migrator.Update();
var mockLogger = new Mock<MigrationsLogger>();
migrator = CreateMigrator<ShopContext_v1>(new WarningMigration());
var migratorLoggingDecorator
= new MigratorLoggingDecorator(
migrator,
mockLogger.Object);
migratorLoggingDecorator.Update();
if (LocalizationTestHelpers.IsEnglishLocale())
{
mockLogger
.Verify(
ml => ml.Warning(
"Warning! The maximum key length is 900 bytes. The index 'PK_PkTooLong' has maximum length of 902 bytes. For some combination of large values, the insert/update operation will fail."),
Times.Once());
}
else
{
mockLogger.Verify(ml => ml.Warning(It.IsAny<string>()), Times.Once());
}
}
}
}
| 32.262295 | 212 | 0.526931 |
6af18f5477146094ca6a468f117e1dd3746dd56b | 781 | h | C | thumbor/ext/filters/lib/image_utils.h | dynamicguy/thumbor | 4e69ec6289ef549109cdfc72bf765b9dc62f9763 | [
"MIT"
] | 6,837 | 2015-01-01T14:33:12.000Z | 2022-03-31T22:21:05.000Z | thumbor/ext/filters/lib/image_utils.h | dynamicguy/thumbor | 4e69ec6289ef549109cdfc72bf765b9dc62f9763 | [
"MIT"
] | 1,055 | 2015-01-03T22:22:05.000Z | 2022-03-31T21:56:17.000Z | thumbor/ext/filters/lib/image_utils.h | dynamicguy/thumbor | 4e69ec6289ef549109cdfc72bf765b9dc62f9763 | [
"MIT"
] | 744 | 2015-01-05T03:49:31.000Z | 2022-03-30T02:35:16.000Z | #ifndef __IMAGE_UTILS__H__
#define __IMAGE_UTILS__H__
#include <math.h>
#define MAX_RGB_DOUBLE 255.0
#define MAX_RGB 255
#define SMALL_DOUBLE 1.0e-12
#define ADJUST_COLOR(c) ((c > MAX_RGB) ? MAX_RGB : ((c < 0) ? 0 : c))
#define ADJUST_COLOR_DOUBLE(c) ((int)((c > MAX_RGB_DOUBLE) ? MAX_RGB : ((c < 0.0) ? 0 : c)))
#define ALPHA_COMPOSITE_COLOR_CHANNEL(color1, alpha1, color2, alpha2) \
( ((1.0 - (alpha1 / MAX_RGB_DOUBLE)) * (double) color1) + \
((1.0 - (alpha2 / MAX_RGB_DOUBLE)) * (double) color2 * (alpha1 / MAX_RGB_DOUBLE)) )
static inline int
bytes_per_pixel(char *mode)
{
return (int) strlen(mode);
}
static inline int
rgb_order(char *mode, char color)
{
int i = 0;
while (*mode != color && *(++mode)) {
++i;
}
return i;
}
#endif
| 22.314286 | 92 | 0.637644 |
383d174b86cfef3fe279b64629a71121e22a4f1f | 481 | php | PHP | api/modules/v1/controllers/UserattendenceController.php | johnsunam/freelancer-management-system | 6866e8af923b4b3f408e4b24031718a88dbeeaae | [
"BSD-3-Clause"
] | null | null | null | api/modules/v1/controllers/UserattendenceController.php | johnsunam/freelancer-management-system | 6866e8af923b4b3f408e4b24031718a88dbeeaae | [
"BSD-3-Clause"
] | null | null | null | api/modules/v1/controllers/UserattendenceController.php | johnsunam/freelancer-management-system | 6866e8af923b4b3f408e4b24031718a88dbeeaae | [
"BSD-3-Clause"
] | null | null | null | <?php
/**
* Created by PhpStorm.
* User: osho
* Date: 5/4/17
* Time: 5:25 PM
*/
namespace api\modules\v1\controllers;
use yii\rest\ActiveController;
class UserattendenceController extends ActiveController
{
public $modelClass = 'api\modules\v1\models\Userattendence';
public function actions()
{
$actions=parent::actions();
unset($actions['create'],$actions['update'],$actions['delete'],$actions['view']);
return $actions;
}
} | 20.041667 | 89 | 0.648649 |
cd12c7585a60bc6e593abd3f61fc720ab6859f06 | 1,305 | cs | C# | Datahub.Core/Model/Datahub/PBI_License_Request.cs | chuxuantinh/data-hub-chu | 1ae9b82f4781a6fa553715c6dfd5cc88627b70c2 | [
"MIT"
] | 7 | 2021-08-10T19:27:45.000Z | 2022-03-13T13:55:55.000Z | Datahub.Core/Model/Datahub/PBI_License_Request.cs | chuxuantinh/data-hub-chu | 1ae9b82f4781a6fa553715c6dfd5cc88627b70c2 | [
"MIT"
] | 20 | 2022-03-24T12:03:28.000Z | 2022-03-31T20:28:18.000Z | Datahub.Core/Model/Datahub/PBI_License_Request.cs | chuxuantinh/data-hub-chu | 1ae9b82f4781a6fa553715c6dfd5cc88627b70c2 | [
"MIT"
] | 3 | 2021-11-27T01:39:50.000Z | 2022-03-13T13:55:56.000Z | using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Elemental.Components;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Graph;
namespace Datahub.Core.EFCore
{
public enum DataSourceProtection
{
Unclassified, ProtectedA, ProtectedB, Unknown
}
public class PBI_License_Request
{
[AeFormIgnore]
[Key]
public int Request_ID { get; set; }
[AeLabel("Is a Premium License required? ***(Refer to Appendix II for more details on licence types)")]
[Required]
public bool Premium_License_Flag { get; set; }
[StringLength(200)]
[Required]
[AeLabel("Contact Email")]
public string Contact_Email { get; set; }
[StringLength(200)]
[Required]
[AeLabel("Contact Name")]
public string Contact_Name { get; set; }
public Datahub_Project Project { get; set; }
[AeFormIgnore]
public int Project_ID { get; set; }
public bool Desktop_Usage_Flag { get; set; }
public List<PBI_User_License_Request> User_License_Requests { get; set; }
[Required]
public string User_ID { get; set; }
[AeFormIgnore]
[Timestamp]
public byte[] Timestamp { get; set; }
}
} | 25.096154 | 111 | 0.623755 |
586fa1da8420dc0164979c9fe718ed4286436eef | 206 | css | CSS | src/pages/Termsandcondition.module.css | sanjith-kumar-048/react-clone-hennacrafts | ceaa5fef5ef9a7d21940b3b876e4e99865bf0894 | [
"MIT"
] | null | null | null | src/pages/Termsandcondition.module.css | sanjith-kumar-048/react-clone-hennacrafts | ceaa5fef5ef9a7d21940b3b876e4e99865bf0894 | [
"MIT"
] | null | null | null | src/pages/Termsandcondition.module.css | sanjith-kumar-048/react-clone-hennacrafts | ceaa5fef5ef9a7d21940b3b876e4e99865bf0894 | [
"MIT"
] | null | null | null | .border {
width: 80%;
margin: 0 auto;
margin-top: 1em;
}
.border p {
margin-top: 1.5em;
margin-bottom: 1.5em;
}
.lastchild {
color: green;
}
.bullets {
margin-bottom: 0;
margin-left: 1em;
}
| 12.117647 | 23 | 0.601942 |
256c35d771147d3707dff8e01331578c0d255676 | 668 | cs | C# | src/Twilio.Twiml.Tests/RedirectTests.cs | clarartp/twilio-csharp | 4b0ffc066db8ba55327e0b619d7624663f6d04ac | [
"Apache-2.0"
] | null | null | null | src/Twilio.Twiml.Tests/RedirectTests.cs | clarartp/twilio-csharp | 4b0ffc066db8ba55327e0b619d7624663f6d04ac | [
"Apache-2.0"
] | null | null | null | src/Twilio.Twiml.Tests/RedirectTests.cs | clarartp/twilio-csharp | 4b0ffc066db8ba55327e0b619d7624663f6d04ac | [
"Apache-2.0"
] | 1 | 2020-07-06T23:00:26.000Z | 2020-07-06T23:00:26.000Z | using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Twilio.TwiML.Tests
{
[TestClass]
public class RedirectTests : TestBase
{
[TestMethod]
public void Can_Generate_Single_Redirect()
{
var response = new TwilioResponse();
response.Redirect("url");
Assert.IsTrue(IsValidTwiML(response.ToXDocument()));
}
[TestMethod]
public void Can_Generate_Single_Redirect_With_Method()
{
var response = new TwilioResponse();
response.Redirect("url", "GET");
Assert.IsTrue(IsValidTwiML(response.ToXDocument()));
}
}
} | 20.875 | 56 | 0.73503 |
f7b2661864e6a5323b7c01348597f773867fd11f | 377 | sql | SQL | migrations/sql/V2021.05.26.16.47__update_drilling_and_blasting_activity.sql | bcgov/mds | 6c427a66a5edb4196222607291adef8fd6677038 | [
"Apache-2.0"
] | 25 | 2018-07-09T19:04:37.000Z | 2022-03-15T17:27:10.000Z | migrations/sql/V2021.05.26.16.47__update_drilling_and_blasting_activity.sql | areyeslo/mds | e8c38e593e09b78e2a57009c0d003d6c4bfa32e6 | [
"Apache-2.0"
] | 983 | 2018-04-25T20:08:07.000Z | 2022-03-31T21:45:20.000Z | migrations/sql/V2021.05.26.16.47__update_drilling_and_blasting_activity.sql | areyeslo/mds | e8c38e593e09b78e2a57009c0d003d6c4bfa32e6 | [
"Apache-2.0"
] | 58 | 2018-05-15T22:35:50.000Z | 2021-11-29T19:40:52.000Z | ALTER TABLE exploration_surface_drilling ADD COLUMN IF NOT EXISTS drill_program varchar;
ALTER TABLE now_submissions.application ADD COLUMN IF NOT EXISTS expsurfacedrillprogam varchar;
ALTER TABLE now_submissions.application ADD COLUMN IF NOT EXISTS describeexplosivetosite varchar;
ALTER TABLE blasting_operation ADD COLUMN IF NOT EXISTS describe_explosives_to_site varchar; | 62.833333 | 97 | 0.875332 |
ad75076027b4a3fd19219514e9a085f7044ef9d8 | 1,147 | lua | Lua | schema/factions/sh_shock.lua | Nytelife26/RenegadeRP-Imperial-Helix | ac71d636a98dbe91cfae07885c6920e8bca65ef0 | [
"MIT"
] | 2 | 2019-06-20T22:20:00.000Z | 2021-07-18T02:12:57.000Z | schema/factions/sh_shock.lua | Nytelife26/RenegadeRP-Imperial-Helix | ac71d636a98dbe91cfae07885c6920e8bca65ef0 | [
"MIT"
] | null | null | null | schema/factions/sh_shock.lua | Nytelife26/RenegadeRP-Imperial-Helix | ac71d636a98dbe91cfae07885c6920e8bca65ef0 | [
"MIT"
] | 1 | 2019-06-20T22:20:01.000Z | 2019-06-20T22:20:01.000Z | FACTION.name = "Shock Trooper"
FACTION.description = "The military police and detectives of the ship, tasked with investigations and counterintelligence."
FACTION.color = Color(204, 0, 0)
FACTION.pay = 50
FACTION.isDefault = false
FACTION.isGloballyRecognized = true
function FACTION:OnCharacterCreated(client, character)
local inventory = character:GetInventory()
inventory:Add("dlt20a", 1)
inventory:Add("pulses", 4)
inventory:Add("shock", 1)
inventory:Add("idc", 1)
end
function FACTION:GetDefaultName(client)
return "SHT-" .. Schema:ZeroNumber(math.random(1, 99999), 5), true
end
function FACTION:OnTransfered(client)
local character = client:GetCharacter()
character:SetName(self:GetDefaultName())
character:SetModel(self.models[1])
end
function FACTION:OnNameChanged(client, oldValue, value)
local character = client:GetCharacter()
if (!Schema:IsEmpireRank(oldValue, "SHT") and Schema:IsEmpireRank(value, "SHT")) then
character:JoinClass(CLASS_SHT)
elseif (!Schema:IsEmpireRank(oldValue, "SHTO") and Schema:IsEmpireRank(value, "SHTO")) then
character:JoinClass(CLASS_SHTO)
end
end
FACTION_SHOCK = FACTION.index
| 26.674419 | 123 | 0.769834 |
3054cd842d94b71b31412211bfc037761f2ec285 | 1,265 | dart | Dart | lib/main.dart | csells/flutter_cropping | bb9eb840e4b6f46f39cc99bfa6f61cb8c1e07f78 | [
"BSD-3-Clause"
] | 37 | 2019-07-22T22:11:36.000Z | 2021-12-12T12:28:59.000Z | lib/main.dart | csells/flutter_cropping | bb9eb840e4b6f46f39cc99bfa6f61cb8c1e07f78 | [
"BSD-3-Clause"
] | null | null | null | lib/main.dart | csells/flutter_cropping | bb9eb840e4b6f46f39cc99bfa6f61cb8c1e07f78 | [
"BSD-3-Clause"
] | 3 | 2019-09-11T02:32:47.000Z | 2022-03-23T05:47:46.000Z | import 'package:flutter/material.dart';
import 'image_before_after_crop.dart';
import 'package:flutter/foundation.dart' show debugDefaultTargetPlatformOverride;
import 'dart:io';
void _desktopInitHack() {
bool isWeb = identical(0, 0.0);
if (isWeb) return;
if (Platform.isMacOS) {
debugDefaultTargetPlatformOverride = TargetPlatform.iOS;
} else if (Platform.isLinux || Platform.isWindows) {
debugDefaultTargetPlatformOverride = TargetPlatform.android;
} else if (Platform.isFuchsia) {
debugDefaultTargetPlatformOverride = TargetPlatform.fuchsia;
}
}
void main() {
_desktopInitHack();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
final title = 'Flutter Cropping';
final image = AssetImage('images/cat.jpg');
@override
Widget build(BuildContext context) => MaterialApp(
title: title,
theme: ThemeData(primarySwatch: Colors.blue),
home: Scaffold(
appBar: AppBar(title: Text(title)),
body: Column(
children: [
Expanded(child: ImageBeforeAfterCrop(image)),
Text('Tap and drag inside image on the left. Single tap to reset to entire image.'),
],
),
),
);
}
| 29.418605 | 99 | 0.647431 |
4477f5833219d9f4e4b0ce43885c8cf135ad5195 | 2,320 | py | Python | hwtLib/examples/hierarchy/unitWrapper.py | optical-o/hwtLib | edad621f5ad4cdbea20a5751ff4468979afe2f77 | [
"MIT"
] | 24 | 2017-02-23T10:00:50.000Z | 2022-01-28T12:20:21.000Z | hwtLib/examples/hierarchy/unitWrapper.py | optical-o/hwtLib | edad621f5ad4cdbea20a5751ff4468979afe2f77 | [
"MIT"
] | 32 | 2017-04-28T10:29:34.000Z | 2021-04-27T09:16:43.000Z | hwtLib/examples/hierarchy/unitWrapper.py | optical-o/hwtLib | edad621f5ad4cdbea20a5751ff4468979afe2f77 | [
"MIT"
] | 8 | 2019-09-19T03:34:36.000Z | 2022-01-21T06:56:58.000Z | from hwt.hdl.constants import INTF_DIRECTION
from hwt.synthesizer.param import Param
from hwt.synthesizer.unit import Unit
class UnitWrapper(Unit):
"""
Class which creates wrapper around original unit instance,
original unit will be stored inside as subunit named baseUnit
:note: This is example of lazy loaded interfaces
and generating of external interfaces based on internal structure.
"""
def __init__(self, baseUnit: Unit):
"""
:param baseUnit: An :class:`hwt.synthesizer.unit.Unit` instance which should be hidden in this wrapper.
"""
super(UnitWrapper, self).__init__()
self._baseUnit = baseUnit
def _copyParamsAndInterfaces(self):
for p in self._baseUnit._params:
myP = Param(p.get_value())
self._registerParameter(p._name, myP)
myP.set_value(p.get_value())
origToWrapInfMap = {}
for intf in self.baseUnit._interfaces:
# clone interface
myIntf = intf.__copy__()
# sub-interfaces are not instantiated yet
# myIntf._direction = intf._direction
myIntf._direction = INTF_DIRECTION.opposite(intf._direction)
self._registerInterface(intf._name, myIntf)
object.__setattr__(self, intf._name, myIntf)
origToWrapInfMap[intf] = myIntf
ei = self._ctx.interfaces
for i in self._interfaces:
self._loadInterface(i, True)
assert i._isExtern
i._signalsForInterface(self._ctx, ei,
self._store_manager.name_scope,
reverse_dir=True)
return origToWrapInfMap
def _getDefaultName(self):
return self._baseUnit._getDefaultName()
def _get_hdl_doc(self):
return self._baseUnit._get_hdl_doc()
def _connectBaseUnitToThisWrap(self, origToWrapInfMap):
for baseIntf, wrapIntf in origToWrapInfMap.items():
if baseIntf._direction is INTF_DIRECTION.MASTER:
wrapIntf(baseIntf)
else:
baseIntf(wrapIntf)
def _impl(self):
self.baseUnit = self._baseUnit
origToWrapInfMap = self._copyParamsAndInterfaces()
self._connectBaseUnitToThisWrap(origToWrapInfMap)
| 33.623188 | 111 | 0.638793 |
83940af38e3e8325fbec71e9c217f884d08f051b | 2,354 | rs | Rust | resources/afl/runner.rs | ntoskrnl7/hopper | 953980139c53309dd1f353ff74ab8055ff205d18 | [
"MIT"
] | 51 | 2016-12-18T03:50:11.000Z | 2021-06-14T08:04:59.000Z | resources/afl/runner.rs | ntoskrnl7/hopper | 953980139c53309dd1f353ff74ab8055ff205d18 | [
"MIT"
] | 15 | 2016-12-18T18:43:41.000Z | 2020-08-11T21:35:11.000Z | resources/afl/runner.rs | ntoskrnl7/hopper | 953980139c53309dd1f353ff74ab8055ff205d18 | [
"MIT"
] | 6 | 2016-12-18T07:26:54.000Z | 2021-06-25T15:28:08.000Z | #![feature(plugin)]
#![plugin(afl_plugin)]
extern crate afl;
extern crate tempdir;
extern crate hopper;
use self::hopper::channel_with_max_bytes;
use std::io;
use std::io::BufRead;
use std::str::FromStr;
use std::time;
use std::thread;
fn main() {
let stdin = io::stdin();
for s in stdin.lock().lines() {
let pyld: Vec<u64> = s.unwrap()
.split_whitespace()
.filter_map(|f| u64::from_str(f).ok())
.collect();
if pyld.len() < 3 {
return;
}
let cap = pyld[0] as usize;
let max_thrs = pyld[1] as usize;
if max_thrs > 1000 {
return;
}
let max_bytes = pyld[2] as usize;
if max_bytes < 8 {
return;
}
let dir = tempdir::TempDir::new("hopper").unwrap();
let (snd, mut rcv) = channel_with_max_bytes("concurrent_snd_and_rcv_small_max_bytes",
dir.path(),
max_bytes)
.unwrap();
let mut joins = Vec::new();
// start our receiver thread
let mut nxt = 0;
let expected = max_thrs * cap;
let recv_jh = thread::spawn(move || {
let mut count = 0;
let dur = time::Duration::from_millis(1);
for _ in 0..200 {
thread::sleep(dur);
loop {
if let Some(i) = rcv.next() {
count += 1;
if max_thrs == 1 {
assert_eq!(i, nxt);
nxt += 1;
}
} else {
break;
}
}
}
count
});
// start all our sender threads and blast away
for _ in 0..max_thrs {
let mut thr_snd = snd.clone();
joins.push(thread::spawn(move || {
for i in 0..cap {
thr_snd.send(i);
}
}));
}
// wait until the senders are for sure done
for jh in joins {
jh.join().expect("Uh oh, child thread paniced!");
}
let count = recv_jh.join().expect("no count! :<");
assert_eq!(count, expected);
}
}
| 27.694118 | 93 | 0.430331 |
add5ecb43265fc3e678d901ae405d693353b1156 | 427 | lua | Lua | example_mods/stages/ballisticAlley.lua | Crappy-Productions/VS.-Mario-Ultra-Rebooted-Source-Code | 0673bcb83ec27d881cc2cad951f9093616c2192d | [
"Apache-2.0"
] | null | null | null | example_mods/stages/ballisticAlley.lua | Crappy-Productions/VS.-Mario-Ultra-Rebooted-Source-Code | 0673bcb83ec27d881cc2cad951f9093616c2192d | [
"Apache-2.0"
] | null | null | null | example_mods/stages/ballisticAlley.lua | Crappy-Productions/VS.-Mario-Ultra-Rebooted-Source-Code | 0673bcb83ec27d881cc2cad951f9093616c2192d | [
"Apache-2.0"
] | null | null | null | function onCreate()
-- background shit
makeAnimatedLuaSprite('bgg','BallisticBackground',-570.15, -285.45);
setLuaSpriteScrollFactor('bgg', 1, 0.95);
addAnimationByPrefix('bgg','BallisticBackground','Background Whitty Moving',24,true);
addLuaSprite('bgg',false);
close(true); --For performance reasons, close this script once the stage is fully loaded, as this script won't be used anymore after loading the stage
end | 38.818182 | 151 | 0.763466 |
e26128126dc8b214e0ed3c8b14e5300c7daa8d93 | 769 | py | Python | convnet/convnetlib/convnetlib_test.py | tech-team/convnet | ee401c29349e163a95a868304e120de215158e37 | [
"MIT"
] | null | null | null | convnet/convnetlib/convnetlib_test.py | tech-team/convnet | ee401c29349e163a95a868304e120de215158e37 | [
"MIT"
] | null | null | null | convnet/convnetlib/convnetlib_test.py | tech-team/convnet | ee401c29349e163a95a868304e120de215158e37 | [
"MIT"
] | null | null | null | import convnetlib
import numpy as np
filters_count = 2
s = 1
filter_size = 5
X = np.zeros((28, 28, 1))
w = [np.zeros((filter_size, filter_size, 1)) for _ in xrange(filters_count)]
b = [0] * filters_count
out = np.zeros((24, 24, filters_count))
out2 = np.zeros((24, 24, filters_count))
pool_shape = (12, 12, filters_count)
max_indices = np.zeros(pool_shape, dtype=(int, 2))
pool_out = np.zeros(pool_shape)
for _ in xrange(10000000):
# convnetlib.conv_forward(X, w, b, s, out)
# convnetlib.conv_backward(out2, X, w, b)
# convnetlib.conv_prev_layer_delta(out, w, X)
# convnetlib.pool_forward(out, s, 2, max_indices, pool_out)
res = np.zeros(out.shape)
convnetlib.pool_prev_layer_delta(pool_out, max_indices, res)
# print(convnetlib.test(out))
| 28.481481 | 76 | 0.703511 |
bb3d71859c206ef5f48849fc7d56e02843980bf2 | 1,399 | cs | C# | src/Tests/Windows/WindowsTests.cs | eXpandFramework/XAF | 07c52fabd91388ab858200a6853ffef9c59a74dc | [
"Apache-2.0"
] | 39 | 2019-04-20T09:16:06.000Z | 2021-01-13T14:39:39.000Z | src/Tests/Windows/WindowsTests.cs | eXpandFramework/Reactive.XAF | 783fd01dcdfd9ded619c98b73b52a5692ab3bfdf | [
"Apache-2.0"
] | 2 | 2020-06-25T12:11:48.000Z | 2020-07-28T18:10:54.000Z | src/Tests/Windows/WindowsTests.cs | eXpandFramework/DevExpress.XAF | de43d149f4e7f9e0fc5ac4f4ab79a82337aaca37 | [
"Apache-2.0"
] | 22 | 2019-03-29T07:43:10.000Z | 2020-11-18T13:04:39.000Z | using System;
using System.IO;
using System.Reactive.Linq;
using System.Threading;
using akarnokd.reactive_extensions;
using NUnit.Framework;
using Xpand.TestsLib;
using Xpand.TestsLib.Common.Attributes;
using Xpand.XAF.Modules.Reactive;
using Xpand.XAF.Modules.Reactive.Services;
namespace Xpand.XAF.Modules.Windows.Tests {
public class WindowsTests : BaseWindowsTest {
[Test]
[XpandTest]
[Apartment(ApartmentState.STA)]
[TestCase(true)]
[TestCase(false)]
public void StartupWithWindows(bool enable){
using var application = WindowsModule().Application;
var modelWindows = application.Model.ToReactiveModule<IModelReactiveModuleWindows>().Windows;
modelWindows.Startup=enable;
application.WhenWindowCreated(true).Do(_ => application.Exit()).Test();
((TestWinApplication) application).Start();
string deskDir = Environment.GetFolderPath(Environment.SpecialFolder.Startup);
var path = deskDir + "\\" + application.Title + ".url";
if (enable) {
if (!File.Exists(path)) {
throw new FileNotFoundException(path);
}
}
else {
if (File.Exists(path)) {
throw new FileNotFoundException(path);
}
}
}
}
} | 32.534884 | 105 | 0.613295 |
1a79cc2c04ef5b447f7a8a400217e836d80e3ebc | 432 | cs | C# | SheepAspect/Runtime/PropertyJointPoint.cs | erhan0/aop | 02cf13b31734d07d32d8836ea50aede9b10b75c6 | [
"MIT"
] | 12 | 2017-06-08T20:01:31.000Z | 2021-08-24T01:09:39.000Z | SheepAspect/Runtime/PropertyJointPoint.cs | erhan0/aop | 02cf13b31734d07d32d8836ea50aede9b10b75c6 | [
"MIT"
] | null | null | null | SheepAspect/Runtime/PropertyJointPoint.cs | erhan0/aop | 02cf13b31734d07d32d8836ea50aede9b10b75c6 | [
"MIT"
] | 2 | 2019-12-25T02:04:06.000Z | 2020-05-28T01:42:44.000Z | using System.Reflection;
namespace SheepAspect.Runtime
{
public abstract class PropertyJointPoint : MemberJointPointBase
{
protected PropertyJointPoint(PropertyInfo property, AdviceCallback callback, object thisInstance, object[] args)
: base(property, callback, thisInstance, args)
{
Property = property;
}
public PropertyInfo Property { get; private set; }
}
} | 28.8 | 120 | 0.678241 |
1ac077aaa9e69bf8d2e14a668c51799aa360d0b1 | 410 | py | Python | fruering/settings/review_app.py | frueringborgerforening/fruering | cb482268272698d34482dbb956b79f0d114e1834 | [
"MIT"
] | 1 | 2018-05-14T20:19:42.000Z | 2018-05-14T20:19:42.000Z | fruering/settings/review_app.py | andreasbrakhagecarstensen/fruering | cb482268272698d34482dbb956b79f0d114e1834 | [
"MIT"
] | 78 | 2018-03-18T09:36:26.000Z | 2019-12-16T21:06:09.000Z | fruering/settings/review_app.py | andreasbrakhagecarstensen/fruering | cb482268272698d34482dbb956b79f0d114e1834 | [
"MIT"
] | null | null | null | from .base import *
HEROKU_APP_NAME = os.getenv('HEROKU_APP_NAME')
HEROKU_PARENT_APP_NAME = os.getenv('HEROKU_PARENT_APP_NAME')
SECURE_SSL_REDIRECT = True
ALLOWED_HOSTS = ['{}.herokuapp.com'.format(HEROKU_APP_NAME)]
AWS_LOCATION = 'review_app'
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
HOST_NAME = '{}.herokuapp.com'.format(HEROKU_APP_NAME)
BASE_URL = 'https://{}/'.format(HOST_NAME)
| 34.166667 | 65 | 0.785366 |
643876a5f35a46d24c82c77c04e7078059c3561f | 57 | py | Python | src/__init__.py | mahyar-osn/lung-point-generator | 58e6eaf53f40e0c6c80c63bd17e4d6d6f60d72fe | [
"Apache-2.0"
] | null | null | null | src/__init__.py | mahyar-osn/lung-point-generator | 58e6eaf53f40e0c6c80c63bd17e4d6d6f60d72fe | [
"Apache-2.0"
] | null | null | null | src/__init__.py | mahyar-osn/lung-point-generator | 58e6eaf53f40e0c6c80c63bd17e4d6d6f60d72fe | [
"Apache-2.0"
] | null | null | null | __version__ = '0.1'
from .pts_generator import generate
| 14.25 | 35 | 0.77193 |
a368516b6fecb27869fcd4d40a2e770d89ad820d | 341 | h | C | lab5/keyboard.h | reeckset/LCOM_Minix_2017 | 422068bc25d6f50aceb2341e9381af4f4194e6e6 | [
"MIT"
] | null | null | null | lab5/keyboard.h | reeckset/LCOM_Minix_2017 | 422068bc25d6f50aceb2341e9381af4f4194e6e6 | [
"MIT"
] | null | null | null | lab5/keyboard.h | reeckset/LCOM_Minix_2017 | 422068bc25d6f50aceb2341e9381af4f4194e6e6 | [
"MIT"
] | null | null | null | #ifndef _LCOM_KEYBOARD_H_
#define _LCOM_KEYBOARD_H_
int kbd_get_key(unsigned short stopCode);
int kbd_subscribe_int();
int kbd_unsubscribe_int();
int kbd_int_handler(unsigned short);
void processOutputCode(unsigned short scancode);
void processDualOutputCode(unsigned short firstByte, unsigned short scancode);
#endif /* __KEYBOARD_H */
| 24.357143 | 78 | 0.824047 |
d68f93a0b39d0e7333e3cfa0d988e1a57b66fdd9 | 2,169 | cs | C# | Utilities/Utilities/Extensions/StringExtension.cs | nbouilhol/bouilhol-lib | fd4027c122397a6fc9f2fffb6c591b064e3823ff | [
"MIT"
] | 2 | 2017-08-08T11:23:22.000Z | 2017-08-08T11:23:32.000Z | Utilities/Utilities/Extensions/StringExtension.cs | nbouilhol/bouilhol-lib | fd4027c122397a6fc9f2fffb6c591b064e3823ff | [
"MIT"
] | null | null | null | Utilities/Utilities/Extensions/StringExtension.cs | nbouilhol/bouilhol-lib | fd4027c122397a6fc9f2fffb6c591b064e3823ff | [
"MIT"
] | null | null | null | using System;
using System.Globalization;
using Utilities.Helpers;
namespace Utilities.Extensions
{
public static class StringExtension
{
public static decimal DistanceToInPercent(this string source, string target)
{
return 1 - ((decimal) Levenshtein.CalculateDistance(source, target)/target.Length);
}
public static int DistanceTo(this string source, string target)
{
return Levenshtein.CalculateDistance(source, target);
}
public static int ToInt(this string source)
{
int result;
return source != null && int.TryParse(source, out result)
? result
: 0;
}
public static bool ToBool(this string source)
{
bool result;
return source != null && bool.TryParse(source, out result) && result;
}
public static bool ToBool(this string source, bool defaultValue)
{
bool result;
return source != null && bool.TryParse(source, out result) ? result : defaultValue;
}
public static short ToShort(this int source)
{
try
{
return Convert.ToInt16(source);
}
catch (Exception)
{
return default(short);
}
}
public static int ToInt(this double source)
{
try
{
return Convert.ToInt32(source);
}
catch (Exception)
{
return default(int);
}
}
public static double ToDouble(this string source)
{
double result;
return double.TryParse(source, out result)
? result
: default(double);
}
public static TimeSpan ToTimeSpan(this string value, string format)
{
TimeSpan result;
return value != null && TimeSpan.TryParseExact(value, format, CultureInfo.InvariantCulture, out result)
? result
: TimeSpan.Zero;
}
}
} | 27.455696 | 115 | 0.523744 |
ef801db8c57e586c05854b99ae866dfde2383a73 | 428 | c | C | 08exer/01-soma.c | marcos-bah/language-c | ba17700d59dfdd580ccfdc23919b6c78b1d0bd88 | [
"MIT"
] | null | null | null | 08exer/01-soma.c | marcos-bah/language-c | ba17700d59dfdd580ccfdc23919b6c78b1d0bd88 | [
"MIT"
] | null | null | null | 08exer/01-soma.c | marcos-bah/language-c | ba17700d59dfdd580ccfdc23919b6c78b1d0bd88 | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <stdlib.h>
int soma(int n1, int n2)
{
int soma = 0;
if (n2 >= n1)
{
for (int i = n1 + 1; i < n2; i++)
{
soma += i;
}
}
return soma;
}
int main()
{
int n1, n2;
printf("Digite n1: ");
scanf("%d", &n1);
printf("Digite n2: ");
scanf("%d", &n2);
printf("Soma dos valores entre os dois: %d\n", soma(n1, n2));
return 0;
} | 16.461538 | 65 | 0.450935 |
87109a52c6eaf269a7e539ae0db0201a2fd4e93a | 3,184 | dart | Dart | printing/lib/src/preview/controller.dart | HazemElgohary/dart_pdf | 753c73c67d0f18e9c6090e21bb2e997e9a8f334b | [
"Apache-2.0"
] | null | null | null | printing/lib/src/preview/controller.dart | HazemElgohary/dart_pdf | 753c73c67d0f18e9c6090e21bb2e997e9a8f334b | [
"Apache-2.0"
] | null | null | null | printing/lib/src/preview/controller.dart | HazemElgohary/dart_pdf | 753c73c67d0f18e9c6090e21bb2e997e9a8f334b | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2017, David PHAM-VAN <[email protected]>
*
* 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.
*/
import 'package:flutter/material.dart';
import 'package:pdf/pdf.dart';
import '../callback.dart';
typedef ComputePageFormat = PdfPageFormat Function();
class PdfPreviewData extends ChangeNotifier {
PdfPreviewData({
PdfPageFormat? initialPageFormat,
required this.buildDocument,
required Map<String, PdfPageFormat> pageFormats,
required ComputePageFormat onComputeActualPageFormat,
}) : assert(pageFormats.isNotEmpty),
_onComputeActualPageFormat = onComputeActualPageFormat {
_pageFormat = initialPageFormat ??
(pageFormats[localPageFormat] ?? pageFormats.values.first);
}
late PdfPageFormat _pageFormat;
final LayoutCallback buildDocument;
final ComputePageFormat _onComputeActualPageFormat;
PdfPageFormat get pageFormat => _pageFormat;
set pageFormat(PdfPageFormat value) {
if (_pageFormat != value) {
_pageFormat = value;
notifyListeners();
}
}
/// Is the print horizontal
bool get horizontal => _pageFormat.width > _pageFormat.height;
set horizontal(bool value) {
final format = value ? _pageFormat.landscape : _pageFormat.portrait;
if (format != _pageFormat) {
_pageFormat = format;
notifyListeners();
}
}
/// Computed page format
@Deprecated('Use pageFormat instead')
PdfPageFormat get computedPageFormat => _pageFormat;
/// The page format of the document
PdfPageFormat get actualPageFormat => _onComputeActualPageFormat();
String get localPageFormat {
final locale = WidgetsBinding.instance!.window.locale;
// ignore: unnecessary_cast
final cc = (locale as Locale?)?.countryCode ?? 'US';
if (cc == 'US' || cc == 'CA' || cc == 'MX') {
return 'Letter';
}
return 'A4';
}
}
class PdfPreviewController extends InheritedNotifier {
const PdfPreviewController({
Key? key,
required this.data,
required Widget child,
}) : super(key: key, child: child, notifier: data);
final PdfPreviewData data;
static PdfPreviewData of(BuildContext context) {
final result =
context.findAncestorWidgetOfExactType<PdfPreviewController>();
assert(result != null, 'No PdfPreview found in context');
return result!.data;
}
static PdfPreviewData listen(BuildContext context) {
final result =
context.dependOnInheritedWidgetOfExactType<PdfPreviewController>();
assert(result != null, 'No PdfPreview found in context');
return result!.data;
}
@override
bool updateShouldNotify(covariant InheritedWidget oldWidget) {
return false;
}
}
| 29.211009 | 75 | 0.715138 |
3feeafb7a82eaf27a2b32c773234a47115d33343 | 12,042 | rb | Ruby | lib/CORL/configuration/file.rb | coralnexus/corl | 43d1e40c7e61231aaef91f7062dc832c05bebc43 | [
"Apache-2.0"
] | 1 | 2015-09-08T04:21:56.000Z | 2015-09-08T04:21:56.000Z | lib/CORL/configuration/file.rb | coralnexus/corl | 43d1e40c7e61231aaef91f7062dc832c05bebc43 | [
"Apache-2.0"
] | null | null | null | lib/CORL/configuration/file.rb | coralnexus/corl | 43d1e40c7e61231aaef91f7062dc832c05bebc43 | [
"Apache-2.0"
] | null | null | null |
module CORL
module Configuration
class File < Nucleon.plugin_class(:CORL, :configuration)
#-----------------------------------------------------------------------------
# Configuration plugin interface
def normalize(reload)
super do
_set(:search, Config.new({}, {}, true, false))
_set(:router, Config.new({}, {}, true, false))
end
end
#-----------------------------------------------------------------------------
# Property accessors / modifiers
def search
_get(:search)
end
#---
def router
_get(:router)
end
#-----------------------------------------------------------------------------
def set_location(directory)
super
search_files if directory
end
#-----------------------------------------------------------------------------
# Configuration loading / saving
def load(options = {})
super do |method_config, properties|
success = true
myself.status = code.success
generate_routes = lambda do |config_name, file_properties, parents = []|
file_properties.each do |name, value|
keys = [ parents, name ].flatten
if value.is_a?(Hash) && ! value.empty?
generate_routes.call(config_name, value, keys)
else
router.set(keys, config_name)
end
end
end
if fetch_project(method_config)
search.export.each do |config_name, info|
provider = info[:provider]
file = info[:file]
logger.info("Loading #{provider} translated source configuration from #{file}")
parser = CORL.translator(method_config, provider)
raw = Util::Disk.read(file)
if parser && raw && ! raw.empty?
logger.debug("Source configuration file contents: #{raw}")
begin
parse_properties = parser.parse(raw)
generate_routes.call(config_name, parse_properties)
properties.import(parse_properties)
rescue => error
ui_group(file) do
error(error.message.sub(/^[^\:]+\:\s+/, ''), { :i18n => false })
end
myself.status = 255
success = false
end
end
CORL.remove_plugin(parser) if parser
end
end
success
end
end
#---
# properties[key...] = values
#
# to
#
# file_data[config_name][key...] = config
def separate
file_data = Config.new
default_provider = CORL.type_default(:nucleon, :translator)
split_config = lambda do |properties, local_router, parents = []|
properties.each do |name, value|
next if name.to_sym == :nodes
keys = [ parents, name ].flatten
if value.is_a?(Hash) && ! value.empty?
# Nested configurations
if local_router.is_a?(Hash) && local_router.has_key?(name)
# Router and configuration values are nested
split_config.call(value, local_router[name], keys)
else
# Just configuration values are nested
if local_router.is_a?(String)
# We are down to a config_name router. Inherit on down the line
split_config.call(value, local_router, keys)
else
# Never encountered before
config_name = nil
config_name = select_largest(router.get(parents)) unless parents.empty?
split_config.call(value, config_name, keys)
end
end
else
if local_router.is_a?(String)
# Router is a config_name string
file_data.set([ local_router, keys ].flatten, value)
elsif local_router.is_a?(Hash)
# Router is a hash with sub options we have to pick from
config_name = select_largest(local_router)
file_data.set([ config_name, keys ].flatten, value)
else
# Router is non existent. Resort to easily found default
config_name = "corl.#{default_provider}"
file_data.set([ config_name, keys ].flatten, value)
end
end
end
end
if config.get(:nodes, false)
config[:nodes].each do |provider, data|
data.each do |name, info|
config_name = ::File.join('nodes', provider.to_s, "#{name}.#{default_provider}")
file_data.set([ config_name, :nodes, provider, name ], info)
unless search[config_name]
search[config_name] = {
:provider => default_provider,
:file => ::File.join(project.directory, config_name)
}
end
end
end
end
# Whew! Glad that's over...
split_config.call(Util::Data.subset(config.export, config.keys - [ :nodes ]), router.export)
file_data
end
protected :separate
#---
def save(options = {})
super do |method_config|
config_files = []
success = true
deleted_keys = search.export.keys
separate.export.each do |config_name, router_data|
info = search[config_name]
provider = info[:provider]
file = info[:file]
file_dir = ::File.dirname(file)
deleted_keys = deleted_keys - [ config_name ]
FileUtils.mkdir_p(file_dir) unless Dir.exists?(file_dir)
if renderer = CORL.translator(method_config, provider)
rendering = renderer.generate(router_data)
if Util::Disk.write(file, rendering)
config_files << config_name
else
success = false
end
CORL.remove_plugin(renderer)
else
success = false
end
break unless success
end
if success
# Check for removals
deleted_keys.each do |config_name|
info = search[config_name]
search.delete(config_name)
FileUtils.rm_f(info[:file])
config_files << config_name
end
end
if success && ! config_files.empty?
# Commit changes
commit_files = [ config_files, method_config.get_array(:files) ].flatten
logger.debug("Source configuration rendering: #{rendering}")
success = update_project(commit_files, method_config)
end
success
end
end
#---
def remove(options = {})
super do |method_config|
success = true
config_files = []
search.each do |config_name, info|
config_files << info[:file]
success = false unless Util::Disk.delete(info[:file])
end
success = update_project(config_files, method_config) if success
success
end
end
#---
def attach(type, name, data, options = {})
super do |method_config|
attach_path = Util::Disk.filename([ project.directory, type.to_s ])
success = true
begin
FileUtils.mkdir_p(attach_path) unless Dir.exists?(attach_path)
rescue => error
warn(error.message, { :i18n => false })
success = false
end
if success
case method_config.get(:type, :source)
when :source
new_file = project.local_path(Util::Disk.filename([ attach_path, name ]))
logger.debug("Attaching source data (length: #{data.length}) to configuration at #{attach_path}")
success = Util::Disk.write(new_file, data)
when :file
file = ::File.expand_path(data)
attach_ext = ::File.basename(file)
new_file = project.local_path(Util::Disk.filename([ attach_path, "#{name}-#{attach_ext}" ]))
logger.debug("Attaching file #{file} to configuration at #{attach_path}")
begin
FileUtils.mkdir_p(attach_path) unless Dir.exists?(attach_path)
FileUtils.cp(file, new_file)
rescue => error
warn(error.message, { :i18n => false })
success = false
end
end
end
if success && autosave
logger.debug("Attaching data to project as #{new_file}")
success = update_project(new_file, method_config)
end
success ? new_file : nil
end
end
#---
def delete_attachments(ids, options = {})
super do |method_config|
success = true
files = []
array(ids).each do |id|
file = ::File.join(project.directory, id.to_s)
if Util::Disk.delete(file)
files << file
else
success = false
end
end
if success && autosave
logger.debug("Removing attached data from project as #{files.join(', ')}")
success = update_project(files, method_config)
end
success ? files : nil
end
end
#-----------------------------------------------------------------------------
# Utilities
def search_files
add_search_file = lambda do |config_name, file, provider, info|
if Util::Disk.exists?(file)
search[config_name] = {
:provider => provider,
:info => info,
:file => file
}
else
logger.info("Configuration file #{file} does not exist")
end
end
if Util::Data.empty?(project.directory)
logger.debug("Clearing configuration file information")
search.clear
else
translators = CORL.loaded_plugins(:nucleon, :translator)
file_bases = [ :corl, extension_set(:base, []) ].flatten.uniq
project.localize do
translators.each do |provider, info|
Dir.glob(::File.join('nodes', '**', "*.#{provider}")).each do |file|
config_name = file
file = ::File.join(project.directory, file)
add_search_file.call(config_name, file, provider, info)
end
end
end
translators.each do |provider, info|
file_bases.each do |file_base|
config_name = "#{file_base}.#{provider}"
file = Util::Disk.filename([ project.directory, config_name ])
add_search_file.call(config_name, file, provider, info)
end
end
logger.debug("Setting configuration file information to #{search.inspect}")
end
load(_export) if autoload
end
protected :search_files
#---
def fetch_project(options = {})
config = Config.ensure(options)
success = true
if remote = config.get(:remote, nil)
logger.info("Pulling configuration updates from remote #{remote}")
success = project.pull(remote, config) if config.get(:pull, true)
end
success
end
protected :fetch_project
#---
def update_project(files = [], options = {})
config = Config.ensure(options)
success = true
commit_files = '.'
commit_files = array(files).flatten unless files.empty?
logger.info("Committing changes to configuration files")
success = project.commit(commit_files, config)
if success && remote = config.get(:remote, nil)
logger.info("Pushing configuration updates to remote #{remote}")
success = project.pull(remote, config) if config.get(:pull, true) && ! config.get(:push, false)
success = project.push(remote, config) if success && config.get(:push, true)
end
success
end
protected :update_project
#---
def select_largest(router)
return router unless router.is_a?(Hash)
config_map = {}
count_config_names = lambda do |data|
data = data.export if data.is_a?(CORL::Config)
data.each do |name, value|
if value.is_a?(Hash)
count_config_names.call(value)
else
config_map[value] = 0 unless config_map.has_key?(value)
config_map[value] = config_map[value] + 1
end
end
end
config_name = nil
config_weight = nil
count_config_names.call(router)
config_map.each do |name, weight|
if config_name.nil? || weight > config_weight
config_name = name
config_weight = weight
end
end
config_name
end
protected :select_largest
end
end
end
| 28.267606 | 107 | 0.571749 |
c191fa7b8969bc5cce2409efbc603612f5314ba2 | 549 | sql | SQL | src/test/resources/com/github/vr_f/sqlparser/select/with_variables.sql | vr-f/sqlparser | 4fc95f53f5781e2feaa0e9813be6bb9ef1fdc21c | [
"MIT"
] | null | null | null | src/test/resources/com/github/vr_f/sqlparser/select/with_variables.sql | vr-f/sqlparser | 4fc95f53f5781e2feaa0e9813be6bb9ef1fdc21c | [
"MIT"
] | null | null | null | src/test/resources/com/github/vr_f/sqlparser/select/with_variables.sql | vr-f/sqlparser | 4fc95f53f5781e2feaa0e9813be6bb9ef1fdc21c | [
"MIT"
] | null | null | null | SELECT category_id, entity_id
FROM (SELECT category_id,
@ce :=
(SELECT entity_id
FROM category_entity cei
WHERE cei.category_id = ced.category_id
AND NOT FIND_IN_SET(entity_id, @r)
ORDER BY RAND()
LIMIT 1) AS entity_id,
(SELECT @r := CAST(CONCAT_WS(',', @r, @ce) AS CHAR))
FROM (SELECT @r := '') vars,
(SELECT DISTINCT category_id FROM category_entity ORDER BY RAND() LIMIT 15) ced) q
WHERE entity_id IS NOT NULL
LIMIT 6; | 39.214286 | 93 | 0.570128 |
fa07f64fd2e732f36b583c07f1bc9aa264706f7c | 7,480 | cpp | C++ | lib/djvViewApp/ViewData.cpp | belzecue/DJV | 94fb63a2f56cc0c41ab5d518ef9f2e0590c295c0 | [
"BSD-3-Clause"
] | 456 | 2018-10-06T00:07:14.000Z | 2022-03-31T06:14:22.000Z | lib/djvViewApp/ViewData.cpp | belzecue/DJV | 94fb63a2f56cc0c41ab5d518ef9f2e0590c295c0 | [
"BSD-3-Clause"
] | 438 | 2018-10-31T15:05:51.000Z | 2022-03-31T09:01:24.000Z | lib/djvViewApp/ViewData.cpp | belzecue/DJV | 94fb63a2f56cc0c41ab5d518ef9f2e0590c295c0 | [
"BSD-3-Clause"
] | 54 | 2018-10-29T10:18:36.000Z | 2022-03-23T06:56:11.000Z | // SPDX-License-Identifier: BSD-3-Clause
// Copyright (c) 2020 Darby Johnston
// All rights reserved.
#include <djvViewApp/ViewData.h>
#include <djvImage/Color.h>
using namespace djv::Core;
namespace djv
{
namespace ViewApp
{
bool GridOptions::operator == (const GridOptions& other) const
{
return enabled == other.enabled &&
size == other.size &&
color == other.color &&
labels == other.labels &&
labelsColor == other.labelsColor;
}
bool HUDData::operator == (const HUDData& other) const
{
return
fileName == other.fileName &&
layer == other.layer &&
size == other.size &&
type == other.type &&
isSequence == other.isSequence &&
currentFrame == other.currentFrame &&
speed == other.speed &&
realSpeed == other.realSpeed;
}
bool HUDOptions::operator == (const HUDOptions& other) const
{
return
enabled == other.enabled &&
color == other.color &&
background == other.background;
}
bool ViewBackgroundOptions::operator == (const ViewBackgroundOptions& other) const
{
return
background == other.background &&
color == other.color &&
checkersSize == other.checkersSize &&
checkersColors[0] == other.checkersColors[0] &&
checkersColors[1] == other.checkersColors[1] &&
border == other.border &&
borderWidth == other.borderWidth &&
borderColor == other.borderColor;
}
} // namespace ViewApp
rapidjson::Value toJSON(const ViewApp::GridOptions& value, rapidjson::Document::AllocatorType& allocator)
{
rapidjson::Value out(rapidjson::kObjectType);
out.AddMember("Enabled", toJSON(value.enabled, allocator), allocator);
out.AddMember("Size", toJSON(value.size, allocator), allocator);
out.AddMember("Color", toJSON(value.color, allocator), allocator);
out.AddMember("Labels", toJSON(value.labels, allocator), allocator);
out.AddMember("LabelsColor", toJSON(value.labelsColor, allocator), allocator);
return out;
}
rapidjson::Value toJSON(const ViewApp::HUDOptions& value, rapidjson::Document::AllocatorType& allocator)
{
rapidjson::Value out(rapidjson::kObjectType);
out.AddMember("Enabled", toJSON(value.enabled, allocator), allocator);
out.AddMember("Color", toJSON(value.color, allocator), allocator);
out.AddMember("Background", toJSON(value.background, allocator), allocator);
return out;
}
rapidjson::Value toJSON(const ViewApp::ViewBackgroundOptions& value, rapidjson::Document::AllocatorType& allocator)
{
rapidjson::Value out(rapidjson::kObjectType);
out.AddMember("Background", toJSON(value.background, allocator), allocator);
out.AddMember("Color", toJSON(value.color, allocator), allocator);
out.AddMember("CheckersSize", toJSON(value.checkersSize, allocator), allocator);
out.AddMember("CheckersColors0", toJSON(value.checkersColors[0], allocator), allocator);
out.AddMember("CheckersColors1", toJSON(value.checkersColors[1], allocator), allocator);
out.AddMember("Border", toJSON(value.border, allocator), allocator);
out.AddMember("BorderWidth", toJSON(value.borderWidth, allocator), allocator);
out.AddMember("BorderColor", toJSON(value.borderColor, allocator), allocator);
return out;
}
void fromJSON(const rapidjson::Value& value, ViewApp::GridOptions& out)
{
if (value.IsObject())
{
for (const auto& i : value.GetObject())
{
if (0 == strcmp("Enabled", i.name.GetString()))
{
fromJSON(i.value, out.enabled);
}
else if (0 == strcmp("Size", i.name.GetString()))
{
fromJSON(i.value, out.size);
}
else if (0 == strcmp("Color", i.name.GetString()))
{
fromJSON(i.value, out.color);
}
else if (0 == strcmp("Labels", i.name.GetString()))
{
fromJSON(i.value, out.labels);
}
else if (0 == strcmp("LabelsColor", i.name.GetString()))
{
fromJSON(i.value, out.labelsColor);
}
}
}
else
{
//! \todo How can we translate this?
throw std::invalid_argument(DJV_TEXT("error_cannot_parse_the_value"));
}
}
void fromJSON(const rapidjson::Value& value, ViewApp::HUDOptions& out)
{
if (value.IsObject())
{
for (const auto& i : value.GetObject())
{
if (0 == strcmp("Enabled", i.name.GetString()))
{
fromJSON(i.value, out.enabled);
}
else if (0 == strcmp("Color", i.name.GetString()))
{
fromJSON(i.value, out.color);
}
else if (0 == strcmp("Background", i.name.GetString()))
{
fromJSON(i.value, out.background);
}
}
}
else
{
//! \todo How can we translate this?
throw std::invalid_argument(DJV_TEXT("error_cannot_parse_the_value"));
}
}
void fromJSON(const rapidjson::Value& value, ViewApp::ViewBackgroundOptions& out)
{
if (value.IsObject())
{
for (const auto& i : value.GetObject())
{
if (0 == strcmp("Background", i.name.GetString()))
{
fromJSON(i.value, out.background);
}
else if (0 == strcmp("Color", i.name.GetString()))
{
fromJSON(i.value, out.color);
}
else if (0 == strcmp("CheckersSize", i.name.GetString()))
{
fromJSON(i.value, out.checkersSize);
}
else if (0 == strcmp("CheckersColors0", i.name.GetString()))
{
fromJSON(i.value, out.checkersColors[0]);
}
else if (0 == strcmp("CheckersColors1", i.name.GetString()))
{
fromJSON(i.value, out.checkersColors[1]);
}
else if (0 == strcmp("Border", i.name.GetString()))
{
fromJSON(i.value, out.border);
}
else if (0 == strcmp("BorderWidth", i.name.GetString()))
{
fromJSON(i.value, out.borderWidth);
}
else if (0 == strcmp("BorderColor", i.name.GetString()))
{
fromJSON(i.value, out.borderColor);
}
}
}
else
{
//! \todo How can we translate this?
throw std::invalid_argument(DJV_TEXT("error_cannot_parse_the_value"));
}
}
} // namespace djv
| 36.487805 | 119 | 0.512299 |
99ca74158f0f567b34a22010f6bf7300ffe79a6c | 3,254 | rs | Rust | src/config.rs | camchenry/wikidump | 3a3c0711428497e9bb8cb57a669c0c6a44db8764 | [
"MIT"
] | 2 | 2020-02-24T08:54:39.000Z | 2022-03-22T14:08:55.000Z | src/config.rs | camchenry/wikidump | 3a3c0711428497e9bb8cb57a669c0c6a44db8764 | [
"MIT"
] | null | null | null | src/config.rs | camchenry/wikidump | 3a3c0711428497e9bb8cb57a669c0c6a44db8764 | [
"MIT"
] | null | null | null | //! Wiki text parsing configurations for Mediawiki sites and languages.c
//!
//! These are the currently supported Mediawiki websites and languages:
//! * Wikipedia
//! * English
//! * Simple English Wikipedia
//!
//! ## Example
//! ```rust
//! use wikidump::{config, Parser};
//! let parser = Parser::new()
//! .use_config(config::wikipedia::english());
//!```
/// Configurations for [Wikipedia, the free encyclopedia](https://www.wikipedia.org/).
pub mod wikipedia {
use parse_wiki_text::ConfigurationSource;
/// Configuration for the English Wikipedia.
pub fn english<'c>() -> ConfigurationSource<'c> {
ConfigurationSource {
category_namespaces: &["category"],
extension_tags: &[
"categorytree",
"ce",
"charinsert",
"chem",
"gallery",
"graph",
"hiero",
"imagemap",
"indicator",
"inputbox",
"mapframe",
"maplink",
"math",
"nowiki",
"poem",
"pre",
"ref",
"references",
"score",
"section",
"source",
"syntaxhighlight",
"templatedata",
"templatestyles",
"timeline",
],
file_namespaces: &["file", "image"],
link_trail: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
magic_words: &[
"DISAMBIG",
"EXPECTUNUSEDCATEGORY",
"FORCETOC",
"HIDDENCAT",
"INDEX",
"NEWSECTIONLINK",
"NOCC",
"NOCOLLABORATIONHUBTOC",
"NOCONTENTCONVERT",
"NOEDITSECTION",
"NOGALLERY",
"NOGLOBAL",
"NOINDEX",
"NONEWSECTIONLINK",
"NOTC",
"NOTITLECONVERT",
"NOTOC",
"STATICREDIRECT",
"TOC",
],
protocols: &[
"//",
"bitcoin:",
"ftp://",
"ftps://",
"geo:",
"git://",
"gopher://",
"http://",
"https://",
"irc://",
"ircs://",
"magnet:",
"mailto:",
"mms://",
"news:",
"nntp://",
"redis://",
"sftp://",
"sip:",
"sips:",
"sms:",
"ssh://",
"svn://",
"tel:",
"telnet://",
"urn:",
"worldwind://",
"xmpp:",
],
redirect_magic_words: &["REDIRECT"],
}
}
/// Configuration for Simple English Wikipedia. At the moment, this is
/// exactly the same as the English Wikipedia configuration.
pub fn simple_english<'c>() -> ConfigurationSource<'c> {
english()
}
}
| 28.79646 | 86 | 0.388138 |
217fb98e1f1e4209ffee24d7692431231e3d85d9 | 13,073 | js | JavaScript | packages/sw-cache-expiration/src/lib/plugin.js | samdutton/sw-helpers | d779765a8a92d98b552e8f6feeea19dfe30be7d2 | [
"Apache-2.0"
] | 1 | 2021-09-19T22:56:20.000Z | 2021-09-19T22:56:20.000Z | packages/sw-cache-expiration/src/lib/plugin.js | samdutton/sw-helpers | d779765a8a92d98b552e8f6feeea19dfe30be7d2 | [
"Apache-2.0"
] | null | null | null | packages/sw-cache-expiration/src/lib/plugin.js | samdutton/sw-helpers | d779765a8a92d98b552e8f6feeea19dfe30be7d2 | [
"Apache-2.0"
] | null | null | null | /*
Copyright 2016 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
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.
*/
import idb from 'idb';
import assert from '../../../../lib/assert';
import {
idbName,
idbVersion,
urlPropertyName,
timestampPropertyName,
} from './constants';
import ErrorFactory from './error-factory';
/**
* The cache expiration plugin allows you define an expiration and / or
* limit on the responses cached.
*
* @example
* const expirationPlugin = new goog.cacheExpiration.Plugin({
* maxEntries: 2,
* maxAgeSeconds: 10,
* });
*
* @memberof module:sw-cache-expiration
*/
class Plugin {
/**
* Creates a new `Plugin` instance, which is used to remove entries from a
* [`Cache`](https://developer.mozilla.org/en-US/docs/Web/API/Cache) once
* certain criteria—maximum number of entries, age of entry, or both—is met.
*
* @param {Object} input
* @param {Number} [input.maxEntries] The maximum size of the cache. Entries
* will be expired using a LRU policy once the cache reaches this size.
* @param {Number} [input.maxAgeSeconds] The maximum age for fresh entries.
*/
constructor({maxEntries, maxAgeSeconds} = {}) {
if (!(maxEntries || maxAgeSeconds)) {
throw ErrorFactory.createError('max-entries-or-age-required');
}
if (maxEntries && typeof maxEntries !== 'number') {
throw ErrorFactory.createError('max-entries-must-be-number');
}
if (maxAgeSeconds && typeof maxAgeSeconds !== 'number') {
throw ErrorFactory.createError('max-age-seconds-must-be-number');
}
this.maxEntries = maxEntries;
this.maxAgeSeconds = maxAgeSeconds;
// These are used to keep track of open IndexDB and Caches for a given name.
this._dbs = new Map();
this._caches = new Map();
}
/**
* Returns a promise for the IndexedDB database used to keep track of state.
*
* @private
* @param {Object} input
* @param {string} input.cacheName Name of the cache the Responses belong to.
* @return {DB} An open DB instance.
*/
async getDB({cacheName} = {}) {
assert.isType({cacheName}, 'string');
const idbId = `${idbName}-${cacheName}`;
if (!this._dbs.has(idbId)) {
const openDb = await idb.open(idbId, idbVersion, (upgradeDB) => {
const objectStore = upgradeDB.createObjectStore(cacheName,
{keyPath: urlPropertyName});
objectStore.createIndex(timestampPropertyName, timestampPropertyName,
{unique: false});
});
this._dbs.set(idbId, openDb);
}
return this._dbs.get(idbId);
}
/**
* Returns a promise for an open Cache instance named `cacheName`.
*
* @private
* @param {Object} input
* @param {string} input.cacheName Name of the cache the Responses belong to.
* @return {Cache} An open Cache instance.
*/
async getCache({cacheName} = {}) {
assert.isType({cacheName}, 'string');
if (!this._caches.has(cacheName)) {
const openCache = await caches.open(cacheName);
this._caches.set(cacheName, openCache);
}
return this._caches.get(cacheName);
}
/**
* A "lifecycle" callback that will be triggered automatically by the
* `goog.runtimeCaching` handlers when a `Response` is about to be returned
* from a [Cache](https://developer.mozilla.org/en-US/docs/Web/API/Cache) to
* the handler. It allows the `Response` to be inspected for freshness and
* prevents it from being used if the `Response`'s `Date` header value is
* older than the configured `maxAgeSeconds`.
*
* Developers who are not using `goog.runtimeCaching` would normally not call
* this method directly; instead, use [`isResponseFresh`](#isResponseFresh)
* to perform the same freshness check.
*
* @private
* @param {Object} input
* @param {Response} input.cachedResponse The `Response` object that's been
* read from a cache and whose freshness should be checked.
* @param {Number} [input.now] A timestamp. Defaults to the current time.
* @return {Response|null} Either the `cachedResponse`, if it's fresh, or
* `null` if the `Response` is older than `maxAgeSeconds`.
*/
cacheWillMatch({cachedResponse, now} = {}) {
if (this.isResponseFresh({cachedResponse, now})) {
return cachedResponse;
}
return null;
}
/**
* Checks whether a `Response` is fresh, based on the `Response`'s
* `Date` header and the configured `maxAgeSeconds`.
*
* If `maxAgeSeconds` or the `Date` header is not set then it will
* default to returning `true`.
*
* @param {Object} input
* @param {Response} input.cachedResponse The `Response` object that's been
* read from a cache and whose freshness should be checked.
* @param {Number} [input.now] A timestamp. Defaults to the current time.
* @return {boolean} Either the `true`, if it's fresh, or `false` if the
* `Response` is older than `maxAgeSeconds`.
*
* @example
* expirationPlugin.isResponseFresh({
* cachedResponse: responseFromCache
* });
*/
isResponseFresh({cachedResponse, now} = {}) {
// Only bother checking for freshness if we have a valid response and if
// maxAgeSeconds is set. Otherwise, skip the check and always return true.
if (cachedResponse && this.maxAgeSeconds) {
assert.isInstance({cachedResponse}, Response);
const dateHeader = cachedResponse.headers.get('date');
if (dateHeader) {
if (typeof now === 'undefined') {
now = Date.now();
}
const parsedDate = new Date(dateHeader);
// If the Date header was invalid for some reason, parsedDate.getTime()
// will return NaN, and the comparison will always be false. That means
// that an invalid date will be treated as if the response is fresh.
if ((parsedDate.getTime() + (this.maxAgeSeconds * 1000)) < now) {
// Only return false if all the conditions are met.
return false;
}
}
}
return true;
}
/**
* A "lifecycle" callback that will be triggered automatically by the
* `goog.runtimeCaching` handlers when an entry is added to a cache.
*
* Developers would normally not call this method directly; instead,
* [`updateTimestamp`](#updateTimestamp) combined with
* [`expireEntries`](#expireEntries) provides equivalent plugin.
*
* @private
* @param {Object} input
* @param {string} input.cacheName Name of the cache the responses belong to.
* @param {Response} input.newResponse The new value in the cache.
* @param {string} input.url The URL for the cache entry.
* @param {Number} [input.now] A timestamp. Defaults to the current time.
*/
cacheDidUpdate({cacheName, newResponse, url, now} = {}) {
assert.isType({cacheName}, 'string');
assert.isInstance({newResponse}, Response);
if (typeof now === 'undefined') {
now = Date.now();
}
this.updateTimestamp({cacheName, url, now}).then(() => {
this.expireEntries({cacheName, now});
});
}
/**
* Updates the timestamp stored in IndexedDB for `url` to be equal to `now`.
*
* @param {Object} input
* @param {string} input.cacheName Name of the cache the Responses belong to.
* @param {string} input.url The URL for the entry to update.
* @param {Number} [input.now] A timestamp. Defaults to the current time.
*
* @example
* expirationPlugin.updateTimestamp({
* cacheName: 'example-cache-name',
* url: '/example-url'
* });
*/
async updateTimestamp({cacheName, url, now} = {}) {
assert.isType({url}, 'string');
assert.isType({cacheName}, 'string');
if (typeof now === 'undefined') {
now = Date.now();
}
const db = await this.getDB({cacheName});
const tx = db.transaction(cacheName, 'readwrite');
tx.objectStore(cacheName).put({
[timestampPropertyName]: now,
[urlPropertyName]: url,
});
await tx.complete;
}
/**
* Expires entries, both based on the the maximum age and the maximum number
* of entries, depending on how this instance is configured.
*
* @param {Object} input
* @param {string} input.cacheName Name of the cache the Responses belong to.
* @param {Number} [input.now] A timestamp. Defaults to the current time.
* @return {Array<string>} A list of the URLs that were expired.
*
* @example
* expirationPlugin.expireEntries({
* cacheName: 'example-cache-name'
* });
*/
async expireEntries({cacheName, now} = {}) {
assert.isType({cacheName}, 'string');
if (typeof now === 'undefined') {
now = Date.now();
}
// First, expire old entries, if maxAgeSeconds is set.
const oldEntries = this.maxAgeSeconds ?
await this.findOldEntries({cacheName, now}) :
[];
// Once that's done, check for the maximum size.
const extraEntries = this.maxEntries ?
await this.findExtraEntries({cacheName}) :
[];
// Use a Set to remove any duplicates following the concatenation, then
// convert back into an array.
const urls = [...new Set(oldEntries.concat(extraEntries))];
await this.deleteFromCacheAndIDB({cacheName, urls});
return urls;
}
/**
* Expires entries based on the the maximum age.
*
* @private
* @param {Object} input
* @param {string} input.cacheName Name of the cache the Responses belong to.
* @param {Number} [input.now] A timestamp.
* @return {Array<string>} A list of the URLs that were expired.
*/
async findOldEntries({cacheName, now} = {}) {
assert.isType({cacheName}, 'string');
assert.isType({now}, 'number');
const expireOlderThan = now - (this.maxAgeSeconds * 1000);
const urls = [];
const db = await this.getDB({cacheName});
const tx = db.transaction(cacheName, 'readonly');
const store = tx.objectStore(cacheName);
const timestampIndex = store.index(timestampPropertyName);
timestampIndex.iterateCursor((cursor) => {
if (!cursor) {
return;
}
if (cursor.value[timestampPropertyName] < expireOlderThan) {
urls.push(cursor.value[urlPropertyName]);
}
cursor.continue();
});
await tx.complete;
return urls;
}
/**
* Finds the URLs that should be expired as per the current state of IndexedDB
* and the `maxEntries` configuration. A least-recently used policy is
* enforced, so if `maxEntries` is `N`, and there are `N + M` URLs listed in
* IndexedDB, then this function will return the least-recently used `M` URLs.
*
* @private
* @param {Object} input
* @param {string} input.cacheName Name of the cache the Responses belong to.
* @return {Array<string>} A list of the URLs that are candidates for
* expiration.
*/
async findExtraEntries({cacheName} = {}) {
assert.isType({cacheName}, 'string');
const urls = [];
const db = await this.getDB({cacheName});
let tx = db.transaction(cacheName, 'readonly');
let store = tx.objectStore(cacheName);
let timestampIndex = store.index(timestampPropertyName);
const initialCount = await timestampIndex.count();
if (initialCount > this.maxEntries) {
// We need to create a new transaction to make Firefox happy.
tx = db.transaction(cacheName, 'readonly');
store = tx.objectStore(cacheName);
timestampIndex = store.index(timestampPropertyName);
timestampIndex.iterateCursor((cursor) => {
if (!cursor) {
return;
}
urls.push(cursor.value[urlPropertyName]);
if (initialCount - urls.length > this.maxEntries) {
cursor.continue();
}
});
}
await tx.complete;
return urls;
}
/**
* Removes entries corresponding to each of the URLs from both the Cache
* Storage API and from IndexedDB.
*
* @private
* @param {Object} input
* @param {string} input.cacheName Name of the cache the Responses belong to.
* @param {Array<string>} urls The URLs to delete.
*/
async deleteFromCacheAndIDB({cacheName, urls} = {}) {
assert.isType({cacheName}, 'string');
assert.isArrayOfType({urls}, 'string');
if (urls.length > 0) {
const cache = await this.getCache({cacheName});
const db = await this.getDB({cacheName});
await urls.forEach(async (url) => {
await cache.delete(url);
const tx = db.transaction(cacheName, 'readwrite');
const store = tx.objectStore(cacheName);
await store.delete(url);
await tx.complete;
});
}
}
}
export default Plugin;
| 33.012626 | 80 | 0.652872 |
23056b47bc2b141b800c1b85117a80b4db3d4a04 | 4,102 | css | CSS | framework/Targets/horde_3_3_12/application/themes/tango-blue/screen.css | UncleWillis/BugBox | 25682f25fc3222db383649a4924bcd65f2ddcb34 | [
"BSD-3-Clause"
] | 1 | 2019-01-25T21:32:42.000Z | 2019-01-25T21:32:42.000Z | framework/Targets/horde_3_3_12/application/themes/tango-blue/screen.css | UncleWillis/BugBox | 25682f25fc3222db383649a4924bcd65f2ddcb34 | [
"BSD-3-Clause"
] | null | null | null | framework/Targets/horde_3_3_12/application/themes/tango-blue/screen.css | UncleWillis/BugBox | 25682f25fc3222db383649a4924bcd65f2ddcb34 | [
"BSD-3-Clause"
] | 1 | 2021-06-23T04:44:25.000Z | 2021-06-23T04:44:25.000Z | /**
* $Horde: horde/themes/tango-blue/screen.css,v 1.13.2.2 2008/06/12 12:37:10 jan Exp $
*/
*, select, body, a, input, textarea, td, td.light, {
font-family: Verdana, sans-serif;
font-size: 9pt;
line-height: 1.5;
}
body {
background: #5d7cba;
}
.smallheader {
background: #efefef none repeat scroll 0%;
font-family: Verdana, sans-serif;
font-size: 9pt;
line-height: 1.5;
color: #204a87;
}
body {
border: 0;
margin: 0;
}
html {
height: 100%;
}
a {
color: #343dba;
}
.linedRow, tr.linedRow td, table.linedRow td {
background: #dae6f2 none repeat scroll 0%;
border-bottom: 1px solid #ddd;
#color: #000;
}
.text {
background: #c9daed none repeat scroll 0% 50%;
}
.headerbox p, .headerbox em {
margin: 6px;
padding: 6px;
}
.header {
color: #000;
background: #efefef;
border-bottom: 1px solid #000;
margin-bottom: 6px;
}
.header a {
color: #343dba;
}
.header a:hover, a.header:hover {
color: darkblue;
text-decoration: underline;
}
a.header {
border-bottom: 0;
background: transparent;
}
a.fixed {
color: #339;
}
.light {
color: #333;
}
.control {
background: #ddd;
padding: 6px;
}
.widget {
color: #224;
}
/* Form styles. */
input, select, textarea {
font-size: 12px;
color: #000;
background: #f3f3f9;
border: 1px solid #ccc;
padding: 2px;
}
input:focus, textarea:focus {
background: #fff;
border: 1px solid #000;
}
.button, .button:focus {
background: #f3f9f9;
border: 1px solid #000;
cursor: pointer;
padding: 2px;
font-weight: bold;
}
.button:hover {
background: #ddd;
}
input[type="reset"] {
background-color: #faa;
}
input[type="reset"]:hover {
background-color: #fcc;
}
input[type="submit"] {
background-color: #afa;
}
input[type="submit"]:hover {
background-color: #cfc;
}
fieldset {
padding: 12px;
border: 0;
border-top: 3px solid #555;
}
legend {
padding: 6px;
font-weight: bold;
}
/* Alternating styles. item0, item1 are deprecated. */
.rowEven, .item0 {
background: #eee;
}
.rowOdd, .item1, .item {
background: #dae6f2;
}
.selected {
background: #C6D3FF;
}
h1 {
margin: 0;
}
/* Various popup and status layers. */
.tooltip, div.nicetitle {
color: #fff;
background: #5d7cba;
border: 2px double #fff;
}
/* Menu styles. */
#menu {
background: #5d7cba;
border-bottom: 1px solid #555;
padding: 2px;
margin: 0;
}
#menu a {
color: #fff;
}
#menu a:hover {
background-color: #555;
}
#menu a.current {
background: #333;
padding: 2px;
}
#menuBottom {
margin: 0;
background: #c9daed;
}
/* Sidebar styles. */
body.sidebar {
border-right: 1px solid #000;
background-color: #c9daed;
height: 100%;
}
body.sidebar #menu {
border-right: 1px solid #5d7cba;
margin-right: -1px;
}
#sidebarPanel {
-moz-border-radius: 0;
-webkit-border-radius: 0;
background-color: #c9daed;
}
#sidebarPanel span.toggle, #sidebarPanel a {
padding-left: 1px;
padding-bottom: 2px;
}
#sidebarPanel span.toggle {
border: 1px none transparent;
}
#sidebarPanel a {
color: #343dba;
padding: 2px;
}
#sidebarPanel a:hover {
color: #fff;
background: #5d7cba;
text-decoration: none;
}
#expandButton {
margin-right: 1px;
}
/* Tab styles. */
.tabset {
background: none;
border-bottom: 1px solid #efefef;
}
.tabset li a {
border: 1px solid #ccc;
background-color: #ccc;
}
.tabset li.activeTab a, .tabset li.activeTab a:hover {
color: #000;
background-color: #efefef;
border-bottom-color: #efefef;
}
td.notice {
background-color: #faa;
padding: 2px;
border: 1px solid #000;
-moz-border-radius: 0;
-webkit-border-radius: 0;
}
p.notice {
background-color: #ffc;
-moz-border-radius: 0;
-webkit-border-radius: 0;
border: 0;
border-bottom: 1px solid #000;
margin: 0;
padding: 6px;
}
.headerbox {
background: #A8C4E1 none repeat scroll 0% 50%;
padding: 0;
border-top: 1px solid #000;
}
| 16.607287 | 86 | 0.609703 |
1a4af37cf8cda73896c1a3302e394842af811bbf | 971 | py | Python | receiver.py | i-adarsh/Live-Streaming-Video-Chat-App | 2bfac20188694265afc4b59fccae98cdce49e4a8 | [
"MIT"
] | null | null | null | receiver.py | i-adarsh/Live-Streaming-Video-Chat-App | 2bfac20188694265afc4b59fccae98cdce49e4a8 | [
"MIT"
] | null | null | null | receiver.py | i-adarsh/Live-Streaming-Video-Chat-App | 2bfac20188694265afc4b59fccae98cdce49e4a8 | [
"MIT"
] | null | null | null | import socket
import os
import cv2
import pickle
import threading
import struct
def sendImage():
os.system('python sender.py')
t1 = threading.Thread(target=sendImage)
t1.start()
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host_ip = '192.168.43.6'
port = 9900
client_socket.connect((host_ip, port))
data = b""
payload_size = struct.calcsize("Q")
while True:
while len(data) < payload_size:
packet = client_socket.recv(4 * 1024)
if not packet: break
data += packet
packed_msg_size = data[:payload_size]
data = data[payload_size:]
msg_size = struct.unpack("Q", packed_msg_size)[0]
while len(data) < msg_size:
data += client_socket.recv(4 * 1024)
frame_data = data[:msg_size]
data = data[msg_size:]
frame = pickle.loads(frame_data)
cv2.imshow("Live Streaming Video Chat", frame)
key = cv2.waitKey(1) & 0xFF
if key == ord('q'):
break
client_socket.close()
| 21.577778 | 65 | 0.673532 |
daa5955d10163cf8050d4077285f25a85d103a50 | 1,565 | php | PHP | application/views/tutor/alumnos/oportunidades.php | grupodesoft/appwoori | db7f1bd5fda100974ca45e6b2fd10157fb37a7db | [
"MIT"
] | 1 | 2020-02-25T00:24:23.000Z | 2020-02-25T00:24:23.000Z | application/views/tutor/alumnos/oportunidades.php | grupodesoft/sice | db7f1bd5fda100974ca45e6b2fd10157fb37a7db | [
"MIT"
] | null | null | null | application/views/tutor/alumnos/oportunidades.php | grupodesoft/sice | db7f1bd5fda100974ca45e6b2fd10157fb37a7db | [
"MIT"
] | null | null | null | <!-- page content -->
<div class="right_col" role="main">
<div class="">
<div class="row">
<div class="col-md-12">
<div class="x_panel">
<div class="x_title">
<h2><strong><?php
if(isset($nombreoportunidad) && !empty($nombreoportunidad)){
echo $nombreoportunidad;
}
?></strong></h2>
<div class="clearfix"></div>
</div>
<div class="x_content">
<div class="row">
<?php
if(isset($tabla) && !empty($tabla)){
echo $tabla;
}
?>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- footer content -->
<footer>
<div class="copyright-info">
<p class="pull-right">SICE - Sistema Integral para el Control Escolar</a>
</p>
</div>
<div class="clearfix"></div>
</footer>
<!-- /footer content -->
</div>
<!-- /page content -->
</div>
</div>
<div id="custom_notifications" class="custom-notifications dsp_none">
<ul class="list-unstyled notifications clearfix" data-tabbed_notifications="notif-group">
</ul>
<div class="clearfix"></div>
<div id="notif-group" class="tabbed_notifications"></div>
</div>
| 28.981481 | 93 | 0.410863 |
a38693f050b1f56eac624acbb0acc29a8c1b51ad | 1,370 | ts | TypeScript | src/oauth/oauth.guard.ts | open-hotel/sirius-emulator | f852fe3f7bdbd15d713bcb2cf92bb2be28649065 | [
"MIT"
] | 5 | 2020-06-09T04:38:04.000Z | 2021-10-17T22:37:36.000Z | src/oauth/oauth.guard.ts | open-hotel/sirius-emulator | f852fe3f7bdbd15d713bcb2cf92bb2be28649065 | [
"MIT"
] | 4 | 2019-10-18T01:31:50.000Z | 2022-01-22T09:03:31.000Z | src/oauth/oauth.guard.ts | open-hotel/sirius-emulator | f852fe3f7bdbd15d713bcb2cf92bb2be28649065 | [
"MIT"
] | 4 | 2020-04-30T09:09:12.000Z | 2022-03-06T10:34:49.000Z | import {
CanActivate,
ExecutionContext,
Injectable,
Inject,
} from '@nestjs/common';
import { OAuthServerProvider } from './oauth.service';
import * as OAuthServer from 'oauth2-server';
import { Request, Response } from 'express';
const getPublic = (value: Function) =>
Reflect.getMetadata('OAUTH_PUBLIC', value);
const getScopes = (value: Function) =>
Reflect.getMetadata('OAUTH_SCOPES', value) || [];
@Injectable()
export class OAuthGuard implements CanActivate {
@Inject(OAuthServerProvider)
oauth: OAuthServerProvider;
async canActivate(context: ExecutionContext): Promise<boolean> {
const http = context.switchToHttp();
const request: Request = http.getRequest();
const response: Response = http.getResponse();
const req = new OAuthServer.Request(request);
const res = new OAuthServer.Response(response);
const controller = context.getClass();
const handler = context.getHandler();
const isPublic = getPublic(handler) || getPublic(controller);
if (isPublic) return true;
let scope = getScopes(controller).concat(getScopes(handler));
scope = scope.length ? scope.join(',') : [];
return this.oauth.server
.authenticate(req, res, { scope: scope.length ? scope : undefined })
.then(token => {
response.locals.user = token.user;
return !!token.user;
});
}
}
| 28.541667 | 74 | 0.688321 |
c97c68e254f985faf3d8b297649937bdde7eed4b | 775 | ts | TypeScript | tests/app/validators/required-buffer.spec.ts | Leandro2585/hyperion-api | b2eb4bfc382536a42db86c7b8d3c1f25c9520675 | [
"MIT"
] | 2 | 2021-11-10T20:18:14.000Z | 2022-02-02T01:22:19.000Z | tests/app/validators/required-buffer.spec.ts | Leandro2585/hyperion-api | b2eb4bfc382536a42db86c7b8d3c1f25c9520675 | [
"MIT"
] | null | null | null | tests/app/validators/required-buffer.spec.ts | Leandro2585/hyperion-api | b2eb4bfc382536a42db86c7b8d3c1f25c9520675 | [
"MIT"
] | null | null | null | import { RequiredFieldError } from '@app/errors'
import { RequiredBufferValidator, RequiredValidator } from '@app/validators'
describe('required-buffer validator', () => {
test('should extend required validator', () => {
const sut = new RequiredBufferValidator(Buffer.from(''))
expect(sut).toBeInstanceOf(RequiredValidator)
})
test('should return RequiredFieldError if value is empty', () => {
const sut = new RequiredBufferValidator(Buffer.from(''))
const error = sut.validate()
expect(error).toEqual(new RequiredFieldError())
})
test('should return undefined if value is not empty', () => {
const sut = new RequiredBufferValidator(Buffer.from('any_buffer'))
const error = sut.validate()
expect(error).toBeUndefined()
})
})
| 31 | 76 | 0.698065 |
b02cc9d2c38b0fb90a84b88441ab8520e5382bbb | 11,547 | py | Python | skore/skore.py | hackorama/sandbox | 9484b0428c0bdcf5b0556406f9bf98b9d1058d28 | [
"MIT"
] | null | null | null | skore/skore.py | hackorama/sandbox | 9484b0428c0bdcf5b0556406f9bf98b9d1058d28 | [
"MIT"
] | 5 | 2021-03-19T20:18:16.000Z | 2021-06-02T03:37:39.000Z | skore/skore.py | hackorama/sandbox | 9484b0428c0bdcf5b0556406f9bf98b9d1058d28 | [
"MIT"
] | null | null | null | """
Find the DOTA 2 teams with the most combined player score,
where score is defined as the length of a player's recorded history.
"""
import heapq
import logging as log
import sys
from argparse import ArgumentParser, FileType
from datetime import datetime
from operator import itemgetter
from sys import stdout
from typing import List, Tuple, Dict, Any, TextIO
import requests
import yaml
class Skore:
"""
Finds the top DOTA 2 teams with most combined player score
"""
def __init__(self, api_base_url: str, output_file: TextIO = None) -> None:
"""
Initialize the score calculation
:param api_base_url: the URL base for the API server
:param output_file: the output file for printing the results
:return: None
"""
# Combined score map of teams
self.team_score: Dict[int, Any] = {}
self.api_base_url: str = api_base_url
self.output_file: TextIO = output_file
def print_top_score_teams(self, num_teams: int) -> None:
"""
Find and print the given number of team data with the highest combined score.
:param num_teams: the expected number of teams in result to be printed
:return: None
"""
log.info('Printing top %d team(s) to result yaml %s', num_teams, self.output_file.name)
with self.output_file:
for team in self.calculate_top_teams(self.__get_players(), self.__get_teams(), num_teams):
yaml.dump({team: self.team_score[team]}, self.output_file, default_flow_style=False)
def get_top_score_teams(self, num_teams: int) -> List:
"""
Find the given number of team data with the highest combined score.
:param num_teams: the expected number of teams in result
:return: None
"""
log.info('Getting top %d team(s)', num_teams)
result: List[Any] = []
for team in self.calculate_top_teams(self.__get_players(), self.__get_teams(), num_teams):
result.append(self.team_score[team])
return result
def calculate_top_teams(self, players: list, teams: list, num_teams: int) -> List[int]:
"""
Find the given number of team ids with the highest score.
:param players: the players list json
:param teams: the teams list json
:param num_teams: the expected number of teams in list
:return: the list of ids of the top teams
"""
log.info('Finding top %d team(s) from %s', num_teams, self.api_base_url)
if num_teams < 1:
log.error('Please provide a valid top number of teams instead of the provided %d', num_teams)
return []
if not players or not teams:
log.error('Invalid players/teams provided')
return []
self.__calculate_team_score(players)
self.__update_team_info(teams)
return self.__find_top_teams(num_teams)
def __find_top_teams(self, num_teams: int) -> List[int]:
"""
Find the given number of teams with the highest combined score from the already built team score map.
TODO: Measure/understand Python heap/sorted performance for fine tune the top k of n search
:param num_teams: the expected number of teams in result
:return: the list of ids of the top teams
"""
# When result size is one optimize with linear search. O(n)
if num_teams == 1:
log.debug('Using linear search for single result out of %d', len(self.team_score))
max_score = 0
team_with_max_score = 0
for key, value in self.team_score.items():
if value['xp'] > max_score:
max_score = value['xp']
team_with_max_score = key
return [team_with_max_score]
# When the result size is larger use in place sorting without additional space. O(n log n)
if num_teams >= len(self.team_score) / 2:
log.debug('Using sorted for finding %d largest out of %d', num_teams, len(self.team_score))
return sorted(self.team_score, key=lambda x: self.team_score[x]['xp'], reverse=True)[:num_teams]
# When the result size k is smaller use a max heap. O(n + k log n) and O(n) space
log.debug('Using max heap for finding %d largest out of %d', num_teams, len(self.team_score))
score_id: List[Tuple[int, int]] = []
# Create a list of (xp, id) for the teams from team_score
for key, value in self.team_score.items():
score_id.append((value['xp'], key))
# Use heap to find largest team scores from score_id using id (score_id[0]) as key,
# then map and return the corresponding ids (score_id[1]) as a list
return list(map(itemgetter(1), heapq.nlargest(num_teams, score_id, key=itemgetter(0))))
def __calculate_team_score(self, players: list) -> None:
"""
Calculate team score combining player scores.
Players with invalid account id and/or team id and/or history time will be excluded from calculation
Other player and team attributes are optional and any invalid attribute values will be ignored
and defaults (0 for numbers and '' for strings) will be used.
Optional team attributes are initialized with defaults to be updated later in __update_team_info().
:param players: list of players
:return: None
"""
for player in players:
if player['team_id'] > 0 and player['account_id'] > 0:
try:
player_score = Skore.calculate_score(player['full_history_time'])
except ValueError:
log.debug(
'Excluding invalid player %d time %s', player['account_id'], player['full_history_time'])
# Exclude players with invalid history time from team calculation
continue
self.team_score.setdefault(player['team_id'],
{'name': '', 'team_id': player['team_id'], 'wins': 0, 'losses': 0, 'rating': 0,
'players': []})
self.team_score[player['team_id']]['players'].append(
{'personaname': player['personaname'], 'xp': player_score, 'country_code': player["country_code"]})
if 'xp' in self.team_score[player['team_id']]:
self.team_score[player['team_id']]['xp'] += player_score
else:
self.team_score[player['team_id']]['xp'] = player_score
else:
log.debug('Excluding invalid player %d team %d', player['account_id'], player['team_id'])
def __update_team_info(self, teams: list) -> None:
"""
Update the team score map with the optional team attributes.
:param teams: the list of teams
:return: None
"""
for team in teams:
if team['team_id'] > 0 and team['team_id'] in self.team_score.keys():
self.team_score[team['team_id']]['name'] = team['name']
self.team_score[team['team_id']]['wins'] = team['wins']
self.team_score[team['team_id']]['losses'] = team['losses']
self.team_score[team['team_id']]['rating'] = team['rating']
def __get_players(self) -> list:
"""
Get the list of players from API server.
:return: list of players
"""
players = self.__get('proPlayers')
if players is None:
log.critical("Found no valid players, please check the logs")
sys.exit(1)
else:
return players
def __get_teams(self) -> list:
"""
Get the list of teams from API server.
:return: list of teams
"""
teams = self.__get('teams')
if teams is None:
log.critical("Found no valid teams, please check the logs")
sys.exit(1)
else:
return teams
def __get(self, api: str) -> list:
"""
Get the response for the given API call.
:param api: the API to call
:return: the API response
"""
api_url = '{0}/{1}'.format(self.api_base_url, api)
try:
return Skore.process_response(requests.get(api_url))
except requests.exceptions.RequestException as exception:
log.error('There was an error connecting to %s, please correct the URL or retry', api_url)
log.exception(exception)
@staticmethod
def calculate_score(timestamp: str) -> int:
"""
Calculate a players score based on the amount of time that has passed since the start of a player's data.
:param timestamp: the timestamp when a players data started
:return: the calculated score of the player
"""
timestamp = str(timestamp)
if timestamp is None or not timestamp.strip():
raise ValueError('Timestamp should not be None or empty')
hist_time = datetime.strptime(timestamp, "%Y-%m-%dT%H:%M:%S.%fZ")
# Using precision of seconds for xp calculation
# TODO: Explore using minutes/hours precision to avoid int overflow
# for teams with large number of players with long history time
return int((datetime.now() - hist_time).total_seconds())
@staticmethod
def process_response(response: requests.Response) -> list:
"""
Process the given API response json body and check for valid format and response code.
:param response: the API response to process
:return: the json response body
"""
if response.status_code == 200:
try:
return response.json()
except ValueError as error:
log.error('Unexpected response format')
log.exception(error)
else:
log.error('Unexpected response code %s', response)
return []
def parse_args():
"""
Retrieve args from command line.
"""
parser = ArgumentParser(
description='Find the DOTA 2 teams with the most combined player *score',
epilog='*Experience is defined as the length of a player\'s recorded history.',
)
parser.add_argument(
'output',
type=FileType('w'),
nargs='?',
default=stdout,
help='result output file. (default: stdout)'
)
parser.add_argument(
'-n',
'--numteams',
type=int,
default=5,
help='number of teams in output. (default: %(default)s)'
)
parser.add_argument(
'-l',
'--loglevel',
choices=['CRITICAL', 'ERROR', 'WARNING', 'INFO', 'DEBUG'],
default='WARNING',
help='Only output log messages of this severity or above. Writes to stderr. (default: %(default)s)'
)
parser.add_argument(
'-s',
'--server',
default='https://api.opendota.com/api',
help='The API server base URL. (default: %(default)s)'
)
return parser.parse_args()
def main():
"""
Main entry point with args processing and log initialization.
"""
args = parse_args()
log.basicConfig(format='%(asctime)s %(levelname)-8s [%(filename)s:%(lineno)d] - %(message)s',
level=log.getLevelName(args.loglevel))
Skore(api_base_url=args.server, output_file=args.output).print_top_score_teams(args.numteams)
if __name__ == '__main__':
main()
| 40.374126 | 119 | 0.606391 |
e4c3cbbb0771ece56dba37d0e4bde7d174ba10c7 | 116 | rs | Rust | src/wild_terrain.rs | 5mattmatt1/generation_iii_rom_editor | 5aa4b6410ad6cfef74cd3609c655b748a621d440 | [
"MIT"
] | null | null | null | src/wild_terrain.rs | 5mattmatt1/generation_iii_rom_editor | 5aa4b6410ad6cfef74cd3609c655b748a621d440 | [
"MIT"
] | null | null | null | src/wild_terrain.rs | 5mattmatt1/generation_iii_rom_editor | 5aa4b6410ad6cfef74cd3609c655b748a621d440 | [
"MIT"
] | null | null | null | #[derive(Eq, PartialEq, Hash, Copy, Clone)]
pub enum WildTerrain
{
Grass,
Water,
Tree,
Fishing
} | 14.5 | 43 | 0.594828 |
75ba6a5e76b09c56aa5181420a763874fd86cfab | 1,041 | css | CSS | src/components/services-brief.module.css | Cea-Personal/IDoJAMStack | 88f9eb645792f1c18c5cbaaccfae8b29937c27a1 | [
"MIT"
] | null | null | null | src/components/services-brief.module.css | Cea-Personal/IDoJAMStack | 88f9eb645792f1c18c5cbaaccfae8b29937c27a1 | [
"MIT"
] | 3 | 2021-09-02T00:58:54.000Z | 2022-02-18T10:10:15.000Z | src/components/services-brief.module.css | basilcea/IDoJAMStack | 88f9eb645792f1c18c5cbaaccfae8b29937c27a1 | [
"MIT"
] | null | null | null |
.servicesDiv{
width:100%;
display:flex;
flex-direction: column;
align-items:center;
background-color:white;
box-shadow: 0 8px 16px 0 rgba(0, 0, 0, 0.2),
0 6px 20px 0 rgba(0, 0, 0, 0.19);
}
.heading{
font-size:1.5rem;
color:rgb(228, 182 , 210 ,1);
padding-top:10%;
padding-bottom:5%;
font-family:Arial, Helvetica, sans-serif;
}
.goDown{
font-size:3em;
width:100%;
padding-top:5%;
padding-bottom:2%;
display: flex;
justify-content: center;
align-items:flex-end;
color:rgb(84, 20 , 84 ,1);
}
.paragraph{
padding:0% 10%;
padding-bottom:5%;
line-height:1.5rem;
color:black;
font-family:'Trebuchet MS', 'Lucida Sans Unicode', 'Lucida Grande', 'Lucida Sans', Arial, sans-serif
}
@media (min-width:500px){
.header{
padding-top:2%
}
.paragraph{
padding-bottom: 1%;
}
.serviceInfo{
width:100%;
margin-top:0%;
height:43vh;
display:flex;
justify-content:space-evenly
}
}
| 20.411765 | 104 | 0.582133 |
a36f5b3b15d74105ecc139b409d3a25c137e92a6 | 3,402 | java | Java | src/main/java/com/github/sergueik/jprotractor/NgBy.java | sergueik/jProtractor | 00ae9dcef44533ea23527e3d83e263c5d73908f1 | [
"MIT"
] | 13 | 2015-12-25T18:19:04.000Z | 2018-10-23T17:35:09.000Z | src/main/java/com/github/sergueik/jprotractor/NgBy.java | sergueik/jProtractor | 00ae9dcef44533ea23527e3d83e263c5d73908f1 | [
"MIT"
] | null | null | null | src/main/java/com/github/sergueik/jprotractor/NgBy.java | sergueik/jProtractor | 00ae9dcef44533ea23527e3d83e263c5d73908f1 | [
"MIT"
] | 3 | 2015-12-30T04:56:02.000Z | 2018-08-23T19:17:00.000Z | package com.github.sergueik.jprotractor;
import java.util.regex.Pattern;
import org.openqa.selenium.By;
import com.github.sergueik.jprotractor.scripts.FindAllRepeaterColumns;
import com.github.sergueik.jprotractor.scripts.FindAllRepeaterRows;
import com.github.sergueik.jprotractor.scripts.FindBindings;
import com.github.sergueik.jprotractor.scripts.FindButtonText;
import com.github.sergueik.jprotractor.scripts.FindCssSelectorContainingText;
import com.github.sergueik.jprotractor.scripts.FindModel;
import com.github.sergueik.jprotractor.scripts.FindOptions;
import com.github.sergueik.jprotractor.scripts.FindPartialButtonText;
import com.github.sergueik.jprotractor.scripts.FindRepeaterElements;
import com.github.sergueik.jprotractor.scripts.FindRepeaterRows;
import com.github.sergueik.jprotractor.scripts.FindSelectedOption;
import com.github.sergueik.jprotractor.scripts.FindSelectedRepeaterOption;
public final class NgBy {
private NgBy() {
}
public static By binding(final String binding) {
return new JavaScriptBy(new FindBindings(), binding);
}
public static By binding(final String binding, String rootSelector) {
return new JavaScriptBy(new FindBindings(), binding, rootSelector);
}
public static By buttonText(final String text) {
return new JavaScriptBy(new FindButtonText(), text);
}
public static By cssContainingText(final String cssSelector, String text) {
return new JavaScriptBy(new FindCssSelectorContainingText(), cssSelector,
text);
}
public static By cssContainingText(final String cssSelector,
Pattern pattern) {
int patternFlags = pattern.flags();
String patternText = String
.format("__REGEXP__/%s/%s%s",
pattern.pattern(),
((patternFlags
& Pattern.CASE_INSENSITIVE) == Pattern.CASE_INSENSITIVE) ? "i"
: "",
((patternFlags & Pattern.MULTILINE) == Pattern.MULTILINE) ? "m"
: "");
return new JavaScriptBy(new FindCssSelectorContainingText(), cssSelector,
patternText);
}
public static By input(final String input) {
return new JavaScriptBy(new FindModel(), input);
}
public static By model(final String model) {
return new JavaScriptBy(new FindModel(), model);
}
public static By model(final String model, String rootSelector) {
return new JavaScriptBy(new FindModel(), model, rootSelector);
}
public static By partialButtonText(final String text) {
return new JavaScriptBy(new FindPartialButtonText(), text);
}
public static By repeater(final String repeat) {
return new JavaScriptBy(new FindAllRepeaterRows(), repeat);
}
public static By repeaterColumn(final String repeat, String binding) {
return new JavaScriptBy(new FindAllRepeaterColumns(), repeat, binding);
}
public static By repeaterElement(final String repeat, Integer index,
String binding) {
return new JavaScriptBy(new FindRepeaterElements(), repeat, index, binding);
}
public static By repeaterRows(final String repeat, Integer index) {
return new JavaScriptBy(new FindRepeaterRows(), repeat, index);
}
public static By options(final String options) {
return new JavaScriptBy(new FindOptions(), options);
}
public static By selectedOption(final String model) {
return new JavaScriptBy(new FindSelectedOption(), model);
}
public static By selectedRepeaterOption(final String repeat) {
return new JavaScriptBy(new FindSelectedRepeaterOption(), repeat);
}
}
| 33.352941 | 78 | 0.773075 |
6afeaa3a4a35c6bc6375ecb382d75fb7fc6d7630 | 1,869 | h | C | bkserial.h | jnwatts/bksupply | c222e370b180c817318a6b26fb67762d8053412c | [
"MIT"
] | null | null | null | bkserial.h | jnwatts/bksupply | c222e370b180c817318a6b26fb67762d8053412c | [
"MIT"
] | null | null | null | bkserial.h | jnwatts/bksupply | c222e370b180c817318a6b26fb67762d8053412c | [
"MIT"
] | null | null | null | #ifndef BKSERIAL_H
#define BKSERIAL_H
#include <QObject>
#include <QtSerialPort/QSerialPort>
#include <QTimer>
#include <QVector>
#include <functional>
#include <QMap>
class BKSerial : public QObject
{
Q_OBJECT
public:
typedef std::function<void(QStringList)> response_handler_t;
typedef std::function<void(void)> completed_handler_t;
typedef std::function<QString(QString)> transform_t;
typedef struct {
int first;
int last;
transform_t transform;
} response_part_t;
typedef struct {
int size;
QVector<response_part_t> parts;
} response_t;
typedef struct {
QString command;
response_t *response;
response_handler_t response_handler;
} request_t;
explicit BKSerial(QObject *parent = 0);
~BKSerial(void);
void open(QString port, completed_handler_t complete = nullptr);
void close(completed_handler_t complete);
bool isOpen(void) { return this->_serial.isOpen(); }
void setAddress(int address) { this->_address = address; }
int address(void) { return this->_address; }
void command(QString command, response_handler_t response_handler = nullptr);
void command(QString command, QList<QString> &args, response_handler_t response_handler = nullptr);
static QList<QString> ports();
protected:
void registerResponse(QString command, const response_t &response);
void failure(request_t &request, QString reason);
void parseResponse(request_t &request, QString data);
signals:
void openChanged(void);
public slots:
private slots:
void dataReady(void);
void timeout(void);
private:
int _address;
QSerialPort _serial;
QByteArray _response;
QTimer _timeout;
QList<request_t> _requests;
QMap<QString, response_t> _responses;
int _timeout_count;
};
#endif // BKSERIAL_H
| 24.592105 | 103 | 0.70519 |
5e1de44943a7c8f70d732acc35c34b5c9defaed7 | 851 | rb | Ruby | spec/spec_helper.rb | ryanhouston/elasticsearch-documents | db7d175265111eae7afe27b4d522cfe630f80602 | [
"MIT"
] | null | null | null | spec/spec_helper.rb | ryanhouston/elasticsearch-documents | db7d175265111eae7afe27b4d522cfe630f80602 | [
"MIT"
] | 1 | 2015-10-26T22:23:21.000Z | 2015-10-27T13:51:03.000Z | spec/spec_helper.rb | ryanhouston/elasticsearch-documents | db7d175265111eae7afe27b4d522cfe630f80602 | [
"MIT"
] | 1 | 2018-07-20T20:53:01.000Z | 2018-07-20T20:53:01.000Z | require 'elasticsearch-documents'
def reset_configuration
Elasticsearch::Extensions::Documents.configuration = nil
configure_documents
end
def configure_documents
Elasticsearch::Extensions::Documents.configure do |config|
config.index_name = 'test_index'
config.settings = :fake_settings
config.mappings = :fake_mappings
config.client.url = 'http://example.com:9200'
end
end
RSpec.configure do |config|
config.treat_symbols_as_metadata_keys_with_true_values = true
config.run_all_when_everything_filtered = true
config.filter_run :focus
config.order = 'random'
config.before(:suite) do
configure_documents
end
end
class TestDocumentsDocument < Elasticsearch::Extensions::Documents::Document
indexes_as_type :documents_test
def as_hash
{
a: object.a,
b: object.b,
}
end
end
| 21.275 | 76 | 0.753231 |
938aaa6453503b6d45e9d6a261691ec57c618b7a | 1,287 | cs | C# | ShiroiCutscenes-Runtime/Tokens/WaitForSecondsToken.cs | LunariStudios/ShiroiCutscenes | 77795a64b44f11183b8c5df83d805bd0694a6f58 | [
"MIT"
] | 13 | 2019-01-11T03:20:48.000Z | 2022-03-27T04:23:52.000Z | ShiroiCutscenes-Runtime/Tokens/WaitForSecondsToken.cs | BrunoSilvaFreire/ShiroiCutscenes | 77795a64b44f11183b8c5df83d805bd0694a6f58 | [
"MIT"
] | 6 | 2018-01-29T17:32:37.000Z | 2018-05-16T13:43:33.000Z | ShiroiCutscenes-Runtime/Tokens/WaitForSecondsToken.cs | BrunoSilvaFreire/ShiroiCutscenes | 77795a64b44f11183b8c5df83d805bd0694a6f58 | [
"MIT"
] | 5 | 2019-03-21T08:44:19.000Z | 2022-03-13T11:36:20.000Z | using System.Collections;
using System.Collections.Generic;
using JetBrains.Annotations;
using UnityEngine;
namespace Shiroi.Cutscenes.Tokens {
[UsedImplicitly]
public class WaitForSecondsToken : Token, ISkippable {
public float Duration;
public bool Realtime;
private readonly Dictionary<CutsceneExecutor, Waiter> cache = new Dictionary<CutsceneExecutor, Waiter>();
public override IEnumerator Execute(CutscenePlayer player, CutsceneExecutor executor) {
var w = new Waiter(Duration, Realtime);
cache[executor] = w;
while (w.Tick()) {
yield return null;
}
}
public void Skip(CutscenePlayer player, CutsceneExecutor executor) { }
}
public class Waiter {
private float timeLeft;
private readonly bool realtime;
public Waiter(float duration, bool realtime) {
this.timeLeft = duration;
this.realtime = realtime;
}
public bool Tick() {
return (timeLeft -= GetDeltaTime()) > 0;
}
private float GetDeltaTime() {
return realtime ? Time.unscaledDeltaTime : Time.deltaTime;
}
public void Clear() {
timeLeft = 0;
}
}
} | 29.25 | 113 | 0.609946 |
4433e8419f604d8ad0a64c95181753f481dee03d | 4,315 | py | Python | teras/dataset/loader.py | chantera/nlplibs-py | 413c90ba85beeaf062cb451fdb92eb4273b4d5bf | [
"MIT"
] | 8 | 2017-07-02T14:24:18.000Z | 2021-12-18T08:17:41.000Z | teras/dataset/loader.py | chantera/nlplibs-py | 413c90ba85beeaf062cb451fdb92eb4273b4d5bf | [
"MIT"
] | 1 | 2018-03-01T10:18:45.000Z | 2018-03-01T13:59:47.000Z | teras/dataset/loader.py | chantera/nlplibs-py | 413c90ba85beeaf062cb451fdb92eb4273b4d5bf | [
"MIT"
] | 4 | 2019-01-22T01:03:05.000Z | 2020-05-26T07:45:20.000Z | from abc import ABC, abstractmethod
from teras.dataset.dataset import Dataset, BucketDataset
from teras.io.cache import Cache
from teras.preprocessing import text
class Loader(ABC):
def load(self, file):
raise NotImplementedError
class TextLoader(Loader):
def __init__(self, reader):
self._reader = reader
self._processors = {}
self.train = False
self._context = None
def add_processor(self, name, *args, **kwargs):
self._processors[name] = text.Preprocessor(*args, **kwargs)
def get_processor(self, name):
return self._processors[name]
def get_embeddings(self, name, normalize=False):
if isinstance(self._processors[name].vocab, text.EmbeddingVocab):
return self._processors[name].vocab.get_embeddings(normalize)
return None
@abstractmethod
def map(self, item):
raise NotImplementedError
def map_attr(self, attr, value, update=True):
return self._processors[attr].fit_transform(value, fit=update)
def filter(self, item):
return True
def load(self, file, train=False, size=None, bucketing=False):
self.train = train
self._reader.set_file(file)
self._context = {
'train': train,
'item_index': -1,
'num_samples': 0,
}
def _next_sample(reader):
context = self._context
for item in reader:
context['item_index'] += 1
if self.filter(item):
sample = self.map(item)
context['num_samples'] += 1
yield sample
if size is None:
samples = list(_next_sample(self._reader))
else:
samples = []
for sample in _next_sample(self._reader):
samples.append(sample)
if len(samples) >= size:
break
self._context = None
if bucketing:
return BucketDataset(samples, key=0, equalize_by_key=True)
else:
return Dataset(samples)
class CachedTextLoader(TextLoader):
DEFAULT_CACHE_OPTIONS = {
'key': None,
'dir': None,
'ext': '.pkl',
'prefix': '',
'mkdir': False,
'hash_length': 16,
'serializer': None,
'deserializer': None,
'logger': None,
}
_cache_io = None
@classmethod
def build(cls, enable_cache=True, cache_options=None, extra_ids=None,
refresh_cache=False, **kwargs):
cache_io = None
if enable_cache:
if cache_options is None:
cache_options = dict()
cache_options = {**cls.DEFAULT_CACHE_OPTIONS, **cache_options}
if cache_options['dir'] is None:
raise FileNotFoundError("cache dir was must be specified")
elif cache_options['key'] is None:
cache_options['key'] = dict(kwargs, extra_ids=extra_ids)
cache_io = Cache(**cache_options)
def _instantiate():
instance = cls(**kwargs)
instance._cache_io = cache_io
return instance
if cache_io is None:
return _instantiate()
else:
instance = cache_io.load_or_create(_instantiate, refresh_cache)
if instance._cache_io is None:
instance._cache_io = cache_io
return instance
def update_cache(self):
if self._cache_io is None:
raise RuntimeError('caching is not enabled')
self._cache_io.dump(self)
def load(self, file, train=False, size=None, bucketing=False,
extra_ids=None, refresh_cache=False, disable_cache=False):
def _load():
return super(CachedTextLoader, self) \
.load(file, train, size, bucketing)
if self._cache_io is None or disable_cache:
return _load()
else:
hash_key = (self._cache_io.id,
file, train, size, bucketing, extra_ids)
cache_io = self._cache_io.clone(hash_key)
return cache_io.load_or_create(_load, refresh_cache)
def __getstate__(self):
state = self.__dict__.copy()
state['_cache_io'] = None
return state
| 30.602837 | 75 | 0.581228 |
ba41d269453ece7751b98fe1f6ec8c087f390711 | 3,032 | swift | Swift | DD_Swift4.0/Class/View/DDBaseView.swift | DanDanXiaoMu/aSwiftProject | b85588d6d4d971096738009514f233b5e01d5d8e | [
"Apache-2.0"
] | 1 | 2017-12-20T06:02:40.000Z | 2017-12-20T06:02:40.000Z | DD_Swift4.0/Class/View/DDBaseView.swift | DanDanXiaoMu/aSwiftProject | b85588d6d4d971096738009514f233b5e01d5d8e | [
"Apache-2.0"
] | null | null | null | DD_Swift4.0/Class/View/DDBaseView.swift | DanDanXiaoMu/aSwiftProject | b85588d6d4d971096738009514f233b5e01d5d8e | [
"Apache-2.0"
] | null | null | null | //
// DDBaseView.swift
// Demo
//
// Created by DDCJ_XiaoZhu on 2017/11/13.
// Copyright © 2017年 DDCJ_XiaoZhu. All rights reserved.
//
import UIKit
import MJRefresh
class DDBaseView: UIView {
var currentVc = DDBaseViewController()
public lazy var ModelMeArr : [joke] = [joke]()
lazy var DDTableView:UITableView = {
let tableView = UITableView()
tableView.frame = CGRect(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height)
let header = MJRefreshNormalHeader()
header.setRefreshingTarget(self, refreshingAction: #selector(loadData))
tableView.mj_header = header
let footer = MJRefreshAutoNormalFooter()
footer.setRefreshingTarget(self, refreshingAction: #selector(loadNextData))
tableView.mj_footer = footer
return tableView
}()
// 下拉刷新
/*
这里之所以用objc func 是用到了OC 的一些东西,具体的我也没有整明白,
*/
@objc func loadData() {
currentVc.loadData(pageNumber: currentVc.pageNumber, pageSize: currentVc.pageSize)
DDTableView.mj_header.endRefreshing()
self.DDTableView.reloadData()
}
//上拉加载
@objc func loadNextData() {
let pageNub : Int = 1
currentVc.loadData(pageNumber:String(pageNub+1), pageSize: currentVc.pageSize)
self.DDTableView.reloadData()
}
init(frame: CGRect , currentVC:DDBaseViewController , modelArr:[joke]) {
super.init(frame: frame)
self.ModelMeArr = modelArr
currentVc = currentVC
installUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func installUI() {
// 配合下文自动适配Cell行高
DDTableView.estimatedRowHeight = 44.0
self.registerCell()
self.DDTableView.delegate = self;
self.DDTableView.dataSource = self;
addSubview(self.DDTableView)
}
func registerCell() {
self.DDTableView.register(UINib.init(nibName: "MyTableViewCell", bundle: nil), forCellReuseIdentifier: "MyTableViewCell")
}
}
extension DDBaseView : UITableViewDelegate,UITableViewDataSource{
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: "MyTableViewCell")as? MyTableViewCell
if cell == nil {
cell = Bundle.main.loadNibNamed("MyTableViewCell", owner: self, options: nil)?.last as? MyTableViewCell
}
cell?.xiaomin = self.ModelMeArr[indexPath.row]
return cell!
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
return self.ModelMeArr.count
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("别点了,没又详情")
}
// 这么写有点粗,非常影响性能。 待修改!
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
}
| 34.850575 | 129 | 0.663259 |
cd49baf26c5e1d21f0240e823d84df6af8c2e929 | 151 | cs | C# | LibraCore/Components/ShooterComponent.cs | KamiNeko/Libra | 96bea89c923ed80ae9938dff4ee5e651c39402d5 | [
"MIT"
] | 2 | 2020-07-04T16:44:30.000Z | 2020-08-18T05:54:38.000Z | LibraCore/Components/ShooterComponent.cs | KamiNeko/Libra | 96bea89c923ed80ae9938dff4ee5e651c39402d5 | [
"MIT"
] | null | null | null | LibraCore/Components/ShooterComponent.cs | KamiNeko/Libra | 96bea89c923ed80ae9938dff4ee5e651c39402d5 | [
"MIT"
] | 1 | 2019-11-03T21:12:19.000Z | 2019-11-03T21:12:19.000Z | using Nez;
namespace LibraCore.Components
{
public class ShooterComponent : Component
{
public int Health { get; set; } = 5;
}
}
| 15.1 | 45 | 0.622517 |
af7eeb01ba090c1df7956b9471b4ad665d3d68af | 1,622 | py | Python | lisrd/datasets/utils/data_reader.py | liuyuzhenn/LISRD | bfd890b81defebea971db0b744be617ed58f5ffa | [
"MIT"
] | 225 | 2020-07-20T10:15:41.000Z | 2022-03-04T15:07:26.000Z | lisrd/datasets/utils/data_reader.py | liuyuzhenn/LISRD | bfd890b81defebea971db0b744be617ed58f5ffa | [
"MIT"
] | 15 | 2020-07-25T02:54:38.000Z | 2022-03-12T13:39:19.000Z | lisrd/datasets/utils/data_reader.py | liuyuzhenn/LISRD | bfd890b81defebea971db0b744be617ed58f5ffa | [
"MIT"
] | 21 | 2020-07-23T00:33:04.000Z | 2022-03-26T12:48:57.000Z | import csv
import numpy as np
import cv2
def resize_and_crop(image, img_size):
""" Resize an image to the given img_size by first rescaling it
and then applying a central crop to fit the given dimension. """
source_size = np.array(image.shape[:2], dtype=float)
target_size = np.array(img_size, dtype=float)
# Scale
scale = np.amax(target_size / source_size)
inter_size = np.round(source_size * scale).astype(int)
image = cv2.resize(image, (inter_size[1], inter_size[0]))
# Central crop
pad = np.round((source_size * scale - target_size) / 2.).astype(int)
image = image[pad[0]:(pad[0] + int(target_size[0])),
pad[1]:(pad[1] + int(target_size[1])), :]
return image
def read_timestamps(text_file):
"""
Read a text file containing the timestamps of images
and return a dictionary matching the name of the image
to its timestamp.
"""
timestamps = {'name': [], 'date': [], 'hour': [],
'minute': [], 'time': []}
with open(text_file, 'r') as csvfile:
reader = csv.reader(csvfile, delimiter=' ')
for row in reader:
timestamps['name'].append(row[0])
timestamps['date'].append(row[1])
hour = int(row[2])
timestamps['hour'].append(hour)
minute = int(row[3])
timestamps['minute'].append(minute)
timestamps['time'].append(hour + minute / 60.)
return timestamps
def ascii_to_string(s):
""" Convert the array s of ascii values into the corresponding string. """
return ''.join(chr(i) for i in s) | 33.791667 | 78 | 0.606658 |
22019dd8d49129b54763de2c742999545f96c336 | 3,599 | sql | SQL | oracle/ora/ash/ashcorr.sql | hyee/dbcli | a39fdffdc5a15b9a6e17dc8e6e852003a8dedf0d | [
"MIT"
] | 44 | 2015-05-07T16:11:03.000Z | 2021-09-19T08:59:20.000Z | oracle/ora/ash/ashcorr.sql | hyee/dbcli | a39fdffdc5a15b9a6e17dc8e6e852003a8dedf0d | [
"MIT"
] | 8 | 2015-05-08T03:38:03.000Z | 2020-05-22T11:00:47.000Z | oracle/ora/ash/ashcorr.sql | hyee/dbcli | a39fdffdc5a15b9a6e17dc8e6e852003a8dedf0d | [
"MIT"
] | 24 | 2015-05-07T16:17:41.000Z | 2022-01-02T13:10:29.000Z | /*[[Show the coefficient of correlation against the ASH. Usage: @@NAME "<keyword>" [yymmddhh24mi] [yymmddhh24mi] [-dash]
--[[
&V2: default={&starttime}
&V3: default={&endtime}
&ASH: default={gv$active_Session_history} dash={dba_hist_active_sess_history}
@binst: 11={'@'|| BLOCKING_INST_ID} default={''}
&INST1 : default={inst_id}, dash={instance_number}
--]]
]]*/
--lag correlation in case of l=0: sum((x-avg(x)) * (y-avg(y))) / sqrt(sum(power(x-avg(x)))) / sqrt(sum(power(y-avg(y))))
WITH ash1 AS
(SELECT /*+ no_merge(ash) ordered*/ clz,name,sample_id,sum(cost) v
FROM (SELECT DECODE(r, 1, 'sql_id', 2, 'event', 3, 'object_id', 4, 'program',5,'blocker',6,'sid') clz,
trim(DECODE(r,
1,
sql_id,
2,
NVL(event, 'CPU => ' || TRIM(',' FROM p1text || ',' || p2text || ',' || p3text)),
3,
CASE WHEN current_obj# > 1 THEN to_char(current_obj#) when current_obj# in(0,-1) then 'UNDO' else '-2' END,
4,
CASE
WHEN SUBSTR(program,-6) LIKE '(%)' AND upper(SUBSTR(program,-5,1))=SUBSTR(program,-5,1) THEN
CASE WHEN SUBSTR(program,-6) LIKE '(%)' AND SUBSTR(program,-5,1) IN('P','W','J') THEN
'('||SUBSTR(program,-5,1)||'nnn)'
ELSE regexp_replace(SUBSTR(program,-6),'[0-9a-z]','n') END
WHEN instr(program,'@')>1 THEN
nullif(substr(program,1,instr(program,'@')-1),'oracle')
ELSE program
END,
5,
blocking_session||&binst,
6,
SESSION_ID||'@'||&INST1)) NAME,
nvl(tm_delta_db_time,delta_time) cost,
TRUNC(sample_time,'MI') sample_id
FROM (SELECT /*+no_expand*/ a.* FROM &ash a
WHERE :V2<100000 AND sample_time+0> SYSDATE-:V2/86400 OR
nvl(:V2,'100000')>=100000 AND sample_time+0 BETWEEN nvl(to_date(:V2,'YYMMDDHH24MI'),sysdate-1) AND nvl(to_date(:V3,'YYMMDDHH24MI'),SYSDATE+1)) ash,
(SELECT ROWNUM r FROM dual CONNECT BY ROWNUM <=5) r)
WHERE NAME IS NOT NULL
GROUP BY clz,name,sample_id),
st2 AS(SELECT sample_id, v FROM ash1 WHERE lower(NAME) = lower(:V1)),
st1 AS(SELECT * FROM ash1 a
WHERE lower(NAME) != lower(:V1)
AND exists(select * from (select min(sample_id) mn,max(sample_id) mx from st2) b where a.sample_id between mn and mx)),
RES AS(
SELECT a.*,CEIL(ROWNUM / 3) r1, MOD(ROWNUM, 3) R2
FROM (
SELECT /*+use_hash(st1 st2) ordered*/ clz CLASS, NAME, ROUND(CORR(st2.v, st1.v) / COUNT(st2.v) * COUNT(st1.v)*100,3) coe
FROM st2
LEFT JOIN st1
USING (sample_id)
GROUP BY clz, NAME
HAVING CORR (st2.v, st1.v) IS NOT NULL
ORDER BY abs(coe) DESC NULLS LAST) a
WHERE rownum<=150 AND ABS(COE)<100)
SELECT MAX(DECODE(R2, 1, CLASS)) CLASS,
MAX(DECODE(R2, 1, NAME)) NAME,
MAX(DECODE(R2, 1, coe)) "CORR(%)",
'|' "|",
MAX(DECODE(R2, 2, CLASS)) CLASS,
MAX(DECODE(R2, 2, NAME)) NAME,
MAX(DECODE(R2, 2, coe)) "CORR(%)",
'|' "|",
MAX(DECODE(R2, 0, CLASS)) CLASS,
MAX(DECODE(R2, 0, NAME)) NAME,
MAX(DECODE(R2, 0, coe)) "CORR(%)"
FROM res
GROUP BY r1
ORDER BY r1 | 49.986111 | 173 | 0.511531 |
fc0ed3b8da07f541c44d53b007aef87626492c45 | 3,442 | swift | Swift | Sources/GBLPing/GBLPingService/GBLPingService+PingHostnameForcingIPVersion.swift | GigabiteLabs/GBLPing | 64efe8bba973eb0db406c011ac789b23ad98e3a5 | [
"BSD-4-Clause-UC"
] | 1 | 2022-02-17T11:43:50.000Z | 2022-02-17T11:43:50.000Z | Sources/GBLPing/GBLPingService/GBLPingService+PingHostnameForcingIPVersion.swift | GigabiteLabs/GBLPing | 64efe8bba973eb0db406c011ac789b23ad98e3a5 | [
"BSD-4-Clause-UC"
] | 1 | 2020-05-09T02:24:18.000Z | 2020-05-09T02:24:18.000Z | Sources/GBLPing/GBLPingService/GBLPingService+PingHostnameForcingIPVersion.swift | GigabiteLabs/GBLPing | 64efe8bba973eb0db406c011ac789b23ad98e3a5 | [
"BSD-4-Clause-UC"
] | null | null | null | // GBLPingService+ForcingIPVersion.swift
//
// Created by GigabiteLabs on 9/29/20
// Swift Version: 5.0
// Copyright © 2020 GigabiteLabs. All rights reserved.
//
import Foundation
extension GBLPingService {
/// Pings a hostname continuously until either stopped or
/// deallocated by the operating system. Ping events will be
/// explicitly forced use either an ICMP version v4 or v6 IP addresss.
///
/// - Parameters:
/// - ipVersion: a `GBLPingIPVersion` configuration that will restrict
/// the ping service to the configured icmp IP version.
/// - hostname: the hostname to ping, e.g.: gigabitelabs.com
///
/// - Warning: If you use this function, make sure you
/// also manually configure your application to stop, or it will
/// continue indefinitely. In some cases, this could cause issues
/// if not handled properly.
///
public func pingHostnameForcing(ipVersion: GBLPingIPVersion, hostname: String) {
// setup ip configuration
switch ipVersion {
case .ipv4:
cache.pinger?.addressStyle = .icmPv4
case .ipv6:
cache.pinger?.addressStyle = .icmPv6
}
// start service
startPinging(hostname)
}
/// Pings a hostname stopping after a designated number
/// of pings, while explicitly forcing ping events to use
/// either to use either an ICMP version v4 or v6 IP addresss.
///
/// - Parameters:
/// - ipVersion: a `GBLPingIPVersion` configuration that will restrict
/// the ping service to the configured icmp IP version.
/// - hostname: the hostname to ping, e.g.: gigabitelabs.com
/// - maxPings: the number of ping events the service should
/// be limited to. The ping service stops automatically
/// when the number of ping events is reached.
///
public func pingHostnameForcing(ipVersion: GBLPingIPVersion, hostname: String, maxPings: Int) {
// Ensure the setting for max pings is not zero.
if !(maxPings > 0) {
delegate?.gblPingError(.maxPingsInvalid)
}
// set max ping configuration on service
self.cache.maxPings = maxPings
// pass-through to basic forcing func
pingHostnameForcing(ipVersion: ipVersion, hostname: hostname)
}
/// Pings a hostname and stops after the configured
/// amount of time.while explicitly forcing ping events to use
/// either to use either an ICMP version v4 or v6 IP addresss.
///
/// - Parameters:
/// - ipVersion: a `GBLPingIPVersion` configuration that will restrict
/// the ping service to the configured icmp IP version.
/// - hostname: the hostname to ping, e.g.: gigabitelabs.com
/// - stopAfter: the amount of time in seconds the ping
/// event should be limited to. The ping service stops automatically
/// when the number of seconds elapses.
///
public func pingHostnameForcing(ipVersion: GBLPingIPVersion, hostname: String, stopAfter seconds: Int) {
// Ensure the setting for max pings is not zero.
if !(seconds > 1) {
delegate?.gblPingError(.timeLimitInvalid)
}
// set max ping configuration on service
self.cache.timeLimit = seconds
// pass-through to basic forcing func
pingHostnameForcing(ipVersion: ipVersion, hostname: hostname)
}
}
| 42.493827 | 108 | 0.651365 |
a4869d665cb32361a5bd98580379b43ae3a7e7b5 | 1,039 | php | PHP | src/Dashboard/Widgets/SharpBarGraphWidget.php | Insolita/sharp | a4cfa8ca1882b8edfc410e00bdd88c2ac3d3213f | [
"MIT"
] | 582 | 2017-06-06T16:29:14.000Z | 2022-03-31T19:51:19.000Z | src/Dashboard/Widgets/SharpBarGraphWidget.php | Insolita/sharp | a4cfa8ca1882b8edfc410e00bdd88c2ac3d3213f | [
"MIT"
] | 248 | 2017-09-06T13:26:50.000Z | 2022-03-16T08:20:54.000Z | src/Dashboard/Widgets/SharpBarGraphWidget.php | Insolita/sharp | a4cfa8ca1882b8edfc410e00bdd88c2ac3d3213f | [
"MIT"
] | 83 | 2017-09-05T07:32:48.000Z | 2022-03-25T10:59:19.000Z | <?php
namespace Code16\Sharp\Dashboard\Widgets;
class SharpBarGraphWidget extends SharpGraphWidget
{
protected bool $horizontal = false;
protected bool $displayHorizontalAxisAsTimeline = false;
public static function make(string $key): SharpBarGraphWidget
{
$widget = new static($key, 'graph');
$widget->display = 'bar';
return $widget;
}
public function setHorizontal(bool $horizontal = true): self
{
$this->horizontal = $horizontal;
return $this;
}
public function setDisplayHorizontalAxisAsTimeline(bool $displayAsTimeline = true): self
{
$this->displayHorizontalAxisAsTimeline = $displayAsTimeline;
return $this;
}
public function toArray(): array
{
return array_merge(
parent::toArray(), [
"dateLabels" => $this->displayHorizontalAxisAsTimeline,
"options" => [
"horizontal" => $this->horizontal
]
]
);
}
} | 24.162791 | 92 | 0.596728 |
b3255969a11829d4eca51fcd63512dfdf22efcd3 | 214 | py | Python | reports/serializers.py | mohammadanarul/drf-blog-api | 25d6d72235b2d995639ac1eed5367cf6a8a1535c | [
"MIT"
] | null | null | null | reports/serializers.py | mohammadanarul/drf-blog-api | 25d6d72235b2d995639ac1eed5367cf6a8a1535c | [
"MIT"
] | null | null | null | reports/serializers.py | mohammadanarul/drf-blog-api | 25d6d72235b2d995639ac1eed5367cf6a8a1535c | [
"MIT"
] | null | null | null | from rest_framework import serializers
from .models import PostReport
class PostReportSerializer(serializers.ModelSerializer):
class Meta:
model = PostReport
fields = ['post', 'user', 'body']
| 23.777778 | 56 | 0.719626 |
bebb64910598906b9cc7d54a5cd9f7c93072d3b5 | 207 | ts | TypeScript | src/ui-carto/geocoding/service.common.ts | farfromrefug/nativescript-carto | 811af23c102a03a983822342d8fc7223ccb030a1 | [
"Apache-2.0"
] | null | null | null | src/ui-carto/geocoding/service.common.ts | farfromrefug/nativescript-carto | 811af23c102a03a983822342d8fc7223ccb030a1 | [
"Apache-2.0"
] | null | null | null | src/ui-carto/geocoding/service.common.ts | farfromrefug/nativescript-carto | 811af23c102a03a983822342d8fc7223ccb030a1 | [
"Apache-2.0"
] | null | null | null | import { BaseNative } from '../BaseNative';
import { GeocodingServiceOptions } from './service';
export abstract class BaseGeocodingService<T, U extends GeocodingServiceOptions> extends BaseNative<T, U> {}
| 41.4 | 108 | 0.772947 |
7ec91fac751641be2f6eadf4d514e48e2efccce9 | 1,389 | dart | Dart | apps/modules/common/packages/widgets/lib/src/youtube/youtube_video.dart | bleonard252-forks/pangolin-mobile | 392df6c8a66d39f31d0e2512caf3d31ae40c758f | [
"Apache-2.0"
] | null | null | null | apps/modules/common/packages/widgets/lib/src/youtube/youtube_video.dart | bleonard252-forks/pangolin-mobile | 392df6c8a66d39f31d0e2512caf3d31ae40c758f | [
"Apache-2.0"
] | null | null | null | apps/modules/common/packages/widgets/lib/src/youtube/youtube_video.dart | bleonard252-forks/pangolin-mobile | 392df6c8a66d39f31d0e2512caf3d31ae40c758f | [
"Apache-2.0"
] | null | null | null | // Copyright 2016 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:meta/meta.dart';
import 'package:widgets_meta/widgets_meta.dart';
import 'youtube_comments_list.dart';
import 'youtube_player.dart';
import 'youtube_video_overview.dart';
/// UI Widget that represents a single Youtube "Video View"
/// Includes:
/// 1. Video Player
/// 2. Video Overview
/// 3. Video Comments
class YoutubeVideo extends StatelessWidget {
/// ID for given youtube video
final String videoId;
/// Youtube API key needed to access the Youtube Public APIs
final String apiKey;
/// Constructor
YoutubeVideo({
Key key,
@required @ExampleValue('a6KGPBflhiM') this.videoId,
@required @ConfigKey('google_api_key') this.apiKey,
})
: super(key: key) {
assert(videoId != null);
assert(apiKey != null);
}
@override
Widget build(BuildContext context) {
return new ListView(
children: <Widget>[
new YoutubePlayer(
videoId: videoId,
apiKey: apiKey,
),
new YoutubeVideoOverview(
videoId: videoId,
apiKey: apiKey,
),
new YoutubeCommentsList(
videoId: videoId,
apiKey: apiKey,
),
],
);
}
}
| 24.803571 | 73 | 0.654428 |
8b7ef8fa2ba9b23f7639eed8448b27e73606e9f1 | 4,631 | dart | Dart | packages/firebase_performance/firebase_performance/lib/src/http_metric.dart | demirdev/flutterfire | f1fda2b661a61020e0e8ea3df9964d50a6d67c7e | [
"BSD-3-Clause"
] | 28 | 2022-03-23T23:24:24.000Z | 2022-03-31T19:54:43.000Z | packages/firebase_performance/firebase_performance/lib/src/http_metric.dart | demirdev/flutterfire | f1fda2b661a61020e0e8ea3df9964d50a6d67c7e | [
"BSD-3-Clause"
] | 94 | 2022-03-24T01:03:38.000Z | 2022-03-31T21:03:18.000Z | packages/firebase_performance/firebase_performance/lib/src/http_metric.dart | demirdev/flutterfire | f1fda2b661a61020e0e8ea3df9964d50a6d67c7e | [
"BSD-3-Clause"
] | 31 | 2022-03-24T05:28:04.000Z | 2022-03-31T21:02:03.000Z | // Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
part of firebase_performance;
/// Metric used to collect data for network requests/responses.
///
/// It is possible to have more than one [HttpMetric] running at a time.
/// Attributes can also be added to help measure performance related events. A
/// [HttpMetric] also measures the time between calling `start()` and `stop()`.
///
/// Data collected is automatically sent to the associated Firebase console
/// after stop() is called.
///
/// You can confirm that Performance Monitoring results appear in the Firebase
/// console. Results should appear within 12 hours.
///
/// It is highly recommended that one always calls `start()` and `stop()` on
/// each created [HttpMetric] to avoid leaking on the platform side.
class HttpMetric {
HttpMetric._(this._delegate);
HttpMetricPlatform _delegate;
/// HttpResponse code of the request.
int? get httpResponseCode => _delegate.httpResponseCode;
/// Size of the request payload.
int? get requestPayloadSize => _delegate.requestPayloadSize;
/// Content type of the response such as text/html, application/json, etc...
String? get responseContentType => _delegate.responseContentType;
/// Size of the response payload.
int? get responsePayloadSize => _delegate.responsePayloadSize;
/// HttpResponse code of the request.
///
/// If the [HttpMetric] has already been stopped, returns immediately without
/// taking action.
set httpResponseCode(int? httpResponseCode) {
_delegate.httpResponseCode = httpResponseCode;
}
/// Size of the request payload.
///
/// If the [HttpMetric] has already been stopped, returns immediately without
/// taking action.
set requestPayloadSize(int? requestPayloadSize) {
_delegate.requestPayloadSize = requestPayloadSize;
}
/// Content type of the response such as text/html, application/json, etc...
///
/// If the [HttpMetric] has already been stopped, returns immediately without
/// taking action.
set responseContentType(String? responseContentType) {
_delegate.responseContentType = responseContentType;
}
/// Size of the response payload.
///
/// If the [HttpMetric] has already been stopped, returns immediately without
/// taking action.
set responsePayloadSize(int? responsePayloadSize) {
_delegate.responsePayloadSize = responsePayloadSize;
}
/// Starts this [HttpMetric].
///
/// Can only be called once.
///
/// Using `await` with this method is only necessary when accurate timing
/// is relevant.
Future<void> start() {
return _delegate.start();
}
/// Stops this [HttpMetric].
///
/// Can only be called once and only after start(), Data collected is
/// automatically sent to the associate Firebase console after stop() is
/// called. You can confirm that Performance Monitoring results appear in the
/// Firebase console. Results should appear within 12 hours.
///
/// Not necessary to use `await` with this method.
Future<void> stop() {
return _delegate.stop();
}
/// Sets a String [value] for the specified attribute with [name].
///
/// Updates the value of the attribute if the attribute already exists.
/// The maximum number of attributes that can be added are
/// [maxCustomAttributes]. An attempt to add more than [maxCustomAttributes]
/// to this object will return without adding the attribute.
///
/// Name of the attribute has max length of [maxAttributeKeyLength]
/// characters. Value of the attribute has max length of
/// [maxAttributeValueLength] characters. If the name has a length greater
/// than [maxAttributeKeyLength] or the value has a length greater than
/// [maxAttributeValueLength], this method will return without adding
/// anything.
///
/// If this object has been stopped, this method returns without adding the
/// attribute.
void putAttribute(String name, String value) {
return _delegate.putAttribute(name, value);
}
/// Removes an already added attribute.
///
/// If this object has been stopped, this method returns without removing the
/// attribute.
void removeAttribute(String name) {
return _delegate.removeAttribute(name);
}
/// Returns the value of an attribute.
///
/// Returns `null` if an attribute with this [name] has not been added.
String? getAttribute(String name) => _delegate.getAttribute(name);
/// All attributes added.
Map<String, String> getAttributes() {
return _delegate.getAttributes();
}
}
| 35.623077 | 79 | 0.717556 |
d67381608fddd7fcac9e0e20279346a470b49808 | 431 | cs | C# | Antrv.FFMpeg/Interop/libavutil/frame.h/AVFrameSideData.cs | antrv/ffmpeg-net | 24d009f473fe3f5cfb01d15d5d16294e9038e82f | [
"MIT"
] | null | null | null | Antrv.FFMpeg/Interop/libavutil/frame.h/AVFrameSideData.cs | antrv/ffmpeg-net | 24d009f473fe3f5cfb01d15d5d16294e9038e82f | [
"MIT"
] | null | null | null | Antrv.FFMpeg/Interop/libavutil/frame.h/AVFrameSideData.cs | antrv/ffmpeg-net | 24d009f473fe3f5cfb01d15d5d16294e9038e82f | [
"MIT"
] | null | null | null | namespace Antrv.FFMpeg.Interop;
/// <summary>
/// Structure to hold side data for an AVFrame.
///
/// sizeof(AVFrameSideData) is not a part of the public ABI, so new fields may be added
/// to the end with a minor bump.
/// </summary>
public struct AVFrameSideData
{
public AVFrameSideDataType Type;
public Ptr<byte> Data;
public nuint Size;
public Ptr<AVDictionary> Metadata;
public Ptr<AVBufferRef> Buf;
}
| 25.352941 | 87 | 0.705336 |
147ae42f95bf6ac61bcd1d7f039063d9c8269ebe | 3,203 | tsx | TypeScript | pwa/components/common/actionmenu.tsx | ConductionNL/pwa-pip-nijmegen | 6155711498afcf979ecff71fde3ff2bc3f645b81 | [
"MIT"
] | null | null | null | pwa/components/common/actionmenu.tsx | ConductionNL/pwa-pip-nijmegen | 6155711498afcf979ecff71fde3ff2bc3f645b81 | [
"MIT"
] | null | null | null | pwa/components/common/actionmenu.tsx | ConductionNL/pwa-pip-nijmegen | 6155711498afcf979ecff71fde3ff2bc3f645b81 | [
"MIT"
] | null | null | null | import React from 'react';
import makeStyles from '@mui/styles/makeStyles';
import List from '@mui/material/List';
import ListItem from '@mui/material/ListItem';
import ListItemIcon from '@mui/material/ListItemIcon';
import ListItemText from '@mui/material/ListItemText';
import Divider from '@mui/material/Divider';
import Typography from '@mui/material/Typography';
import { useRouter } from 'next/router';
import MessageIcon from '@mui/icons-material/Message';
import DateRangeIcon from '@mui/icons-material/DateRange';
import PlaylistAddCheckIcon from '@mui/icons-material/PlaylistAddCheck';
import LockIcon from '@mui/icons-material/Lock';
import WorkIcon from '@mui/icons-material/Work';
import ExitToAppIcon from '@mui/icons-material/ExitToApp';
import AssignmentIndIcon from '@mui/icons-material/AssignmentInd';
import InboxIcon from '@mui/icons-material/Inbox';
import DraftsIcon from '@mui/icons-material/Drafts';
import SubscriptionsIcon from '@mui/icons-material/Subscriptions';
import HomeIcon from '@mui/icons-material/Home';
import RadioButtonCheckedIcon from '@mui/icons-material/RadioButtonChecked';
import ShoppingCartIcon from '@mui/icons-material/ShoppingCart';
import {ListItemButton} from "@mui/material";
const useStyles = makeStyles((theme) => ({
root: {
width: '100%',
maxWidth: 360,
},
paddingMobile: {
[theme.breakpoints.down('md')]: {
padding: '15px',
},
},
paddingListItemMobile: {
marginTop: '12px !important',
},
}));
function ListItemLink(props) {
return <ListItem button component="a" {...props} />;
}
export default function ActionMenu() {
const classes = useStyles();
const router = useRouter()
return (
<div className={classes.root}>
<List component="nav" aria-label="main mailbox folders" className={classes.paddingMobile}>
<ListItem button onClick={() => router.push('/products')} className={classes.paddingListItemMobile}>
<ListItemIcon>
<ShoppingCartIcon />
</ListItemIcon>
<ListItemText
disableTypography
primary={<Typography>Diensten</Typography>}
/>
</ListItem>
<ListItem button onClick={() => router.push('/cases')} className={classes.paddingListItemMobile}>
<ListItemIcon>
<SubscriptionsIcon />
</ListItemIcon>
<ListItemText
disableTypography
primary={<Typography>Mijn aanvragen</Typography>}
/>
</ListItem>
<ListItem button onClick={() => router.push('/data')} className={classes.paddingListItemMobile}>
<ListItemIcon>
<AssignmentIndIcon/>
</ListItemIcon>
<ListItemText
disableTypography
primary={<Typography>Mijn gegevens</Typography>}
/>
</ListItem>
<ListItem button onClick={() => router.push('/vault')} className={classes.paddingListItemMobile}>
<ListItemIcon>
<LockIcon />
</ListItemIcon>
<ListItemText
disableTypography
primary={<Typography>Mijn kluis</Typography>}
/>
</ListItem>
</List>
</div>
);
}
| 32.353535 | 108 | 0.659382 |
43f27ed2ba59ec636bff8aad14ba23825f1ad0ff | 2,670 | ts | TypeScript | src/referables/Property.ts | SAP/i40-aas-objects | f3f0e3583fa93e0e3212504eba8a7608957d1f61 | [
"Apache-2.0"
] | 7 | 2019-11-13T14:27:35.000Z | 2021-06-16T09:42:33.000Z | src/referables/Property.ts | SAP/i40-aas-objects | f3f0e3583fa93e0e3212504eba8a7608957d1f61 | [
"Apache-2.0"
] | 5 | 2020-01-17T16:32:55.000Z | 2021-09-15T14:18:29.000Z | src/referables/Property.ts | SAP/i40-aas-objects | f3f0e3583fa93e0e3212504eba8a7608957d1f61 | [
"Apache-2.0"
] | 2 | 2020-01-14T21:10:37.000Z | 2022-02-27T18:41:44.000Z | import { KindEnum } from '../types/KindEnum';
import { IReference, Reference } from '../baseClasses/Reference';
import { IEmbeddedDataSpecification } from '../baseClasses/EmbeddedDataSpecification';
import { IModelType } from '../baseClasses/ModelType';
import { ILangString } from '../baseClasses/LangString';
import { AnyAtomicTypeEnum } from '../types/AnyAtomicTypeEnum';
import { SubmodelElement, ISubmodelElement } from './SubmodelElement';
import { KeyElementsEnum } from '../types/ModelTypeElementsEnum';
import { IConstraint } from '../baseClasses/Constraint';
interface IProperty extends ISubmodelElement {
valueId?: IReference;
value?: string;
valueType: AnyAtomicTypeEnum;
}
type TPropertyJSON = {
kind?: KindEnum;
semanticId: IReference;
embeddedDataSpecifications?: Array<IEmbeddedDataSpecification>;
modelType?: IModelType;
idShort: string;
parent?: IReference;
category?: string;
description?: Array<ILangString>;
valueId?: IReference;
value?: string;
valueType: AnyAtomicTypeEnum;
qualifiers?: Array<IConstraint>;
};
class Property extends SubmodelElement implements IProperty {
valueId?: IReference;
value?: string;
valueType: AnyAtomicTypeEnum;
static fromJSON(obj: TPropertyJSON): Property {
return new Property(
obj.idShort,
obj.valueType,
obj.value,
obj.valueId,
obj.semanticId,
obj.kind,
obj.embeddedDataSpecifications,
obj.qualifiers,
obj.description,
obj.category,
obj.parent,
);
}
constructor(
idShort: string,
valueType: AnyAtomicTypeEnum,
value?: string,
valueId?: IReference,
semanticId?: IReference,
kind?: KindEnum,
embeddedDataSpecifications?: Array<IEmbeddedDataSpecification>,
qualifiers?: Array<IConstraint>,
description?: Array<ILangString>,
category?: string,
parent?: IReference,
) {
super(
idShort,
{ name: KeyElementsEnum.Property },
semanticId,
kind,
embeddedDataSpecifications,
qualifiers,
description,
category,
parent,
);
this.valueId = valueId;
this.value = value;
this.valueType = valueType;
}
toJSON(): TPropertyJSON {
let res: any = super.toJSON();
res.value = this.value;
res.valueType = this.valueType;
res.valueId = this.valueId;
return res;
}
}
export { Property, IProperty, TPropertyJSON };
| 30.340909 | 86 | 0.62397 |
6dd9fff25d53ffefd3ecdcae8d3b118d22beaaab | 1,866 | c | C | One/Quick_Gather.c | yellowzhou-person/Algorithm | 00c8782ac35820b88e75621685acb23001466347 | [
"MIT"
] | 70 | 2016-07-29T08:24:21.000Z | 2021-12-01T02:28:11.000Z | One/Quick_Gather.c | yellowzhou-person/Algorithm | 00c8782ac35820b88e75621685acb23001466347 | [
"MIT"
] | null | null | null | One/Quick_Gather.c | yellowzhou-person/Algorithm | 00c8782ac35820b88e75621685acb23001466347 | [
"MIT"
] | 34 | 2016-09-01T09:57:04.000Z | 2021-12-01T02:28:12.000Z |
/*当重复数值较多时,把与基准点相同的数据聚合在一起 ,不进行下一趟排序*/
#include <stdio.h>
void Quick(int *arr, int first, int end);
int main(int argc, char const *argv[])
{
int arr[10] = {10, 58, 36, 1, 45, 64, 14, 200, 11, 69};
int len = sizeof(arr) / sizeof(arr[0]);
Quick(arr, 0, len - 1);
int i = 0;
for (; i < len; i++)
{
printf(" %d", arr[i]);
}
printf("\n");
return 0;
}
void swap(int *arr, int firstIndex, int secondIndex)
{
int tmp = arr[firstIndex];
arr[firstIndex] = arr[secondIndex];
arr[secondIndex] = tmp;
}
void gather(int arr[], int first, int end, int mid,int *left, int *right){
if (first < end)
{
int count = mid - 1;
for (int i = mid - 1; i >= first; i--)
{
if (arr[i] == arr[mid])
{
swap(arr, i, count);
count --;
}
}
*left = count;
count = mid + 1;
for (int i = mid + 1; i <= end; i++)
{
if (arr[i] == arr[mid])
{
swap(arr, i ,count);
count++;
}
}
*right = count;
}
}
int PartSort(int *arr, int first, int end)
{
int tmp = arr[first];
while (first != end)
{
while (first < end && arr[end] >= tmp)
{
end--;
}
arr[first] = arr[end];
while (first < end && arr[first] <= tmp)
{
first++;
}
arr[end] = arr[first];
}
arr[first] = tmp;
return first;
}
void Quick(int *arr, int first, int end)
{
if (first < end)
{
gather(arr, first, end, (first + end) / 2 + first,&arr[first],&arr[end]);
int mid = PartSort(arr, first, end);
Quick(arr, first, mid - 1);
Quick(arr, mid + 1, end);
}
} | 20.733333 | 81 | 0.43194 |
39254d6813611e3ab21aad6633d9ba9ebcd6f15c | 2,529 | py | Python | todb.py | HackNJIT/HackNJIT.github.io | a0cd7978f2576f28b010929c1ccea430c72cccad | [
"MIT"
] | null | null | null | todb.py | HackNJIT/HackNJIT.github.io | a0cd7978f2576f28b010929c1ccea430c72cccad | [
"MIT"
] | null | null | null | todb.py | HackNJIT/HackNJIT.github.io | a0cd7978f2576f28b010929c1ccea430c72cccad | [
"MIT"
] | null | null | null | import paho.mqtt.client as mqtt
import mysql.connector
from mysql.connector import Error
from datetime import datetime
import os
import time
add_temp = ("INSERT INTO temp "
"(temp, time) "
"VALUES (%s, %s)")
add_moist = ("INSERT INTO moisture "
"(moisture, time) "
"VALUES (%s, %s)")
add_light = ("INSERT INTO light "
"(light, time) "
"VALUES (%s, %s)")
# Define event callbacks
def on_connect(client, userdata, flags, rc):
print("rc: " + str(rc))
def on_message(client, obj, msg):
if msg.payload != b'Hello from ESP32':
try:
cnx = mysql.connector.connect(user='root', password='1234',
host='104.196.173.138',
database='sensorData')
cursor = cnx.cursor()
data = (msg.payload, datetime.now())
if msg.topic == temp:
print(msg.topic)
cursor.execute(add_temp, data)
if msg.topic == moist:
print(msg.topic)
cursor.execute(add_moist, data)
if msg.topic == light:
print(msg.topic)
cursor.execute(add_light, data)
cnx.commit()
cursor.close()
cnx.close()
except Error as e:
print(e)
print(msg.topic + " " + str(msg.qos) + " " + str(msg.payload))
def on_publish(client, obj, mid):
print("mid: " + str(mid))
def on_subscribe(client, obj, mid, granted_qos):
print("Subscribed: " + str(mid) + " " + str(granted_qos))
def on_log(client, obj, level, string):
print(string)
mqttc = mqtt.Client()
# Assign event callbacks
mqttc.on_message = on_message
mqttc.on_connect = on_connect
mqttc.on_publish = on_publish
mqttc.on_subscribe = on_subscribe
# Uncomment to enable debug messages
#mqttc.on_log = on_log
# Parse CLOUDMQTT_URL (or fallback to localhost)
url_str = os.environ.get('m15.cloudmqtt.com')
temp = 'Sensors/Temperature'
moist = 'Sensors/Light'
light = 'Sensors/Moisture'
# Connect
mqttc.username_pw_set('python', '1234')
mqttc.connect('m15.cloudmqtt.com',11252) #mqtt TCP port
# Start subscribe, with QoS level 0
mqttc.subscribe(temp, 0)
mqttc.subscribe(moist,0)
mqttc.subscribe(light,0)
# Publish a message
# mqttc.publish(topic, "my message")
# Continue the network loop, exit when an error occurs
rc = 0
while rc == 0:
rc = mqttc.loop()
print("rc: " + str(rc))
| 28.738636 | 71 | 0.585607 |
583872abbb8d4fc9198bbe533ea71f05a793e00c | 543 | css | CSS | src/qt/res/ewc/css/style.css | cvsae/vcoincore | 3e5c7c9989f456d9e31eac278d53029781ac7c8a | [
"MIT"
] | 7 | 2016-05-29T13:09:13.000Z | 2020-05-23T09:27:02.000Z | src/qt/res/ewc/css/style.css | cvsae/vcoincore | 3e5c7c9989f456d9e31eac278d53029781ac7c8a | [
"MIT"
] | 4 | 2016-06-02T13:27:58.000Z | 2016-07-21T16:11:23.000Z | src/qt/res/ewc/css/style.css | cvsae/vcoincore | 3e5c7c9989f456d9e31eac278d53029781ac7c8a | [
"MIT"
] | 6 | 2016-05-29T13:12:50.000Z | 2020-08-24T22:16:10.000Z | body {
margin-left: 50px;
margin-right: 50px;
}
textarea {
resize: none;
}
.github-corner:hover .octo-arm {
animation: octocat-wave 560ms ease-in-out
}
@keyframes octocat-wave {
0%, 100% {
transform: rotate(0)
}
20%, 60% {
transform: rotate(-25deg)
}
40%, 80% {
transform: rotate(10deg)
}
}
@media (max-width: 500px) {
.github-corner:hover .octo-arm {
animation: none
}
.github-corner .octo-arm {
animation: octocat-wave 560ms ease-in-out
}
} | 15.970588 | 49 | 0.561694 |
383e93f35ff1bd7fee3171068bef72198b3ff134 | 937 | php | PHP | database/migrations/2017_06_29_162730_create_reactivos_table.php | danielboy/voy | f661e8f7eb67c06c4a66133c09f32d117a6fc0a1 | [
"MIT"
] | null | null | null | database/migrations/2017_06_29_162730_create_reactivos_table.php | danielboy/voy | f661e8f7eb67c06c4a66133c09f32d117a6fc0a1 | [
"MIT"
] | null | null | null | database/migrations/2017_06_29_162730_create_reactivos_table.php | danielboy/voy | f661e8f7eb67c06c4a66133c09f32d117a6fc0a1 | [
"MIT"
] | null | null | null | <?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateReactivosTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('reactivos', function (Blueprint $table) {
$table->increments('id');
$table->String('REACTIVOS');
$table->text('RESPUESTAS');
$table->String('RE_CORRECTA');
$table->String('TIPO');
$table->integer('VALOR');
$table->integer('ID_AREA')->unsigned();
$table->timestamps();
$table->foreign('ID_AREA')->references('id')->on('areas');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('reactivos');
}
}
| 22.853659 | 71 | 0.53682 |
a3288b115059ce54f8236e6c3b4a181e6eb80c8a | 966 | java | Java | src/modul3_opgaver/assignments/Assignment5_3.java | Benz56/Modul3_Opgaver | 4b748a22cfe12ce391e5801ea67bc3021ca3464f | [
"MIT"
] | null | null | null | src/modul3_opgaver/assignments/Assignment5_3.java | Benz56/Modul3_Opgaver | 4b748a22cfe12ce391e5801ea67bc3021ca3464f | [
"MIT"
] | null | null | null | src/modul3_opgaver/assignments/Assignment5_3.java | Benz56/Modul3_Opgaver | 4b748a22cfe12ce391e5801ea67bc3021ca3464f | [
"MIT"
] | null | null | null | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package modul3_opgaver.assignments;
import java.util.Scanner;
public class Assignment5_3 extends AbstractAssignment {
public Assignment5_3() {
super("5.3");
}
@Override
public void print(Scanner scanner) {
System.out.println("Celsius Fahrenheit"); //Print header.
for (int celsius = 0; celsius <= 100; celsius++) { //Loop from 0-100(inclusive) celsius.
if (celsius % 2 == 1) {
continue; //Skip the value if it is an uneven number.
}
double fahrenheit = celsius * 9.0 / 5.0 + 32; // Convert celsius to fahrenheit.
//Print the formatted table row.
System.out.printf("%-7s %7s%n", celsius, String.format("%.2f", fahrenheit));
}
}
}
| 31.16129 | 97 | 0.60766 |
6b30ee727af8bcd80f69d07280c034205c645a36 | 319 | js | JavaScript | src/views/Group/common/context/GroupProvider.js | qulam/react-rbac | ae653ec52658d9a3c17edd47f41f9a0d50c4377a | [
"MIT"
] | null | null | null | src/views/Group/common/context/GroupProvider.js | qulam/react-rbac | ae653ec52658d9a3c17edd47f41f9a0d50c4377a | [
"MIT"
] | null | null | null | src/views/Group/common/context/GroupProvider.js | qulam/react-rbac | ae653ec52658d9a3c17edd47f41f9a0d50c4377a | [
"MIT"
] | 1 | 2022-01-06T07:04:55.000Z | 2022-01-06T07:04:55.000Z | import GroupContext from "./GroupContext";
import {useGroup} from "./hooks";
const GroupProvider = ({children}) => {
const providerProps = useGroup();
return (
<GroupContext.Provider value={providerProps}>
{children}
</GroupContext.Provider>
)
};
export default GroupProvider; | 22.785714 | 53 | 0.648903 |
3f30c13f2a3c6e6c9a2775b9eac93492e3684c61 | 2,060 | php | PHP | inc/story-map-page.php | aparabolica/amazon-rivers-wptheme | cc0b8db357dac814c389a80229b1d0baa60a62cf | [
"MIT"
] | null | null | null | inc/story-map-page.php | aparabolica/amazon-rivers-wptheme | cc0b8db357dac814c389a80229b1d0baa60a62cf | [
"MIT"
] | null | null | null | inc/story-map-page.php | aparabolica/amazon-rivers-wptheme | cc0b8db357dac814c389a80229b1d0baa60a62cf | [
"MIT"
] | null | null | null | <?php
/*
* ARP Story Map Page
*/
class ARP_Story_Map_Page {
function __construct() {
add_action('init', array($this, 'register_field_group'));
}
function get_text_field() {
$field = 'text';
if(function_exists('qtranxf_generateLanguageSelectCode')) {
$field = 'qtranslate_text';
}
return $field;
}
function register_field_group() {
if(function_exists("register_field_group")) {
register_field_group(array (
'id' => 'acf_story_map_page_settings',
'title' => __('Story Map Settings', 'arp'),
'fields' => array (
array (
'key' => 'field_story_map_page',
'label' => __('Story Map URL', 'arp'),
'name' => 'story_map_url',
'type' => $this->get_text_field(),
'instructions' => __('Enter the story map url or YouTube video url for embed on the library page.', 'arp'),
'required' => 0,
'default_value' => '',
'placeholder' => '',
'prepend' => '',
'append' => '',
'formatting' => 'html',
'maxlength' => '',
),
),
'location' => array (
array (
array (
'param' => 'page_template',
'operator' => '==',
'value' => 'story-map.php',
'order_no' => 0,
'group_no' => 0,
),
),
),
'options' => array (
'position' => 'normal',
'layout' => 'no_box',
'hide_on_screen' => array (
0 => 'the_content',
1 => 'excerpt',
2 => 'custom_fields',
3 => 'discussion',
4 => 'comments',
5 => 'revisions',
6 => 'author',
7 => 'format',
8 => 'featured_image',
9 => 'categories',
10 => 'tags',
11 => 'send-trackbacks',
),
),
'menu_order' => 0,
));
}
}
}
$arp_story_map_page = new ARP_Story_Map_Page();
| 26.410256 | 119 | 0.447573 |
b02d976d10c624b431369b3e9150b7d4b8066db4 | 6,515 | py | Python | desertbot/modules/urlfollow/Steam.py | Helle-Daryd/DesertBot | 0b497db135a4c08dfbdb59108f830ba12fdc6465 | [
"MIT",
"BSD-3-Clause"
] | 7 | 2018-03-20T17:10:10.000Z | 2021-11-17T18:58:04.000Z | desertbot/modules/urlfollow/Steam.py | Helle-Daryd/DesertBot | 0b497db135a4c08dfbdb59108f830ba12fdc6465 | [
"MIT",
"BSD-3-Clause"
] | 109 | 2015-08-20T13:16:35.000Z | 2022-01-21T19:40:35.000Z | desertbot/modules/urlfollow/Steam.py | Helle-Daryd/DesertBot | 0b497db135a4c08dfbdb59108f830ba12fdc6465 | [
"MIT",
"BSD-3-Clause"
] | 7 | 2018-03-29T05:55:01.000Z | 2021-02-05T19:19:39.000Z | """
Created on Jan 26, 2014
@author: StarlitGhost
"""
import re
from twisted.plugin import IPlugin
from twisted.words.protocols.irc import assembleFormattedText as colour, attributes as A
from zope.interface import implementer
from desertbot.message import IRCMessage
from desertbot.moduleinterface import IModule
from desertbot.modules.commandinterface import BotCommand
@implementer(IPlugin, IModule)
class Steam(BotCommand):
def actions(self):
return super(Steam, self).actions() + [('urlfollow', 2, self.follow)]
def help(self, query):
return 'Automatic module that follows Steam URLs'
def follow(self, _: IRCMessage, url: str) -> [str, None]:
match = re.search(r'store\.steampowered\.com/(?P<steamType>(app|sub))/(?P<steamID>[0-9]+)',
url)
if not match:
return
steamType = match.group('steamType')
steamId = match.group('steamID')
steamType = {'app': 'app', 'sub': 'package'}[steamType]
params = '{0}details/?{0}ids={1}&cc=US&l=english&v=1'.format(steamType, steamId)
url = 'http://store.steampowered.com/api/{}'.format(params)
response = self.bot.moduleHandler.runActionUntilValue('fetch-url', url)
j = response.json()
if not j[steamId]['success']:
return # failure
appData = j[steamId]['data']
data = []
# name
if 'developers' in appData:
developers = ', '.join(appData['developers'])
name = colour(A.normal[appData['name'], A.fg.gray[' by '], developers])
else:
name = appData['name']
data.append(name)
# package contents (might need to trim this...)
if 'apps' in appData:
appNames = [app['name'] for app in appData['apps']]
apps = 'Package containing: {}'.format(', '.join(appNames))
data.append(apps)
# genres
if 'genres' in appData:
genres = ', '.join([genre['description'] for genre in appData['genres']])
data.append('Genres: ' + genres)
# release date
releaseDate = appData['release_date']
if not releaseDate['coming_soon']:
if releaseDate['date']:
data.append('Released: ' + releaseDate['date'])
else:
upcomingDate = A.fg.cyan[A.bold[str(releaseDate['date'])]]
data.append(colour(A.normal['To Be Released: ', upcomingDate]))
# metacritic
# http://www.metacritic.com/faq#item32
# (Why is the breakdown of green, yellow, and red scores different for games?)
if 'metacritic' in appData:
metaScore = appData['metacritic']['score']
if metaScore < 50:
metacritic = colour(A.fg.red[str(metaScore)])
elif metaScore < 75:
metacritic = colour(A.fg.orange[str(metaScore)])
else:
metacritic = colour(A.fg.green[str(metaScore)])
data.append('Metacritic: {}'.format(metacritic))
# dlc count
if 'dlc' in appData:
dlc = 'DLC: {}'.format(len(appData['dlc']))
data.append(dlc)
# prices
if 'is_free' in appData:
if appData['is_free']:
free = colour(A.fg.cyan['Free'])
data.append(free)
priceField = {'app': 'price_overview', 'package': 'price'}[steamType]
if priceField in appData:
prices = {'USD': appData[priceField],
'GBP': self.getSteamPrice(steamType, steamId, 'GB'),
'EUR': self.getSteamPrice(steamType, steamId, 'FR'),
'AUD': self.getSteamPrice(steamType, steamId, 'AU')}
currencies = {'USD': '$',
'GBP': '\u00A3',
'EUR': '\u20AC',
'AUD': 'AU$'}
# filter out AUD if same as USD (most are)
if not prices['AUD'] or prices['AUD']['final'] == prices['USD']['final']:
del prices['AUD']
# filter out any missing prices
prices = {key: val for key, val in prices.items() if val}
priceList = ['{}{:,.2f}'.format(currencies[val['currency']], val['final'] / 100.0)
for val in prices.values()]
priceString = '/'.join(priceList)
if prices['USD']['discount_percent'] > 0:
discount = ' ({}% sale!)'.format(prices['USD']['discount_percent'])
priceString += colour(A.fg.green[A.bold[discount]])
data.append(priceString)
# platforms
if 'platforms' in appData:
platforms = appData['platforms']
platformArray = []
if platforms['windows']:
platformArray.append('Win')
else:
platformArray.append('---')
if platforms['mac']:
platformArray.append('Mac')
else:
platformArray.append('---')
if platforms['linux']:
platformArray.append('Lin')
else:
platformArray.append('---')
data.append('/'.join(platformArray))
# description
if 'short_description' in appData and appData['short_description'] is not None:
limit = 100
description = appData['short_description']
if len(description) > limit:
description = '{} ...'.format(description[:limit].rsplit(' ', 1)[0])
data.append(description)
url = ('http://store.steampowered.com/{}/{}'
.format({'app': 'app', 'package': 'sub'}[steamType],
steamId))
graySplitter = colour(A.normal[' ', A.fg.gray['|'], ' '])
return graySplitter.join(data), url
def getSteamPrice(self, appType, appId, region):
url = ('http://store.steampowered.com/api/{0}details/?{0}ids={1}&cc={2}&l=english&v=1'
.format(appType, appId, region))
response = self.bot.moduleHandler.runActionUntilValue('fetch-url', url)
priceField = {'app': 'price_overview', 'package': 'price'}[appType]
j = response.json()
if 'data' not in j[appId]:
return
data = j[appId]['data']
if priceField not in data:
return
if region == 'AU':
data[priceField]['currency'] = 'AUD'
return data[priceField]
steam = Steam()
| 36.396648 | 99 | 0.540906 |
f390455d6dae396d6c425a30bfd82c292bc3af9a | 2,595 | rs | Rust | mqtt3/src/error.rs | RemakeAONTeam/rust-mq | c5ed369adcb408a690e89d458b8c097ab3209e31 | [
"MIT"
] | 210 | 2016-02-24T13:19:31.000Z | 2022-03-08T14:46:57.000Z | mqtt3/src/error.rs | RemakeAONTeam/rust-mq | c5ed369adcb408a690e89d458b8c097ab3209e31 | [
"MIT"
] | 23 | 2016-04-17T22:30:08.000Z | 2021-01-31T04:58:14.000Z | mqtt3/src/error.rs | RemakeAONTeam/rust-mq | c5ed369adcb408a690e89d458b8c097ab3209e31 | [
"MIT"
] | 42 | 2016-04-22T08:19:42.000Z | 2021-06-25T06:51:47.000Z | use std::result;
use std::io;
use std::fmt;
use std::error;
use std::string::FromUtf8Error;
use byteorder;
pub type Result<T> = result::Result<T, Error>;
#[derive(Debug)]
pub enum Error {
IncorrectPacketFormat,
InvalidTopicPath,
UnsupportedProtocolName,
UnsupportedProtocolVersion,
UnsupportedQualityOfService,
UnsupportedPacketType,
UnsupportedConnectReturnCode,
PayloadSizeIncorrect,
PayloadTooLong,
PayloadRequired,
TopicNameMustNotContainNonUtf8,
TopicNameMustNotContainWildcard,
MalformedRemainingLength,
UnexpectedEof,
Io(io::Error)
}
impl From<io::Error> for Error {
fn from(err: io::Error) -> Error {
Error::Io(err)
}
}
impl From<FromUtf8Error> for Error {
fn from(_: FromUtf8Error) -> Error {
Error::TopicNameMustNotContainNonUtf8
}
}
impl From<byteorder::Error> for Error {
fn from(err: byteorder::Error) -> Error {
match err {
byteorder::Error::UnexpectedEOF => Error::UnexpectedEof,
byteorder::Error::Io(err) => Error::Io(err)
}
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::write(f, format_args!("{:?}", *self))
}
}
impl error::Error for Error {
fn description<'a>(&'a self) -> &'a str {
match *self {
Error::IncorrectPacketFormat => "Incorrect Packet Format",
Error::InvalidTopicPath => "Invalid Topic Path",
Error::UnsupportedProtocolName => "Unsupported Protocol Name",
Error::UnsupportedProtocolVersion => "Unsupported Protocol Version",
Error::UnsupportedQualityOfService => "Unsupported Quality Of Service",
Error::UnsupportedPacketType => "Unsupported Packet Type",
Error::UnsupportedConnectReturnCode => "Unsupported Connect Return Code",
Error::PayloadSizeIncorrect => "Payload Size Incorrect",
Error::PayloadTooLong => "Payload Too Long",
Error::PayloadRequired => "Payload Required",
Error::TopicNameMustNotContainNonUtf8 => "Topic Name Must Not Contain Non Utf 8",
Error::TopicNameMustNotContainWildcard => "Topic Name Must Not Contain Wildcard",
Error::MalformedRemainingLength => "Malformed Remaining Length",
Error::UnexpectedEof => "Unexpected Eof",
Error::Io(ref err) => err.description(),
}
}
fn cause(&self) -> Option<&error::Error> {
match *self {
Error::Io(ref err) => Some(err),
_ => None,
}
}
}
| 30.892857 | 93 | 0.633141 |
e72e1ecb7ab1c9cdd2ff3ffad47b106696caadae | 962 | php | PHP | app/Integrante.php | luiscarlosmarca/app-prae | 7b04075c778eae14da2ff3988091f7c9542f3354 | [
"MIT"
] | null | null | null | app/Integrante.php | luiscarlosmarca/app-prae | 7b04075c778eae14da2ff3988091f7c9542f3354 | [
"MIT"
] | null | null | null | app/Integrante.php | luiscarlosmarca/app-prae | 7b04075c778eae14da2ff3988091f7c9542f3354 | [
"MIT"
] | null | null | null | <?php namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Integrante;
use Illuminate\Support\Facades\Session;
class Integrante extends Model {
protected $table="integrantes";
protected $fillable = ['nombre','apellido','foto','rol','tipoDoc','direccion','telefono','id','email','observaciones','numDoc'];
public function scopeNombre($query,$nombre)
{
if (trim($nombre) != "")
{
$query->where(\DB::raw("CONCAT(nombre)"),"LIKE","%$nombre%");
Session::flash('message','Nombre:'.' '.$nombre.' ' .' Resultado de la busqueda');
}
}
public function scopeid($query,$id)
{
if (trim($id) != "")
{
$query->where(\DB::raw("CONCAT(id)"),"LIKE","%$id%");
}
}
public function getfullnameAttribute()
{
return $this->nombre.' '.$this->apellido;
}
public static function filter($nombre,$id)
{
return Integrante::nombre($nombre)
->id($id)
->orderBy('nombre','ASC')
->paginate(5);
}
}
| 18.862745 | 129 | 0.617464 |
d6a779815069ef262e570d3c455f29f05b18e519 | 7,046 | swift | Swift | Dailye/View/Tabs/SettingsView.swift | GeorgeiGoncharik/Itra-Coursework | 7df1c78d0548a67a385df61d1bc8d4cb48617b66 | [
"MIT"
] | null | null | null | Dailye/View/Tabs/SettingsView.swift | GeorgeiGoncharik/Itra-Coursework | 7df1c78d0548a67a385df61d1bc8d4cb48617b66 | [
"MIT"
] | null | null | null | Dailye/View/Tabs/SettingsView.swift | GeorgeiGoncharik/Itra-Coursework | 7df1c78d0548a67a385df61d1bc8d4cb48617b66 | [
"MIT"
] | null | null | null | //
// SettingsView.swift
// Dailye
//
// Created by Mac on 17.01.21.
//
import SwiftUI
struct SettingsView: View {
@StateObject private var viewModel = SettingsViewModel()
@State private var showDetailCountry = false
@State private var showDetailLanguage = false
var body: some View {
NavigationView{
ScrollView{
VStack(spacing: 20) {
GroupBox(
label: SettingsLabel(text: "Dailye", imageSF: "info.circle")
){
Divider().padding(.vertical, 4)
HStack(alignment: .center, spacing: 10){
Image(uiImage: UIImage(named: "AppIcon") ?? UIImage())
.resizable()
.scaledToFit()
.frame(width: 80, height: 80)
.cornerRadius(9.0)
Text("Fast and easy news reader for your country's most popular news and newspapers. Stay up to date with your country news and compare them with different sources.")
.font(.footnote)
}
}.cardLook()
GroupBox(
label: SettingsLabel(text: "Localization", imageSF: "flag")
){
VStack{
Group{
Divider().padding(.vertical, 4)
HStack{
Text("Country").foregroundColor(.gray)
Spacer()
Text("\(viewModel.selectedCountry.rawValue)")
Button(
action: {
showDetailCountry.toggle()
}
){
Image(systemName: "arrow.right.square").cardAccent()
.rotationEffect(.degrees(showDetailCountry ? 90 : 0))
.scaleEffect(showDetailCountry ? 1.2 : 1.0)
}
}
if showDetailCountry{
Picker(selection: $viewModel.selectedCountry, label: Text("Please choose a country")) {
ForEach(viewModel.countries, id: \.self) { country in
Text("\(country.rawValue)")
.tag(country)
}
}
}
}
Group{
Divider().padding(.vertical, 4)
HStack{
Text("Language").foregroundColor(.gray)
Spacer()
Text("\(viewModel.selectedLanguage.rawValue)")
Button(
action: {
showDetailLanguage.toggle()
}
){
Image(systemName: "arrow.right.square").cardAccent()
.rotationEffect(.degrees(showDetailLanguage ? 90 : 0))
.scaleEffect(showDetailLanguage ? 1.2 : 1.0)
}
}
if showDetailLanguage{
Picker(selection: $viewModel.selectedLanguage, label: Text("Please choose a language")) {
ForEach(viewModel.languages, id: \.self) { language in
Text("\(language.rawValue)")
.tag(language)
}
}
}
}
}
}.cardLook()
GroupBox(
label: SettingsLabel(text: "Application", imageSF: "apps.iphone")
){
SettingsRow(name: "Developer", content: "Georgei Goncharik")
SettingsRow(name: "E-mail", linkLabel: "contact a developer", email: "[email protected]")
SettingsRow(name: "VK", linkLabel: "@g.goncharik", link: "https://vk.com/g.goncharik")
}.cardLook()
}
.padding()
}
.navigationTitle("Settings")
.navigationBarTitleDisplayMode(.large)
}
}
}
struct SettingsLabel: View{
var text: String
var imageSF: String
var body: some View{
HStack{
Text(text)
.bold()
Spacer()
Image(systemName: imageSF)
}
.font(.title3)
.lineLimit(1)
.cardText()
}
}
struct SettingsRow: View{
var name: String
var content: String?
var linkLabel: String?
var link: String?
var email: String?
var body: some View{
VStack{
Divider().padding(.vertical, 4)
HStack{
Text(name).foregroundColor(.gray)
Spacer()
if(content != nil){
Text(content!)
} else if (linkLabel != nil){
if(link != nil){
Link(linkLabel!, destination: URL(string: "\(link!)")!)
Image(systemName: "arrow.up.right.square").cardAccent()
}
if(email != nil){
Button(linkLabel!){
if let url = URL(string: "mailto:\(email!)") {
if #available(iOS 10.0, *) {
UIApplication.shared.open(url)
} else {
UIApplication.shared.openURL(url)
}
}
}.buttonStyle(BorderlessButtonStyle())
Image(systemName: "arrow.up.right.square").cardAccent()
}
} else {
EmptyView()
}
}
}
}
}
struct SettingsView_Previews: PreviewProvider {
static var previews: some View {
SettingsView()
.preferredColorScheme(.dark)
}
}
| 41.204678 | 194 | 0.367017 |
c999e739a08c562a756f1c71e5a3dce944beccd2 | 3,564 | ts | TypeScript | src/auth/auth.service.ts | mohdalivas/iconnect_backend | ffa2c0f88d42f6df0e7750eaa3dbb9d9c87b3bb6 | [
"MIT"
] | null | null | null | src/auth/auth.service.ts | mohdalivas/iconnect_backend | ffa2c0f88d42f6df0e7750eaa3dbb9d9c87b3bb6 | [
"MIT"
] | null | null | null | src/auth/auth.service.ts | mohdalivas/iconnect_backend | ffa2c0f88d42f6df0e7750eaa3dbb9d9c87b3bb6 | [
"MIT"
] | null | null | null | import { Injectable, UnprocessableEntityException } from '@nestjs/common';
import { CreateAuthDto } from './auth.dto';
import { UsersService } from '../users/users.service';
import { JwtService } from '@nestjs/jwt';
import * as bcrypt from 'bcryptjs';
@Injectable()
export class AuthService {
constructor(
private readonly usersService: UsersService,
private readonly jwtService: JwtService
) {}
register(input: CreateAuthDto) {
try {
return this.usersService.create(input);
} catch (error) {
console.log(error);
throw new UnprocessableEntityException(error);
}
}
login(user) {
try {
if (user) {
const payload = { sub: user.id };
var token = this.jwtService.sign(payload)
var decodedToken = this.jwtService.decode(token)
let data = {
_id: user._id,
username: user.username,
fullname: user.fullname,
email: user.email,
token,
tokenExpires: decodedToken['exp'],
refreshToken: undefined,
admin: user.admin,
superadmin: user.superadmin
}
return data
}
else throw 'User not found!';
} catch (error) {
console.log(error)
throw new UnprocessableEntityException(error)
}
}
async validateUser(username: string, pass: string) {
if (!username || !pass) return { status: 'error', message: 'Username or password not found!' }
var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
let query;
if (re.test(String(username).toLowerCase())) query = { email: username };
else query = { username: username };
return this.usersService.findOne(query).then(user=>{
if (user && user['password']) {
return new Promise((resolve, reject) => {
bcrypt.compare(pass, user['password'], (err, isMatch) => {
if (err) reject(err);
if (user && !user['active']) return reject('User not active!')
else if (isMatch) {
resolve(user)
}
else reject('Wrong Password!')
})
})
} else {
// console.log('2validateUser user', user, pass)
return { status: 'error', message: 'User not found!' };
}
})
}
async validatePayload(req: any, payload: string): Promise<any> {
return await this.usersService.findOne({ id: payload.sub }, { id: 1, fullname: 1, clientId: 1, _clientId: 1, admin: 1, superadmin: 1, image: 1 }).then(async user => {
// console.log(user)
if (user) { // && user.deviceMAC
req.user = {}
payload['id'] = req.user.id = user.id
payload['name'] = req.user.name = user.fullname
payload['_id'] = req.user._id = user._id
payload['clientId'] = req.user.clientId = user.clientId
payload['_clientId'] = req.user._clientId = user._clientId
payload['image'] = req.user.image = user.image
payload['admin'] = req.user.admin = user.admin
payload['superadmin'] = req.user.superadmin = user.superadmin
payload['appPermissions'] = req.user.appPermissions = user.appPermissions
return payload
} else {
// console.log('2validateUser user', user, pass)
return { status: 'error', message: 'User not found!' };
}
}).catch(error => {
console.log('validatePayload error', error, 'validateUser error.Error', error.Error);
return error;
});
}
} | 36.367347 | 170 | 0.575758 |
e3477dce037afd74a8f9d790883788fbb45ecd74 | 919 | rb | Ruby | spec/unit/data-import/logger_spec.rb | stmichael/data-import | ef93894ec548f237ef07a3d82298f5a6975643e5 | [
"MIT"
] | 9 | 2015-01-02T14:35:18.000Z | 2020-02-21T15:43:12.000Z | spec/unit/data-import/logger_spec.rb | stmichael/data-import | ef93894ec548f237ef07a3d82298f5a6975643e5 | [
"MIT"
] | null | null | null | spec/unit/data-import/logger_spec.rb | stmichael/data-import | ef93894ec548f237ef07a3d82298f5a6975643e5 | [
"MIT"
] | 3 | 2015-04-20T14:25:17.000Z | 2018-01-31T15:15:51.000Z | require 'unit/spec_helper'
describe DataImport::Logger do
let(:important) { double }
let(:full) { double }
subject { described_class.new(full, important) }
it 'writes debug and info messages only to the full logger' do
full.should_receive(:debug).with('debug message')
full.should_receive(:info).with('info message')
subject.debug 'debug message'
subject.info 'info message'
end
it 'writes warn, error and fatal messages to both loggers' do
full.should_receive(:warn).with('warn message')
full.should_receive(:error).with('error message')
full.should_receive(:fatal).with('fatal message')
important.should_receive(:warn).with('warn message')
important.should_receive(:error).with('error message')
important.should_receive(:fatal).with('fatal message')
subject.warn 'warn message'
subject.error 'error message'
subject.fatal 'fatal message'
end
end
| 31.689655 | 64 | 0.718172 |
bb7434ae546438f1a499f516b02d9c09acf3218c | 1,283 | cshtml | C# | src/DunderMifflinInfinity.WebApp/Views/Sales/Index.cshtml | jordanbean-msft/AspNetCoreAppRolesFineGrainedApi | e30e68215018a29e221dab2387e7b588e19a650d | [
"MIT"
] | 2 | 2022-01-20T21:28:20.000Z | 2022-01-25T16:49:32.000Z | src/DunderMifflinInfinity.WebApp/Views/Sales/Index.cshtml | jordanbean-msft/AspNetCoreAppRolesFineGrainedApi | e30e68215018a29e221dab2387e7b588e19a650d | [
"MIT"
] | null | null | null | src/DunderMifflinInfinity.WebApp/Views/Sales/Index.cshtml | jordanbean-msft/AspNetCoreAppRolesFineGrainedApi | e30e68215018a29e221dab2387e7b588e19a650d | [
"MIT"
] | null | null | null | @model IEnumerable<DunderMifflinInfinity.WebApp.Models.Sale>
@{
ViewData["Title"] = "Index";
}
<h1>Index</h1>
<p>
<a asp-action="Create">Create New</a>
</p>
<table class="table">
<thead>
<tr>
<th>
@Html.DisplayNameFor(model => model.Employee.Branch)
</th>
<th>
@Html.DisplayNameFor(model => model.Employee)
</th>
<th>
@Html.DisplayNameFor(model => model.Value)
</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Employee.Branch.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Employee.FirstName) @Html.DisplayFor(modelItem => item.Employee.LastName)
</td>
<td>
@Html.DisplayFor(modelItem => item.Value)
</td>
<td>
<a asp-action="Edit" asp-route-id="@item.SaleID">Edit</a> |
<a asp-action="Details" asp-route-id="@item.SaleID">Details</a> |
<a asp-action="Delete" asp-route-id="@item.SaleID">Delete</a>
</td>
</tr>
}
</tbody>
</table>
| 26.729167 | 124 | 0.476228 |
74bce5d9f3ddb352f04f0bccd1f14a39dd43ed64 | 7,568 | css | CSS | lib/dump.css | MysticalPa/muledump-master | 771821ad76e2f040fd05ff076f148ed96e56c20c | [
"Unlicense"
] | null | null | null | lib/dump.css | MysticalPa/muledump-master | 771821ad76e2f040fd05ff076f148ed96e56c20c | [
"Unlicense"
] | null | null | null | lib/dump.css | MysticalPa/muledump-master | 771821ad76e2f040fd05ff076f148ed96e56c20c | [
"Unlicense"
] | null | null | null | body {
background-color: #363636;
color: #b3b3b3;
padding: 10px;
margin: 0;
font-size: 11px;
line-height: 1.2;
cursor: default;
font-family: Arial, sans-serif;
min-height: 100vh;
}
#bgImage {
width: 100vw;
height: 100vh;
position: fixed;
background-size: cover;
top: 0;
left: 0;
z-index: -1;
}
#cnt {
position: fixed;
top: 4px;
left: 4px;
padding: 4px;
z-index: 200;
background-color: #ccc;
color: #333;
}
#top {
font-size: 15px;
margin: 0 3px;
text-align: right;
z-index: 99;
}
#top>div,
#top>a {
display: inline-block;
cursor: pointer;
border: 2px solid #555;
padding: 0 4px;
}
#top>a {
color: inherit;
text-decoration: none;
}
.menu {
display: none;
position: absolute;
right: -2px;
z-index: 100;
padding: 5px;
border: solid 2px #555;
background: #363636;
color: #b3b3b3;
width: 200px;
text-align: left;
font-weight: normal;
font-size: 15px;
}
.menu:hover {
display: block;
}
.handle {
position: relative;
}
.handle:hover .menu {
display: block;
}
.menu input,
label {
cursor: pointer;
}
.menu input {
float: left;
clear: left;
margin: 4px;
}
.menu label {
display: block;
padding: 2px;
}
.menu label:hover,
.menu input:hover~label,
#export div:hover,
#top>div:hover,
#top>a:hover {
background: #555;
color: #fff;
}
.menu div>div>div {
padding-left: 15px;
}
#export {
width: auto;
text-align: center;
}
#export div {
padding: 0 5px;
}
#totals,
.mule,
.guid,
.reload,
.item {
display: inline-block;
}
#totals {
margin: 10px 3px;
border: solid 2px #555;
line-height: 0;
max-width: 528px;
padding: 5px;
}
#errors {
color: pink;
display: inline-block;
font: 16px/28px sans-serif;
max-width: 600px;
}
#errors:empty {
display: none;
}
.mule {
padding: 2px;
margin: 3px;
border: solid 2px #555;
min-width: 184px;
}
.guid {
color: #ccc;
background: #303030;
border: solid 1px #888;
font-family: monospace;
width: 100%;
}
.name,
.error,
.reload,
#counter {
font-weight: bold;
}
.name {
font-size: 16px;
margin: 4px;
text-align: center;
cursor: pointer;
overflow: hidden;
}
.button {
display: inline-block;
float: right;
width: 18px;
height: 18px;
line-height: 18px;
vertical-align: middle;
text-align: center;
font-size: 16px;
color: white;
background-color: #545454;
cursor: pointer;
overflow: hidden;
margin: 4px 2px;
text-decoration: none;
}
.portrait {
float: left;
width: 22px;
height: 22px;
margin: 4px 6px 0 4px;
}
hr {
margin: 0;
background-color: #555;
border-style: none;
height: 2px;
}
.stats,
.pcstats,
.chdesc {
width: 180px;
margin: 4px 0;
}
.chdesc {
white-space: nowrap;
}
.stats td {
line-height: 1em;
padding: 0;
}
.stats td.sname {
text-align: right;
padding: 0 5px 0 0;
}
.stat.avg {
/*color: #73cce2;*/
}
.stat.max {
color: #f0f0a0;
}
.stat.maxed {
color: #fcdf00;
}
.stat.good {
color: #90ff90;
}
.stat.good.very {
color: #00ff00;
}
.stat.bad {
color: #ff9090;
}
.stat.bad.very {
color: #ff0000;
}
.stat.small {
font-size: 11px;
}
.items {
line-height: 0;
}
.itemsc {
width: 176px;
margin: 2px;
padding: 0;
overflow: hidden;
}
.item {
position: relative;
width: 40px;
height: 40px;
margin: 2px;
background: url(renders.png) #545454;
overflow: hidden;
}
.item.selected {
background-color: #ffcd57;
outline: 2px solid #fefe8e;
outline-offset: -1px;
}
/* counter */
.item div {
position: absolute;
right: 4px;
bottom: 1px;
color: white;
font: bold 15px Arial, sans-serif;
text-shadow: -1px 0 3px black, 0 1px 3px black, 1px 0 3px black, 0 -1px 3px black;
}
/* unknown item indicator */
.item span {
position: absolute;
left: 2px;
font: 11px monospace;
color: white;
}
/*hp and mp */
.hp {
background-color: #545454;
background-image: url(hp.png);
background-position: 22px 2px;
background-repeat: no-repeat;
color: white;
float: left;
font: bold 15px/20px Arial, sans-serif;
height: 20px;
margin: 0 2px 4px 4px;
padding: 2px 2px 2px 17px;
text-align: center;
text-shadow: -1px 0px 1px black, 1px 0px 1px black, 0px -1px 1px black, 0px 1px 1px black;
width: 65px;
}
.mp {
background-color: #545454;
background-image: url(mp.png);
background-position: 22px 2px;
background-repeat: no-repeat;
color: white;
float: right;
font: bold 15px/20px Arial, sans-serif;
height: 20px;
margin: 0 4px 4px 2px;
padding: 2px 2px 2px 17px;
text-align: center;
text-shadow: -1px 0px 1px black, 1px 0px 1px black, 0px -1px 1px black, 0px 1px 1px black;
width: 65px;
}
/* achievements etc */
.pcstats {
overflow: hidden;
}
.pcstats td {
padding: 0;
line-height: 1.1em;
text-align: right;
overflow: hidden;
max-width: 110px;
}
.pcstats .goal {
text-align: left;
}
.pcstats .goal .bonus {
white-space: nowrap;
font-weight: normal;
padding: 0;
}
.pcstats .pcstat,
.pcstats .bonus,
.pcstats .info {
text-align: left;
font-weight: bold;
padding-left: 5px;
}
.pcstats .pcstat {
color: #57AD62;
}
.pcstats .bonus {
color: #FFC800;
}
.mule.disabled {
opacity: 0.5;
}
.mule>table {
margin: 0;
padding: 2px;
border-spacing: 0;
width: 100%;
}
td.cont {
vertical-align: top;
text-align: center;
padding: 0;
}
td.cont>div {
text-align: left;
display: inline-block;
}
.giftchest .itemsc {
background-color: #8b4513;
margin-left: 0;
margin-right: 0;
padding: 2px;
}
.giftchest .item {
background-color: #daa520;
}
/* stars */
.scont {
background-color: #222;
border-radius: 6px;
float: left;
padding: 1px 1px 1px 4px;
font-weight: normal;
font-size: 14px;
margin: 4px 2px;
}
.scont .star {
font-size: 1.2em;
line-height: 0;
margin: 0 0.1em 0 0.2em;
}
.warn {
color: #d70;
}
/* overlay + log */
.overlay {
top: 0px;
bottom: 0px;
position: absolute;
right: 0px;
left: 0px;
background-color: rgba(0, 0, 0, 0.7);
overflow: hidden;
padding: 2px;
}
.log {
font: 12px monospace;
position: absolute;
right: 5px;
left: 5px;
bottom: 5px;
margin: 0px;
}
.line.error {
color: #eaa;
}
.jscolor {
background-color: #363636 !important;
padding: 15px 32px;
text-align: center;
text-decoration: none;
color:#b3b3b3 !important;
display: inline-block;
font-size: 15px;
width: 200px;
padding: 5px;
border: solid 0px #555;
text-align: left;
}
.jscolor:hover {
background: #555 !important;
color: #fff !important;
}
.button {
background-color: #555;
border: 0 3px;
color: #b3b3b3;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
border-radius: 8px;
}
.button1 {
background-color: #363636 !important;
padding: 15px 32px;
text-align: center;
text-decoration: none;
color:#b3b3b3 !important;
display: inline-block;
font-size: 15px;
width: 200px;
padding: 5px;
border: solid 0px #555;
text-align: left;
}
.button1:hover {
background: #555 !important;
color: #fff !important;
}
h7 {
color: white;
} | 14.810176 | 94 | 0.592759 |
8323cbb4090ad8fd1f46538177e16c4161ecd67b | 1,140 | ts | TypeScript | src/blockchain/xsnx/asset.ts | xtokenmarket/xtoken-js | 86ca213c17123896017a5839ccf262905f5120f9 | [
"MIT"
] | 1 | 2021-02-02T08:01:56.000Z | 2021-02-02T08:01:56.000Z | src/blockchain/xsnx/asset.ts | xtokenmarket/xtoken-js | 86ca213c17123896017a5839ccf262905f5120f9 | [
"MIT"
] | 1 | 2021-01-05T09:55:34.000Z | 2021-01-05T12:12:33.000Z | src/blockchain/xsnx/asset.ts | xtokenmarket/xtoken-js | 86ca213c17123896017a5839ccf262905f5120f9 | [
"MIT"
] | 1 | 2021-01-25T02:11:35.000Z | 2021-01-25T02:11:35.000Z | import { BaseProvider } from '@ethersproject/providers'
import { ADDRESSES, X_SNX_A, X_SNX_ADMIN } from '@xtoken/abis'
import { Contract } from 'ethers'
import { ExchangeRates } from '../../types'
import { IAsset } from '../../types/xToken'
import { getExchangeRateContract } from '../utils'
import { getXSnxContracts } from './helper'
import { getXSnxPrices } from './prices'
export const getXSnxAsset = async (
symbol: typeof X_SNX_A,
provider: BaseProvider
): Promise<IAsset> => {
const {
network,
snxContract,
tradeAccountingContract,
xsnxContract,
} = await getXSnxContracts(provider)
const { chainId } = network
const xsnxAdminAddress = ADDRESSES[X_SNX_ADMIN][chainId]
const exchangeRatesContract = (await getExchangeRateContract(
provider
)) as ExchangeRates
const { aum, priceEth, priceUsd } = await getXSnxPrices(
xsnxContract,
xsnxAdminAddress,
tradeAccountingContract,
exchangeRatesContract,
snxContract as Contract,
provider
)
return {
aum,
mandate: 'Aggressive staker; ETH bull',
order: 3,
price: priceUsd,
priceEth,
symbol,
}
}
| 24.255319 | 63 | 0.697368 |
0dd2dbb5153ff27fdfce52c89850524497d2cea3 | 1,526 | cs | C# | VinylStop/Migrations/20180516020757_ChangeRecordToAlbum.cs | davidm5963/Vinyl-Stop | 9dbe4b4b27adadd6679b3c13a9f65cd9f2e8bb7d | [
"MIT"
] | 2 | 2018-07-18T15:01:03.000Z | 2019-10-27T05:53:27.000Z | VinylStop/Migrations/20180516020757_ChangeRecordToAlbum.cs | davidm5963/Vinyl-Stop | 9dbe4b4b27adadd6679b3c13a9f65cd9f2e8bb7d | [
"MIT"
] | null | null | null | VinylStop/Migrations/20180516020757_ChangeRecordToAlbum.cs | davidm5963/Vinyl-Stop | 9dbe4b4b27adadd6679b3c13a9f65cd9f2e8bb7d | [
"MIT"
] | null | null | null | using Microsoft.EntityFrameworkCore.Migrations;
using System;
using System.Collections.Generic;
namespace VinylStop.Migrations
{
public partial class ChangeRecordToAlbum : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "AlbumName",
table: "OrderDetails");
migrationBuilder.AlterColumn<string>(
name: "LongDescription",
table: "Albums",
nullable: false,
oldClrType: typeof(string),
oldNullable: true);
migrationBuilder.AlterColumn<string>(
name: "AlbumLabel",
table: "Albums",
nullable: false,
oldClrType: typeof(string),
oldNullable: true);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "AlbumName",
table: "OrderDetails",
nullable: true);
migrationBuilder.AlterColumn<string>(
name: "LongDescription",
table: "Albums",
nullable: true,
oldClrType: typeof(string));
migrationBuilder.AlterColumn<string>(
name: "AlbumLabel",
table: "Albums",
nullable: true,
oldClrType: typeof(string));
}
}
}
| 29.921569 | 71 | 0.529489 |
185f07f54a568141aea8f7a8483cca405c889403 | 3,670 | swift | Swift | dSRelay/Classes/Device.swift | Label305/dSRelay | 4d09dc7ec7f36a683d76667f92f1edb05354c8f6 | [
"Apache-2.0"
] | 2 | 2018-11-21T09:56:44.000Z | 2018-11-21T09:59:25.000Z | dSRelay/Classes/Device.swift | Label305/dSRelay | 4d09dc7ec7f36a683d76667f92f1edb05354c8f6 | [
"Apache-2.0"
] | null | null | null | dSRelay/Classes/Device.swift | Label305/dSRelay | 4d09dc7ec7f36a683d76667f92f1edb05354c8f6 | [
"Apache-2.0"
] | null | null | null | //
// dSRelay.swift
// dSRelay
//
// Created by Mèir Noordermeer on 12/11/2018.
// Copyright © 2018 Label305 B.V. All rights reserved.
//
import Foundation
import SwiftSocket
import then
open class Device {
let timeout: Int
var ipaddress: String
var port: Int32
var connection: TCPClient?
public var status: Dictionary<String, UInt>?
public init?(ipaddress: String, port: UInt, timeout: Int = 5) {
self.ipaddress = ipaddress
self.port = Int32(port)
self.timeout = timeout
self.connection = nil
let connection = self.connect().value
if connection == nil {
return nil
}
}
public init(connection: TCPClient, timeout: Int = 5) {
self.ipaddress = connection.address
self.port = connection.port
self.timeout = timeout
self.connection = connection
}
deinit {
if self.connection != nil {
self.connection!.close()
}
}
public func isConnected() -> Bool {
return self.connection != nil
}
public func connect() -> Promise<TCPClient> {
return Promise {resolve, reject in
if let client = self.connection {
resolve(client)
} else {
let client = TCPClient(address: self.ipaddress, port: self.port)
switch client.connect(timeout: self.timeout) {
case .success:
self.connection = client
self.getStatus().then { status in
self.status = status
resolve(client)
}
case .failure(let error):
self.status = nil
self.connection = nil
client.close()
reject(error)
}
}
}
}
open func send(data: [UInt8], expectedLength: Int) -> Promise<[Byte]> {
return Promise { resolve, reject in
self.connect()
.then { client in
switch client.send(data: data) {
case .success:
if let data = client.read(expectedLength, timeout: self.timeout) {
resolve(data)
}
case .failure(let error):
reject(error)
}
}.onError { error in
reject(error)
}
}
}
open func getStatus() -> Promise<Dictionary<String, UInt>> {
let payload: [UInt8] = [0x30]
return Promise { resolve, reject in
self.send(data: payload, expectedLength: 8)
.then { data in
if data.count < 8 {
reject(StatusError.MinimumResponseLengthNotSatisfiedError)
}
let status: Dictionary<String, UInt> = [
"moduleID": UInt(data[0]),
"systemFirmwareMajor": UInt(data[1]),
"systemFirmwareMinor": UInt(data[2]),
"appFirmwareMajor": UInt(data[3]),
"appFirmwareMinor": UInt(data[4]),
"volts": UInt(data[5]),
"internalTemperature": UInt((data[6] << 8) | data[7]) // 6th byte is high byte, 7th byte is low byte
]
resolve(status)
}.onError { error in
reject(error)
}
}
}
}
public enum Status: UInt8 {
case On = 0x01
case Off = 0x00
}
| 29.36 | 124 | 0.479837 |
c6da3967c71835fe358f3ec4c0cf910d44461aa5 | 332 | py | Python | indifferent/__init__.py | LandRegistry/audit | f0404195b0c90d5f96c4ce523ac8a179a1b479d5 | [
"MIT"
] | null | null | null | indifferent/__init__.py | LandRegistry/audit | f0404195b0c90d5f96c4ce523ac8a179a1b479d5 | [
"MIT"
] | null | null | null | indifferent/__init__.py | LandRegistry/audit | f0404195b0c90d5f96c4ce523ac8a179a1b479d5 | [
"MIT"
] | null | null | null | import os, sys
from flask import Flask
app = Flask(__name__)
# add config
app.config.from_object('config')
if not os.environ.get('REDIS_URL'):
print "REDIS_URL not set. Using default=[%s]" % app.config['REDIS_URL']
if not os.environ.get('REDIS_NS'):
print "REDIS_NS not set. Using default=[%s]" % app.config['REDIS_NS']
| 23.714286 | 75 | 0.701807 |
da13cfe4fc93482cdffeda2c6839afa2bf82cb48 | 2,468 | rb | Ruby | spec/serializers/post_serializer_spec.rb | janzenisaac/discourse-staff-alias | 4253e92325313a83537323b8da513acc97e8cea8 | [
"MIT"
] | 4 | 2020-05-12T17:19:00.000Z | 2022-03-19T04:12:53.000Z | spec/serializers/post_serializer_spec.rb | janzenisaac/discourse-staff-alias | 4253e92325313a83537323b8da513acc97e8cea8 | [
"MIT"
] | 3 | 2020-06-26T06:19:36.000Z | 2022-01-25T04:55:31.000Z | spec/serializers/post_serializer_spec.rb | janzenisaac/discourse-staff-alias | 4253e92325313a83537323b8da513acc97e8cea8 | [
"MIT"
] | 2 | 2020-11-19T11:00:59.000Z | 2021-09-12T04:58:10.000Z | # frozen_string_literal: true
require 'rails_helper'
describe PostSerializer do
fab!(:moderator) do
user = Fabricate(:moderator)
Group.find(Group::AUTO_GROUPS[:staff]).add(user)
user
end
let(:post) do
post = Fabricate(:post, user: DiscourseStaffAlias.alias_user)
DiscourseStaffAlias::UsersPostsLink.create!(
user: moderator,
post: post,
)
post
end
fab!(:post2) { Fabricate(:post) }
before do
SiteSetting.set(:staff_alias_username, 'some_alias')
SiteSetting.set(:staff_alias_enabled, true)
end
describe '#is_staff_aliased' do
it 'should be true if post is created by staff alias user' do
serializer = PostSerializer.new(post,
scope: Guardian.new(moderator),
root: false
)
payload = serializer.as_json
expect(payload[:is_staff_aliased]).to eq(true)
end
end
describe '#aliased_username' do
it 'should not be included if staff_alias_enabled is false' do
SiteSetting.set(:staff_alias_enabled, false)
payload = PostSerializer.new(post,
scope: Guardian.new(moderator),
root: false
).as_json
expect(payload[:aliased_username]).to eq(nil)
end
it 'should not be included if post is not created by staff alias user' do
payload = PostSerializer.new(post2,
scope: Guardian.new(moderator),
root: false
).as_json
expect(payload[:aliased_username]).to eq(nil)
end
it 'should not be included for a non staff user' do
serializer = PostSerializer.new(post,
scope: Guardian.new,
root: false
)
serializer.topic_view = TopicView.new(post.topic_id, moderator)
payload = serializer.as_json
expect(payload[:aliased_username]).to eq(nil)
end
it 'should be included if post is created by staff alias user with topic view' do
serializer = PostSerializer.new(post,
scope: Guardian.new(moderator),
root: false
)
serializer.topic_view = TopicView.new(post.topic_id, moderator)
payload = serializer.as_json
expect(payload[:aliased_username]).to eq(moderator.username)
end
it 'should be included if post is created by staff alias user without topic view' do
payload = PostSerializer.new(post,
scope: Guardian.new(moderator),
root: false
).as_json
expect(payload[:aliased_username]).to eq(moderator.username)
end
end
end
| 25.183673 | 88 | 0.666937 |
244b62beb700e41cc88bd269201ba604a55defb3 | 4,580 | ps1 | PowerShell | Functions/Set-OneShellUserProfile.ps1 | exactmike/OneShell | 8d766e30648632c895f2c62e7904f61b1a30d9e2 | [
"MIT"
] | 11 | 2018-04-05T15:26:43.000Z | 2021-10-03T12:23:13.000Z | Functions/Set-OneShellUserProfile.ps1 | exactmike/OneShell | 8d766e30648632c895f2c62e7904f61b1a30d9e2 | [
"MIT"
] | 6 | 2016-12-14T19:40:51.000Z | 2018-12-13T22:45:07.000Z | Functions/Set-OneShellUserProfile.ps1 | exactmike/OneShell | 8d766e30648632c895f2c62e7904f61b1a30d9e2 | [
"MIT"
] | 4 | 2017-10-03T19:55:24.000Z | 2018-10-11T15:39:38.000Z | Function Set-OneShellUserProfile
{
[cmdletbinding(DefaultParameterSetName = "Identity")]
param
(
[parameter(ValueFromPipelineByPropertyName, ValueFromPipeline)]
[string[]]$Identity
,
[parameter(ValueFromPipelineByPropertyName)]
[ValidateScript( {Test-DirectoryPath -Path $_})]
[string]$ProfileFolder
,
[parameter(ValueFromPipelineByPropertyName)]
[ValidateScript( {Test-DirectoryPath -Path $_})]
[string]$LogFolder
,
[parameter(ValueFromPipelineByPropertyName)]
[ValidateScript( {Test-DirectoryPath -Path $_})]
[string]$ExportDataFolder
,
[parameter(ValueFromPipelineByPropertyName)]
[ValidateScript( {Test-DirectoryPath -Path $_})]
[string]$InputFilesFolder
,
[parameter(ValueFromPipelineByPropertyName)]
[string]$Name
,
[parameter(ValueFromPipelineByPropertyName)]
[ValidateScript( {Test-EmailAddress -EmailAddress $_})]
$MailFromSMTPAddress
,
[parameter()]
[switch]$UpdateSystemsFromOrgProfile
,
[parameter()]
[ValidateScript( {Test-DirectoryPath -Path $_})]
[string[]]$Path = $Script:OneShellUserProfilePath
,
[parameter()]
[ValidateScript( {Test-DirectoryPath -Path $_})]
[string[]]$OrgProfilePath = $Script:OneShellOrgProfilePath
)
Begin
{
$PotentialUserProfiles = GetPotentialUserProfiles -path $Path
}
Process
{
foreach ($i in $Identity)
{
$UserProfile = GetSelectProfile -ProfileType User -Path $path -PotentialProfiles $PotentialUserProfiles -Identity $i -Operation Edit
$GetOrgProfileParams = @{
ErrorAction = 'Stop'
Path = $orgProfilePath
Identity = $UserProfile.organization.identity
}
$targetOrgProfile = @(Get-OneShellOrgProfile @GetOrgProfileParams)
#Check the Org Identity for validity (exists, not ambiguous)
switch ($targetOrgProfile.Count)
{
1
{}
0
{
$errorRecord = New-ErrorRecord -Exception System.Exception -ErrorId 0 -ErrorCategory ObjectNotFound -TargetObject $UserProfile.organization.identity -Message "No matching Organization Profile was found for identity $OrganizationIdentity"
$PSCmdlet.ThrowTerminatingError($errorRecord)
}
Default
{
$errorRecord = New-ErrorRecord -Exception System.Exception -ErrorId 0 -ErrorCategory InvalidData -TargetObject $UserProfile.organization.identity -Message "Multiple matching Organization Profiles were found for identity $OrganizationIdentity"
$PSCmdlet.ThrowTerminatingError($errorRecord)
}
}
#Update the User Profile Version if necessary
$UserProfile = UpdateUserProfileObjectVersion -UserProfile $UserProfile
#Update the profile itself
if ($PSBoundParameters.ContainsKey('UpdateSystemsFromOrgProfile') -and $UpdateSystemsFromOrgProfile -eq $true)
{
$UpdateUserProfileSystemParams = @{
ErrorAction = 'Stop'
ProfileObject = $UserProfile
OrgProfilePath = $OrgProfilePath
}
Update-OneShellUserProfileSystem @UpdateUserProfileSystemParams
}
foreach ($p in $PSBoundParameters.GetEnumerator())
{
if ($p.key -in 'ProfileFolder', 'Name', 'MailFromSMTPAddress', 'LogFolder', 'ExportDataFolder', 'InputFilesFolder')
{
if ($p.key -in 'ProfileFolder', 'LogFolder', 'ExportDataFolder', 'InputFilesFolder')
{
if (-not (Test-Path -PathType Container -Path $p.Value))
{
Write-Warning -Message "The specified ProfileFolder $($p.key) $ProfileFolder does not exist. Attempting to Create it."
[void](New-Item -Path $p.value -ItemType Directory)
}
}
$UserProfile.$($p.key) = $p.value
}
}#end foreach
Export-OneShellUserProfile -profile $UserProfile -ErrorAction 'Stop'
}#end foreach
}#End Process
}
| 42.407407 | 262 | 0.579694 |
a8c6cbd46f9eb7f02fd39b0897688e3eb036bf10 | 5,919 | ps1 | PowerShell | Tests/Unit/Module/MimeTypeRule.tests.ps1 | JakeDean3631/PowerStig | 6eaf02d7b7bae910ec8cefc8cd1f2caee8e5955e | [
"MIT"
] | 304 | 2019-05-07T19:29:43.000Z | 2022-03-27T12:58:07.000Z | Tests/Unit/Module/MimeTypeRule.tests.ps1 | JakeDean3631/PowerStig | 6eaf02d7b7bae910ec8cefc8cd1f2caee8e5955e | [
"MIT"
] | 536 | 2019-05-07T02:56:27.000Z | 2022-03-24T17:02:07.000Z | Tests/Unit/Module/MimeTypeRule.tests.ps1 | JakeDean3631/PowerStig | 6eaf02d7b7bae910ec8cefc8cd1f2caee8e5955e | [
"MIT"
] | 82 | 2019-05-10T03:35:55.000Z | 2022-01-11T19:04:04.000Z | #region Header
. $PSScriptRoot\.tests.header.ps1
#endregion
try
{
InModuleScope -ModuleName "$($global:moduleName).Convert" {
#region Test Setup
$testRuleList = @(
@{
Ensure = 'absent'
MimeType = 'application/octet-stream'
Extension = '.exe'
OrganizationValueRequired = $false
CheckContent = 'Follow the procedures below for each site hosted on the IIS 8.5 web server:
Open the IIS 8.5 Manager.
Click on the IIS 8.5 site.
Under IIS, double-click the MIME Types icon.
From the "Group by:" drop-down list, select "Content Type".
From the list of extensions under "Application", verify MIME types for OS shell program extensions have been removed, to include at a minimum, the following extensions:
.exe
If any OS shell MIME types are configured, this is a finding.'
},
@{
Ensure = 'absent'
MimeType = 'application/x-msdownload'
Extension = '.dll'
OrganizationValueRequired = $false
CheckContent = 'Open the IIS 8.5 Manager.
Click the IIS 8.5 web server name.
Under IIS, double-click the “MIME Types” icon.
From the "Group by:" drop-down list, select "Content Type".
From the list of extensions under "Application", verify MIME types for OS shell program extensions have been removed, to include at a minimum, the following extensions:
If any OS shell MIME types are configured, this is a finding.
.dll
If any OS shell MIME types are configured, this is a finding.'
},
@{
Ensure = 'absent'
MimeType = 'application/x-bat'
Extension = '.bat'
OrganizationValueRequired = $false
CheckContent = 'Open the IIS 8.5 Manager.
Click the IIS 8.5 web server name.
Under IIS, double-click the “MIME Types” icon.
From the "Group by:" drop-down list, select "Content Type".
From the list of extensions under "Application", verify MIME types for OS shell program extensions have been removed, to include at a minimum, the following extensions:
If any OS shell MIME types are configured, this is a finding.
.bat'
},
@{
Ensure = 'absent'
MimeType = 'application/x-csh'
Extension = '.csh'
OrganizationValueRequired = $false
CheckContent = 'Open the IIS 8.5 Manager.
Click the IIS 8.5 web server name.
Under IIS, double-click the “MIME Types” icon.
From the "Group by:" drop-down list, select "Content Type".
From the list of extensions under "Application", verify MIME types for OS shell program extensions have been removed, to include at a minimum, the following extensions:
If any OS shell MIME types are configured, this is a finding.
.csh'
},
@{
Ensure = $null
MimeType = $null
Extension = '.not'
OrganizationValueRequired = $false
CheckContent = 'Open the IIS 8.5 Manager.
Click the IIS 8.5 web server name.
Under IIS, double-click the “MIME Types” icon.
From the "Group by:" drop-down list, select "Content Type".
From the list of extensions under "Application", verify MIME types for OS shell program extensions have been something, to include at a minimum, the following extensions:
If any OS shell MIME types are configured, this is a finding.
.not'
}
)
#endregion
foreach ($testRule in $testRuleList)
{
. $PSScriptRoot\Convert.CommonTests.ps1
}
#region Add Custom Tests Here
Describe 'MultipleRules' {
# TODO move this to the CommonTests
$testRuleList = @(
@{
Count = 5
CheckContent = 'Follow the procedures below for each site hosted on the IIS 8.5 web server:
Open the IIS 8.5 Manager.
Click on the IIS 8.5 site.
Under IIS, double-click the MIME Types icon.
From the "Group by:" drop-down list, select "Content Type".
From the list of extensions under "Application", verify MIME types for OS shell program extensions have been removed, to include at a minimum, the following extensions:
.exe
.dll
.com
.bat
.csh
If any OS shell MIME types are configured, this is a finding.'
}
)
foreach ($testRule in $testRuleList)
{
It "Should return $true" {
$multipleRule = [MimeTypeRuleConvert]::HasMultipleRules($testRule.CheckContent)
$multipleRule | Should -Be $true
}
It "Should return $($testRule.Count) rules" {
$multipleRule = [MimeTypeRuleConvert]::SplitMultipleRules($testRule.CheckContent)
$multipleRule.count | Should -Be $testRule.Count
}
}
}
#endregion
}
}
finally
{
. $PSScriptRoot\.tests.footer.ps1
}
| 35.872727 | 190 | 0.523061 |
15656795ec14294d83b8c1a912f0c2ef2b697c80 | 3,366 | rb | Ruby | spec/patch/mysql2_spec.rb | JuanitoFatas/faulty | e674f0348833d867528c56b62bbb7ac9536dc49c | [
"MIT"
] | 63 | 2020-08-28T03:15:31.000Z | 2022-03-03T14:06:07.000Z | spec/patch/mysql2_spec.rb | JuanitoFatas/faulty | e674f0348833d867528c56b62bbb7ac9536dc49c | [
"MIT"
] | 15 | 2020-12-31T13:56:02.000Z | 2022-02-24T00:55:07.000Z | spec/patch/mysql2_spec.rb | JuanitoFatas/faulty | e674f0348833d867528c56b62bbb7ac9536dc49c | [
"MIT"
] | 8 | 2020-08-28T21:47:17.000Z | 2022-01-26T13:46:48.000Z | # frozen_string_literal: true
RSpec.describe 'Faulty::Patch::Mysql2', if: defined?(Mysql2) do # rubocop:disable RSpec/DescribeClass
def new_client(opts = {})
Mysql2::Client.new({
username: ENV['MYSQL_USER'],
password: ENV['MYSQL_PASSWORD'],
host: ENV['MYSQL_HOST'],
port: ENV['MYSQL_PORT'],
socket: ENV['MYSQL_SOCKET']
}.merge(opts))
end
def create_table(client, name)
client.query("CREATE TABLE `#{db_name}`.`#{name}`(id INT NOT NULL)")
end
def trip_circuit
client
4.times do
begin
new_client(host: '127.0.0.1', port: 9999, faulty: { instance: faulty })
rescue Mysql2::Error
# Expect connection failure
end
end
end
let(:client) { new_client(database: db_name, faulty: { instance: faulty }) }
let(:bad_client) { new_client(host: '127.0.0.1', port: 9999, faulty: { instance: faulty }) }
let(:bad_unpatched_client) { new_client(host: '127.0.0.1', port: 9999) }
let(:db_name) { SecureRandom.hex(6) }
let(:faulty) { Faulty.new(listeners: [], circuit_defaults: { sample_threshold: 2 }) }
before do
new_client.query("CREATE DATABASE `#{db_name}`")
end
after do
new_client.query("DROP DATABASE `#{db_name}`")
end
it 'captures connection error' do
expect { bad_client.query('SELECT 1 FROM dual') }.to raise_error do |error|
expect(error).to be_a(Faulty::Patch::Mysql2::CircuitError)
expect(error.cause).to be_a(Mysql2::Error::ConnectionError)
end
expect(faulty.circuit('mysql2').status.failure_rate).to eq(1)
end
it 'does not capture unpatched client errors' do
expect { bad_unpatched_client.query('SELECT 1 FROM dual') }.to raise_error(Mysql2::Error::ConnectionError)
expect(faulty.circuit('mysql2').status.failure_rate).to eq(0)
end
it 'does not capture application errors' do
expect { client.query('SELECT * FROM not_a_table') }.to raise_error(Mysql2::Error)
expect(faulty.circuit('mysql2').status.failure_rate).to eq(0)
end
it 'successfully executes query' do
create_table(client, 'test')
client.query('INSERT INTO test VALUES(1)')
expect(client.query('SELECT * FROM test').to_a).to eq([{ 'id' => 1 }])
expect(faulty.circuit('mysql2').status.failure_rate).to eq(0)
end
it 'prevents additional queries when tripped' do
trip_circuit
expect { client.query('SELECT 1 FROM dual') }
.to raise_error(Faulty::Patch::Mysql2::OpenCircuitError)
end
it 'allows COMMIT when tripped' do
create_table(client, 'test')
client.query('BEGIN')
client.query('INSERT INTO test VALUES(1)')
trip_circuit
expect(client.query('COMMIT')).to eq(nil)
expect { client.query('SELECT * FROM test') }
.to raise_error(Faulty::Patch::Mysql2::OpenCircuitError)
faulty.circuit('mysql2').reset!
expect(client.query('SELECT * FROM test').to_a).to eq([{ 'id' => 1 }])
end
it 'allows ROLLBACK with leading comment when tripped' do
create_table(client, 'test')
client.query('BEGIN')
client.query('INSERT INTO test VALUES(1)')
trip_circuit
expect(client.query('/* hi there */ ROLLBACK')).to eq(nil)
expect { client.query('SELECT * FROM test') }
.to raise_error(Faulty::Patch::Mysql2::OpenCircuitError)
faulty.circuit('mysql2').reset!
expect(client.query('SELECT * FROM test').to_a).to eq([])
end
end
| 34.346939 | 110 | 0.670826 |
980e83b0412094291abeb26f6197c363c2b5f49d | 12,921 | py | Python | B2G/gecko/ipc/ipdl/ipdl/ast.py | wilebeast/FireFox-OS | 43067f28711d78c429a1d6d58c77130f6899135f | [
"Apache-2.0"
] | 3 | 2015-08-31T15:24:31.000Z | 2020-04-24T20:31:29.000Z | B2G/gecko/ipc/ipdl/ipdl/ast.py | wilebeast/FireFox-OS | 43067f28711d78c429a1d6d58c77130f6899135f | [
"Apache-2.0"
] | null | null | null | B2G/gecko/ipc/ipdl/ipdl/ast.py | wilebeast/FireFox-OS | 43067f28711d78c429a1d6d58c77130f6899135f | [
"Apache-2.0"
] | 3 | 2015-07-29T07:17:15.000Z | 2020-11-04T06:55:37.000Z | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import sys
class Visitor:
def defaultVisit(self, node):
raise Exception, "INTERNAL ERROR: no visitor for node type `%s'"% (
node.__class__.__name__)
def visitTranslationUnit(self, tu):
for cxxInc in tu.cxxIncludes:
cxxInc.accept(self)
for inc in tu.includes:
inc.accept(self)
for su in tu.structsAndUnions:
su.accept(self)
for using in tu.builtinUsing:
using.accept(self)
for using in tu.using:
using.accept(self)
if tu.protocol:
tu.protocol.accept(self)
def visitCxxInclude(self, inc):
pass
def visitInclude(self, inc):
# Note: we don't visit the child AST here, because that needs delicate
# and pass-specific handling
pass
def visitStructDecl(self, struct):
for f in struct.fields:
f.accept(self)
def visitStructField(self, field):
field.typespec.accept(self)
def visitUnionDecl(self, union):
for t in union.components:
t.accept(self)
def visitUsingStmt(self, using):
pass
def visitProtocol(self, p):
for namespace in p.namespaces:
namespace.accept(self)
for spawns in p.spawnsStmts:
spawns.accept(self)
for bridges in p.bridgesStmts:
bridges.accept(self)
for opens in p.opensStmts:
opens.accept(self)
for mgr in p.managers:
mgr.accept(self)
for managed in p.managesStmts:
managed.accept(self)
for msgDecl in p.messageDecls:
msgDecl.accept(self)
for transitionStmt in p.transitionStmts:
transitionStmt.accept(self)
def visitNamespace(self, ns):
pass
def visitSpawnsStmt(self, spawns):
pass
def visitBridgesStmt(self, bridges):
pass
def visitOpensStmt(self, opens):
pass
def visitManager(self, mgr):
pass
def visitManagesStmt(self, mgs):
pass
def visitMessageDecl(self, md):
for inParam in md.inParams:
inParam.accept(self)
for outParam in md.outParams:
outParam.accept(self)
def visitTransitionStmt(self, ts):
ts.state.accept(self)
for trans in ts.transitions:
trans.accept(self)
def visitTransition(self, t):
for toState in t.toStates:
toState.accept(self)
def visitState(self, s):
pass
def visitParam(self, decl):
pass
def visitTypeSpec(self, ts):
pass
def visitDecl(self, d):
pass
class Loc:
def __init__(self, filename='<??>', lineno=0):
assert filename
self.filename = filename
self.lineno = lineno
def __repr__(self):
return '%r:%r'% (self.filename, self.lineno)
def __str__(self):
return '%s:%s'% (self.filename, self.lineno)
Loc.NONE = Loc(filename='<??>', lineno=0)
class _struct:
pass
class Node:
def __init__(self, loc=Loc.NONE):
self.loc = loc
def accept(self, visitor):
visit = getattr(visitor, 'visit'+ self.__class__.__name__, None)
if visit is None:
return getattr(visitor, 'defaultVisit')(self)
return visit(self)
def addAttrs(self, attrsName):
if not hasattr(self, attrsName):
setattr(self, attrsName, _struct())
class NamespacedNode(Node):
def __init__(self, loc=Loc.NONE, name=None):
Node.__init__(self, loc)
self.name = name
self.namespaces = [ ]
def addOuterNamespace(self, namespace):
self.namespaces.insert(0, namespace)
def qname(self):
return QualifiedId(self.loc, self.name,
[ ns.name for ns in self.namespaces ])
class TranslationUnit(NamespacedNode):
def __init__(self, type, name):
NamespacedNode.__init__(self, name=name)
self.filetype = type
self.filename = None
self.cxxIncludes = [ ]
self.includes = [ ]
self.builtinUsing = [ ]
self.using = [ ]
self.structsAndUnions = [ ]
self.protocol = None
def addCxxInclude(self, cxxInclude): self.cxxIncludes.append(cxxInclude)
def addInclude(self, inc): self.includes.append(inc)
def addStructDecl(self, struct): self.structsAndUnions.append(struct)
def addUnionDecl(self, union): self.structsAndUnions.append(union)
def addUsingStmt(self, using): self.using.append(using)
def setProtocol(self, protocol): self.protocol = protocol
class CxxInclude(Node):
def __init__(self, loc, cxxFile):
Node.__init__(self, loc)
self.file = cxxFile
class Include(Node):
def __init__(self, loc, type, name):
Node.__init__(self, loc)
suffix = 'ipdl'
if type == 'header':
suffix += 'h'
self.file = "%s.%s" % (name, suffix)
class UsingStmt(Node):
def __init__(self, loc, cxxTypeSpec):
Node.__init__(self, loc)
self.type = cxxTypeSpec
# "singletons"
class ASYNC:
pretty = 'async'
@classmethod
def __hash__(cls): return hash(cls.pretty)
@classmethod
def __str__(cls): return cls.pretty
class RPC:
pretty = 'rpc'
@classmethod
def __hash__(cls): return hash(cls.pretty)
@classmethod
def __str__(cls): return cls.pretty
class SYNC:
pretty = 'sync'
@classmethod
def __hash__(cls): return hash(cls.pretty)
@classmethod
def __str__(cls): return cls.pretty
class INOUT:
pretty = 'inout'
@classmethod
def __hash__(cls): return hash(cls.pretty)
@classmethod
def __str__(cls): return cls.pretty
class IN:
pretty = 'in'
@classmethod
def __hash__(cls): return hash(cls.pretty)
@classmethod
def __str__(cls): return cls.pretty
@staticmethod
def prettySS(cls, ss): return _prettyTable['in'][ss.pretty]
class OUT:
pretty = 'out'
@classmethod
def __hash__(cls): return hash(cls.pretty)
@classmethod
def __str__(cls): return cls.pretty
@staticmethod
def prettySS(ss): return _prettyTable['out'][ss.pretty]
_prettyTable = {
IN : { 'async': 'AsyncRecv',
'sync': 'SyncRecv',
'rpc': 'RpcAnswer' },
OUT : { 'async': 'AsyncSend',
'sync': 'SyncSend',
'rpc': 'RpcCall' }
# inout doesn't make sense here
}
class Namespace(Node):
def __init__(self, loc, namespace):
Node.__init__(self, loc)
self.name = namespace
class Protocol(NamespacedNode):
def __init__(self, loc):
NamespacedNode.__init__(self, loc)
self.sendSemantics = ASYNC
self.spawnsStmts = [ ]
self.bridgesStmts = [ ]
self.opensStmts = [ ]
self.managers = [ ]
self.managesStmts = [ ]
self.messageDecls = [ ]
self.transitionStmts = [ ]
self.startStates = [ ]
class StructField(Node):
def __init__(self, loc, type, name):
Node.__init__(self, loc)
self.typespec = type
self.name = name
class StructDecl(NamespacedNode):
def __init__(self, loc, name, fields):
NamespacedNode.__init__(self, loc, name)
self.fields = fields
class UnionDecl(NamespacedNode):
def __init__(self, loc, name, components):
NamespacedNode.__init__(self, loc, name)
self.components = components
class SpawnsStmt(Node):
def __init__(self, loc, side, proto, spawnedAs):
Node.__init__(self, loc)
self.side = side
self.proto = proto
self.spawnedAs = spawnedAs
class BridgesStmt(Node):
def __init__(self, loc, parentSide, childSide):
Node.__init__(self, loc)
self.parentSide = parentSide
self.childSide = childSide
class OpensStmt(Node):
def __init__(self, loc, side, proto):
Node.__init__(self, loc)
self.side = side
self.proto = proto
class Manager(Node):
def __init__(self, loc, managerName):
Node.__init__(self, loc)
self.name = managerName
class ManagesStmt(Node):
def __init__(self, loc, managedName):
Node.__init__(self, loc)
self.name = managedName
class MessageDecl(Node):
def __init__(self, loc):
Node.__init__(self, loc)
self.name = None
self.sendSemantics = ASYNC
self.direction = None
self.inParams = [ ]
self.outParams = [ ]
self.compress = ''
def addInParams(self, inParamsList):
self.inParams += inParamsList
def addOutParams(self, outParamsList):
self.outParams += outParamsList
def hasReply(self):
return self.sendSemantics is SYNC or self.sendSemantics is RPC
class Transition(Node):
def __init__(self, loc, trigger, msg, toStates):
Node.__init__(self, loc)
self.trigger = trigger
self.msg = msg
self.toStates = toStates
def __cmp__(self, o):
c = cmp(self.msg, o.msg)
if c: return c
c = cmp(self.trigger, o.trigger)
if c: return c
def __hash__(self): return hash(str(self))
def __str__(self): return '%s %s'% (self.trigger, self.msg)
@staticmethod
def nameToTrigger(name):
return { 'send': SEND, 'recv': RECV, 'call': CALL, 'answer': ANSWER }[name]
Transition.NULL = Transition(Loc.NONE, None, None, [ ])
class TransitionStmt(Node):
def __init__(self, loc, state, transitions):
Node.__init__(self, loc)
self.state = state
self.transitions = transitions
@staticmethod
def makeNullStmt(state):
return TransitionStmt(Loc.NONE, state, [ Transition.NULL ])
class SEND:
pretty = 'send'
@classmethod
def __hash__(cls): return hash(cls.pretty)
@classmethod
def direction(cls): return OUT
class RECV:
pretty = 'recv'
@classmethod
def __hash__(cls): return hash(cls.pretty)
@classmethod
def direction(cls): return IN
class CALL:
pretty = 'call'
@classmethod
def __hash__(cls): return hash(cls.pretty)
@classmethod
def direction(cls): return OUT
class ANSWER:
pretty = 'answer'
@classmethod
def __hash__(cls): return hash(cls.pretty)
@classmethod
def direction(cls): return IN
class State(Node):
def __init__(self, loc, name, start=False):
Node.__init__(self, loc)
self.name = name
self.start = start
def __eq__(self, o):
return (isinstance(o, State)
and o.name == self.name
and o.start == self.start)
def __hash__(self):
return hash(repr(self))
def __ne__(self, o):
return not (self == o)
def __repr__(self): return '<State %r start=%r>'% (self.name, self.start)
def __str__(self): return '<State %s start=%s>'% (self.name, self.start)
State.ANY = State(Loc.NONE, '[any]', start=True)
State.DEAD = State(Loc.NONE, '[dead]', start=False)
State.DYING = State(Loc.NONE, '[dying]', start=False)
class Param(Node):
def __init__(self, loc, typespec, name):
Node.__init__(self, loc)
self.name = name
self.typespec = typespec
class TypeSpec(Node):
def __init__(self, loc, spec, state=None, array=0, nullable=0,
myChmod=None, otherChmod=None):
Node.__init__(self, loc)
self.spec = spec # QualifiedId
self.state = state # None or State
self.array = array # bool
self.nullable = nullable # bool
self.myChmod = myChmod # None or string
self.otherChmod = otherChmod # None or string
def basename(self):
return self.spec.baseid
def isActor(self):
return self.state is not None
def __str__(self): return str(self.spec)
class QualifiedId: # FIXME inherit from node?
def __init__(self, loc, baseid, quals=[ ]):
assert isinstance(baseid, str)
for qual in quals: assert isinstance(qual, str)
self.loc = loc
self.baseid = baseid
self.quals = quals
def qualify(self, id):
self.quals.append(self.baseid)
self.baseid = id
def __str__(self):
if 0 == len(self.quals):
return self.baseid
return '::'.join(self.quals) +'::'+ self.baseid
# added by type checking passes
class Decl(Node):
def __init__(self, loc):
Node.__init__(self, loc)
self.progname = None # what the programmer typed, if relevant
self.shortname = None # shortest way to refer to this decl
self.fullname = None # full way to refer to this decl
self.loc = loc
self.type = None
self.scope = None
| 28.150327 | 83 | 0.610092 |
258315c5596b01e0d16c0b858d81bf455304e74a | 5,021 | cs | C# | dialogflow/api/DialogflowSamples/EntityManagement.cs | leroberto8/leroberto8.gethub.io | b04338172fe9d3feafbb21fb9435c9df1a557669 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | dialogflow/api/DialogflowSamples/EntityManagement.cs | leroberto8/leroberto8.gethub.io | b04338172fe9d3feafbb21fb9435c9df1a557669 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | dialogflow/api/DialogflowSamples/EntityManagement.cs | leroberto8/leroberto8.gethub.io | b04338172fe9d3feafbb21fb9435c9df1a557669 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | // Copyright(c) 2018 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
using System;
using CommandLine;
using Google.Cloud.Dialogflow.V2;
namespace GoogleCloudSamples
{
// Samples demonstrating how to Create, List, Delete Entities
public class EntityManagement
{
public static void RegisterCommands(VerbMap<object> verbMap)
{
verbMap
.Add((CreateOptions opts) => Create(opts.ProjectId, opts.EntityTypeId, opts.EntityValue, opts.Synonyms))
.Add((ListOptions opts) => List(opts.ProjectId, opts.EntityTypeId))
.Add((DeleteOptions opts) => Delete(opts.ProjectId, opts.EntityTypeId, opts.EntityValue));
}
[Verb("entities:create", HelpText = "Create new entity type")]
public class CreateOptions : OptionsWithProjectId
{
[Value(0, MetaName = "entityTypeId", HelpText = "ID of existing EntityType", Required = true)]
public string EntityTypeId { get; set; }
[Value(1, MetaName = "entityValue", HelpText = "New entity value", Required = true)]
public string EntityValue { get; set; }
[Value(2, MetaName = "synonyms", HelpText = "Comma separated synonyms", Required = true)]
public string SynonymsInput { get; set; }
public string[] Synonyms => SynonymsInput.Split(',');
}
// [START dialogflow_create_entity]
public static int Create(string projectId,
string entityTypeId,
string entityValue,
string[] synonyms)
{
var client = EntityTypesClient.Create();
var entity = new EntityType.Types.Entity() { Value = entityValue };
entity.Synonyms.AddRange(synonyms);
var operation = client.BatchCreateEntities(
parent: new EntityTypeName(projectId, entityTypeId),
entities: new[] { entity }
);
Console.WriteLine("Waiting for the entity creation operation to complete.");
operation.PollUntilCompleted();
Console.WriteLine($"Entity creation completed.");
return 0;
}
// [END dialogflow_create_entity]
[Verb("entities:list", HelpText = "Print list of entities for given EntityType")]
public class ListOptions : OptionsWithProjectId
{
[Value(0, MetaName = "entityTypeId", HelpText = "ID of existing EntityType", Required = true)]
public string EntityTypeId { get; set; }
}
// [START dialogflow_list_entities]
public static int List(string projectId, string entityTypeId)
{
var client = EntityTypesClient.Create();
var entityType = client.GetEntityType(new EntityTypeName(
projectId, entityTypeId
));
foreach (var entity in entityType.Entities)
{
Console.WriteLine($"Entity value: {entity.Value}");
Console.WriteLine($"Entity synonyms: {string.Join(',', entity.Synonyms)}");
}
return 0;
}
// [END dialogflow_list_entities]
[Verb("entities:delete", HelpText = "Delete specified EntityType")]
public class DeleteOptions : OptionsWithProjectId
{
[Value(0, MetaName = "entityTypeId", HelpText = "ID of existing EntityType", Required = true)]
public string EntityTypeId { get; set; }
[Value(1, MetaName = "entityValue", HelpText = "Existing entity value", Required = true)]
public string EntityValue { get; set; }
}
// [START dialogflow_delete_entity]
public static int Delete(string projectId, string entityTypeId, string entityValue)
{
var client = EntityTypesClient.Create();
var operation = client.BatchDeleteEntities(
parent: new EntityTypeName(projectId, entityTypeId),
entityValues: new[] { entityValue }
);
Console.WriteLine("Waiting for the entity deletion operation to complete.");
operation.PollUntilCompleted();
Console.WriteLine($"Deleted Entity: {entityValue}");
return 0;
}
// [END dialogflow_delete_entity]
}
}
| 39.535433 | 121 | 0.594702 |
bf01e26a8296934e24040cba83d31b592262c1b3 | 8,587 | sql | SQL | database/facil_consulta.sql | kelvinfer4/crud-medicos-agendamentos | 508568b58eeaa49b2be7f03ec1b2612987320461 | [
"MIT"
] | null | null | null | database/facil_consulta.sql | kelvinfer4/crud-medicos-agendamentos | 508568b58eeaa49b2be7f03ec1b2612987320461 | [
"MIT"
] | 3 | 2021-03-10T10:45:15.000Z | 2022-02-27T01:06:59.000Z | database/facil_consulta.sql | kelvinfer4/crud-medicos-agendamentos | 508568b58eeaa49b2be7f03ec1b2612987320461 | [
"MIT"
] | null | null | null | -- phpMyAdmin SQL Dump
-- version 4.9.0.1
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Tempo de geração: 10-Mar-2020 às 21:20
-- Versão do servidor: 10.3.16-MariaDB
-- versão do PHP: 7.3.6
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Banco de dados: `facil_consulta`
--
-- --------------------------------------------------------
--
-- Estrutura da tabela `doctors`
--
CREATE TABLE `doctors` (
`id` int(10) UNSIGNED NOT NULL,
`email` varchar(112) COLLATE utf8mb4_unicode_ci NOT NULL,
`name` varchar(112) COLLATE utf8mb4_unicode_ci NOT NULL,
`password` varchar(112) COLLATE utf8mb4_unicode_ci NOT NULL,
`address` varchar(112) COLLATE utf8mb4_unicode_ci NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
`remember_token` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Extraindo dados da tabela `doctors`
--
INSERT INTO `doctors` (`id`, `email`, `name`, `password`, `address`, `created_at`, `updated_at`, `remember_token`) VALUES
(3, '[email protected]', 'Kelvin Ferreira Souza', '$2y$10$2iaGm2vtJ33lRK2a5kWJFO8CxdlQNAo5QjaNcseinU6ULoUZfD.aa', 'Av. Pinheiro Machado, 676', '2020-03-08 06:22:31', '2020-03-11 03:07:40', NULL),
(4, '[email protected]', 'Eduardo Rotta', '$2y$10$14Ly5PBHK9jCszBoyw.kz.01P0Aak9RPKq5KCCioAmJ.CYD4cec92', 'R. Lôbo da Costa, 726', '2020-03-10 19:16:27', '2020-03-10 19:16:27', NULL),
(5, '[email protected]', 'Felix Antonio Insaurriaga', '$2y$10$wQkL0wnP/JoxhYeZqdwa8u2AsLWnkFM5xtodjtiPwJ7KuXnmHkgZ.', 'R. Santos Dumont, 172', '2020-03-10 19:19:45', '2020-03-10 19:19:45', NULL),
(6, '[email protected]', 'Marcelo Passos da Rocha', '$2y$10$ARfcbN7j624xLSCuE02NMe2WqINQGs8780bxm2se0bt/qBd7aG7vS', 'R. Félix Xavier da Cunha, 824', '2020-03-10 19:20:50', '2020-03-10 19:20:50', NULL),
(7, '[email protected]', 'Enio Paulo Araujo', '$2y$10$/ntrd/LjliX7Rhmw3eXP0uSb/1Bd2lI4JWVJ0ycJtOaMhg7UI9sgm', 'R. Félix Xavier da Cunha, 755', '2020-03-10 19:22:48', '2020-03-10 19:22:48', NULL);
-- --------------------------------------------------------
--
-- Estrutura da tabela `failed_jobs`
--
CREATE TABLE `failed_jobs` (
`id` bigint(20) UNSIGNED NOT NULL,
`connection` text COLLATE utf8mb4_unicode_ci NOT NULL,
`queue` text COLLATE utf8mb4_unicode_ci NOT NULL,
`payload` longtext COLLATE utf8mb4_unicode_ci NOT NULL,
`exception` longtext COLLATE utf8mb4_unicode_ci NOT NULL,
`failed_at` timestamp NOT NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- --------------------------------------------------------
--
-- Estrutura da tabela `migrations`
--
CREATE TABLE `migrations` (
`id` int(10) UNSIGNED NOT NULL,
`migration` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`batch` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Extraindo dados da tabela `migrations`
--
INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES
(1, '2014_10_12_000000_create_users_table', 1),
(2, '2019_08_19_000000_create_failed_jobs_table', 1),
(3, '2014_10_12_100000_create_password_resets_table', 2),
(4, '2020_03_07_170352_create_doctors_table', 2),
(5, '2020_03_07_171720_create_schedules_table', 2);
-- --------------------------------------------------------
--
-- Estrutura da tabela `password_resets`
--
CREATE TABLE `password_resets` (
`email` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`token` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`created_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- --------------------------------------------------------
--
-- Estrutura da tabela `schedules`
--
CREATE TABLE `schedules` (
`id` int(10) UNSIGNED NOT NULL,
`doctor_id` int(10) UNSIGNED NOT NULL,
`date` timestamp NULL DEFAULT NULL,
`busy` int(11) NOT NULL DEFAULT 0,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Extraindo dados da tabela `schedules`
--
INSERT INTO `schedules` (`id`, `doctor_id`, `date`, `busy`, `created_at`, `updated_at`) VALUES
(9, 3, '2020-03-09 20:00:00', 0, '2020-03-08 06:03:37', '2020-03-09 15:53:21'),
(10, 3, '2020-03-09 21:30:00', 1, '2020-03-08 12:03:29', '2020-03-09 16:04:32'),
(13, 3, '2020-03-10 14:00:00', 1, '2020-03-10 14:03:38', '2020-03-10 19:39:50'),
(15, 4, '2020-03-10 18:45:00', 0, '2020-03-10 07:03:50', '2020-03-10 19:16:50'),
(16, 5, '2020-03-11 14:00:00', 1, '2020-03-10 07:03:53', '2020-03-11 03:15:00'),
(17, 6, '2020-03-15 21:00:00', 0, '2020-03-10 07:03:04', '2020-03-10 19:21:04'),
(18, 7, '2020-03-18 13:45:00', 0, '2020-03-10 07:03:00', '2020-03-10 19:23:00'),
(19, 4, '2020-03-10 20:00:00', 0, '2020-03-10 07:03:03', '2020-03-10 19:53:03'),
(20, 4, '2020-03-10 21:00:00', 0, '2020-03-10 07:03:24', '2020-03-10 19:53:24'),
(21, 5, '2020-03-11 16:00:00', 1, '2020-03-10 07:03:57', '2020-03-10 19:54:13'),
(22, 5, '2020-03-12 17:00:00', 0, '2020-03-10 07:03:06', '2020-03-10 19:54:06');
-- --------------------------------------------------------
--
-- Estrutura da tabela `users`
--
CREATE TABLE `users` (
`id` bigint(20) UNSIGNED NOT NULL,
`name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`email` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`email_verified_at` timestamp NULL DEFAULT NULL,
`password` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`remember_token` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Extraindo dados da tabela `users`
--
INSERT INTO `users` (`id`, `name`, `email`, `email_verified_at`, `password`, `remember_token`, `created_at`, `updated_at`) VALUES
(1, 'Kelvin Souza', '[email protected]', NULL, '$2y$10$XEh8dl/4QYTEyPk0qDku5e54.nc57SLDWZoh2zrKizaL9GuV1nKQK', NULL, '2020-03-07 20:47:22', '2020-03-07 20:47:22'),
(2, 'Greicy', '[email protected]', NULL, '$2y$10$TeKthZxvw0CL6wn//T.bC.rowAiUSDTAMuvG1db6GASVWhfgRyrd.', NULL, '2020-03-07 20:48:36', '2020-03-07 20:48:36');
--
-- Índices para tabelas despejadas
--
--
-- Índices para tabela `doctors`
--
ALTER TABLE `doctors`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `doctors_email_unique` (`email`);
--
-- Índices para tabela `failed_jobs`
--
ALTER TABLE `failed_jobs`
ADD PRIMARY KEY (`id`);
--
-- Índices para tabela `migrations`
--
ALTER TABLE `migrations`
ADD PRIMARY KEY (`id`);
--
-- Índices para tabela `password_resets`
--
ALTER TABLE `password_resets`
ADD KEY `password_resets_email_index` (`email`);
--
-- Índices para tabela `schedules`
--
ALTER TABLE `schedules`
ADD PRIMARY KEY (`id`),
ADD KEY `schedules_doctor_id_foreign` (`doctor_id`);
--
-- Índices para tabela `users`
--
ALTER TABLE `users`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `users_email_unique` (`email`);
--
-- AUTO_INCREMENT de tabelas despejadas
--
--
-- AUTO_INCREMENT de tabela `doctors`
--
ALTER TABLE `doctors`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=9;
--
-- AUTO_INCREMENT de tabela `failed_jobs`
--
ALTER TABLE `failed_jobs`
MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT de tabela `migrations`
--
ALTER TABLE `migrations`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;
--
-- AUTO_INCREMENT de tabela `schedules`
--
ALTER TABLE `schedules`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=25;
--
-- AUTO_INCREMENT de tabela `users`
--
ALTER TABLE `users`
MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
--
-- Restrições para despejos de tabelas
--
--
-- Limitadores para a tabela `schedules`
--
ALTER TABLE `schedules`
ADD CONSTRAINT `schedules_doctor_id_foreign` FOREIGN KEY (`doctor_id`) REFERENCES `doctors` (`id`) ON DELETE CASCADE;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
| 34.211155 | 208 | 0.686736 |
4cf7b7a7524c3718e7874de514036e5a0cfd2659 | 1,210 | py | Python | urls.py | aysiu/manana | 8af8b57c72f6154affdb5f3a9a3469a49e5818fe | [
"Apache-2.0"
] | 75 | 2015-01-05T18:32:38.000Z | 2022-02-18T23:27:52.000Z | urls.py | aysiu/manana | 8af8b57c72f6154affdb5f3a9a3469a49e5818fe | [
"Apache-2.0"
] | 8 | 2015-02-02T18:15:43.000Z | 2016-03-23T23:23:10.000Z | urls.py | aysiu/manana | 8af8b57c72f6154affdb5f3a9a3469a49e5818fe | [
"Apache-2.0"
] | 22 | 2015-02-02T15:30:33.000Z | 2021-03-26T14:53:49.000Z | from django.conf.urls import patterns, include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
url(r'^login/$', 'django.contrib.auth.views.login', name='login'),
url(r'^logout/$', 'django.contrib.auth.views.logout_then_login', name='logout'),
url(r'^manifest/', include('manifests.urls')),
url(r'^catalog/', include('catalogs.urls')),
url(r'^report/', include('reports.urls')),
url(r'^inventory/', include('inventory.urls')),
url(r'^licenses/', include('licenses.urls')),
# for compatibility with MunkiReport scripts
url(r'^update/', include('reports.urls')),
url(r'^lookup/', include('reports.urls')),
url(r'^$', include('reports.urls')),
)
# comment out the following if you are serving
# static files a different way
urlpatterns += staticfiles_urlpatterns()
| 40.333333 | 84 | 0.695041 |
7fce30ae03967ca09cb912a072ab65d85a4d425a | 3,287 | kt | Kotlin | core/src/jsMain/kotlin/de/p7s1/qa/sevenfacette/http/HttpClientAbility.kt | PDoering/SevenFacette | f457cde54673f2fd3210d3bf9dd47d6423a07bd3 | [
"MIT"
] | 23 | 2020-02-28T13:38:31.000Z | 2020-10-07T16:01:49.000Z | core/src/jsMain/kotlin/de/p7s1/qa/sevenfacette/http/HttpClientAbility.kt | PDoering/SevenFacette | f457cde54673f2fd3210d3bf9dd47d6423a07bd3 | [
"MIT"
] | 77 | 2020-02-28T12:53:56.000Z | 2020-10-15T09:55:41.000Z | core/src/jsMain/kotlin/de/p7s1/qa/sevenfacette/http/HttpClientAbility.kt | PDoering/SevenFacette | f457cde54673f2fd3210d3bf9dd47d6423a07bd3 | [
"MIT"
] | 1 | 2020-03-10T07:55:33.000Z | 2020-03-10T07:55:33.000Z | package de.p7s1.qa.sevenfacette.http
import io.ktor.util.KtorExperimentalAPI
import kotlin.js.Promise
/**
* TODO: Add Description
*
* @author Patrick Döring
*/
@KtorExperimentalAPI
@ExperimentalJsExport
@JsName("HttpClientAbility")
open class HttpClientAbility(private val client: GenericHttpClient) {
private var abilities = mutableListOf<HttpAbility>()
private var httpAbility = client
get() {
return field
}
set(value) {
field = value
}
@JsName("withConfiguration")
fun withConfiguration(name: String) : Array<HttpAbility> {
httpAbility = createHttpClient(name)
abilities.add(HttpAbility(name, httpAbility))
return abilities.toTypedArray()
}
@JsName("post")
suspend fun post(path: String, content: String, contentType: CONTENTTYPES = CONTENTTYPES.APPLICATION_JSON, headers: HttpHeader? = null): Promise<HttpResponse> =
client.post(path, content, contentType, headers)
@JsName("postByteArray")
suspend fun post(path: String, content: ByteArray, headers: HttpHeader? = null): Promise<HttpResponse> =
client.post(path, content, headers)
@JsName("postMultipart")
suspend fun post(path: String, content: MultipartBody, headers: HttpHeader? = null): Promise<HttpResponse> =
client.post(path, content, headers)
@JsName("patch")
suspend fun patch(path: String, content: String, contentType: CONTENTTYPES = CONTENTTYPES.APPLICATION_JSON, headers: HttpHeader? = null): Promise<HttpResponse> =
client.patch(path, content, contentType, headers)
@JsName("patchByteArray")
suspend fun patch(path: String, content: ByteArray, headers: HttpHeader? = null): Promise<HttpResponse> =
client.patch(path, content, headers)
@JsName("patchMultipart")
suspend fun patch(path: String, content: MultipartBody, headers: HttpHeader? = null): Promise<HttpResponse> =
client.patch(path, content, headers)
@JsName("put")
suspend fun put(path: String, content: String, contentType: CONTENTTYPES = CONTENTTYPES.APPLICATION_JSON, headers: HttpHeader? = null): Promise<HttpResponse> =
client.put(path, content, contentType, headers)
@JsName("putByteArray")
suspend fun put(path: String, content: ByteArray, headers: HttpHeader? = null): Promise<HttpResponse> =
client.put(path, content, headers)
@JsName("putMultipart")
suspend fun put(path: String, content: MultipartBody, headers: HttpHeader? = null): Promise<HttpResponse> =
client.put(path, content, headers)
@JsName("delete")
suspend fun delete(path: String, headers: HttpHeader? = null): Promise<HttpResponse> =
client.delete(path, headers)
@JsName("deleteString")
suspend fun delete(path: String, content: String, contentType: CONTENTTYPES = CONTENTTYPES.APPLICATION_JSON, headers: HttpHeader? = null): Promise<HttpResponse> =
client.delete(path, content, contentType, headers)
@JsName("get")
suspend fun get(path: String, headers: HttpHeader? = null): Promise<HttpResponse> =
client.get(path, headers)
@JsName("head")
suspend fun head(path: String, headers: HttpHeader? = null): Promise<HttpResponse> =
client.head(path, headers)
}
| 39.130952 | 166 | 0.697901 |
5888d197a1ce63fd251f30b3339498777b50fe5b | 103 | css | CSS | public/css/admin-recipe-list-smaller.css | hergarp/Recept | aa6f39bcb15518ec9267ad5fd3d643cd61efd3e7 | [
"MIT"
] | null | null | null | public/css/admin-recipe-list-smaller.css | hergarp/Recept | aa6f39bcb15518ec9267ad5fd3d643cd61efd3e7 | [
"MIT"
] | 22 | 2022-02-06T23:58:14.000Z | 2022-03-29T19:27:24.000Z | public/css/admin-recipe-list-smaller.css | hergarp/Recept | aa6f39bcb15518ec9267ad5fd3d643cd61efd3e7 | [
"MIT"
] | null | null | null | @media screen and (max-width: 550px) {
.image {
width: 100px;
height: 66px;
}
} | 17.166667 | 38 | 0.504854 |
f23ecfa353e95633b9ee32574a274fbe7c2db37d | 2,698 | php | PHP | resources/views/tambah/tambah_user.blade.php | aldiwebprogreming/Laravel_ebunga | f74862879b113be7d79b07e7e8bcd714a9e03bd0 | [
"MIT"
] | null | null | null | resources/views/tambah/tambah_user.blade.php | aldiwebprogreming/Laravel_ebunga | f74862879b113be7d79b07e7e8bcd714a9e03bd0 | [
"MIT"
] | null | null | null | resources/views/tambah/tambah_user.blade.php | aldiwebprogreming/Laravel_ebunga | f74862879b113be7d79b07e7e8bcd714a9e03bd0 | [
"MIT"
] | null | null | null | @extends('layout.app')
@section('title','Tambah user')
@section('content')
<div class="main-content">
<section class="section">
<div class="section-header">
<h1>Tambah User</h1>
</div>
<div class="row">
<div class="col-12 col-md-12 col-lg-12">
<div class="card">
<div class="card-header">
<h4>Tambah User</h4>
</div>
<div class="card-body">
<form method="POST" action="{{url('')}}/user/tambah/store">
@csrf
<div class="col-md-8 col-lg-8">
<div class="mb-3">
<label for="" class="form-label">Username</label>
<input type="text" class="form-control" name="username" placeholder="Masukan username">
@error('username')
<smal class="text-danger"> {{ $message }} </smal>
@enderror
</div>
<div class="mb-3">
<label for="" class="form-label">Type</label>
<select class="form-control" name="type">
<option>--Pilih Type User--</option>
<option>Admin</option>
<option>Super Admin</option>
<option>Buyyer</option>
<option>Seller</option>
</select>
</div>
<div class="mb-3">
<label for="" class="form-label">Password</label>
<input type="password" name="password" class="form-control" >
@error('password')
<smal class="text-danger"> {{ $message }} </smal>
@enderror
</div>
<div class="mb-3">
<input type="submit" name="kirim" class="btn btn-primary" value="Save">
<a href="{{url('/oprator')}}" class ="btn btn-success"> Kembali </a>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</section>
</div>
@endsection
| 33.725 | 118 | 0.344329 |
d66500d3886d28b9d367328502dc736dd32ef1af | 3,985 | cs | C# | TabulateSmarterTestPackage/Utilities/ReportingUtility.cs | SmarterApp/TabulateSmarterTestAdminPackage | 2c8226b3f53c82dcc83a7b0ba3f2eaa79f30399d | [
"ECL-2.0"
] | 1 | 2021-03-30T22:46:14.000Z | 2021-03-30T22:46:14.000Z | TabulateSmarterTestPackage/Utilities/ReportingUtility.cs | SmarterApp/TabulateSmarterTestAdminPackage | 2c8226b3f53c82dcc83a7b0ba3f2eaa79f30399d | [
"ECL-2.0"
] | 4 | 2017-01-30T06:56:57.000Z | 2018-08-09T00:17:55.000Z | TabulateSmarterTestPackage/Utilities/ReportingUtility.cs | SmarterApp/TabulateSmarterTestAdminPackage | 2c8226b3f53c82dcc83a7b0ba3f2eaa79f30399d | [
"ECL-2.0"
] | 1 | 2016-09-15T16:33:49.000Z | 2016-09-15T16:33:49.000Z | using System.Collections.Generic;
using System.IO;
using System.Linq;
using ProcessSmarterTestPackage.External;
using SmarterTestPackage.Common.Data;
namespace TabulateSmarterTestPackage.Utilities
{
public static class ReportingUtility
{
internal static CsvWriter ErrorWriter;
internal static CsvWriter ItemWriter;
internal static CsvWriter ItemWriterRDW;
internal static CsvWriter StimuliWriter;
static ReportingUtility()
{
ErrorHandling = new ErrorHandling();
}
public static string ErrorFileName { get; set; }
public static string ItemFileName { get; set; }
public static string ItemFileNameRDW { get; set; }
public static string StimuliFileName { get; set; }
public static ErrorHandling ErrorHandling { get; set; }
public static string TestName { get; set; }
public static string ContentItemDirectoryPath { get; set; }
public static string ContentStimuliDirectoryPath { get; set; }
public static CrossProcessor CrossProcessor { get; set; }
public static CsvWriter GetItemWriter()
{
return ItemWriter ?? (ItemWriter = new CsvWriter(ItemFileName, false));
}
public static CsvWriter GetItemWriterRDW()
{
return ItemWriterRDW ?? (ItemWriterRDW = new CsvWriter(ItemFileNameRDW, false));
}
public static CsvWriter GetStimuliWriter()
{
return StimuliWriter ?? (StimuliWriter = new CsvWriter(StimuliFileName, false));
}
public static CsvWriter GetErrorWriter()
{
return ErrorWriter ?? (ErrorWriter = new CsvWriter(ErrorFileName, false));
}
public static void SetFileName(string fileName)
{
ErrorFileName = fileName + ".errors.csv";
ItemFileName = fileName + ".items.csv";
ItemFileNameRDW = fileName + ".items-RDW.csv";
StimuliFileName = fileName + ".stims.csv";
}
public static void InitializeCrossProcessor()
{
if (string.IsNullOrEmpty(ContentItemDirectoryPath) || string.IsNullOrEmpty(ContentStimuliDirectoryPath))
{
return;
}
var items = new List<ContentPackageItemRow>();
using (
var itemStream = new FileStream(ContentItemDirectoryPath, FileMode.Open, FileAccess.Read,
FileShare.Read))
{
items = CsvProcessor.Process<ContentPackageItemRow>(itemStream).ToList();
}
var stimuli = new List<ContentPackageStimRow>();
using (
var stimuliStream = new FileStream(ContentStimuliDirectoryPath, FileMode.Open, FileAccess.Read,
FileShare.Read))
{
stimuli = CsvProcessor.Process<ContentPackageStimRow>(stimuliStream).ToList();
}
CrossProcessor = new CrossProcessor(items, stimuli);
}
public static void ReportError(string testName, PackageType packageType, string path, ErrorSeverity severity,
string itemId, string value,
string message, params object[] args)
{
ErrorHandling.ReportError(GetErrorWriter(), ErrorFileName, testName, packageType, path, severity,
itemId.Split('-').Last(), value, message, args);
}
public static void Dispose(bool disposing)
{
if (ItemWriter != null)
{
ItemWriter.Dispose();
ItemWriterRDW.Dispose();
ItemWriter = null;
}
if (StimuliWriter != null)
{
StimuliWriter.Dispose();
StimuliWriter = null;
}
if (ErrorWriter != null)
{
ErrorWriter.Dispose();
ErrorWriter = null;
}
}
}
} | 35.580357 | 117 | 0.591719 |
996234fe7471954da2d58e0b672e60fa6be86655 | 2,718 | dart | Dart | lib/src/types/map_objects/map_object_collection.dart | FetFrumos/yandex_mapkit | 67290fd9bd46d4a2166ede218de67df5a0d8c631 | [
"MIT"
] | null | null | null | lib/src/types/map_objects/map_object_collection.dart | FetFrumos/yandex_mapkit | 67290fd9bd46d4a2166ede218de67df5a0d8c631 | [
"MIT"
] | null | null | null | lib/src/types/map_objects/map_object_collection.dart | FetFrumos/yandex_mapkit | 67290fd9bd46d4a2166ede218de67df5a0d8c631 | [
"MIT"
] | null | null | null | part of yandex_mapkit;
/// A collection of [MapObject] to be displayed on [YandexMap]
/// All [mapObjects] must be unique, i.e. each [MapObject.mapId] must be unique
class MapObjectCollection extends Equatable implements MapObject {
MapObjectCollection({
required this.mapId,
required List<MapObject> mapObjects,
this.zIndex = 0.0,
this.onTap,
this.isVisible = true
}) : _mapObjects = mapObjects.groupFoldBy<MapObjectId, MapObject>(
(element) => element.mapId,
(previous, element) => element
).values.toList();
final List<MapObject> _mapObjects;
List<MapObject> get mapObjects => List.unmodifiable(_mapObjects);
final double zIndex;
final TapCallback<MapObjectCollection>? onTap;
/// Manages visibility of the object on the map.
final bool isVisible;
MapObjectCollection copyWith({
List<MapObject>? mapObjects,
double? zIndex,
TapCallback<MapObjectCollection>? onTap,
bool? isVisible
}) {
return MapObjectCollection(
mapId: mapId,
mapObjects: mapObjects ?? this.mapObjects,
zIndex: zIndex ?? this.zIndex,
onTap: onTap ?? this.onTap,
isVisible: isVisible ?? this.isVisible
);
}
@override
final MapObjectId mapId;
@override
MapObjectCollection clone() => copyWith();
@override
MapObjectCollection dup(MapObjectId mapId) {
return MapObjectCollection(
mapId: mapId,
mapObjects: mapObjects,
zIndex: zIndex,
onTap: onTap,
isVisible: isVisible
);
}
@override
void _tap(Point point) {
if (onTap != null) {
onTap!(this, point);
}
}
@override
Map<String, dynamic> toJson() {
return <String, dynamic>{
'id': mapId.value,
'mapObjects': _mapObjects.map((MapObject p) => p.toJson()).toList(),
'zIndex': zIndex,
'isVisible': isVisible
};
}
@override
Map<String, dynamic> _createJson() {
return toJson()..addAll({
'type': runtimeType.toString(),
'mapObjects': MapObjectUpdates.from(
<MapObject>{...[]},
mapObjects.toSet()
).toJson()
});
}
@override
Map<String, dynamic> _updateJson(MapObject previous) {
assert(mapId == previous.mapId);
return toJson()..addAll({
'type': runtimeType.toString(),
'mapObjects': MapObjectUpdates.from(
(previous as MapObjectCollection).mapObjects.toSet(),
mapObjects.toSet()
).toJson()
});
}
@override
Map<String, dynamic> _removeJson() {
return {
'id': mapId.value,
'type': runtimeType.toString()
};
}
@override
List<Object> get props => <Object>[
mapId,
mapObjects,
zIndex
];
@override
bool get stringify => true;
}
| 23.230769 | 79 | 0.639809 |
3194e4860f02a4a83acfa422b93a475469b7f809 | 1,749 | lua | Lua | rtklua/Accepted/Spells/mage/pestilence.lua | The-Kingdom-of-The-Winds/RTK-Server | b306c3411af42ea54c6ecaa785cea9ab4e97ff28 | [
"Xnet",
"X11"
] | 1 | 2021-03-08T06:33:34.000Z | 2021-03-08T06:33:34.000Z | rtklua/Accepted/Spells/mage/pestilence.lua | The-Kingdom-of-The-Winds/RTK-Server | b306c3411af42ea54c6ecaa785cea9ab4e97ff28 | [
"Xnet",
"X11"
] | null | null | null | rtklua/Accepted/Spells/mage/pestilence.lua | The-Kingdom-of-The-Winds/RTK-Server | b306c3411af42ea54c6ecaa785cea9ab4e97ff28 | [
"Xnet",
"X11"
] | 3 | 2020-11-19T22:01:46.000Z | 2021-03-16T21:05:37.000Z | pestilence_mage = {
cast = function(player, target)
local duration = 200000
local magicCost = 20
if (not player:canCast(1, 1, 0)) then
return
end
if (player.magic < magicCost) then
player:sendMinitext("Not enough mana.")
return
end
if (target.state == 1) then
player:sendMinitext("That is no longer useful.")
return
end
if (target.blType == BL_PC and not player:canPK(target)) or target.blType == BL_NPC then
player:sendMinitext("You cannot attack that target.")
return
end
if target:checkIfCast(curses) then
player:sendMinitext("Another spell of this type is in effect.")
return
end
if target:checkIfCast(protections) then
player:sendMinitext("The target is already protected.")
return
end
player:sendAction(6, 20)
player.magic = player.magic - magicCost
player:sendStatus()
player:playSound(5)
player:sendMinitext("You cast Pestilence.")
target:setDuration("pestilence_mage", duration)
target:sendAnimation(1, 0)
if (target.blType == BL_MOB) then
target.armor = target.armor + 5
target.cursed = 1
elseif (target.blType == BL_PC and player:canPK(target)) then
target:sendMinitext(player.name .. " casts Pestilence on you.")
target:calcStat()
end
end,
while_cast = function(block)
block:sendAnimation(34, 0)
end,
recast = function(target)
target.armor = target.armor + 5
target.cursed = 1
target:sendStatus()
end,
uncast = function(target)
target.armor = target.armor - 5
target.cursed = 0
target:SendStatus()
end,
requirements = function(player)
local level = 7
local items = {"acorn", "wooden_sword", 0}
local itemAmounts = {15, 1, 50}
local desc = "A minor curse."
return level, items, itemAmounts, desc
end
}
| 23.958904 | 90 | 0.699257 |
e2577765e2f5f7f4b23d0d55b15fa9ba7873a610 | 2,792 | py | Python | pkg/v1/providers/tests/clustergen/gencluster_params.py | ykakarap/tanzu-framework | 35a410d8ddc8b2f606a66ea0d1d696744b3c89b8 | [
"Apache-2.0"
] | 1 | 2022-03-24T12:13:01.000Z | 2022-03-24T12:13:01.000Z | pkg/v1/providers/tests/clustergen/gencluster_params.py | ykakarap/tanzu-framework | 35a410d8ddc8b2f606a66ea0d1d696744b3c89b8 | [
"Apache-2.0"
] | 5 | 2022-02-08T09:52:10.000Z | 2022-03-29T11:28:40.000Z | pkg/v1/providers/tests/clustergen/gencluster_params.py | ykakarap/tanzu-framework | 35a410d8ddc8b2f606a66ea0d1d696744b3c89b8 | [
"Apache-2.0"
] | 1 | 2021-11-10T11:01:42.000Z | 2021-11-10T11:01:42.000Z | #!/usr/bin/env python3
# Copyright 2020 The TKG Contributors.
#
# 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.
import csv
import os
import sys
import hashlib
def write_test_cases(params_file, test_dir):
test_num = 0
with open(params_file, 'r') as file:
my_reader = csv.DictReader(file, delimiter=',')
for var_dict in my_reader:
test_num+=1
cmd_args = []
cfg_args = []
dict_contents = ""
for k, v in sorted(var_dict.items()):
dict_contents += '{}{}'.format(k, v)
if k == "_CNAME":
cmd_args.insert(0, v)
elif k == "_PLAN":
cmd_args.append('{} {}'.format("--plan", v))
elif k == "_INFRA":
cmd_args.append('{} {}'.format("-i", v))
if k.startswith('--'):
if v != "NOTPROVIDED":
k = k.lower()
if k.startswith('--enable-'):
cmd_args.append('{}={}'.format(k, v))
else:
cmd_args.append('{} {}'.format(k, v))
else:
# hack to workaround the problem with pict where there is no escape char for comma.
# sets "AZURE_CUSTOM_TAGS" to "tagKey1=tagValue1, tagKey2=tagValue2"
if k == "AZURE_CUSTOM_TAGS" and v.startswith('tagKey1='):
cfg_args.append('{}: {}'.format(k, 'tagKey1=tagValue1, tagKey2=tagValue2'))
elif v != "NA":
cfg_args.append('{}: {}'.format(k, v.replace("<comma>", ",")))
testid = int(hashlib.sha256(dict_contents.encode('utf-8')).hexdigest(), 16) % 10**8
filename = "%8.8d.case" % (testid)
with open(os.path.join(test_dir, filename), "w") as w:
w.write('#! ({}) EXE: {}\n\n'.format("%4.4d" % test_num, " ".join(cmd_args)))
w.write('{}\n'.format("\n".join(cfg_args)))
def main():
if len(sys.argv) != 3:
print("Usage {} csv_params_file test_data_dir".format(sys.argv[0]))
sys.exit(1)
else:
write_test_cases(sys.argv[1], sys.argv[2])
if __name__ == "__main__":
main()
| 38.246575 | 103 | 0.534742 |
4211cde1dc86e74f7ec8103c6bf946910e2d9001 | 1,358 | cs | C# | 2019/advent.2019.tests/Day1Tests.cs | zmj/advent | fb0b2a609ae1dac8f672b71a1ecb65faa97aff34 | [
"MIT"
] | null | null | null | 2019/advent.2019.tests/Day1Tests.cs | zmj/advent | fb0b2a609ae1dac8f672b71a1ecb65faa97aff34 | [
"MIT"
] | null | null | null | 2019/advent.2019.tests/Day1Tests.cs | zmj/advent | fb0b2a609ae1dac8f672b71a1ecb65faa97aff34 | [
"MIT"
] | null | null | null | using advent._2019._1;
using System;
using System.Threading.Tasks;
using Xunit;
namespace advent._2019.tests
{
public class Day1Tests
{
[Theory]
[InlineData(12, 2)]
[InlineData(14, 2)]
[InlineData(1969, 654)]
[InlineData(100756, 33583)]
public void MassToFuel(ulong mass, ulong fuel)
{
var x = FuelCalculator.MassToFuel(mass);
Assert.Equal(fuel, x);
}
[Theory]
[InlineData("input_1_1", 3301059)]
public async Task Day_1_1(string inputFile, ulong answer)
{
var lines = LineReader.Open(inputFile);
var sum = await new FuelCalculator().SumFuel(lines);
Assert.Equal(answer, sum);
}
[Theory]
[InlineData(14, 2)]
[InlineData(1969, 966)]
[InlineData(100756, 50346)]
public void MassToFuel_Limit(ulong mass, ulong fuel)
{
var x = FuelCalculator.MassToFuel_Limit(mass);
Assert.Equal(fuel, x);
}
[Theory]
[InlineData("input_1_1", 4948732)]
public async Task Day_1_2(string inputFile, ulong answer)
{
var lines = LineReader.Open(inputFile);
var sum = await new FuelCalculator().SumFuel_Limit(lines);
Assert.Equal(answer, sum);
}
}
}
| 27.16 | 70 | 0.565538 |
8beb945897c134be4c09dc4fa3aec4a4547cff31 | 665 | swift | Swift | tempestclient/Controllers/Account/AccountsViewController.swift | chriskievit/tempest-reddit-client | 444775f8bc90c2e80da8b9807d5f1819a75d1f19 | [
"MIT"
] | null | null | null | tempestclient/Controllers/Account/AccountsViewController.swift | chriskievit/tempest-reddit-client | 444775f8bc90c2e80da8b9807d5f1819a75d1f19 | [
"MIT"
] | null | null | null | tempestclient/Controllers/Account/AccountsViewController.swift | chriskievit/tempest-reddit-client | 444775f8bc90c2e80da8b9807d5f1819a75d1f19 | [
"MIT"
] | null | null | null | //
// AccountsViewController.swift
// tempestclient
//
// Created by Chris on 15/08/2019.
// Copyright © 2019 Tempest. All rights reserved.
//
import Foundation
import Cocoa
class AccountsViewController: NSViewController, NSTableViewDataSource, NSTableViewDelegate {
@IBOutlet weak var tableView: NSTableView!
@IBAction func closeButtonPressed(_ sender: NSButton) {
if presentingViewController == nil {
view.window?.close()
} else {
dismiss(self)
}
}
@IBAction func addButtonPressed(_ sender: NSButton) {
}
@IBAction func removeButtonPressed(_ sender: NSButton) {
}
}
| 22.931034 | 92 | 0.66015 |
caac42c1af7432afdc11fb33b03b740d68281c93 | 780 | zsh | Shell | zsh/omz/mgmt.zsh | kevin-morgan/dotfiles | 2b7a1a614c3d13b12148d5869563f8e71f770204 | [
"MIT"
] | null | null | null | zsh/omz/mgmt.zsh | kevin-morgan/dotfiles | 2b7a1a614c3d13b12148d5869563f8e71f770204 | [
"MIT"
] | null | null | null | zsh/omz/mgmt.zsh | kevin-morgan/dotfiles | 2b7a1a614c3d13b12148d5869563f8e71f770204 | [
"MIT"
] | null | null | null | # ---------------------------------------------------------------------
# KEVIN'S OMZ V2015.04.03
# ---------------------------------------------------------------------
# ---------------------------------------------------------------------
# CONFIGURATION
# ---------------------------------------------------------------------
if [[ "$OSTYPE" = darwin* ]]; then
alias dots='st ~/.dotfiles'
alias reload='source ~/.zshrc && echo "sourced ~/.zshrc"'
else
alias dots='cd ~/.dotfiles && vim'
alias reload='source ~/.zshrc && echo "sourced ~/.zshrc"'
fi
# ---------------------------------------------------------------------
# HOSTS
# ---------------------------------------------------------------------
alias vhosts='sudo vi /etc/hosts'
alias shosts='st /etc/hosts'
| 32.5 | 71 | 0.285897 |
1fe521ba5498b34b9d878a60cfdee4280234b14f | 9,770 | lua | Lua | Engine/Includes/Lua/Modules/wxLua/samples/art.wx.lua | GCourtney27/Retina-Engine | 5358b9c499f4163a209024dc303c3efe6c520c01 | [
"MIT"
] | 141 | 2015-01-12T12:02:17.000Z | 2022-03-06T15:52:27.000Z | Engine/Includes/Lua/Modules/wxLua/samples/art.wx.lua | GCourtney27/Retina-Engine | 5358b9c499f4163a209024dc303c3efe6c520c01 | [
"MIT"
] | 15 | 2015-02-07T05:59:52.000Z | 2022-01-24T18:17:03.000Z | Engine/Includes/Lua/Modules/wxLua/samples/art.wx.lua | GCourtney27/Retina-Engine | 5358b9c499f4163a209024dc303c3efe6c520c01 | [
"MIT"
] | 72 | 2015-01-15T14:08:59.000Z | 2022-01-22T21:06:27.000Z | -----------------------------------------------------------------------------
-- Name: art.wx.lua
-- Purpose: wxArtProvider wxLua sample
-- Author: John Labenski
-- Modified by:
-- Created: 16/11/2012
-- Copyright: (c) 2012 John Labenski. All rights reserved.
-- Licence: wxWidgets licence
-----------------------------------------------------------------------------
-- Load the wxLua module, does nothing if running from wxLua, wxLuaFreeze, or wxLuaEdit
package.cpath = package.cpath..";./?.dll;./?.so;../lib/?.so;../lib/vc_dll/?.dll;../lib/bcc_dll/?.dll;../lib/mingw_dll/?.dll;"
require("wx")
-- --------------------------------------------------------------------------
frame = nil
-- --------------------------------------------------------------------------
-- Initialize the wxArtProvider variables
local artClients = {}
local artIds = {}
for k, v in pairs(wx) do
if (k:find("wxART_[A-Z_]*") ~= nil) then
-- wxArtClients values end with "_C"
if v:sub(-2,-1) == "_C" then
artClients[#artClients+1] = k
else
artIds[#artIds+1] = k
end
end
end
table.sort(artClients)
table.sort(artIds)
local char_width = nil -- cache value
local char_height = nil
local colLefts = nil
local colWidths = nil
local rowTops = nil
local rowHeights = nil
local did_set_scrollbars = false
-- --------------------------------------------------------------------------
-- paint event handler for the panel that's called by wxEVT_PAINT
function OnPaint(event)
-- must always create a wxPaintDC in a wxEVT_PAINT handler
local dc = wx.wxPaintDC(panel)
panel:PrepareDC(dc)
local row_height = 50
local x_padding = 10
-- Find the sizes of things for later
if not char_height then
local textExtentSize = dc:GetTextExtentSize("MMMM")
char_height = textExtentSize:GetHeight()/2
char_width = textExtentSize:GetWidth()/4
-- find the max width of the wxArtID strings
local col0_width = 0
for r = 1, #artIds do
local artIdTextExtent = dc:GetTextExtentSize(artIds[r])
local w = artIdTextExtent:GetWidth();
if w > col0_width then
col0_width = w
end
end
colWidths = {};
colWidths[0] = col0_width + x_padding
colLefts = {};
colLefts[0] = 0
colLefts[1] = colWidths[0]
rowHeights = {}
rowHeights[0] = 50
rowTops = {}
rowTops[0] = 0
rowTops[1] = rowHeights[0]
for c = 1, #artClients do
local artClientTextExtent = dc:GetTextExtentSize(artClients[c])
local w = artClientTextExtent:GetWidth();
colWidths[c] = w + x_padding
colLefts[c+1] = colLefts[c] + colWidths[c]
for r = 1, #artIds do
local artClient = wx[artClients[c]]
local artId = wx[artIds[r]]
local bmp = wx.wxArtProvider.GetBitmap(artId, artClient)
if bmp:Ok() then
local w, h = bmp:GetWidth(), bmp:GetHeight()
if (not rowHeights[r]) or (rowHeights[r] < h + 10) then
rowHeights[r] = h + 10
end
else
rowHeights[r] = 50
end
bmp:delete()
end
end
for r = 0, #rowHeights do
rowTops[r+1] = rowTops[r]+rowHeights[r]
end
rowTops[#rowTops+1] = rowTops[#rowTops] + rowHeights[#rowHeights]
end
dc:DrawText("wxArtID / wxArtClient", x_padding/2, rowHeights[0]/2-char_height/2)
for c = 0, #artClients do
for r = 0, #artIds do
local artClient = wx[artClients[c]]
local artId = wx[artIds[r]]
local row_top = rowTops[r+1]
local row_height = rowHeights[r]
if r == 0 then
if c > 0 then
dc:DrawText(artClients[c], colLefts[c]+x_padding/2, rowTops[r]+rowHeights[r]/2-char_height/2)
local artSizePlatform = wx.wxArtProvider.GetSizeHint(artClient, true)
local artSize = wx.wxArtProvider.GetSizeHint(artClient, false)
local art_size_platform_str = string.format("(%d, %d)", artSizePlatform:GetWidth(), artSizePlatform:GetHeight())
local art_size_str = string.format("(%d, %d)", artSize:GetWidth(), artSize:GetHeight())
local textExtentPlatformStr = dc:GetTextExtentSize(art_size_platform_str)
local textExtentSizeStr = dc:GetTextExtentSize(art_size_str)
dc:DrawText(art_size_platform_str,
colLefts[c]+colWidths[c]/2 - textExtentPlatformStr:GetWidth()/2 + x_padding/2,
rowTops[r+1] + (rowHeights[r+1]/2 - textExtentPlatformStr:GetHeight())/2 )
dc:DrawText(art_size_str,
colLefts[c]+colWidths[c]/2 - textExtentSizeStr:GetWidth()/2 + x_padding/2,
rowTops[r+1] + rowHeights[r+1]/2 + (rowHeights[r+1]/2 - textExtentSizeStr:GetHeight())/2 )
elseif c == 0 then
dc:DrawText("Native Size", x_padding/2, rowTops[r+1] + (rowHeights[r+1]/2 - char_height)/2 )
dc:DrawText("ArtProvider Size", x_padding/2, rowTops[r+1] + rowHeights[r+1]/2 + (rowHeights[r+1]/2 - char_height)/2 )
end
elseif c == 0 then
if r > 0 then
dc:DrawText(artId, colLefts[c]+x_padding/2, rowTops[r+1]+rowHeights[r]/2-char_height/2)
end
else
local bmp = wx.wxArtProvider.GetBitmap(artId, artClient)
if bmp:Ok() then
local w, h = bmp:GetWidth(), bmp:GetHeight()
dc:DrawBitmap(bmp, colLefts[c]+colWidths[c]/2-w/2, rowTops[r+1]+rowHeights[r]/2-h/2, true)
end
bmp:delete()
end
dc:DrawLine(colLefts[0], rowTops[r+1],
colLefts[#colLefts], rowTops[r+1])
end
dc:DrawLine(colLefts[c]+colWidths[c], 0,
colLefts[c]+colWidths[c], rowTops[#rowTops])
end
dc:DrawLine(colLefts[0], rowTops[#rowTops],
colLefts[#colLefts], rowTops[#rowTops])
if not did_set_scrollbars then
did_set_scrollbars = true
panel:SetScrollbars(20, 20,
math.ceil((colLefts[#colLefts]-10)/20),
math.ceil((rowTops[#rowTops])/20), 0, 0, false);
end
-- the paint DC will be automatically destroyed by the garbage collector,
-- however on Windows 9x/Me this may be too late (DC's are precious resource)
-- so delete it here
dc:delete() -- ALWAYS delete() any wxDCs created when done
end
-- Create a function to encapulate the code, not necessary, but it makes it
-- easier to debug in some cases.
function main()
-- create the wxFrame window
frame = wx.wxFrame( wx.NULL, -- no parent for toplevel windows
wx.wxID_ANY, -- don't need a wxWindow ID
"wxLua wxArtProvider Demo", -- caption on the frame
wx.wxDefaultPosition, -- let system place the frame
wx.wxSize(450, 450), -- set the size of the frame
wx.wxDEFAULT_FRAME_STYLE ) -- use default frame styles
-- create a single child window, wxWidgets will set the size to fill frame
panel = wx.wxScrolledWindow(frame, wx.wxID_ANY)
panel:SetScrollbars(200, 200, 20, 20, 0, 0, true);
-- connect the paint event handler function with the paint event
panel:Connect(wx.wxEVT_PAINT, OnPaint)
-- create a simple file menu
local fileMenu = wx.wxMenu()
fileMenu:Append(wx.wxID_EXIT, "E&xit", "Quit the program")
-- create a simple help menu
local helpMenu = wx.wxMenu()
helpMenu:Append(wx.wxID_ABOUT, "&About", "About the wxLua Minimal Application")
-- create a menu bar and append the file and help menus
local menuBar = wx.wxMenuBar()
menuBar:Append(fileMenu, "&File")
menuBar:Append(helpMenu, "&Help")
-- attach the menu bar into the frame
frame:SetMenuBar(menuBar)
-- create a simple status bar
frame:CreateStatusBar(1)
frame:SetStatusText("Welcome to wxLua.")
-- connect the selection event of the exit menu item to an
-- event handler that closes the window
frame:Connect(wx.wxID_EXIT, wx.wxEVT_COMMAND_MENU_SELECTED,
function (event) frame:Close(true) end )
-- connect the selection event of the about menu item
frame:Connect(wx.wxID_ABOUT, wx.wxEVT_COMMAND_MENU_SELECTED,
function (event)
wx.wxMessageBox('This is the "About" dialog of the Minimal wxLua sample.\n'..
wxlua.wxLUA_VERSION_STRING.." built with "..wx.wxVERSION_STRING,
"About wxLua",
wx.wxOK + wx.wxICON_INFORMATION,
frame)
end )
-- show the frame window
frame:Show(true)
end
main()
-- Call wx.wxGetApp():MainLoop() last to start the wxWidgets event loop,
-- otherwise the wxLua program will exit immediately.
-- Does nothing if running from wxLua, wxLuaFreeze, or wxLuaEdit since the
-- MainLoop is already running or will be started by the C++ program.
wx.wxGetApp():MainLoop()
| 38.464567 | 137 | 0.547185 |
8e5da304c23de36c35857a80868656d0f6c8c329 | 983 | js | JavaScript | lib/queue.js | neil176/node-postgres | 8d619cf4775c13c660578405e44166b3b8760ef6 | [
"MIT"
] | null | null | null | lib/queue.js | neil176/node-postgres | 8d619cf4775c13c660578405e44166b3b8760ef6 | [
"MIT"
] | null | null | null | lib/queue.js | neil176/node-postgres | 8d619cf4775c13c660578405e44166b3b8760ef6 | [
"MIT"
] | null | null | null |
function Queue(){
var queue = []
var offset = 0
// Preserve array length getter and setter
Object.defineProperty(this, 'length', {
get: function getLength() {
return queue.length - offset
},
set: function setLength(len) {
queue.length = len
},
})
this.push = function push(item) {
queue.push(item)
}
this.shift = function shift() {
var item = queue[offset]
// Prevent queue length from growing out of hand
if (++offset * 2 >= queue.length) {
// TODO: compare slice vs splice performance
// queue = queue.slice(offset)
queue = queue.splice(0, offset - 1)
offset = 0
}
return item
}
this.indexOf = function indexOf(val) {
for (var i = offset; i < queue.length; i++) {
if (val === queue[i]) {
return i - offset
}
}
return -1
}
this.splice = function splice(start, end) {
return queue.splice(offset + start, end)
}
}
module.exports = Queue
| 20.061224 | 52 | 0.583927 |
0cb9284c5d3124b1d907d7b3977867c08d95ecb9 | 168 | rb | Ruby | db/migrate/20160427194353_unset_loan_lenders_address_default.rb | NaturalHistoryMuseum/taxonworks | fadf26fb3218279f625c6ce85104e3d66891f964 | [
"NCSA"
] | 61 | 2015-04-16T14:26:35.000Z | 2022-03-17T13:31:06.000Z | db/migrate/20160427194353_unset_loan_lenders_address_default.rb | NaturalHistoryMuseum/taxonworks | fadf26fb3218279f625c6ce85104e3d66891f964 | [
"NCSA"
] | 2,768 | 2015-03-13T05:44:56.000Z | 2022-03-31T22:37:43.000Z | db/migrate/20160427194353_unset_loan_lenders_address_default.rb | NaturalHistoryMuseum/taxonworks | fadf26fb3218279f625c6ce85104e3d66891f964 | [
"NCSA"
] | 22 | 2015-02-26T12:10:18.000Z | 2021-12-08T18:47:26.000Z | class UnsetLoanLendersAddressDefault < ActiveRecord::Migration[4.2]
def change
change_column :loans, :lender_address, :text, default: nil, null: false
end
end
| 24 | 75 | 0.761905 |
14b46d73c82d3064b080c0d0731c5edd24861640 | 202 | ts | TypeScript | src/client/app/helloWorld/helloWorld.routes.ts | Alayode/ngjB | 1e3856edeac39a2e097e113e029bd71dfb6437e1 | [
"MIT"
] | null | null | null | src/client/app/helloWorld/helloWorld.routes.ts | Alayode/ngjB | 1e3856edeac39a2e097e113e029bd71dfb6437e1 | [
"MIT"
] | null | null | null | src/client/app/helloWorld/helloWorld.routes.ts | Alayode/ngjB | 1e3856edeac39a2e097e113e029bd71dfb6437e1 | [
"MIT"
] | null | null | null | import { Route } from '@angular/router';
import { HelloWorldComponent } from './index';
export const HelloWorldRoutes: Route[] = [
{
path: 'helloWorld',
component: HelloWorldComponent
}
];
| 20.2 | 46 | 0.673267 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.