identifier
stringlengths 42
383
| collection
stringclasses 1
value | open_type
stringclasses 1
value | license
stringlengths 0
1.81k
| date
float64 1.99k
2.02k
⌀ | title
stringlengths 0
100
| creator
stringlengths 1
39
| language
stringclasses 157
values | language_type
stringclasses 2
values | word_count
int64 1
20k
| token_count
int64 4
1.32M
| text
stringlengths 5
1.53M
| __index_level_0__
int64 0
57.5k
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|
https://github.com/YouenZeng/LeetCode/blob/master/LeetCode/Leets/MergeTwoListsSln.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
LeetCode
|
YouenZeng
|
C#
|
Code
| 65
| 215
|
using System;
namespace LeetCode.Leets
{
class MergeTwoListsSln : ISolution
{
public ListNode MergeTwoLists(ListNode l1, ListNode l2)
{
if (l1 == null)
{
return l2;
}
if (l2 == null)
{
return l1;
}
if (l1.val < l2.val)
{
l1.next = MergeTwoLists(l1.next, l2);
return l1;
}
else
{
l2.next = MergeTwoLists(l1, l2.next);
return l2;
}
}
public void Execute()
{
throw new NotImplementedException();
}
}
}
| 25,905
|
https://github.com/toowoxx/caddy2-confidentiality-index/blob/master/test.sh
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
caddy2-confidentiality-index
|
toowoxx
|
Shell
|
Code
| 7
| 24
|
#!/bin/sh
xcaddy run -config test/Caddyfile -adapter caddyfile
| 23,931
|
https://github.com/hramezani/django-axes/blob/master/axes/tests/test_logging.py
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
django-axes
|
hramezani
|
Python
|
Code
| 264
| 1,300
|
from unittest.mock import patch
from django.contrib.auth import authenticate
from django.http import HttpRequest
from django.test import override_settings
from django.urls import reverse
from axes.apps import AppConfig
from axes.models import AccessAttempt, AccessLog
from axes.tests.base import AxesTestCase
@patch('axes.apps.AppConfig.logging_initialized', False)
@patch('axes.apps.log')
class AppsTestCase(AxesTestCase):
def test_axes_config_log_re_entrant(self, log):
"""
Test that initialize call count does not increase on repeat calls.
"""
AppConfig.initialize()
calls = log.info.call_count
AppConfig.initialize()
self.assertTrue(
calls == log.info.call_count and calls > 0,
'AxesConfig.initialize needs to be re-entrant',
)
@override_settings(AXES_VERBOSE=False)
def test_axes_config_log_not_verbose(self, log):
AppConfig.initialize()
self.assertFalse(log.info.called)
@override_settings(AXES_ONLY_USER_FAILURES=True)
def test_axes_config_log_user_only(self, log):
AppConfig.initialize()
log.info.assert_called_with('AXES: blocking by username only.')
@override_settings(AXES_ONLY_USER_FAILURES=False)
def test_axes_config_log_ip_only(self, log):
AppConfig.initialize()
log.info.assert_called_with('AXES: blocking by IP only.')
@override_settings(AXES_LOCK_OUT_BY_COMBINATION_USER_AND_IP=True)
def test_axes_config_log_user_ip(self, log):
AppConfig.initialize()
log.info.assert_called_with('AXES: blocking by combination of username and IP.')
class AccessLogTestCase(AxesTestCase):
def test_access_log_on_logout(self):
"""
Test a valid logout and make sure the logout_time is updated.
"""
self.login(is_valid_username=True, is_valid_password=True)
self.assertIsNone(AccessLog.objects.latest('id').logout_time)
response = self.client.get(reverse('admin:logout'))
self.assertContains(response, 'Logged out')
self.assertIsNotNone(AccessLog.objects.latest('id').logout_time)
def test_log_data_truncated(self):
"""
Test that get_query_str properly truncates data to the max_length (default 1024).
"""
# An impossibly large post dict
extra_data = {'a' * x: x for x in range(1024)}
self.login(**extra_data)
self.assertEqual(
len(AccessAttempt.objects.latest('id').post_data), 1024
)
@override_settings(AXES_DISABLE_ACCESS_LOG=True)
def test_valid_logout_without_success_log(self):
AccessLog.objects.all().delete()
response = self.login(is_valid_username=True, is_valid_password=True)
response = self.client.get(reverse('admin:logout'))
self.assertEqual(AccessLog.objects.all().count(), 0)
self.assertContains(response, 'Logged out', html=True)
@override_settings(AXES_DISABLE_ACCESS_LOG=True)
def test_valid_login_without_success_log(self):
"""
Test that a valid login does not generate an AccessLog when DISABLE_SUCCESS_ACCESS_LOG is True.
"""
AccessLog.objects.all().delete()
response = self.login(is_valid_username=True, is_valid_password=True)
self.assertEqual(response.status_code, 302)
self.assertEqual(AccessLog.objects.all().count(), 0)
@override_settings(AXES_DISABLE_ACCESS_LOG=True)
def test_valid_logout_without_log(self):
AccessLog.objects.all().delete()
response = self.login(is_valid_username=True, is_valid_password=True)
response = self.client.get(reverse('admin:logout'))
self.assertEqual(AccessLog.objects.count(), 0)
self.assertContains(response, 'Logged out', html=True)
@override_settings(AXES_DISABLE_ACCESS_LOG=True)
def test_non_valid_login_without_log(self):
"""
Test that a non-valid login does generate an AccessLog when DISABLE_ACCESS_LOG is True.
"""
AccessLog.objects.all().delete()
response = self.login(is_valid_username=True, is_valid_password=False)
self.assertEqual(response.status_code, 200)
self.assertEqual(AccessLog.objects.all().count(), 0)
| 18,803
|
https://github.com/ops-trust/portal/blob/master/mycat.pl
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
portal
|
ops-trust
|
Perl
|
Code
| 203
| 443
|
#!/usr/bin/env perl
#
# This file is part of the Ops-T Portal.
#
# Copyright 2014 Operations Security Administration, 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.
#
use warnings;
use strict;
my $siteconfig = {};
my $file = undef;
my $filename = shift @ARGV;
open($file, "<$filename") || die "$filename: $!";
while (<$file>) {
chomp;
s/^\s+//go; # remove starting blanks
s/\s+$//go; # remove ending blanks
next if /^#/ || !length;
die "siteconfig($_) syntax error" unless /=/o;
$siteconfig->{$`} = eval $';
}
close($file);
while (<STDIN>) {
my $n = 100;
while (--$n > 0 && /\!(\w+)\!/) {
if (!defined($siteconfig->{$1})) {
die "Undefined siteconfig variable: $1";
}
$_ = $`.$siteconfig->{$1}.$';
}
die "expansion loop" if $n == 0;
print;
}
exit 0;
| 24,486
|
https://github.com/RoLiLab/tracking_microscope/blob/master/src/HDF5/hdf5replayer.h
|
Github Open Source
|
Open Source
|
MIT
| 2,017
|
tracking_microscope
|
RoLiLab
|
C++
|
Code
| 125
| 521
|
#ifndef HDF5REPLAYER_H
#define HDF5REPLAYER_H
#include <string>
#include <H5Cpp.h>
#include <H5Exception.h>
#include "hdf5imagereader.h"
#include "hdf5datareader.h"
#include "hdf5.h"
#include "hdf5_hl.h"
using namespace std;
using namespace H5;
class HDF5Replayer
{
public:
HDF5Replayer();
~HDF5Replayer();
HDF5ImageReader * imagereader_NIR;
HDF5ImageReader * imagereader_FLR;
HDF5DataReader * datareader;
int64_t totalframe_NIR;
int64_t totalframe_FLR;
int64_t curframe_NIR;
int64_t curframe_FLR;
int64_t stepframe;
int64_t offsetframe_FLR;
bool master_NIR; // master -> nir image frame number | false : master -> fluorescent image frame number
int64_t samplingtime_NIRus;
int64_t samplingtime_FLRus;
int64_t updatingtime_us;
int64_t currentplaytime_us;
int64_t currentplaytime_usMax;
bool openNIR(const char * hdf5_filename);
bool openFLR(const char * hdf5_filename);
bool openDATA(const char * hdf5_filename);
img_uint8 curNIRimg;
img_uint16 curFLRimg;
void update(void);
void updateNIR_add(int frameDiff);
void updateNIR(INT64 frame);
void updateNIR_time(INT64 _time_us);
void updateFLR_add(int frameDiff);
void updateFLR(INT64 frame);
void updateFLR_time(INT64 _time_us);
bool b_playing;
private:
};
#endif // HDF5REPLAYER_H
| 44,165
|
https://github.com/seanastephens/ts-rust-bridge/blob/master/packages/ts-rust-bridge-codegen/examples/simple.schema.ts
|
Github Open Source
|
Open Source
|
MIT
| null |
ts-rust-bridge
|
seanastephens
|
TypeScript
|
Code
| 120
| 350
|
import { Type } from '../src/schema';
const {
Alias,
Enum,
Tuple,
Struct,
Union,
Newtype,
Vec,
Str,
Bool,
Option,
F32,
U8,
U32
} = Type;
export const MyEnum = Enum('ONE', 'TWO', 'THREE');
const MyTuple = Tuple(Option(Bool), Vec(Str));
const NormalStruct = Struct({
a: U8,
tuple: MyTuple
});
const Message = Union({
Unit: null,
One: F32,
Two: [Option(Bool), U32],
VStruct: { id: Str, data: Str }
});
const Vec3 = Tuple(F32, F32, F32);
const Color = Tuple(U8, U8, U8);
const Figure = Struct({ dots: Vec(Vec3), colors: Vec(Color) });
const Container = Union({
Units: null,
JustNumber: U32,
Figures: Vec(Figure)
});
const NType = Newtype(U32);
const NewtypeAlias = Alias(NType);
export const exampleSchema = {
Message,
NType,
Container,
Color,
Figure,
Vec3,
NewtypeAlias,
NormalStruct,
MyEnum,
MyTuple
};
| 46,472
|
https://github.com/caralin3/review-site/blob/master/razzle/stories/react/SearchBar.stories.tsx
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
review-site
|
caralin3
|
TSX
|
Code
| 50
| 165
|
import React from 'react';
import { storiesOf } from '@storybook/react';
import { action } from '@storybook/addon-actions';
import { SearchBar } from '../../src/client/react/components';
storiesOf('Components|SearchBar', module)
.add('without query', () => (
<SearchBar
onChange={action('changed query')}
onSearch={action('search submitted')}
query=""
/>
))
.add('with query', () => (
<SearchBar
onChange={action('changed query')}
onSearch={action('search submitted')}
query="movie"
/>
));
| 2,278
|
https://github.com/jpgagnebmc/kmp-ssh/blob/master/kmp-ssh/src/jsExternal/fs.fs.link.module_node.kt
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
kmp-ssh
|
jpgagnebmc
|
Kotlin
|
Code
| 76
| 297
|
@file:JsQualifier("fs.link")
@file:Suppress("INTERFACE_WITH_SUPERCLASS", "OVERRIDING_FINAL_MEMBER", "RETURN_TYPE_MISMATCH_ON_OVERRIDE", "CONFLICTING_OVERLOADS")
package fs.link
import kotlin.js.*
import Buffer
import url.URL
external fun __promisify__(existingPath: String, newPath: String): Promise<Unit>
external fun __promisify__(existingPath: String, newPath: Buffer): Promise<Unit>
external fun __promisify__(existingPath: String, newPath: URL): Promise<Unit>
external fun __promisify__(existingPath: Buffer, newPath: String): Promise<Unit>
external fun __promisify__(existingPath: Buffer, newPath: Buffer): Promise<Unit>
external fun __promisify__(existingPath: Buffer, newPath: URL): Promise<Unit>
external fun __promisify__(existingPath: URL, newPath: String): Promise<Unit>
external fun __promisify__(existingPath: URL, newPath: Buffer): Promise<Unit>
external fun __promisify__(existingPath: URL, newPath: URL): Promise<Unit>
| 14,926
|
https://github.com/Mobile-Connect/.net_server_side_sdk/blob/master/mobile-connect-sdk/GSMA.MobileConnect/Cache/BaseCache.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
.net_server_side_sdk
|
Mobile-Connect
|
C#
|
Code
| 604
| 1,834
|
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using GSMA.MobileConnect.Discovery;
using GSMA.MobileConnect.Constants;
using GSMA.MobileConnect.Exceptions;
namespace GSMA.MobileConnect.Cache
{
/// <summary>
/// Base class for Discovery Caches that implements basic cache control mechanisms and type casting reducing the amount of implementation needed in each derived cache class
/// </summary>
public abstract class BaseCache : ICache
{
/// <summary>
/// Convenience field to return when a non-async Task returning method needs to return early
/// </summary>
protected static readonly Task _completedTask = Task.FromResult(Type.Missing);
/// <summary>
/// Values configured for the minimum and maximum configurable cache expiry times
/// </summary>
protected readonly Dictionary<Type, Tuple<TimeSpan?, TimeSpan?>> _cacheExpiryLimits = new Dictionary<Type, Tuple<TimeSpan?, TimeSpan?>>()
{
[typeof(ProviderMetadata)] = Tuple.Create<TimeSpan?, TimeSpan?>(TimeSpan.FromSeconds(60), TimeSpan.FromHours(24))
};
/// <summary>
/// Values configured for cache expiry times of types
/// </summary>
protected readonly Dictionary<Type, TimeSpan> _cacheExpiryTimes = new Dictionary<Type, TimeSpan>()
{
[typeof(ProviderMetadata)] = TimeSpan.FromSeconds(DefaultOptions.PROVIDER_METADATA_TTL_SECONDS),
};
/// <inheritdoc/>
public abstract bool IsEmpty { get; }
/// <inheritdoc/>
public async Task Add(string mcc, string mnc, DiscoveryResponse value)
{
if (string.IsNullOrEmpty(mcc) || string.IsNullOrEmpty(mnc))
{
return;
}
await Add(ConcatKey(mcc, mnc), value).ConfigureAwait(false);
}
/// <inheritdoc/>
public async Task Add<T>(string key, T value) where T : ICacheable
{
if (string.IsNullOrEmpty(key))
{
return;
}
value.TimeCachedUtc = DateTime.UtcNow;
Log.Info(() => $"Adding to cache key={key}");
await InternalAdd<T>(key, value).ConfigureAwait(false);
Log.Info(() => $"Key was added to cache key={key}");
}
/// <summary>
/// Add value to internal cache with given key
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="value"></param>
/// <returns></returns>
protected abstract Task InternalAdd<T>(string key, T value) where T : ICacheable;
/// <inheritdoc/>
public abstract Task Clear();
/// <inheritdoc/>
public async Task<DiscoveryResponse> Get(string mcc, string mnc)
{
if (string.IsNullOrEmpty(mcc) || string.IsNullOrEmpty(mnc))
{
return null;
}
var key = ConcatKey(mcc, mnc);
return await Get<DiscoveryResponse>(key);
}
public async Task<T> Remove<T>(string key)
{
if (! string.IsNullOrEmpty(key))
{
await Remove(key).ConfigureAwait(false);
}
return default(T);
}
/// <inheritdoc/>
public async Task<T> Get<T>(string key, bool removeIfExpired = true) where T : ICacheable
{
if (string.IsNullOrEmpty(key))
{
return default(T);
}
var response = await InternalGet<T>(key);
if (response == null)
{
return response;
}
response.Cached = true;
response.MarkExpired(CheckIsExpired(response));
if (removeIfExpired && response != null && response.HasExpired)
{
response = default(T);
await Remove(key).ConfigureAwait(false);
}
return response;
}
/// <summary>
/// Checks if a object has been cached past the defined caching time or if internally the object has been marked as expired
/// </summary>
/// <param name="value">Object to check for expiry</param>
/// <returns>True if the object has expired</returns>
protected bool CheckIsExpired(ICacheable value)
{
bool isExpired = false;
TimeSpan timeToExpire;
if (_cacheExpiryTimes.TryGetValue(value.GetType(), out timeToExpire))
{
isExpired = value.TimeCachedUtc.HasValue && value.TimeCachedUtc.Value.Add(timeToExpire) < DateTime.UtcNow;
}
return isExpired || value.HasExpired;
}
/// <summary>
/// Get value from internal cache with given key
/// </summary>
/// <typeparam name="T">Type to be returned from cache</typeparam>
/// <param name="key">Cache key to return</param>
/// <returns></returns>
protected abstract Task<T> InternalGet<T>(string key) where T : ICacheable;
/// <inheritdoc/>
public abstract Task Remove(string key);
/// <inheritdoc/>
public abstract Task Remove(string mcc, string mnc);
/// <summary>
/// Concatenates MCC and MNC into a single key
/// </summary>
/// <param name="mcc">Mobile Country Code</param>
/// <param name="mnc">Mobile Network Code</param>
/// <returns>Concatenated key</returns>
protected string ConcatKey(string mcc, string mnc)
{
return string.Format("{0}_{1}", mcc, mnc);
}
/// <inheritdoc/>
public void SetCacheExpiryTime<T>(TimeSpan cacheTime) where T : ICacheable
{
var type = typeof(T);
Tuple<TimeSpan?, TimeSpan?> limits;
if(!_cacheExpiryLimits.TryGetValue(type, out limits))
{
Log.Debug(() => $"Cache expiry time for was set, type={type.FullName} cacheTime={cacheTime}");
_cacheExpiryTimes[typeof(T)] = cacheTime;
return;
}
if ((limits.Item1.HasValue && limits.Item1.Value.CompareTo(cacheTime) > 0) ||
(limits.Item2.HasValue && limits.Item2.Value.CompareTo(cacheTime) < 0))
{
Log.Error(() => $"Attempt was made to set cache limit outside the allowed limits, type={type.FullName} cacheTime={cacheTime} lower={limits.Item1} upper={limits.Item2}");
throw new MobileConnectCacheExpiryLimitException(type, limits.Item1, limits.Item2);
}
_cacheExpiryTimes[typeof(T)] = cacheTime;
Log.Debug(() => $"Cache expiry time for was set, type={type.FullName} cacheTime={cacheTime}");
}
}
}
| 44,667
|
https://github.com/yanni4night/node-dns-window/blob/master/src/reducers/reverse.js
|
Github Open Source
|
Open Source
|
MIT
| null |
node-dns-window
|
yanni4night
|
JavaScript
|
Code
| 62
| 186
|
/**
* Copyright (C) 2016 yanni4night.com
* reverse.js
*
* changelog
* 2016-10-11[15:54:14]:revised
*
* @author [email protected]
* @version 0.1.0
* @since 0.1.0
*/
'use strict';
import * as T from '../action-types';
export function reversedAddress(state = [], action) {
if (T.ACTION_REVERSE_SUCCESS === action.type) {
return [...action.payload];
} else if (T.ACTION_REVERSE_FAILED === action.type) {
return [];
} else {
return state;
}
}
| 14,649
|
https://github.com/CaelestisZ/IrisCore/blob/master/drivers/usb/dwc3/dbm-1_4.c
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
IrisCore
|
CaelestisZ
|
C
|
Code
| 1,348
| 4,639
|
/*
* Copyright (c) 2012-2014, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include <linux/platform_device.h>
#include <linux/of.h>
#include <linux/module.h>
#include <linux/delay.h>
#include <linux/io.h>
#include "dbm.h"
/**
* USB DBM Hardware registers.
*
*/
#define DBM_EP_CFG(n) (0x00 + 4 * (n))
#define DBM_DATA_FIFO(n) (0x10 + 4 * (n))
#define DBM_DATA_FIFO_SIZE(n) (0x20 + 4 * (n))
#define DBM_DATA_FIFO_EN (0x30)
#define DBM_GEVNTADR (0x34)
#define DBM_GEVNTSIZ (0x38)
#define DBM_DBG_CNFG (0x3C)
#define DBM_HW_TRB0_EP(n) (0x40 + 4 * (n))
#define DBM_HW_TRB1_EP(n) (0x50 + 4 * (n))
#define DBM_HW_TRB2_EP(n) (0x60 + 4 * (n))
#define DBM_HW_TRB3_EP(n) (0x70 + 4 * (n))
#define DBM_PIPE_CFG (0x80)
#define DBM_SOFT_RESET (0x84)
#define DBM_GEN_CFG (0x88)
#define DBM_GEVNTADR_LSB (0x98)
#define DBM_GEVNTADR_MSB (0x9C)
#define DBM_DATA_FIFO_LSB(n) (0xA0 + 8 * (n))
#define DBM_DATA_FIFO_MSB(n) (0xA4 + 8 * (n))
#define DBM_1_4_NUM_EP 4
struct dbm_data {
void __iomem *base;
int dbm_num_eps;
u8 ep_num_mapping[DBM_1_4_NUM_EP];
};
static struct dbm_data *dbm_data;
/**
* Write register masked field with debug info.
*
* @base - DWC3 base virtual address.
* @offset - register offset.
* @mask - register bitmask.
* @val - value to write.
*
*/
static inline void msm_dbm_write_reg_field(void *base, u32 offset,
const u32 mask, u32 val)
{
u32 shift = find_first_bit((void *)&mask, 32);
u32 tmp = ioread32(base + offset);
tmp &= ~mask; /* clear written bits */
val = tmp | (val << shift);
iowrite32(val, base + offset);
}
/**
*
* Read register with debug info.
*
* @base - DWC3 base virtual address.
* @offset - register offset.
*
* @return u32
*/
static inline u32 msm_dbm_read_reg(void *base, u32 offset)
{
u32 val = ioread32(base + offset);
return val;
}
/**
*
* Write register with debug info.
*
* @base - DWC3 base virtual address.
* @offset - register offset.
* @val - value to write.
*
*/
static inline void msm_dbm_write_reg(void *base, u32 offset, u32 val)
{
iowrite32(val, base + offset);
}
/**
* Return DBM EP number according to usb endpoint number.
*
*/
static int msm_dbm_find_matching_dbm_ep(u8 usb_ep)
{
int i;
for (i = 0; i < dbm_data->dbm_num_eps; i++)
if (dbm_data->ep_num_mapping[i] == usb_ep)
return i;
pr_err("%s: No DBM EP matches USB EP %d", __func__, usb_ep);
return -ENODEV; /* Not found */
}
/**
* Reset the DBM registers upon initialization.
*
*/
static int soft_reset(bool reset)
{
pr_debug("%s DBM reset\n", (reset ? "Enter" : "Exit"));
msm_dbm_write_reg_field(dbm_data->base, DBM_SOFT_RESET,
DBM_SFT_RST_MASK, reset);
return 0;
}
/**
* Soft reset specific DBM ep.
* This function is called by the function driver upon events
* such as transfer aborting, USB re-enumeration and USB
* disconnection.
*
* @dbm_ep - DBM ep number.
* @enter_reset - should we enter a reset state or get out of it.
*
*/
static int ep_soft_reset(u8 dbm_ep, bool enter_reset)
{
pr_debug("Setting DBM ep %d reset to %d\n", dbm_ep, enter_reset);
if (dbm_ep >= dbm_data->dbm_num_eps) {
pr_err("Invalid DBM ep index %d\n", dbm_ep);
return -ENODEV;
}
if (enter_reset) {
msm_dbm_write_reg_field(dbm_data->base, DBM_SOFT_RESET,
DBM_SFT_RST_EPS_MASK & 1 << dbm_ep, 1);
} else {
msm_dbm_write_reg_field(dbm_data->base, DBM_SOFT_RESET,
DBM_SFT_RST_EPS_MASK & 1 << dbm_ep, 0);
}
return 0;
}
/**
* Soft reset specific DBM ep (by USB EP number).
* This function is called by the function driver upon events
* such as transfer aborting, USB re-enumeration and USB
* disconnection.
*
* The function relies on ep_soft_reset() for checking
* the legality of the resulting DBM ep number.
*
* @usb_ep - USB ep number.
* @enter_reset - should we enter a reset state or get out of it.
*
*/
static int usb_ep_soft_reset(u8 usb_ep, bool enter_reset)
{
int dbm_ep = msm_dbm_find_matching_dbm_ep(usb_ep);
pr_debug("Setting USB ep %d reset to %d\n", usb_ep, enter_reset);
return ep_soft_reset(dbm_ep, enter_reset);
}
/**
* Configure a USB DBM ep to work in BAM mode.
*
*
* @usb_ep - USB physical EP number.
* @producer - producer/consumer.
* @disable_wb - disable write back to system memory.
* @internal_mem - use internal USB memory for data fifo.
* @ioc - enable interrupt on completion.
*
* @return int - DBM ep number.
*/
static int ep_config(u8 usb_ep, u8 bam_pipe, bool producer, bool disable_wb,
bool internal_mem, bool ioc)
{
int dbm_ep;
u32 ep_cfg;
pr_debug("Configuring DBM ep\n");
dbm_ep = msm_dbm_find_matching_dbm_ep(usb_ep);
if (dbm_ep < 0) {
pr_err("usb ep index %d has no corresponding dbm ep\n", usb_ep);
return -ENODEV;
}
/* First, reset the dbm endpoint */
ep_soft_reset(dbm_ep, 0);
/* Set ioc bit for dbm_ep if needed */
msm_dbm_write_reg_field(dbm_data->base, DBM_DBG_CNFG,
DBM_ENABLE_IOC_MASK & 1 << dbm_ep, ioc ? 1 : 0);
ep_cfg = (producer ? DBM_PRODUCER : 0) |
(disable_wb ? DBM_DISABLE_WB : 0) |
(internal_mem ? DBM_INT_RAM_ACC : 0);
msm_dbm_write_reg_field(dbm_data->base, DBM_EP_CFG(dbm_ep),
DBM_PRODUCER | DBM_DISABLE_WB | DBM_INT_RAM_ACC, ep_cfg >> 8);
msm_dbm_write_reg_field(dbm_data->base, DBM_EP_CFG(dbm_ep), USB3_EPNUM,
usb_ep);
msm_dbm_write_reg_field(dbm_data->base, DBM_EP_CFG(dbm_ep),
DBM_BAM_PIPE_NUM, bam_pipe);
msm_dbm_write_reg_field(dbm_data->base, DBM_PIPE_CFG, 0x000000ff,
0xe4);
msm_dbm_write_reg_field(dbm_data->base, DBM_EP_CFG(dbm_ep), DBM_EN_EP,
1);
return dbm_ep;
}
/**
* Configure a USB DBM ep to work in normal mode.
*
* @usb_ep - USB ep number.
*
*/
static int ep_unconfig(u8 usb_ep)
{
int dbm_ep;
u32 data;
pr_debug("Unconfiguring DB ep\n");
dbm_ep = msm_dbm_find_matching_dbm_ep(usb_ep);
if (dbm_ep < 0) {
pr_err("usb ep index %d has no corresponding dbm ep\n", usb_ep);
return -ENODEV;
}
dbm_data->ep_num_mapping[dbm_ep] = 0;
data = msm_dbm_read_reg(dbm_data->base, DBM_EP_CFG(dbm_ep));
data &= (~0x1);
msm_dbm_write_reg(dbm_data->base, DBM_EP_CFG(dbm_ep), data);
/* Reset the dbm endpoint */
ep_soft_reset(dbm_ep, true);
/*
* 10 usec delay is required before deasserting DBM endpoint reset
* according to hardware programming guide.
*/
udelay(10);
ep_soft_reset(dbm_ep, false);
return 0;
}
/**
* Return number of configured DBM endpoints.
*
*/
static int get_num_of_eps_configured(void)
{
int i;
int count = 0;
for (i = 0; i < dbm_data->dbm_num_eps; i++)
if (dbm_data->ep_num_mapping[i])
count++;
return count;
}
/**
* Configure the DBM with the USB3 core event buffer.
* This function is called by the SNPS UDC upon initialization.
*
* @addr - address of the event buffer.
* @size - size of the event buffer.
*
*/
static int event_buffer_config(u32 addr_lo, u32 addr_hi, int size)
{
pr_debug("Configuring event buffer\n");
if (size < 0) {
pr_err("Invalid size. size = %d", size);
return -EINVAL;
}
if (sizeof(phys_addr_t) > sizeof(u32)) {
msm_dbm_write_reg(dbm_data->base, DBM_GEVNTADR_LSB, addr_lo);
msm_dbm_write_reg(dbm_data->base, DBM_GEVNTADR_MSB, addr_hi);
} else {
msm_dbm_write_reg(dbm_data->base, DBM_GEVNTADR, addr_lo);
}
msm_dbm_write_reg_field(dbm_data->base, DBM_GEVNTSIZ,
DBM_GEVNTSIZ_MASK, size);
return 0;
}
static int data_fifo_config(u8 dep_num, phys_addr_t addr,
u32 size, u8 dst_pipe_idx)
{
u8 dbm_ep;
dbm_ep = dst_pipe_idx;
dbm_data->ep_num_mapping[dbm_ep] = dep_num;
if (sizeof(addr) > sizeof(u32)) {
u32 lo = lower_32_bits(addr);
u32 hi = upper_32_bits(addr);
msm_dbm_write_reg(dbm_data->base,
DBM_DATA_FIFO_LSB(dbm_ep), lo);
msm_dbm_write_reg(dbm_data->base,
DBM_DATA_FIFO_MSB(dbm_ep), hi);
} else {
msm_dbm_write_reg(dbm_data->base,
DBM_DATA_FIFO(dbm_ep), addr);
}
msm_dbm_write_reg_field(dbm_data->base, DBM_DATA_FIFO_SIZE(dbm_ep),
DBM_DATA_FIFO_SIZE_MASK, size);
return 0;
}
static void set_speed(bool speed)
{
msm_dbm_write_reg(dbm_data->base, DBM_GEN_CFG, speed);
}
static bool reset_ep_after_lpm(void)
{
return false;
}
static void enable(void) {}
static int msm_dbm_probe(struct platform_device *pdev)
{
struct device *dev = &pdev->dev;
struct dbm *dbm;
struct resource *res;
int ret = 0;
dbm_data = devm_kzalloc(dev, sizeof(*dbm_data), GFP_KERNEL);
if (!dbm_data)
return -ENOMEM;
dbm_data->dbm_num_eps = DBM_1_4_NUM_EP;
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!res) {
dev_err(&pdev->dev, "missing memory base resource\n");
ret = -ENODEV;
goto free_dbm_data;
}
dbm_data->base = devm_ioremap_nocache(&pdev->dev, res->start,
resource_size(res));
if (!dbm_data->base) {
dev_err(&pdev->dev, "ioremap failed\n");
ret = -ENOMEM;
goto free_dbm_data;
}
dbm = devm_kzalloc(dev, sizeof(*dbm), GFP_KERNEL);
if (!dbm) {
dev_err(&pdev->dev, "not enough memory\n");
ret = -ENOMEM;
goto free_dbm_data;
}
dbm->dev = dev;
dbm->soft_reset = soft_reset;
dbm->ep_config = ep_config;
dbm->ep_unconfig = ep_unconfig;
dbm->get_num_of_eps_configured = get_num_of_eps_configured;
dbm->event_buffer_config = event_buffer_config;
dbm->data_fifo_config = data_fifo_config;
dbm->set_speed = set_speed;
dbm->enable = enable;
dbm->ep_soft_reset = usb_ep_soft_reset;
dbm->reset_ep_after_lpm = reset_ep_after_lpm;
platform_set_drvdata(pdev, dbm);
return usb_add_dbm(dbm);
free_dbm_data:
kfree(dbm_data);
return ret;
}
static int msm_dbm_remove(struct platform_device *pdev)
{
struct dbm *dbm = platform_get_drvdata(pdev);
kfree(dbm);
kfree(dbm_data);
return 0;
}
static const struct of_device_id msm_dbm_1_4_id_table[] = {
{
.compatible = "qcom,usb-dbm-1p4",
},
{ },
};
MODULE_DEVICE_TABLE(of, msm_dbm_1_4_id_table);
static struct platform_driver msm_dbm_driver = {
.probe = msm_dbm_probe,
.remove = msm_dbm_remove,
.driver = {
.name = "msm-usb-dbm-1-4",
.of_match_table = of_match_ptr(msm_dbm_1_4_id_table),
},
};
module_platform_driver(msm_dbm_driver);
MODULE_DESCRIPTION("MSM USB DBM 1.4 driver");
MODULE_LICENSE("GPL v2");
| 6,138
|
https://github.com/gero3/tern/blob/master/plugin/requirejs/requirejs.js
|
Github Open Source
|
Open Source
|
MIT
| null |
tern
|
gero3
|
JavaScript
|
Code
| 342
| 995
|
(function() {
var infer = typeof require == "undefined" ? window.tern : require("../../infer.js");
var tern = typeof require == "undefined" ? window.tern : require("../../tern.js");
function resolveName(name, data) {
var opts = data.options;
var base = opts.baseURL || "";
if (!opts.paths) return base + "/" + name + ".js";
var known = opts.paths[name];
if (known) return base + "/" + known + ".js";
var dir = name.match(/^([^\/]+)(\/.*)$/);
if (dir) {
var known = opts.paths[dir[0]];
if (known) return base + "/" + known + dir[1] + ".js";
}
return base + "/" + name + ".js";
}
function flattenPath(path) {
if (!/(^|\/)(\.\/|[^\/]+\/\.\.\/)/.test(path)) return path;
var parts = path.split("/");
for (var i = 0; i < parts.length; ++i) {
if (parts[i] == ".") parts.splice(i--, 1);
else if (i && parts[i] == "..") parts.splice(i-- - 1, 2);
}
return parts.join("/");
}
function getInterface(name, data) {
if (!/^(https?:|\/)|\.js$/.test(name))
name = resolveName(name, data);
name = flattenPath(name);
var known = data.interfaces[name];
if (!known) {
known = data.interfaces[name] = new infer.AVal;
data.parent.require(name);
}
return known;
}
infer.registerFunction("requireJS", function(_self, args, argNodes) {
var manager = infer.cx().parent, data = manager && manager._requireJS;
if (!data || !args.length) return infer.ANull;
var deps = [];
if (argNodes && args.length > 1) {
var node = argNodes[args.length == 2 ? 0 : 1];
if (node.type == "Literal" && typeof node.value == "string") {
deps.push(getInterface(node.value, data));
} else if (node.type == "ArrayExpression") for (var i = 0; i < node.elements.length; ++i) {
var elt = node.elements[i];
if (elt.type == "Literal" && typeof elt.value == "string") deps.push(getInterface(elt.value, data));
}
}
var value = args[Math.min(args.length - 1, 2)];
if (value.isEmpty() || value.getFunctionType()) {
var retval = new infer.AVal;
value.propagate(new infer.IsCallee(infer.ANull, deps, null, retval));
value = retval;
}
var names = data.currentFile, name = names[names.length - 1];
var known = data.interfaces[name];
if (!known) known = data.interfaces[name] = new infer.AVal;
value.propagate(known);
return infer.ANull;
});
tern.registerPlugin("requireJS", function(manager, options) {
manager._requireJS = {
interfaces: Object.create(null),
options: options || {},
currentFile: [],
parent: manager
};
manager.on("beforeLoad", function(file) {
this._requireJS.currentFile.push(file.name);
});
manager.on("afterLoad", function(file) {
this._requireJS.currentFile.pop();
});
manager.on("reset", function(file) {
this._requireJS.interfaces = Object.create(null);
});
});
})();
| 39,954
|
https://github.com/PisalPrasad123/pachyderm/blob/master/etc/btrfs/btrfs-mount.sh
|
Github Open Source
|
Open Source
|
LicenseRef-scancode-generic-cla, Apache-2.0
| 2,015
|
pachyderm
|
PisalPrasad123
|
Shell
|
Code
| 39
| 136
|
#!/bin/sh
set -Ee
if [ -z "${BTRFS_DEVICE}" ]; then
echo "error: BTRFS_DEVICE must be set" >&2
exit 1
fi
sudo modprobe loop
mkdir -p $(dirname "${BTRFS_DEVICE}")
truncate "${BTRFS_DEVICE}" -s 10G
mkfs.btrfs "${BTRFS_DEVICE}"
mkdir -p "${PFS_DRIVER_ROOT}"
mount "${BTRFS_DEVICE}" "${PFS_DRIVER_ROOT}"
$@
| 23,860
|
https://github.com/JonathanWilbur/x500-ts/blob/master/source/modules/UsefulDefinitions/id.va.ts
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
x500-ts
|
JonathanWilbur
|
TypeScript
|
Code
| 86
| 237
|
/* eslint-disable */
import { joint_iso_itu_t, ObjectIdentifier as _OID } from "asn1-ts";
import { ID } from "../UsefulDefinitions/ID.ta";
export { ID, _decode_ID, _encode_ID } from "../UsefulDefinitions/ID.ta";
/* START_OF_SYMBOL_DEFINITION id */
/**
* @summary id
* @description
*
* ### ASN.1 Definition:
*
* ```asn1
* id ID ::= {joint-iso-itu-t registration-procedures(17) module(1) directory-defs(2)}
* ```
*
* @constant
*/
export const id: ID = new _OID(
[/* registration-procedures */ 17, /* module */ 1, /* directory-defs */ 2],
joint_iso_itu_t
);
/* END_OF_SYMBOL_DEFINITION id */
/* eslint-enable */
| 22,069
|
https://github.com/jakec729/matheiken.com/blob/master/web/app/plugins/wp-migrate-db/template/wpmdb/progress-upgrade.php
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
matheiken.com
|
jakec729
|
PHP
|
Code
| 150
| 726
|
<div class="pro-version progress-overlay-container">
<div class="pro-version-content">
<h1><?php _e( 'Seen the PRO version yet?', 'wp-migrate-db' ); ?></h1>
<ul>
<li><span class="dashicons dashicons-yes"></span><?php _e( 'One-click in your WordPress dashboard to push your database up to staging/production or pull it down to dev', 'wp-migrate-db' ); ?></li>
<li><span class="dashicons dashicons-yes"></span><?php _e( 'Sync the Media Libraries of two sites', 'wp-migrate-db' ); ?></li>
<li><span class="dashicons dashicons-yes"></span><?php _e( 'Run migrations from the command line', 'wp-migrate-db' ); ?></li>
</ul>
<div class="pro-quote">
<p class="pro-quote-author">
MortenRandHendriksen @mor10
<a href="https://twitter.com/mor10/status/568514947241488384" title="View on Twitter.com" target="_blank" class="dashicons dashicons-twitter" ></a>
</p>
<p>“<?php _e( 'Even though I\'ve been using it for a long time the push/pull functionality in @dliciousbrains WP Migrate DB Pro continues to impress me.', 'wp-migrate-db' ); ?> ”</p>
<div class="stars"><span class="dashicons dashicons-star-filled"></span><span class="dashicons dashicons-star-filled"></span><span class="dashicons dashicons-star-filled"></span><span class="dashicons dashicons-star-filled"></span><span class="dashicons dashicons-star-filled"></span></div>
</div>
</div>
<div class="iframe">
<iframe width="515" height="289" src="//www.youtube.com/embed/fHFcH4bCzmU?rel=0&showinfo=0&autoplay=0&wmode=transparent&theme=light" frameborder="0" allowfullscreen></iframe>
</div>
<a class="button" href="https://deliciousbrains.com/wp-migrate-db-pro/?utm_source=insideplugin&utm_medium=web&utm_content=progress-bar&utm_campaign=freeplugin" target="_blank"><?php _e( 'More About The Pro Version', 'wp-migrate-db' ); ?> →</a>
<span class="close-pro-version close-pro-version-button" >×</span>
</div>
| 6,733
|
https://github.com/trailheadapps/apex-recipes/blob/master/force-app/tests/Async Apex Recipes/QueueableWithCalloutRecipes_Tests.cls
|
Github Open Source
|
Open Source
|
LicenseRef-scancode-unknown-license-reference, CC0-1.0
| 2,023
|
apex-recipes
|
trailheadapps
|
Apex
|
Code
| 135
| 513
|
@isTest
private inherited sharing class QueueableWithCalloutRecipes_Tests {
@TestSetup
static void makeData() {
TestFactory.createSObjectList(new Account(), 200, true);
}
@isTest
static void testQueueableWithCalloutRecipesPositive() {
HttpCalloutMockFactory httpMock = new HttpCalloutMockFactory(
200,
'OK',
'Success',
new Map<String, String>()
);
Test.setMock(HttpCalloutMock.class, httpMock);
Test.startTest();
QueueableWithCalloutRecipes queueable = new QueueableWithCalloutRecipes();
System.enqueueJob(queueable);
Test.stopTest();
List<Account> checkAccounts = [SELECT Description FROM Account];
System.Assert.areEqual(
200,
checkAccounts.size(),
'Expected to find 200 accounts'
);
for (Account account : checkAccounts) {
System.Assert.isTrue(
account.Description.containsIgnoreCase('200'),
'Expected to find all accounts\'s to have been edited to include edited by queueable class'
);
}
}
@isTest
static void testQueuableWithCalloutNegativeDMLError() {
HttpCalloutMockFactory httpMock = new HttpCalloutMockFactory(
200,
'OK',
'Success',
new Map<String, String>()
);
Test.setMock(HttpCalloutMock.class, httpMock);
QueueableWithCalloutRecipes.throwError = true;
Id enqueuedJobId;
QueueableWithCalloutRecipes queueable = new QueueableWithCalloutRecipes();
Test.startTest();
enqueuedJobId = System.enqueueJob(queueable);
Test.stopTest();
System.Assert.isTrue(
QueueableWithCalloutRecipes.circuitBreakerThrown,
'Expected the test code to have tripped the circuit breaker'
);
}
}
| 2,507
|
https://github.com/ksu-lanceb/minwiki2-onedrive/blob/master/wiki.d
|
Github Open Source
|
Open Source
|
BSL-1.0
| 2,021
|
minwiki2-onedrive
|
ksu-lanceb
|
D
|
Code
| 698
| 2,247
|
import arsd.cgi;
import minwiki.replacelinks, minwiki.staticsite;
import dmarkdown.markdown;
import std.file, std.path, std.process, std.regex, std.stdio;
/*
* Set the text editor used to edit/create pages.
* The `-i` option tells Geany to open a new editor.
* When you edit a page, the web server will wait until the editor
* is closed before it continues. If you open the file in
* an already running editor, you'll have to close that editor
* before you can continue.
*/
enum _editor = "geany -i";
//~ enum _remote = "fastmail:lanceb.fastmail.com/files";
enum _remote = "onedrive:wiki";
// Change markdown parsing options here
MarkdownFlags _mdflags = MarkdownFlags.backtickCodeBlocks|MarkdownFlags.disableUnderscoreEmphasis;
void hello(Cgi cgi) {
string data;
if (cgi.pathInfo == "/") {
if (!exists("index.md")) {
std.file.write("index.md", "# Index Page\n\nThis is the starting point for your wiki. Click the link above to edit.");
executeShell("rclone copy index.md " ~ _remote);
}
data = mdToHtml(readText("index.md"), "index");
}
else if (cgi.pathInfo == "/editpage") {
string name = cgi.get["name"];
executeShell(_editor ~ " '" ~ setExtension(name, "md'"));
executeShell("rclone copy '" ~ name ~ ".md' " ~ _remote);
cgi.setResponseLocation("viewpage?name=" ~ name);
data = mdToHtml(readText(setExtension(name, "md")), name);
}
else if (cgi.pathInfo == "/viewpage") {
string name = cgi.get["name"];
executeShell("rclone copy " ~ _remote ~ " '" ~ name ~ ".md' .");
if (!exists(setExtension(name, "md"))) {
executeShell(_editor ~ " '" ~ setExtension(name, "md") ~ "'");
executeShell("rclone copy '" ~ name ~ ".md' " ~ _remote);
}
data = mdToHtml(readText(setExtension(name, "md")) ~ "\n\n" ~ `<br><a href="/"><u>« Index</u></a>`, name);
}
else if (cgi.pathInfo == "/tag") {
string tagname = cgi.get["tagname"];
data = plainHtml("<h1>Tag: " ~ tagname ~ "</h1>\n" ~ fileLinks(executeShell(`grep -Rl '#` ~ tagname ~ `'`).output));
}
else if (cgi.pathInfo == "/backlinks") {
string pagename = cgi.get["pagename"];
string cmd = `grep -Rl '\[#` ~ pagename ~ `\]'`;
data = plainHtml(`<h1>Backlinks: <a href="viewpage?name=` ~ pagename ~ `">` ~ pagename ~ "</a></h1>\n" ~ fileLinks(executeShell(cmd).output) ~ "<hr><br>" ~ mdToHtml(readText(pagename ~ ".md"), pagename) ~ "<hr><br><br>");
}
else if (cgi.pathInfo == "/save") {
string name = cgi.get["name"];
std.file.write(setExtension(name, "html"), htmlPage(readText(setExtension(name, "md")), name));
cgi.setResponseLocation("/viewpage?name=" ~ name);
}
else if (cgi.pathInfo == "/staticsite") {
string[][string] tags;
foreach(f; listmd()) {
string pagename = stripExtension(f);
string txt = readText(setExtension(f, "md"));
string cmd = `grep -Rl '\[#` ~ pagename ~ `\]'`;
string bl = "<h3 style='font-size: 89%;'>Backlinks</h3>\n" ~ fileLinks(executeShell(cmd).output) ~ "<br><br><br>";
std.file.write(setExtension(f, "html"), htmlPage(txt, f) ~ bl);
auto tagMatches = txt.matchAll(regex(`(?<=^|<br>|\s)(#)([a-zA-Z][a-zA-Z0-9]*?)(?=<br>|\s|$)`, "m"));
foreach(tag; tagMatches) {
string taghit = tag.hit[1..$];
if (taghit in tags) {
tags[taghit] ~= stripExtension(baseName(f));
} else {
tags[taghit] = [stripExtension(baseName(f))];
}
}
}
std.file.write("tags.html", tagsBody(tags));
data = `HTML files written to disk<br><br><a href="/">Index</a>`;
}
cgi.write(data, true);
}
mixin GenericMain!hello;
string fileLinks(string output) {
if (output.length == 0) {
return "";
} else {
string result;
string[] files = output.split("\n");
foreach(file; files) {
if (file.length > 0) {
result ~= `<a href="viewpage?name=` ~ stripExtension(file) ~ `">` ~ stripExtension(file) ~ "<a><br>\n";
}
}
return result;
}
}
string mdToHtml(string s, string name) {
string mdfile = changeLinks(`<a href="/">❖ Home</a> <a href="editpage?name=` ~ name ~ `">✎ Edit</a> <a href="backlinks?pagename=` ~ name ~ `">➥ Backlinks</a> <a href="save?name=` ~ name ~ `">⇩ Save As HTML</a><br><br>` ~ "\n\n" ~ s);
return plaincss ~ mdfile.filterMarkdown(_mdflags);
}
string htmlPage(string s, string name) {
string mdfile = staticLinks(`<a href="index.html">❖ Home</a><br><br>` ~ "\n\n" ~ s);
return plaincss ~ mdfile.filterMarkdown(_mdflags);
}
string plainHtml(string s) {
return plaincss ~ s.filterMarkdown(_mdflags);
}
string[] listmd() {
import std.algorithm, std.array;
return std.file.dirEntries(".", SpanMode.shallow)
.filter!(a => a.isFile)
.filter!(a => extension(a) == ".md")
.map!(a => std.path.baseName(a.name))
.array
.sort!"a < b"
.array;
}
string tagsBody(string[][string] tags) {
string result = `<body onhashchange="displaytag();">
`;
foreach(tag; tags.keys) {
result ~= `<div id='` ~ tag ~ `' class='tag'>
<h1>Tag: ` ~ tag ~ `</h1>
`;
foreach(file; tags[tag]) {
result ~= `<a href="` ~ setExtension(file, "html") ~ `">` ~ stripExtension(file) ~ "</a>\n<br>";
}
result ~= "</div>";
}
return result ~ `</body>
<script>function displaytag() {
for (el of document.getElementsByClassName('tag')) {
el.style = 'display: none;';
}
document.getElementById(location.hash.substr(1)).style.display = "inline";
}
displaytag();
</script>`;
}
enum plaincss = `<style>
body { margin: auto; max-width: 800px; font-size: 120%; margin-top: 20px; }
a { text-decoration: none; }
pre > code {
padding: .2rem .5rem;
margin: 0 .2rem;
font-size: 90%;
white-space: nowrap;
background: #F1F1F1;
border: 1px solid #E1E1E1;
border-radius: 4px;
display: block;
padding: 1rem 1.5rem;
white-space: pre;
}
h1, h2, h3 { font-family: sans; font-size: 140%; }
</style>`;
| 23,565
|
https://github.com/leandrogaspar/microblog/blob/master/middleware/authenticate.js
|
Github Open Source
|
Open Source
|
MIT
| 2,018
|
microblog
|
leandrogaspar
|
JavaScript
|
Code
| 53
| 133
|
const { User } = require('./../models/user')
async function authenticate (req, res, next) {
try {
const token = req.header('x-auth')
if (!token) throw new Error('No auth header')
const user = await User.findByToken(token)
if (!user) throw new Error('Not authenticated')
req.user = user
next()
} catch (e) {
res.status(401).send()
}
}
module.exports = { authenticate }
| 40,826
|
https://github.com/vmichalak/kotlin/blob/master/kotlin-native/backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/llvm/linkModules.kt
|
Github Open Source
|
Open Source
|
Apache-2.0, LicenseRef-scancode-unknown-license-reference
| 2,022
|
kotlin
|
vmichalak
|
Kotlin
|
Code
| 136
| 383
|
/*
* Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.backend.konan.llvm
import llvm.*
import org.jetbrains.kotlin.backend.konan.Context
import org.jetbrains.kotlin.backend.konan.NativeGenerationState
internal fun llvmLinkModules2(generationState: NativeGenerationState, dest: LLVMModuleRef, src: LLVMModuleRef): LLVMBool {
val diagnosticHandler = DefaultLlvmDiagnosticHandler(generationState.context, object : DefaultLlvmDiagnosticHandler.Policy {
override fun suppressWarning(diagnostic: LlvmDiagnostic): Boolean {
if (super.suppressWarning(diagnostic)) return true
// Workaround https://youtrack.jetbrains.com/issue/KT-35001.
// Note: SDK version mismatch is generally harmless.
// Also it is expected: LLVM bitcode can be built in different environments with different SDK versions,
// and then linked by the compiler altogether.
// Just ignore such warnings for now:
if (diagnostic.message.startsWith("linking module flags 'SDK Version': IDs have conflicting values")) return true
return false
}
})
return withLlvmDiagnosticHandler(generationState.llvmContext, diagnosticHandler) {
LLVMLinkModules2(dest, src)
}
}
| 20,993
|
https://github.com/DORAdreamless/Dapper.AutoMigrate/blob/master/src/Tiantianquan.Common/Tiantianquan.Common/Extensions/DateTimeExtensions.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
Dapper.AutoMigrate
|
DORAdreamless
|
C#
|
Code
| 103
| 282
|
using System;
using Tiantianquan.Common.Utils;
namespace Tiantianquan.Common.Extensions {
/// <summary>
/// Date time extension methods
/// </summary>
public static class DateTimeExtensions {
/// <summary>
/// Truncate datetime, only keep seconds
/// </summary>
/// <param name="time">The time</param>
/// <returns></returns>
public static DateTime Truncate(this DateTime time) {
return time.AddTicks(-(time.Ticks % TimeSpan.TicksPerSecond));
}
/// <summary>
/// Return unix style timestamp
/// Return a minus value if the time early than 1970-1-1
/// The given time will be converted to UTC time first
/// </summary>
/// <param name="time">The time</param>
/// <returns></returns>
public static TimeSpan ToTimestamp(this DateTime time) {
return time.ToUniversalTime() - new DateTime(1970, 1, 1);
}
}
}
| 26,727
|
https://github.com/ladaas99/WarframeMarketAnalyzer/blob/master/WarframeMarketAnalyzer/src/enums/comparable/interfaces/ComparableByValue.java
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
WarframeMarketAnalyzer
|
ladaas99
|
Java
|
Code
| 15
| 44
|
package enums.comparable.interfaces;
public interface ComparableByValue<T>{
public abstract T getValue();
public abstract boolean valueEquals(T object);
}
| 48,762
|
https://github.com/archerax/etp-devkit/blob/master/src/DevKit/WebSocket4Net/EtpClient.cs
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
etp-devkit
|
archerax
|
C#
|
Code
| 1,247
| 3,452
|
//-----------------------------------------------------------------------
// ETP DevKit, 1.2
//
// Copyright 2018 Energistics
//
// 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 System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Energistics.Etp.Common;
using Energistics.Etp.Common.Datatypes;
using Energistics.Etp.Properties;
using SuperSocket.ClientEngine;
using WebSocket4Net;
namespace Energistics.Etp.WebSocket4Net
{
/// <summary>
/// A wrapper for the WebSocket4Net library providing client connectivity to an ETP server.
/// </summary>
/// <seealso cref="Energistics.Etp.Common.EtpSession" />
public class EtpClient : EtpSession, IEtpClient
{
private static readonly IDictionary<string, string> EmptyHeaders = new Dictionary<string, string>();
private static readonly IDictionary<string, string> BinaryHeaders = new Dictionary<string, string>()
{
{ Settings.Default.EtpEncodingHeader, Settings.Default.EtpEncodingBinary }
};
private WebSocket _socket;
private string _supportedCompression;
/// <summary>
/// Initializes a new instance of the <see cref="EtpClient" /> class.
/// </summary>
/// <param name="uri">The ETP server URI.</param>
/// <param name="application">The client application name.</param>
/// <param name="version">The client application version.</param>
/// <param name="etpSubProtocol">The ETP sub protocol.</param>
public EtpClient(string uri, string application, string version, string etpSubProtocol) : this(uri, application, version, etpSubProtocol, EmptyHeaders)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="EtpClient"/> class.
/// </summary>
/// <param name="uri">The ETP server URI.</param>
/// <param name="application">The client application name.</param>
/// <param name="version">The client application version.</param>
/// <param name="etpSubProtocol">The ETP sub protocol.</param>
/// <param name="headers">The WebSocket headers.</param>
public EtpClient(string uri, string application, string version, string etpSubProtocol, IDictionary<string, string> headers)
: base(EtpWebSocketValidation.GetEtpVersion(etpSubProtocol), application, version, headers, true)
{
var headerItems = Headers.Union(BinaryHeaders.Where(x => !Headers.ContainsKey(x.Key))).ToList();
_socket = new WebSocket(uri,
subProtocol: etpSubProtocol,
cookies: null,
customHeaderItems: headerItems,
userAgent: application);
}
/// <summary>
/// Gets a value indicating whether the connection is open.
/// </summary>
/// <value>
/// <c>true</c> if the connection is open; otherwise, <c>false</c>.
/// </value>
public override bool IsOpen => (_socket?.State ?? WebSocketState.None) == WebSocketState.Open;
/// <summary>
/// Opens the WebSocket connection.
/// </summary>
public void Open()
{
OpenAsync().Wait();
}
/// <summary>
/// Asynchronously opens the WebSocket connection.
/// </summary>
public async Task<bool> OpenAsync()
{
if (IsOpen) return true;
Logger.Trace(Log("Opening web socket connection..."));
bool result = false;
Exception ex = null;
var task = new Task<bool>(() => { if (ex != null) { throw ex; } return result; });
EventHandler openHandler = null;
EventHandler closedHandler = null;
EventHandler<ErrorEventArgs> errorHandler = null;
Action clearHandlers = () =>
{
_socket.Opened -= openHandler;
_socket.Closed -= closedHandler;
_socket.Error -= errorHandler;
};
bool handled = false;
openHandler = (s, e) =>
{
if (!handled)
{
handled = true;
clearHandlers();
SubscribeToSocketEvents();
OnWebSocketOpened();
result = true;
task.Start();
}
};
closedHandler = (s, e) =>
{
if (!handled)
{
handled = true;
clearHandlers();
task.Start();
}
};
errorHandler = (s, e) =>
{
if (!handled)
{
handled = true;
clearHandlers();
handled = true;
ex = e.Exception;
task.Start();
}
};
_socket.Opened += openHandler;
_socket.Closed += closedHandler;
_socket.Error += errorHandler;
_socket.Open();
return await task;
}
/// <summary>
/// Subscribes to socket events.
/// </summary>
private void SubscribeToSocketEvents()
{
_socket.Closed += OnWebSocketClosed;
_socket.DataReceived += OnWebSocketDataReceived;
_socket.MessageReceived += OnWebSocketMessageReceived;
_socket.Error += OnWebSocketError;
}
/// <summary>
/// Unsubscribes from socket events.
/// </summary>
private void UnsubscribeFromSocketEvents()
{
_socket.Closed -= OnWebSocketClosed;
_socket.DataReceived -= OnWebSocketDataReceived;
_socket.MessageReceived -= OnWebSocketMessageReceived;
_socket.Error -= OnWebSocketError;
}
/// <summary>
/// Asynchronously closes the WebSocket connection for the specified reason.
/// </summary>
/// <param name="reason">The reason.</param>
protected override async Task CloseAsyncCore(string reason)
{
if (!IsOpen) return;
Logger.Trace(Log("Closing web socket connection: {0}", reason));
bool result = false;
Exception ex = null;
var task = new Task<bool>(() => { if (ex != null) { throw ex; } return result; });
EventHandler closedHandler = null;
EventHandler<ErrorEventArgs> errorHandler = null;
Action clearHandlers = () =>
{
_socket.Closed -= closedHandler;
_socket.Error -= errorHandler;
};
bool handled = false;
closedHandler = (s, e) =>
{
if (!handled)
{
handled = true;
clearHandlers();
handled = true;
OnWebSocketClosed(s, e);
result = true;
task.Start();
}
};
errorHandler = (s, e) =>
{
if (!handled)
{
handled = true;
clearHandlers();
if (e.Exception.ExceptionMeansConnectionTerminated())
result = true;
else
ex = e.Exception;
task.Start();
}
};
_socket.Closed += closedHandler;
_socket.Error += errorHandler;
UnsubscribeFromSocketEvents();
_socket.Close(reason);
await task;
}
/// <summary>
/// Occurs when the WebSocket is opened.
/// </summary>
public event EventHandler SocketOpened
{
add { _socket.Opened += value; }
remove { _socket.Opened -= value; }
}
/// <summary>
/// Occurs when the WebSocket is closed.
/// </summary>
public event EventHandler SocketClosed
{
add { _socket.Closed += value; }
remove { _socket.Closed -= value; }
}
/// <summary>
/// Occurs when the WebSocket has an error.
/// </summary>
public event EventHandler<Exception> SocketError;
/// <summary>
/// Sets the proxy server host name and port number.
/// </summary>
/// <param name="host">The host name.</param>
/// <param name="port">The port number.</param>
/// <param name="username">The username.</param>
/// <param name="password">The password.</param>
public void SetProxy(string host, int port, string username = null, string password = null)
{
if (_socket == null) return;
var endPoint = new DnsEndPoint(host, port);
var headers = Security.Authorization.Basic(username, password);
_socket.Proxy = new Energistics.Etp.WebSocket4Net.HttpConnectProxy(endPoint, headers[Security.Authorization.Header]);
}
/// <summary>
/// Sets the supported compression type, e.g. gzip.
/// </summary>
/// <param name="supportedCompression">The supported compression.</param>
public void SetSupportedCompression(string supportedCompression)
{
_supportedCompression = supportedCompression;
}
/// <summary>
/// Sends the specified data.
/// </summary>
/// <param name="data">The data.</param>
/// <param name="offset">The offset.</param>
/// <param name="length">The length.</param>
protected override Task SendAsync(byte[] data, int offset, int length)
{
CheckDisposed();
// Queues message internally. No way to know when it has actually been sent.
_socket.Send(data, offset, length);
return Task.FromResult(true);
}
/// <summary>
/// Sends the specified messages.
/// </summary>
/// <param name="message">The message.</param>
protected override Task SendAsync(string message)
{
CheckDisposed();
// Queues message internally. No way to know when it has actually been sent.
_socket.Send(message);
return Task.FromResult(true);
}
/// <summary>
/// Handles the unsupported protocols.
/// </summary>
/// <param name="supportedProtocols">The supported protocols.</param>
protected override void HandleUnsupportedProtocols(IList<ISupportedProtocol> supportedProtocols)
{
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources.
/// </summary>
/// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
protected override void Dispose(bool disposing)
{
if (disposing)
{
UnsubscribeFromSocketEvents();
Close("Shutting down");
_socket?.Dispose();
}
base.Dispose(disposing);
_socket = null;
}
/// <summary>
/// Called when the WebSocket is opened.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
private void OnWebSocketOpened()
{
Logger.Trace(Log("[{0}] Socket opened.", SessionId));
Adapter.RequestSession(this, ApplicationName, ApplicationVersion, _supportedCompression);
}
/// <summary>
/// Called when the WebSocket is closed.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
private void OnWebSocketClosed(object sender, EventArgs e)
{
Logger.Trace(Log("[{0}] Socket closed.", SessionId));
SessionId = null;
}
/// <summary>
/// Called when WebSocket data is received.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="DataReceivedEventArgs"/> instance containing the event data.</param>
private void OnWebSocketDataReceived(object sender, DataReceivedEventArgs e)
{
OnDataReceived(e.Data);
}
/// <summary>
/// Called when a WebSocket message is received.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="MessageReceivedEventArgs"/> instance containing the event data.</param>
private void OnWebSocketMessageReceived(object sender, MessageReceivedEventArgs e)
{
OnMessageReceived(e.Message);
}
/// <summary>
/// Called when an error is raised by the WebSocket.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="ErrorEventArgs"/> instance containing the event data.</param>
private void OnWebSocketError(object sender, ErrorEventArgs e)
{
Logger.Debug(Log("[{0}] Socket error: {1}", SessionId, e.Exception.Message), e.Exception);
SocketError?.Invoke(this, e.Exception);
}
}
}
| 29,420
|
https://github.com/samdqa/crackingthecodinginterview/blob/master/src/main/java/chapter7_objectorienteddesign/Q7_04_Parking_Lot/Motorcycle.java
|
Github Open Source
|
Open Source
|
MIT
| null |
crackingthecodinginterview
|
samdqa
|
Java
|
Code
| 33
| 115
|
package chapter7_objectorienteddesign.Q7_04_Parking_Lot;
public class Motorcycle extends Vehicle {
public Motorcycle() {
spotsNeeded = 1;
size = VehicleSize.Motorcycle;
}
public boolean canFitInSpot(ParkingSpot spot) {
return true;
}
public void print() {
System.out.print("M");
}
}
| 9,067
|
https://github.com/shadow-42/ring/blob/master/src/qt/hivedialog.cpp
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
ring
|
shadow-42
|
C++
|
Code
| 1,236
| 6,180
|
// Copyright (c) 2011-2017 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
// Ring-fork: Hive
#include <wallet/wallet.h>
#include <wallet/fees.h>
#include <qt/hivedialog.h>
#include <qt/forms/ui_hivedialog.h>
#include <qt/clientmodel.h>
#include <qt/sendcoinsdialog.h>
#include <qt/addressbookpage.h>
#include <qt/addresstablemodel.h>
#include <qt/ringunits.h>
#include <qt/optionsmodel.h>
#include <qt/platformstyle.h>
#include <qt/receiverequestdialog.h>
#include <qt/hivetablemodel.h>
#include <qt/walletmodel.h>
#include <qt/tinypie.h>
#include <qt/qcustomplot.h>
#include <qt/optionsdialog.h> // Ring-fork: Hive: Mining optimisations
#include <QAction>
#include <QCursor>
#include <QMessageBox>
#include <QScrollBar>
#include <QTextDocument>
#include <validation.h>
#include <chainparams.h>
HiveDialog::HiveDialog(const PlatformStyle *_platformStyle, QWidget *parent) :
QDialog(parent),
ui(new Ui::HiveDialog),
columnResizingFixer(0),
model(0),
platformStyle(_platformStyle)
{
ui->setupUi(this);
dwarfCost = totalCost = rewardsPaid = cost = profit = 0;
immature = mature = dead = blocksFound = 0;
lastGlobalCheckHeight = 0;
potentialRewards = 0;
currentBalance = 0;
dwarfPopIndex = 0;
ui->globalHiveSummaryError->hide();
ui->dwarfPopIndexPie->foregroundCol = Qt::red;
// Swap cols for hive weight pie
QColor temp = ui->hiveWeightPie->foregroundCol;
ui->hiveWeightPie->foregroundCol = ui->hiveWeightPie->backgroundCol;
ui->hiveWeightPie->backgroundCol = temp;
initGraph();
ui->dwarfPopGraph->hide();
}
void HiveDialog::setClientModel(ClientModel *_clientModel) {
this->clientModel = _clientModel;
if (_clientModel) {
connect(_clientModel, SIGNAL(numBlocksChanged(int,QDateTime,double,bool)), this, SLOT(updateData()));
connect(_clientModel, SIGNAL(numConnectionsChanged(int)), this, SLOT(updateData())); // TODO: This may be too expensive to call here, and the only point is to update the hive status icon.
}
}
void HiveDialog::setModel(WalletModel *_model) {
this->model = _model;
if(_model && _model->getOptionsModel())
{
_model->getHiveTableModel()->sort(HiveTableModel::Created, Qt::DescendingOrder);
interfaces::WalletBalances balances = _model->wallet().getBalances();
setBalance(balances);
connect(_model, &WalletModel::balanceChanged, this, &HiveDialog::setBalance);
connect(_model->getOptionsModel(), &OptionsModel::displayUnitChanged, this, &HiveDialog::updateDisplayUnit);
updateDisplayUnit();
if (_model->getEncryptionStatus() != WalletModel::Locked)
ui->releaseSwarmButton->hide();
connect(_model, SIGNAL(encryptionStatusChanged(int)), this, SLOT(setEncryptionStatus(int)));
QTableView* tableView = ui->currentHiveView;
tableView->verticalHeader()->hide();
tableView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
tableView->setModel(_model->getHiveTableModel());
tableView->setAlternatingRowColors(true);
tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
tableView->setSelectionMode(QAbstractItemView::ContiguousSelection);
tableView->setColumnWidth(HiveTableModel::Created, CREATED_COLUMN_WIDTH);
tableView->setColumnWidth(HiveTableModel::Count, COUNT_COLUMN_WIDTH);
tableView->setColumnWidth(HiveTableModel::Status, STATUS_COLUMN_WIDTH);
tableView->setColumnWidth(HiveTableModel::EstimatedTime, TIME_COLUMN_WIDTH);
tableView->setColumnWidth(HiveTableModel::Cost, COST_COLUMN_WIDTH);
tableView->setColumnWidth(HiveTableModel::Rewards, REWARDS_COLUMN_WIDTH);
//tableView->setColumnWidth(HiveTableModel::Profit, PROFIT_COLUMN_WIDTH);
// Last 2 columns are set by the columnResizingFixer, when the table geometry is ready.
//columnResizingFixer = new GUIUtil::TableViewLastColumnResizingFixer(tableView, PROFIT_COLUMN_WIDTH, HIVE_COL_MIN_WIDTH, this);
columnResizingFixer = new GUIUtil::TableViewLastColumnResizingFixer(tableView, REWARDS_COLUMN_WIDTH, HIVE_COL_MIN_WIDTH, this);
// Populate initial data
updateData(true);
}
}
HiveDialog::~HiveDialog() {
delete ui;
}
void HiveDialog::setBalance(const interfaces::WalletBalances& balances)
{
currentBalance = balances.balance;
setAmountField(ui->currentBalance, currentBalance);
}
void HiveDialog::setEncryptionStatus(int status) {
switch(status) {
case WalletModel::Unencrypted:
case WalletModel::Unlocked:
ui->releaseSwarmButton->hide();
break;
case WalletModel::Locked:
ui->releaseSwarmButton->show();
break;
}
updateData();
}
void HiveDialog::setAmountField(QLabel *field, CAmount value) {
field->setText(
RingUnits::format(model->getOptionsModel()->getDisplayUnit(), value)
+ " "
+ RingUnits::shortName(model->getOptionsModel()->getDisplayUnit())
);
}
QString HiveDialog::formatLargeNoLocale(int i) {
QString i_str = QString::number(i);
// Use SI-style thin space separators as these are locale independent and can't be confused with the decimal marker.
QChar thin_sp(THIN_SP_CP);
int i_size = i_str.size();
for (int i = 3; i < i_size; i += 3)
i_str.insert(i_size - i, thin_sp);
return i_str;
}
void HiveDialog::updateData(bool forceGlobalSummaryUpdate) {
if(IsInitialBlockDownload() || chainActive.Height() == 0) {
ui->globalHiveFrame->hide();
ui->globalHiveSummaryError->show();
return;
}
const Consensus::Params& consensusParams = Params().GetConsensus();
if(model && model->getHiveTableModel()) {
{
model->getHiveTableModel()->updateDCTs(ui->includeDeadDwarvesCheckbox->isChecked());
model->getHiveTableModel()->getSummaryValues(immature, mature, dead, blocksFound, cost, rewardsPaid, profit);
}
// Update labels
setAmountField(ui->rewardsPaidLabel, rewardsPaid);
setAmountField(ui->costLabel, cost);
setAmountField(ui->profitLabel, profit);
ui->matureLabel->setText(formatLargeNoLocale(mature));
ui->immatureLabel->setText(formatLargeNoLocale(immature));
ui->blocksFoundLabel->setText(QString::number(blocksFound));
if(dead == 0) {
ui->deadLabel->hide();
ui->deadTitleLabel->hide();
ui->deadLabelSpacer->changeSize(0, 0, QSizePolicy::Fixed, QSizePolicy::Fixed);
} else {
ui->deadLabel->setText(formatLargeNoLocale(dead));
ui->deadLabel->show();
ui->deadTitleLabel->show();
ui->deadLabelSpacer->changeSize(ui->immatureLabelSpacer->geometry().width(), 0, QSizePolicy::Fixed, QSizePolicy::Fixed);
}
// Set icon and tooltip for tray icon
QString tooltip, icon;
if (clientModel && clientModel->getNumConnections() == 0) {
tooltip = "Not hivemining: Wallet is not connected";
icon = ":/icons/hivestatus_disabled";
} else {
if (mature + immature == 0) {
tooltip = "Not hivemining: No live dwarves currently in wallet";
icon = ":/icons/hivestatus_clear";
} else if (mature == 0) {
tooltip = "Not hivemining: Only immature dwarves currently in wallet";
icon = ":/icons/hivestatus_orange";
} else {
if (model->getEncryptionStatus() == WalletModel::Locked) {
tooltip = "WARNING: Dwarves mature but not mining because wallet is locked";
icon = ":/icons/hivestatus_red";
} else {
tooltip = "Hivemining: Dwarves mature and mining";
icon = ":/icons/hivestatus_green";
}
}
}
// Now update bitcoingui
Q_EMIT hiveStatusIconChanged(icon, tooltip);
}
dwarfCost = GetDwarfCost(chainActive.Tip()->nHeight, consensusParams);
setAmountField(ui->dwarfCostLabel, dwarfCost);
updateTotalCostDisplay();
if (forceGlobalSummaryUpdate || chainActive.Tip()->nHeight >= lastGlobalCheckHeight + 10) { // Don't update global summary every block
int globalImmatureDwarves, globalImmatureDCTs, globalMatureDwarves, globalMatureDCTs;
if (!GetNetworkHiveInfo(globalImmatureDwarves, globalImmatureDCTs, globalMatureDwarves, globalMatureDCTs, potentialRewards, consensusParams, true)) {
ui->globalHiveFrame->hide();
ui->globalHiveSummaryError->show();
} else {
ui->globalHiveSummaryError->hide();
ui->globalHiveFrame->show();
if (globalImmatureDwarves == 0)
ui->globalImmatureLabel->setText("0");
else
ui->globalImmatureLabel->setText(formatLargeNoLocale(globalImmatureDwarves) + " (" + QString::number(globalImmatureDCTs) + " transactions)");
if (globalMatureDwarves == 0)
ui->globalMatureLabel->setText("0");
else
ui->globalMatureLabel->setText(formatLargeNoLocale(globalMatureDwarves) + " (" + QString::number(globalMatureDCTs) + " transactions)");
updateGraph();
}
setAmountField(ui->potentialRewardsLabel, potentialRewards);
double hiveWeight = mature / (double)globalMatureDwarves;
ui->localHiveWeightLabel->setText((mature == 0 || globalMatureDwarves == 0) ? "0" : QString::number(hiveWeight, 'f', 3));
ui->hiveWeightPie->setValue(hiveWeight);
dwarfPopIndex = ((dwarfCost * globalMatureDwarves) / (double)potentialRewards) * 100.0;
if (dwarfPopIndex > 200) dwarfPopIndex = 200;
ui->dwarfPopIndexLabel->setText(QString::number(floor(dwarfPopIndex)));
ui->dwarfPopIndexPie->setValue(dwarfPopIndex / 100);
lastGlobalCheckHeight = chainActive.Tip()->nHeight;
}
ui->blocksTillGlobalRefresh->setText(QString::number(10 - (chainActive.Tip()->nHeight - lastGlobalCheckHeight)));
}
void HiveDialog::updateDisplayUnit() {
if(model && model->getOptionsModel()) {
setAmountField(ui->dwarfCostLabel, dwarfCost);
setAmountField(ui->rewardsPaidLabel, rewardsPaid);
setAmountField(ui->costLabel, cost);
setAmountField(ui->profitLabel, profit);
setAmountField(ui->potentialRewardsLabel, potentialRewards);
setAmountField(ui->currentBalance, currentBalance);
setAmountField(ui->totalCostLabel, totalCost);
}
updateTotalCostDisplay();
}
void HiveDialog::updateTotalCostDisplay() {
totalCost = dwarfCost * ui->dwarfCountSpinner->value();
if(model && model->getOptionsModel()) {
setAmountField(ui->totalCostLabel, totalCost);
interfaces::WalletBalances balances = model->wallet().getBalances();
if (totalCost > balances.balance)
ui->dwarfCountSpinner->setStyleSheet("QSpinBox{background:#FF8080;}");
else
ui->dwarfCountSpinner->setStyleSheet("QSpinBox{background:white;}");
}
}
void HiveDialog::on_dwarfCountSpinner_valueChanged(int i) {
updateTotalCostDisplay();
}
void HiveDialog::on_includeDeadDwarvesCheckbox_stateChanged() {
updateData();
}
void HiveDialog::on_showAdvancedStatsCheckbox_stateChanged() {
if(ui->showAdvancedStatsCheckbox->isChecked()) {
ui->dwarfPopGraph->show();
ui->walletHiveStatsFrame->hide();
} else {
ui->dwarfPopGraph->hide();
ui->walletHiveStatsFrame->show();
}
}
void HiveDialog::on_retryGlobalSummaryButton_clicked() {
updateData(true);
}
void HiveDialog::on_refreshGlobalSummaryButton_clicked() {
updateData(true);
}
void HiveDialog::on_releaseSwarmButton_clicked() {
if(model)
model->requestUnlock(true);
}
void HiveDialog::on_createDwarvesButton_clicked() {
if (model && clientModel) {
const Consensus::Params& consensusParams = Params().GetConsensus();
int chainHeight = clientModel->getHeaderTipHeight();
if (chainHeight < (consensusParams.lastInitialDistributionHeight + consensusParams.slowStartBlocks) - consensusParams.dwarfGestationBlocks) {
QString questionString = tr("Are you sure you want to create dwarves?<br /><br /><span style='color:#aa0000;'><b>WARNING:</b> The pow-only slowstart phase is currently running. We do not recommend creating dwarves yet, as some of their lifespan will be wasted.</span><br />");
SendConfirmationDialog confirmationDialog(tr("Confirm dwarf creation"), questionString);
confirmationDialog.exec();
QMessageBox::StandardButton retval = (QMessageBox::StandardButton)confirmationDialog.result();
if (retval != QMessageBox::Yes)
return;
}
interfaces::WalletBalances balances = model->wallet().getBalances();
if (totalCost > balances.balance) {
QMessageBox::critical(this, tr("Error"), tr("Insufficient balance to create dwarves."));
return;
}
WalletModel::UnlockContext ctx(model->requestUnlock());
if(!ctx.isValid())
return; // Unlock wallet was cancelled
model->createDwarves(ui->dwarfCountSpinner->value(), ui->donateCommunityFundCheckbox->isChecked(), this, dwarfPopIndex);
}
}
// Ring-fork: Hive: Mining optimisations: Shortcut to Hive mining options
void HiveDialog::on_showHiveOptionsButton_clicked() {
if(!clientModel || !clientModel->getOptionsModel())
return;
OptionsDialog dlg(this, model->isWalletEnabled());
dlg.setModel(clientModel->getOptionsModel());
dlg.exec();
}
void HiveDialog::initGraph() {
ui->dwarfPopGraph->addGraph();
ui->dwarfPopGraph->graph(0)->setLineStyle(QCPGraph::lsLine);
ui->dwarfPopGraph->graph(0)->setPen(QPen(Qt::blue));
QColor color(42, 67, 182);
color.setAlphaF(0.35);
ui->dwarfPopGraph->graph(0)->setBrush(QBrush(color));
ui->dwarfPopGraph->addGraph();
ui->dwarfPopGraph->graph(1)->setLineStyle(QCPGraph::lsLine);
ui->dwarfPopGraph->graph(1)->setPen(QPen(Qt::black));
QColor color1(42, 182, 67);
color1.setAlphaF(0.35);
ui->dwarfPopGraph->graph(1)->setBrush(QBrush(color1));
QSharedPointer<QCPAxisTickerDateTime> dateTicker(new QCPAxisTickerDateTime);
dateTicker->setTickStepStrategy(QCPAxisTicker::TickStepStrategy::tssMeetTickCount);
dateTicker->setTickCount(8);
dateTicker->setDateTimeFormat("ddd d MMM");
ui->dwarfPopGraph->xAxis->setTicker(dateTicker);
ui->dwarfPopGraph->yAxis->setLabel("Dwarves");
giTicker = QSharedPointer<QCPAxisTickerGI>(new QCPAxisTickerGI);
ui->dwarfPopGraph->yAxis2->setTicker(giTicker);
ui->dwarfPopGraph->yAxis2->setLabel("Global index");
ui->dwarfPopGraph->yAxis2->setVisible(true);
ui->dwarfPopGraph->xAxis->setTickLabelFont(QFont(QFont().family(), 8));
ui->dwarfPopGraph->xAxis2->setTickLabelFont(QFont(QFont().family(), 8));
ui->dwarfPopGraph->yAxis->setTickLabelFont(QFont(QFont().family(), 8));
ui->dwarfPopGraph->yAxis2->setTickLabelFont(QFont(QFont().family(), 8));
connect(ui->dwarfPopGraph->xAxis, SIGNAL(rangeChanged(QCPRange)), ui->dwarfPopGraph->xAxis2, SLOT(setRange(QCPRange)));
connect(ui->dwarfPopGraph->yAxis, SIGNAL(rangeChanged(QCPRange)), ui->dwarfPopGraph->yAxis2, SLOT(setRange(QCPRange)));
connect(ui->dwarfPopGraph, SIGNAL(mouseMove(QMouseEvent*)), this, SLOT(onMouseMove(QMouseEvent*)));
globalMarkerLine = new QCPItemLine(ui->dwarfPopGraph);
globalMarkerLine->setPen(QPen(Qt::blue, 1, Qt::DashLine));
graphTracerImmature = new QCPItemTracer(ui->dwarfPopGraph);
graphTracerImmature->setGraph(ui->dwarfPopGraph->graph(0));
graphTracerMature = new QCPItemTracer(ui->dwarfPopGraph);
graphTracerMature->setGraph(ui->dwarfPopGraph->graph(1));
graphMouseoverText = new QCPItemText(ui->dwarfPopGraph);
}
void HiveDialog::updateGraph() {
const Consensus::Params& consensusParams = Params().GetConsensus();
ui->dwarfPopGraph->graph()->data()->clear();
double now = QDateTime::currentDateTime().toTime_t();
int totalLifespan = consensusParams.dwarfGestationBlocks + consensusParams.dwarfLifespanBlocks;
QVector<QCPGraphData> dataMature(totalLifespan);
QVector<QCPGraphData> dataImmature(totalLifespan);
for (int i = 0; i < totalLifespan; i++) {
dataImmature[i].key = now + consensusParams.nExpectedBlockSpacing * i;
dataImmature[i].value = (double)dwarfPopGraph[i].immaturePop;
dataMature[i].key = dataImmature[i].key;
dataMature[i].value = (double)dwarfPopGraph[i].maturePop;
}
ui->dwarfPopGraph->graph(0)->data()->set(dataImmature);
ui->dwarfPopGraph->graph(1)->data()->set(dataMature);
double global100 = (double)potentialRewards / dwarfCost;
globalMarkerLine->start->setCoords(now, global100);
globalMarkerLine->end->setCoords(now + consensusParams.nExpectedBlockSpacing * totalLifespan, global100);
giTicker->global100 = global100;
ui->dwarfPopGraph->rescaleAxes();
ui->dwarfPopGraph->replot();
}
void HiveDialog::onMouseMove(QMouseEvent *event) {
QCustomPlot* customPlot = qobject_cast<QCustomPlot*>(sender());
int x = (int)customPlot->xAxis->pixelToCoord(event->pos().x());
int y = (int)customPlot->yAxis->pixelToCoord(event->pos().y());
graphTracerImmature->setGraphKey(x);
graphTracerMature->setGraphKey(x);
int dwarfCountImmature = (int)graphTracerImmature->position->value();
int dwarfCountMature = (int)graphTracerMature->position->value();
QDateTime xDateTime = QDateTime::fromTime_t(x);
int global100 = (int)((double)potentialRewards / dwarfCost);
QColor traceColMature = dwarfCountMature >= global100 ? Qt::red : Qt::black;
QColor traceColImmature = dwarfCountImmature >= global100 ? Qt::red : Qt::black;
graphTracerImmature->setPen(QPen(traceColImmature, 1, Qt::DashLine));
graphTracerMature->setPen(QPen(traceColMature, 1, Qt::DashLine));
graphMouseoverText->setText(xDateTime.toString("ddd d MMM") + " " + xDateTime.time().toString() + ":\n" + formatLargeNoLocale(dwarfCountMature) + " mature dwarves\n" + formatLargeNoLocale(dwarfCountImmature) + " immature dwarves");
graphMouseoverText->setColor(traceColMature);
graphMouseoverText->position->setCoords(QPointF(x, y));
QPointF pixelPos = graphMouseoverText->position->pixelPosition();
int xoffs, yoffs;
if (ui->dwarfPopGraph->height() > 150) {
graphMouseoverText->setFont(QFont(font().family(), 10));
xoffs = 80;
yoffs = 30;
} else {
graphMouseoverText->setFont(QFont(font().family(), 8));
xoffs = 70;
yoffs = 20;
}
if (pixelPos.y() > ui->dwarfPopGraph->height() / 2)
pixelPos.setY(pixelPos.y() - yoffs);
else
pixelPos.setY(pixelPos.y() + yoffs);
if (pixelPos.x() > ui->dwarfPopGraph->width() / 2)
pixelPos.setX(pixelPos.x() - xoffs);
else
pixelPos.setX(pixelPos.x() + xoffs);
graphMouseoverText->position->setPixelPosition(pixelPos);
customPlot->replot();
}
void HiveDialog::resizeEvent(QResizeEvent *event) {
QWidget::resizeEvent(event);
columnResizingFixer->stretchColumnWidth(HiveTableModel::Rewards);
}
| 49,910
|
https://github.com/P79N6A/qingxia/blob/master/.svn/pristine/45/459113de17a0569b069a230eb177304dff24aab6.svn-base
|
Github Open Source
|
Open Source
|
MIT
| 2,018
|
qingxia
|
P79N6A
|
Blade
|
Code
| 244
| 1,215
|
@extends('layouts.simple')
@push('need_css')
<link rel="stylesheet" href="{{ asset('adminlte') }}/plugins/daterangepicker/daterangepicker.css">
<link rel="stylesheet" href="/adminlte/plugins/autocompleter/jquery.autocompleter.css">
<link rel="stylesheet" href="/adminlte/plugins/select2/select2.min.css">
<style>
.raw_title b{
color: red;
}
</style>
@endpush
@push('need_js')
<script src="/adminlte/plugins/autocompleter/jquery.autocompleter.js"></script>
<script src="/adminlte/plugins/layer/layer.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
@endpush
@section('content')
<section class="content-header">
</section>
<section class="content">
<div class="row">
<div id="box-header" class="box-header">
<div class="col-sm-3">
<div class="input-group">
<span class="input-group-addon">
关键词
</span>
<input type="text" class="form-control" id="keyword" value="">
</div>
</div>
<div class="col-sm-3">
<div class="input-group">
<span class="input-group-addon">
排除词
</span>
<input type="text" class="form-control" id="remove">
<span class="input-group-btn">
<button type="button" class="btn btn-info btn-flat" id="search">搜</button>
</span>
</div>
</div>
</div>
</div>
<div class="row">
<ul class="list" style="overflow: hidden;padding-left:21px;list-style: none;">
<div class="box box-widget">
<div class="box-body">
<div class="media">
@foreach($re['list'] as $v)
<li style="height:300px;width:250px;float: left;">
<div class="media-body" >
<a target="_blank" href="{{ $v['url'] }}" class="ad-click-event">
<img src="{{ $v['cover_url'] }}" alt="Now UI Kit" class="media-object" style="max-height: 150px; max-width: 150px; border-radius: 4px;box-shadow: 0 1px 3px rgba(0,0,0,.15);">
</a>
<div class="info" style="width: 200px;">
<div style=" text-align: center; margin-top: 5px; height: 50px;font-size: 13px;overflow:hidden" class="raw_title">
{!! $v['bookname'] !!}
</div>
<div>
ISBN:
<a data-toggle="modal" data-target="#myModal" class="isbn_info" data-isbn="{{ $v['isbn'] }}">
{{ $v['isbn'] }}
</a>
</div>
</div>
</div>
</li>
@endforeach
</div>
</div>
</div>
</ul>
</div>
<div>
{{ $re['paginator']->links() }}
</div>
</section>
@endsection
@push('need_js')
<script src="/adminlte/plugins/select2/select2.full.min.js"></script>
<script>
$("#keyword").val('{{ }}')
$("#search").click(function () {
var keyword = $("#keyword").val();
window.location.href=`{{ route('taobao_search') }}/${keyword}/{{ $re['type'] }}/{{ $re['sort_id'] }}/{{ $re['is_read'] }}/{{ $re['v_status'] }}/{{ $re['remove_isbn'] }}/{{ $re['has_year'] }}/{{ $re['start'] }}/{{ $re['end'] }}`;
});
var isCheckAll = false;
function swapCheck() {
if (isCheckAll) {
$("input[type='checkbox']").each(function() {
this.checked = false;
});
isCheckAll = false;
} else {
$("input[type='checkbox']").each(function() {
this.checked = true;
});
isCheckAll = true;
}
}
</script>
@endpush
| 47
|
https://github.com/sotola/jenkins/blob/master/test/src/test/java/hudson/security/csrf/DefaultCrumbIssuerTest.java
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
jenkins
|
sotola
|
Java
|
Code
| 245
| 945
|
/**
* Copyright (c) 2008-2010 Yahoo! Inc.
* All rights reserved.
* The copyrights to the contents of this file are licensed under the MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
package hudson.security.csrf;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import org.jvnet.hudson.test.Bug;
import org.jvnet.hudson.test.HudsonTestCase;
/**
*
* @author dty
*/
public class DefaultCrumbIssuerTest extends HudsonTestCase {
protected void setUp() throws Exception {
super.setUp();
assertNotNull(hudson);
CrumbIssuer issuer = new DefaultCrumbIssuer(false);
assertNotNull(issuer);
hudson.setCrumbIssuer(issuer);
}
private static final String[] testData = {
"10.2.3.1",
"10.2.3.1,10.20.30.40",
"10.2.3.1,10.20.30.41",
"10.2.3.3,10.20.30.40,10.20.30.41"
};
private static final String HEADER_NAME = "X-Forwarded-For";
@Bug(3854)
public void testClientIPFromHeader() throws Exception {
WebClient wc = new WebClient();
wc.addRequestHeader(HEADER_NAME, testData[0]);
HtmlPage p = wc.goTo("configure");
submit(p.getFormByName("config"));
}
@Bug(3854)
public void testHeaderChange() throws Exception {
WebClient wc = new WebClient();
wc.addRequestHeader(HEADER_NAME, testData[0]);
HtmlPage p = wc.goTo("configure");
wc.removeRequestHeader(HEADER_NAME);
try {
// The crumb should no longer match if we remove the proxy info
submit(p.getFormByName("config"));
}
catch (FailingHttpStatusCodeException e) {
assertEquals(403,e.getStatusCode());
}
}
@Bug(3854)
public void testProxyIPChanged() throws Exception {
WebClient wc = new WebClient();
wc.addRequestHeader(HEADER_NAME, testData[1]);
HtmlPage p = wc.goTo("configure");
wc.removeRequestHeader(HEADER_NAME);
wc.addRequestHeader(HEADER_NAME, testData[2]);
// The crumb should be the same even if the proxy IP changes
submit(p.getFormByName("config"));
}
@Bug(3854)
public void testProxyIPChain() throws Exception {
WebClient wc = new WebClient();
wc.addRequestHeader(HEADER_NAME, testData[3]);
HtmlPage p = wc.goTo("configure");
submit(p.getFormByName("config"));
}
@Bug(7518)
public void testProxyCompatibilityMode() throws Exception {
CrumbIssuer issuer = new DefaultCrumbIssuer(true);
assertNotNull(issuer);
hudson.setCrumbIssuer(issuer);
WebClient wc = new WebClient();
wc.addRequestHeader(HEADER_NAME, testData[0]);
HtmlPage p = wc.goTo("configure");
wc.removeRequestHeader(HEADER_NAME);
// The crumb should still match if we remove the proxy info
submit(p.getFormByName("config"));
}
}
| 38,006
|
https://github.com/itsromiljain/DSTracker/blob/master/ds_tracker/src/main/java/com/tracker/demand/repository/ExtendedTrackerRepo.java
|
Github Open Source
|
Open Source
|
MIT
| null |
DSTracker
|
itsromiljain
|
Java
|
Code
| 18
| 86
|
package com.tracker.demand.repository;
import java.util.List;
import com.tracker.entity.DemandDetail;
public interface ExtendedTrackerRepo{
public List<DemandDetail> getProjectsRepo(long id);
//public List<DemandDetail> getDemandsRepo(long id);
}
| 11,617
|
https://github.com/CtinfoShubham31/test/blob/master/tutorials/Laravel/Laravel/lavtut_storageClass/app/Http/Controllers/StudentController.php
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
test
|
CtinfoShubham31
|
PHP
|
Code
| 346
| 1,392
|
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Student;
use Validator;
use Illuminate\Support\Facades\Storage;
class StudentController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
//echo Storage::url("public/Yqvb0s0qdzSwLhuBH4oAqoLbnFTWGggJLXByXY60.jpeg");
//Storage::makeDirectory("public/owt");
//Storage::deleteDirectory("public/owt");
//echo Storage::lastModified("public/Yqvb0s0qdzSwLhuBH4oAqoLbnFTWGggJLXByXY60.jpeg");
//echo Storage::size("public/Yqvb0s0qdzSwLhuBH4oAqoLbnFTWGggJLXByXY60.jpeg");
Storage::copy("public/Yqvb0s0qdzSwLhuBH4oAqoLbnFTWGggJLXByXY60.jpeg","public/owt.png");
$students = Student::orderBy("id","desc")->get();
return view("student.index",compact("students"));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view("student.create");
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$file = $request->file("image");
if($request->hasfile("image")){
//$file = $request->file("image");
//$file->move("upload/",$file->getClientOriginalName()); //To upload in destination folder
//$file->storeAs("public/",$file->getClientOriginalName());
Storage::putFile("public/",$request->file("image"));
}
die;
$data = Validator :: make($request->all(),[
"name"=>"required|max:255",
"email"=>"required|max:255|unique:students|email",
],[
"name.required" => "Name is needed",
"email.required" => "Email is needed",
"email.email" => "Email should be valid email",
])->validate(); //For auto redirection purpose validate()
$obj = new Student;
$obj->name = $request->name;
$obj->email = $request->email;
$obj->st_image = $file->getClientOriginalName();
$obj->created_dt = date("Y-m-d h:i:s");
$is_saved = $obj->save();
if($is_saved){ //If row inserted
session()->flash("studentMessage","Student has been inserted");
return redirect("student/create");
}
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$student = Student::find($id);
return view("student.edit",compact("student"));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$data = Validator :: make($request->all(),[
"name"=>"required|max:255",
"email"=>"required|max:255|unique:students|email",
],[
"name.required" => "Name is needed",
"email.required" => "Email is needed",
"email.email" => "Email should be valid email",
])->validate(); //For auto redirection purpose validate()
http://localhost/phpmyadmin/sql.php
$student = Student::find($id);
$student->name = $request->name;
$student->email = $request->email;
$is_saved = $student->save();
if($is_saved){ //If row inserted
session()->flash("studentMessage","Student has been updated");
return redirect("student/".$id."/edit");
}
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$student = Student::find($id);
$is_deleted = $student->delete();
if($is_deleted){ //If row inserted
session()->flash("studentMessage","Student has been deleted");
return redirect("student");
}
}
}
| 18,269
|
https://github.com/Mu-L/JCTools/blob/master/jctools-core/src/main/java/org/jctools/queues/atomic/BaseLinkedAtomicQueue.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,022
|
JCTools
|
Mu-L
|
Java
|
Code
| 1,935
| 5,297
|
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jctools.queues.atomic;
import java.util.AbstractQueue;
import java.util.Iterator;
import java.util.Queue;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import java.util.concurrent.atomic.AtomicLongFieldUpdater;
import java.util.concurrent.atomic.AtomicReferenceArray;
import org.jctools.queues.MessagePassingQueue;
import org.jctools.queues.MessagePassingQueue.Supplier;
import org.jctools.queues.MessagePassingQueueUtil;
import org.jctools.queues.QueueProgressIndicators;
import org.jctools.queues.IndexedQueueSizeUtil;
import static org.jctools.queues.atomic.AtomicQueueUtil.*;
/**
* NOTE: This class was automatically generated by org.jctools.queues.atomic.JavaParsingAtomicLinkedQueueGenerator
* which can found in the jctools-build module. The original source file is BaseLinkedQueue.java.
*/
abstract class BaseLinkedAtomicQueuePad0<E> extends AbstractQueue<E> implements MessagePassingQueue<E> {
// 8b
byte b000, b001, b002, b003, b004, b005, b006, b007;
// 16b
byte b010, b011, b012, b013, b014, b015, b016, b017;
// 24b
byte b020, b021, b022, b023, b024, b025, b026, b027;
// 32b
byte b030, b031, b032, b033, b034, b035, b036, b037;
// 40b
byte b040, b041, b042, b043, b044, b045, b046, b047;
// 48b
byte b050, b051, b052, b053, b054, b055, b056, b057;
// 56b
byte b060, b061, b062, b063, b064, b065, b066, b067;
// 64b
byte b070, b071, b072, b073, b074, b075, b076, b077;
// 72b
byte b100, b101, b102, b103, b104, b105, b106, b107;
// 80b
byte b110, b111, b112, b113, b114, b115, b116, b117;
// 88b
byte b120, b121, b122, b123, b124, b125, b126, b127;
// 96b
byte b130, b131, b132, b133, b134, b135, b136, b137;
// 104b
byte b140, b141, b142, b143, b144, b145, b146, b147;
// 112b
byte b150, b151, b152, b153, b154, b155, b156, b157;
// 120b
byte b160, b161, b162, b163, b164, b165, b166, b167;
}
/**
* NOTE: This class was automatically generated by org.jctools.queues.atomic.JavaParsingAtomicLinkedQueueGenerator
* which can found in the jctools-build module. The original source file is BaseLinkedQueue.java.
*/
abstract class BaseLinkedAtomicQueueProducerNodeRef<E> extends BaseLinkedAtomicQueuePad0<E> {
private static final AtomicReferenceFieldUpdater<BaseLinkedAtomicQueueProducerNodeRef, LinkedQueueAtomicNode> P_NODE_UPDATER = AtomicReferenceFieldUpdater.newUpdater(BaseLinkedAtomicQueueProducerNodeRef.class, LinkedQueueAtomicNode.class, "producerNode");
private volatile LinkedQueueAtomicNode<E> producerNode;
final void spProducerNode(LinkedQueueAtomicNode<E> newValue) {
P_NODE_UPDATER.lazySet(this, newValue);
}
final void soProducerNode(LinkedQueueAtomicNode<E> newValue) {
P_NODE_UPDATER.lazySet(this, newValue);
}
final LinkedQueueAtomicNode<E> lvProducerNode() {
return producerNode;
}
final boolean casProducerNode(LinkedQueueAtomicNode<E> expect, LinkedQueueAtomicNode<E> newValue) {
return P_NODE_UPDATER.compareAndSet(this, expect, newValue);
}
final LinkedQueueAtomicNode<E> lpProducerNode() {
return producerNode;
}
protected final LinkedQueueAtomicNode<E> xchgProducerNode(LinkedQueueAtomicNode<E> newValue) {
return P_NODE_UPDATER.getAndSet(this, newValue);
}
}
/**
* NOTE: This class was automatically generated by org.jctools.queues.atomic.JavaParsingAtomicLinkedQueueGenerator
* which can found in the jctools-build module. The original source file is BaseLinkedQueue.java.
*/
abstract class BaseLinkedAtomicQueuePad1<E> extends BaseLinkedAtomicQueueProducerNodeRef<E> {
// 8b
byte b000, b001, b002, b003, b004, b005, b006, b007;
// 16b
byte b010, b011, b012, b013, b014, b015, b016, b017;
// 24b
byte b020, b021, b022, b023, b024, b025, b026, b027;
// 32b
byte b030, b031, b032, b033, b034, b035, b036, b037;
// 40b
byte b040, b041, b042, b043, b044, b045, b046, b047;
// 48b
byte b050, b051, b052, b053, b054, b055, b056, b057;
// 56b
byte b060, b061, b062, b063, b064, b065, b066, b067;
// 64b
byte b070, b071, b072, b073, b074, b075, b076, b077;
// 72b
byte b100, b101, b102, b103, b104, b105, b106, b107;
// 80b
byte b110, b111, b112, b113, b114, b115, b116, b117;
// 88b
byte b120, b121, b122, b123, b124, b125, b126, b127;
// 96b
byte b130, b131, b132, b133, b134, b135, b136, b137;
// 104b
byte b140, b141, b142, b143, b144, b145, b146, b147;
// 112b
byte b150, b151, b152, b153, b154, b155, b156, b157;
// 120b
byte b160, b161, b162, b163, b164, b165, b166, b167;
// 128b
byte b170, b171, b172, b173, b174, b175, b176, b177;
}
/**
* NOTE: This class was automatically generated by org.jctools.queues.atomic.JavaParsingAtomicLinkedQueueGenerator
* which can found in the jctools-build module. The original source file is BaseLinkedQueue.java.
*/
abstract class BaseLinkedAtomicQueueConsumerNodeRef<E> extends BaseLinkedAtomicQueuePad1<E> {
private static final AtomicReferenceFieldUpdater<BaseLinkedAtomicQueueConsumerNodeRef, LinkedQueueAtomicNode> C_NODE_UPDATER = AtomicReferenceFieldUpdater.newUpdater(BaseLinkedAtomicQueueConsumerNodeRef.class, LinkedQueueAtomicNode.class, "consumerNode");
private volatile LinkedQueueAtomicNode<E> consumerNode;
final void spConsumerNode(LinkedQueueAtomicNode<E> newValue) {
C_NODE_UPDATER.lazySet(this, newValue);
}
@SuppressWarnings("unchecked")
final LinkedQueueAtomicNode<E> lvConsumerNode() {
return consumerNode;
}
final LinkedQueueAtomicNode<E> lpConsumerNode() {
return consumerNode;
}
}
/**
* NOTE: This class was automatically generated by org.jctools.queues.atomic.JavaParsingAtomicLinkedQueueGenerator
* which can found in the jctools-build module. The original source file is BaseLinkedQueue.java.
*/
abstract class BaseLinkedAtomicQueuePad2<E> extends BaseLinkedAtomicQueueConsumerNodeRef<E> {
// 8b
byte b000, b001, b002, b003, b004, b005, b006, b007;
// 16b
byte b010, b011, b012, b013, b014, b015, b016, b017;
// 24b
byte b020, b021, b022, b023, b024, b025, b026, b027;
// 32b
byte b030, b031, b032, b033, b034, b035, b036, b037;
// 40b
byte b040, b041, b042, b043, b044, b045, b046, b047;
// 48b
byte b050, b051, b052, b053, b054, b055, b056, b057;
// 56b
byte b060, b061, b062, b063, b064, b065, b066, b067;
// 64b
byte b070, b071, b072, b073, b074, b075, b076, b077;
// 72b
byte b100, b101, b102, b103, b104, b105, b106, b107;
// 80b
byte b110, b111, b112, b113, b114, b115, b116, b117;
// 88b
byte b120, b121, b122, b123, b124, b125, b126, b127;
// 96b
byte b130, b131, b132, b133, b134, b135, b136, b137;
// 104b
byte b140, b141, b142, b143, b144, b145, b146, b147;
// 112b
byte b150, b151, b152, b153, b154, b155, b156, b157;
// 120b
byte b160, b161, b162, b163, b164, b165, b166, b167;
// 128b
byte b170, b171, b172, b173, b174, b175, b176, b177;
}
/**
* NOTE: This class was automatically generated by org.jctools.queues.atomic.JavaParsingAtomicLinkedQueueGenerator
* which can found in the jctools-build module. The original source file is BaseLinkedQueue.java.
*
* A base data structure for concurrent linked queues. For convenience also pulled in common single consumer
* methods since at this time there's no plan to implement MC.
*/
abstract class BaseLinkedAtomicQueue<E> extends BaseLinkedAtomicQueuePad2<E> {
@Override
public final Iterator<E> iterator() {
throw new UnsupportedOperationException();
}
@Override
public String toString() {
return this.getClass().getName();
}
protected final LinkedQueueAtomicNode<E> newNode() {
return new LinkedQueueAtomicNode<E>();
}
protected final LinkedQueueAtomicNode<E> newNode(E e) {
return new LinkedQueueAtomicNode<E>(e);
}
/**
* {@inheritDoc} <br>
* <p>
* IMPLEMENTATION NOTES:<br>
* This is an O(n) operation as we run through all the nodes and count them.<br>
* The accuracy of the value returned by this method is subject to races with producer/consumer threads. In
* particular when racing with the consumer thread this method may under estimate the size.<br>
*
* @see java.util.Queue#size()
*/
@Override
public final int size() {
// Read consumer first, this is important because if the producer is node is 'older' than the consumer
// the consumer may overtake it (consume past it) invalidating the 'snapshot' notion of size.
LinkedQueueAtomicNode<E> chaserNode = lvConsumerNode();
LinkedQueueAtomicNode<E> producerNode = lvProducerNode();
int size = 0;
// must chase the nodes all the way to the producer node, but there's no need to count beyond expected head.
while (// don't go passed producer node
chaserNode != producerNode && // stop at last node
chaserNode != null && // stop at max int
size < Integer.MAX_VALUE) {
LinkedQueueAtomicNode<E> next;
next = chaserNode.lvNext();
// check if this node has been consumed, if so return what we have
if (next == chaserNode) {
return size;
}
chaserNode = next;
size++;
}
return size;
}
/**
* {@inheritDoc} <br>
* <p>
* IMPLEMENTATION NOTES:<br>
* Queue is empty when producerNode is the same as consumerNode. An alternative implementation would be to
* observe the producerNode.value is null, which also means an empty queue because only the
* consumerNode.value is allowed to be null.
*
* @see MessagePassingQueue#isEmpty()
*/
@Override
public boolean isEmpty() {
LinkedQueueAtomicNode<E> consumerNode = lvConsumerNode();
LinkedQueueAtomicNode<E> producerNode = lvProducerNode();
return consumerNode == producerNode;
}
protected E getSingleConsumerNodeValue(LinkedQueueAtomicNode<E> currConsumerNode, LinkedQueueAtomicNode<E> nextNode) {
// we have to null out the value because we are going to hang on to the node
final E nextValue = nextNode.getAndNullValue();
// Fix up the next ref of currConsumerNode to prevent promoted nodes from keeping new ones alive.
// We use a reference to self instead of null because null is already a meaningful value (the next of
// producer node is null).
currConsumerNode.soNext(currConsumerNode);
spConsumerNode(nextNode);
// currConsumerNode is now no longer referenced and can be collected
return nextValue;
}
/**
* {@inheritDoc} <br>
* <p>
* IMPLEMENTATION NOTES:<br>
* Poll is allowed from a SINGLE thread.<br>
* Poll is potentially blocking here as the {@link Queue#poll()} does not allow returning {@code null} if the queue is not
* empty. This is very different from the original Vyukov guarantees. See {@link #relaxedPoll()} for the original
* semantics.<br>
* Poll reads {@code consumerNode.next} and:
* <ol>
* <li>If it is {@code null} AND the queue is empty return {@code null}, <b>if queue is not empty spin wait for
* value to become visible</b>.
* <li>If it is not {@code null} set it as the consumer node and return it's now evacuated value.
* </ol>
* This means the consumerNode.value is always {@code null}, which is also the starting point for the queue.
* Because {@code null} values are not allowed to be offered this is the only node with it's value set to
* {@code null} at any one time.
*
* @see MessagePassingQueue#poll()
* @see java.util.Queue#poll()
*/
@Override
public E poll() {
final LinkedQueueAtomicNode<E> currConsumerNode = lpConsumerNode();
LinkedQueueAtomicNode<E> nextNode = currConsumerNode.lvNext();
if (nextNode != null) {
return getSingleConsumerNodeValue(currConsumerNode, nextNode);
} else if (currConsumerNode != lvProducerNode()) {
nextNode = spinWaitForNextNode(currConsumerNode);
// got the next node...
return getSingleConsumerNodeValue(currConsumerNode, nextNode);
}
return null;
}
/**
* {@inheritDoc} <br>
* <p>
* IMPLEMENTATION NOTES:<br>
* Peek is allowed from a SINGLE thread.<br>
* Peek is potentially blocking here as the {@link Queue#peek()} does not allow returning {@code null} if the queue is not
* empty. This is very different from the original Vyukov guarantees. See {@link #relaxedPeek()} for the original
* semantics.<br>
* Poll reads the next node from the consumerNode and:
* <ol>
* <li>If it is {@code null} AND the queue is empty return {@code null}, <b>if queue is not empty spin wait for
* value to become visible</b>.
* <li>If it is not {@code null} return it's value.
* </ol>
*
* @see MessagePassingQueue#peek()
* @see java.util.Queue#peek()
*/
@Override
public E peek() {
final LinkedQueueAtomicNode<E> currConsumerNode = lpConsumerNode();
LinkedQueueAtomicNode<E> nextNode = currConsumerNode.lvNext();
if (nextNode != null) {
return nextNode.lpValue();
} else if (currConsumerNode != lvProducerNode()) {
nextNode = spinWaitForNextNode(currConsumerNode);
// got the next node...
return nextNode.lpValue();
}
return null;
}
LinkedQueueAtomicNode<E> spinWaitForNextNode(LinkedQueueAtomicNode<E> currNode) {
LinkedQueueAtomicNode<E> nextNode;
while ((nextNode = currNode.lvNext()) == null) {
// spin, we are no longer wait free
}
return nextNode;
}
@Override
public E relaxedPoll() {
final LinkedQueueAtomicNode<E> currConsumerNode = lpConsumerNode();
final LinkedQueueAtomicNode<E> nextNode = currConsumerNode.lvNext();
if (nextNode != null) {
return getSingleConsumerNodeValue(currConsumerNode, nextNode);
}
return null;
}
@Override
public E relaxedPeek() {
final LinkedQueueAtomicNode<E> nextNode = lpConsumerNode().lvNext();
if (nextNode != null) {
return nextNode.lpValue();
}
return null;
}
@Override
public boolean relaxedOffer(E e) {
return offer(e);
}
@Override
public int drain(Consumer<E> c, int limit) {
if (null == c)
throw new IllegalArgumentException("c is null");
if (limit < 0)
throw new IllegalArgumentException("limit is negative: " + limit);
if (limit == 0)
return 0;
LinkedQueueAtomicNode<E> chaserNode = this.lpConsumerNode();
for (int i = 0; i < limit; i++) {
final LinkedQueueAtomicNode<E> nextNode = chaserNode.lvNext();
if (nextNode == null) {
return i;
}
// we have to null out the value because we are going to hang on to the node
final E nextValue = getSingleConsumerNodeValue(chaserNode, nextNode);
chaserNode = nextNode;
c.accept(nextValue);
}
return limit;
}
@Override
public int drain(Consumer<E> c) {
return MessagePassingQueueUtil.drain(this, c);
}
@Override
public void drain(Consumer<E> c, WaitStrategy wait, ExitCondition exit) {
MessagePassingQueueUtil.drain(this, c, wait, exit);
}
@Override
public int capacity() {
return UNBOUNDED_CAPACITY;
}
}
| 45,609
|
https://github.com/beshoo/wit-php/blob/master/spec/Model/EntitySpec.php
|
Github Open Source
|
Open Source
|
MIT
| 2,016
|
wit-php
|
beshoo
|
PHP
|
Code
| 50
| 277
|
<?php
namespace spec\Tgallice\Wit\Model;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
class EntitySpec extends ObjectBehavior
{
function let()
{
$this->beConstructedWith('id', [], 'description');
}
function it_is_initializable()
{
$this->shouldHaveType('Tgallice\Wit\Model\Entity');
}
function it_has_an_id()
{
$this->getId()->shouldReturn('id');
}
function it_has_a_description()
{
$this->getDescription()->shouldReturn('description');
}
function it_has_values()
{
$this->getValues()->shouldReturn([]);
}
function it_must_be_json_serializable()
{
$this->shouldHaveType(\JsonSerializable::class);
$serialized = json_encode($this->getWrappedObject());
$this->jsonSerialize()->shouldReturn(json_decode($serialized, true));
}
}
| 18,176
|
https://github.com/michaelalex1/travel/blob/master/resources/js/views/App.vue
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
travel
|
michaelalex1
|
Vue
|
Code
| 257
| 1,352
|
<template>
<div>
<div id="layoutSidenav">
<div id="layoutSidenav_nav">
<nav class="sb-sidenav accordion sb-sidenav-dark" id="sidenavAccordion">
<div class="sb-sidenav-menu">
<div class="nav">
<div class="sb-sidenav-menu-heading">ALMACEN</div>
<a class="nav-link collapsed" href="#" data-toggle="collapse" data-target="#collapseLayouts" aria-expanded="false" aria-controls="collapseLayouts">
<div class="sb-nav-link-icon"><i class="fas fa-columns"></i></div>
PRODUCTO
<div class="sb-sidenav-collapse-arrow"><i class="fas fa-angle-down"></i></div>
</a>
<div class="collapse" id="collapseLayouts" aria-labelledby="headingOne" data-parent="#sidenavAccordion">
<nav class="sb-sidenav-menu-nested nav">
<router-link :to="{ name: 'ListCategory' }" class="nav-link">
<b-icon icon="chevron-right"></b-icon> Categoría
</router-link>
<router-link :to="{ name: 'ListProduct' }" class="nav-link">
<b-icon icon="chevron-right"></b-icon> Producto
</router-link>
</nav>
</div>
<div class="sb-sidenav-menu-heading">CLIENTES</div>
<a class="nav-link collapsed" href="#" data-toggle="collapse" data-target="#clientes" aria-expanded="false" aria-controls="collapseLayouts">
<div class="sb-nav-link-icon"><i class="fas fa-columns"></i></div>
CLIENTES
<div class="sb-sidenav-collapse-arrow"><i class="fas fa-angle-down"></i></div>
</a>
<div class="collapse" id="clientes" aria-labelledby="headingOne" data-parent="#sidenavAccordion">
<nav class="sb-sidenav-menu-nested nav">
<router-link :to="{ name: 'ListClient' }" class="nav-link" id="activo">
<b-icon icon="chevron-right"></b-icon> Listar
</router-link>
</nav>
</div>
<div class="sb-sidenav-menu-heading">VENTAS</div>
<a class="nav-link collapsed" href="#" data-toggle="collapse" data-target="#ventas" aria-expanded="false" aria-controls="collapseLayouts">
<div class="sb-nav-link-icon"><i class="fas fa-columns"></i></div>
VENTAS
<div class="sb-sidenav-collapse-arrow"><i class="fas fa-angle-down"></i></div>
</a>
<div class="collapse" id="ventas" aria-labelledby="headingOne" data-parent="#sidenavAccordion">
<nav class="sb-sidenav-menu-nested nav">
<router-link :to="{ name: 'ListVenta' }" class="nav-link" id="activo">
<b-icon icon="chevron-right"></b-icon> Ventas
</router-link>
</nav>
</div>
</div>
</div>
<div class="sb-sidenav-footer">
<div class="small">Ecomer</div>
Sistema ecomer
</div>
</nav>
</div>
<div id="layoutSidenav_content">
<main>
<transition name="slide-fade">
<router-view></router-view>
</transition>
</main>
<footer class="py-4 bg-light mt-auto">
<div class="container-fluid">
<div class="d-flex align-items-center justify-content-between small">
<div class="text-muted">Copyright © 2020</div>
<div>
<a href="#">Spaziour.com</a>
</div>
</div>
</div>
</footer>
</div>
</div>
</div>
</template>
<script>
export default {}
</script>
<style>
nav li:hover,
nav li:active{
background-color: indianred;
cursor: pointer;
}
/* Las animaciones de entrada y salida pueden usar */
/* funciones de espera y duración diferentes. */
.slide-fade-enter-active {
transition: all .3s ease;
}
.slide-fade-leave-active {
transition: all .8s cubic-bezier(1.0, 0.5, 0.8, 1.0);
}
.slide-fade-enter, .slide-fade-leave-to
/* .slide-fade-leave-active below version 2.1.8 */ {
transform: translateX(10px);
opacity: 0;
}
</style>
| 26,029
|
https://github.com/Wells4sure/stz/blob/master/app/Http/Controllers/Admin/RoutesController.php
|
Github Open Source
|
Open Source
|
MIT
| null |
stz
|
Wells4sure
|
PHP
|
Code
| 222
| 640
|
<?php
namespace App\Http\Controllers\admin;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Route;
use App\Http\Requests\Routes\CreateRoutesRequest;
class RoutesController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$routes =Route::get();
return view('admin.routes.index', compact('routes'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(CreateRoutesRequest $request)
{
$route = new Route;
$route->name = $request->name;
$route->origin = $request->origin;
$route->destination = $request->destination;
$route->price = $request->price;
if (!$route->save()) {
return redirect()->back()->with(['msg' => 'Action Failed Call Developer', 'type' => 'bg-info']);
}
return redirect()->back()->with(['msg' => 'Route created successfully', 'type' => 'bg-success']);
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
| 33,939
|
https://github.com/uwegeercken/tweakflow/blob/master/src/main/java/com/twineworks/tweakflow/lang/interpreter/memory/MemorySpaceInspector.java
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
tweakflow
|
uwegeercken
|
Java
|
Code
| 459
| 1,171
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2019 Twineworks GmbH
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.twineworks.tweakflow.lang.interpreter.memory;
import com.twineworks.collections.shapemap.ShapeKey;
import com.twineworks.collections.shapemap.ConstShapeMap;
import com.twineworks.tweakflow.lang.scope.Symbol;
import com.twineworks.tweakflow.lang.values.ValueInspector;
import com.twineworks.tweakflow.util.LangUtil;
public class MemorySpaceInspector {
public static String inspect(MemorySpace space){
StringBuilder out = new StringBuilder();
inspect(out, space, "", "", " ", false);
return out.toString();
}
public static String inspect(MemorySpace space, boolean expandFunctions){
StringBuilder out = new StringBuilder();
inspect(out, space, "", "", " ", expandFunctions);
return out.toString();
}
public static void inspect(StringBuilder out, MemorySpace space, String leadingIndent, String inheritedIndent, String indentationUnit, boolean expandFunctions){
if (space == null){
out.append(leadingIndent).append("null");
return;
}
MemorySpaceType spaceType = space.getMemorySpaceType();
boolean inspectChildren = false;
switch (spaceType){
case GLOBAL: {
out.append("# globals").append("\n");
inspectChildren = true;
break;
}
case UNIT: {
out.append("# units").append("\n");
inspectChildren = true;
break;
}
case UNIT_EXPORTS: {
out.append("# unit exports").append("\n");
inspectChildren = true;
break;
}
case MODULE: {
// components inside
Cell cell = (Cell) space;
out.append("# module ").append("\n");
inspectChildren = true;
break;
}
case INTERACTIVE: {
// components inside
out.append("# interactive").append("\n");
inspectChildren = true;
break;
}
case INTERACTIVE_SECTION: {
// components inside
out.append("# interactive section").append("\n");
inspectChildren = true;
break;
}
case LIBRARY: {
String name = ((Symbol) space.getScope()).getName();
out.append("# library \n");
inspectChildren = true;
break;
}
case VAR: {
Cell cell = (Cell) space;
ValueInspector.inspect(out, cell.getValue(), "", inheritedIndent, indentationUnit, expandFunctions);
out.append("\n");
inspectChildren = false;
break;
}
default: {
out.append("unknown memory space type: ").append(spaceType.name());
inspectChildren = false;
}
}
if (inspectChildren){
inspectChildren(out, space, leadingIndent, inheritedIndent, indentationUnit, expandFunctions);
}
}
private static void inspectChildren(StringBuilder out, MemorySpace space, String leadingIndent, String inheritedIndent, String indentationUnit, boolean expandFunctions){
ConstShapeMap<Cell> cells = space.getCells();
String childIndent = inheritedIndent+indentationUnit;
for (ShapeKey key : cells.keySet()) {
out.append(childIndent).append(LangUtil.escapeIdentifier(key.toString())).append(": ");
inspect(out, cells.get(key), childIndent, childIndent, indentationUnit, expandFunctions);
}
}
}
| 43,452
|
https://github.com/Nobledez/Spelunky2ls/blob/master/static/data.js
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
Spelunky2ls
|
Nobledez
|
JavaScript
|
Code
| 5,605
| 19,579
|
const blocks = {
"chunk_ground": 1,
"chunk_air": 2,
"chunk_door": 3,
"empty": 0,
"floor": 4,
"nonreplaceable_floor": 5,
"bone_block": 6,
"bush_block": 7,
"surface_floor": 8,
"surface_hidden_floor": 9,
"jungle_floor": 10,
"styled_floor": 11,
"minewood_floor": 12,
"minewood_floor_noreplace": 13,
"minewood_floor_hanging_hide": 14,
"stone_floor": 15,
"temple_floor": 16,
"pagoda_floor": 17,
"babylon_floor": 18,
"nonreplaceable_babylon_floor": 19,
"sunken_floor": 20,
"beehive_floor": 21,
"vlad_floor": 22,
"cog_floor": 23,
"mothership_floor": 24,
"duat_floor": 25,
"palace_floor": 26,
"guts_floor": 27,
"floor_hard": 28,
"adjacent_floor": 29,
"tomb_floor": 30,
"regenerating_block": 31,
"ladder": 32,
"ladder_plat": 33,
"vine": 34,
"growable_vine": 35,
"climbing_pole": 36,
"growable_climbing_pole": 37,
"platform": 38,
"pagoda_platform": 39,
"entrance": 40,
"entrance_shortcut": 41,
"exit": 42,
"door": 43,
"starting_exit": 44,
"door2": 45,
"door2_secret": 46,
"door_drop_held": 47,
"ghist_door2": 48,
"locked_door": 49,
"dm_spawn_point": 50,
"spikes": 51,
"upsidedown_spikes": 52,
"push_block": 53,
"powder_keg": 54,
"arrow_trap": 55,
"thorn_vine": 56,
"jungle_spear_trap": 57,
"falling_platform": 58,
"chainandblocks_ceiling": 59,
"chain_ceiling": 60,
"conveyorbelt_left": 61,
"conveyorbelt_right": 62,
"factory_generator": 63,
"crushtrap": 64,
"crushtraplarge": 65,
"quicksand": 66,
"timed_powder_keg": 67,
"elevator": 68,
"timed_forcefield": 69,
"forcefield_top": 70,
"ushabti": 71,
"construction_sign": 72,
"singlebed": 73,
"dresser": 74,
"bunkbed": 75,
"diningtable": 76,
"sidetable": 77,
"chair_looking_left": 78,
"chair_looking_right": 79,
"couch": 80,
"tv": 81,
"dog_sign": 82,
"shortcut_station_banner": 83,
"telescope": 84,
"treasure": 87,
"treasure_chest": 88,
"treasure_vaultchest": 89,
"potofgold": 90,
"goldbars": 91,
"crate": 92,
"crate_bombs": 93,
"crate_ropes": 94,
"crate_parachute": 95,
"rock": 96,
"littorch": 97,
"walltorch": 98,
"litwalltorch": 99,
"autowalltorch": 100,
"lockedchest": 101,
"tree_base": 102,
"mushroom_base": 103,
"turkey": 104,
"cooked_turkey": 105,
"royal_jelly": 106,
"clover": 107,
"pot": 108,
"cursed_pot": 109,
"haunted_corpse": 110,
"empty_mech": 111,
"snap_trap": 112,
"snake": 113,
"caveman": 114,
"caveman_asleep": 115,
"scorpion": 116,
"cavemanboss": 117,
"tikiman": 118,
"witchdoctor": 119,
"mantrap": 120,
"mosquito": 121,
"giant_spider": 122,
"robot": 123,
"imp": 124,
"lavamander": 125,
"vlad": 126,
"crown_statue": 127,
"olmec": 128,
"pillar": 129,
"anubis": 130,
"crocman": 131,
"cobra": 132,
"mummy": 133,
"sorceress": 134,
"catmummy": 135,
"necromancer": 136,
"leprechaun": 137,
"jiangshi": 138,
"octopus": 139,
"hermitcrab": 140,
"giantclam": 141,
"fountain_head": 142,
"fountain_drain": 143,
"kingu": 144,
"slidingwall_switch": 145,
"slidingwall_ceiling": 146,
"ufo": 147,
"alien": 148,
"landmine": 149,
"yeti": 150,
"spring_trap": 151,
"icefloor": 152,
"thinice": 153,
"alienqueen": 154,
"shopkeeper_vat": 155,
"alien_generator": 156,
"eggplant_altar": 157,
"moai_statue": 158,
"eggplant_child": 159,
"empress_grave": 160,
"lamassu": 161,
"laser_trap": 162,
"spark_trap": 163,
"olmite": 164,
"zoo_exhibit": 165,
"palace_entrance": 166,
"palace_table": 167,
"palace_table_tray": 168,
"palace_chandelier": 169,
"palace_candle": 170,
"palace_bookcase": 171,
"tiamat": 172,
"olmecship": 173,
"ammit": 174,
"pipe": 175,
"bigspear_trap": 176,
"sticky_trap": 177,
"mother_statue": 178,
"eggplant_door": 179,
"giant_frog": 180,
"jumpdog": 181,
"yama": 182,
"crushing_elevator": 183,
"altar": 184,
"idol": 185,
"idol_floor": 186,
"idol_hold": 187,
"storage_floor": 188,
"woodenlog_trap": 189,
"woodenlog_trap_ceiling": 190,
"cookfire": 191,
"drill": 192,
"udjat_socket": 193,
"vault_wall": 194,
"coffin": 195,
"ankh": 196,
"excalibur_stone": 197,
"honey_upwards": 198,
"honey_downwards": 199,
"mattock": 200,
"crossbow": 201,
"key": 202,
"plasma_cannon": 203,
"houyibow": 204,
"lightarrow": 205,
"shop_door": 206,
"shop_sign": 207,
"lamp_hang": 208,
"shop_wall": 209,
"shop_woodwall": 210,
"shop_pagodawall": 211,
"wanted_poster": 212,
"shopkeeper": 213,
"die": 214,
"merchant": 215,
"forcefield": 216,
"challenge_waitroom": 217,
"cavemanshopkeeper": 218,
"ghist_shopkeeper": 219,
"shop_item": 220,
"sleeping_hiredhand": 221,
"yang": 222,
"pen_floor": 223,
"pen_locked_door": 224,
"sister": 225,
"oldhunter": 226,
"thief": 227,
"madametusk": 228,
"bodyguard": 229,
"storage_guy": 230,
"water": 231,
"coarse_water": 232,
"lava": 233,
"stagnant_lava": 234
}
const items = {
"entrance": 5,
"entrance_drop": 6,
"exit": 7,
"exit_notop": 8,
"side": 0,
"path_normal": 1,
"path_notop": 3,
"path_drop": 2,
"path_drop_notop": 4,
"solid": 21,
"altar": 114,
"idol": 115,
"idol_top": 116,
"vault": 23,
"posse": 24,
"coffin_player": 25,
"coffin_player_vertical": 26,
"coffin_unlockable": 27,
"coffin_unlockable_left": 28,
"shop": 65,
"shop_left": 66,
"shop_attic": 71,
"shop_attic_left": 72,
"shop_entrance_up": 67,
"shop_entrance_up_left": 68,
"shop_entrance_down": 69,
"shop_entrance_down_left": 70,
"shop_basement": 73,
"shop_basement_left": 74,
"diceshop": 75,
"diceshop_left": 76,
"curioshop": 77,
"curioshop_left": 78,
"cavemanshop": 79,
"cavemanshop_left": 80,
"ghistshop": 134,
"empress_grave": 135,
"tuskdiceshop": 83,
"tuskdiceshop_left": 84,
"storage_room": 117,
"challenge_entrance": 81,
"challenge_entrance_left": 82,
"challenge_bottom": 91,
"challenge_0-0": 92,
"challenge_0-1": 93,
"challenge_0-2": 94,
"challenge_0-3": 95,
"challenge_1-0": 96,
"challenge_1-1": 97,
"challenge_1-2": 98,
"challenge_1-3": 99,
"challenge_special": 100,
"machine_bigroom_path": 102,
"machine_bigroom_side": 103,
"feeling_factory": 104,
"feeling_prison": 105,
"feeling_tomb": 106,
"machine_wideroom_path": 107,
"machine_wideroom_side": 108,
"machine_tallroom_path": 109,
"machine_tallroom_side": 110,
"machine_keyroom": 112,
"machine_rewardroom": 113,
"room2": 10,
"passage_horz": 11,
"passage_vert": 12,
"passage_turn": 13,
"beehive": 31,
"beehive_entrance": 32,
"udjatentrance": 29,
"udjattop": 30,
"blackmarket_entrance": 33,
"blackmarket_coffin": 34,
"blackmarket_exit": 35,
"vlad_drill": 119,
"vlad_entrance": 120,
"vlad_bottom_tunnel": 121,
"vlad_bottom_exit": 122,
"vlad_tunnel": 123,
"cog_altar_top": 124,
"mothership_entrance": 40,
"mothership_exit": 126,
"mothership_coffin": 41,
"apep": 127,
"lake_exit": 128,
"lake_normal": 129,
"lake_notop": 130,
"abzu_backdoor": 131,
"anubis_room": 38,
"moai": 39,
"lakeoffire_back_entrance": 36,
"lakeoffire_back_exit": 37,
"ushabti_entrance": 132,
"ushabti_room": 133,
"olmecship_room": 42,
"motherstatue_room": 43,
"pen_room": 45,
"sisters_room": 46,
"oldhunter_keyroom": 136,
"oldhunter_rewardroom": 137,
"oldhunter_cursedroom": 138,
"quest_thief1": 139,
"quest_thief2": 140,
"tuskfrontdiceshop": 47,
"tuskfrontdiceshop_left": 48,
"palaceofpleasure_0-0": 49,
"palaceofpleasure_0-1": 50,
"palaceofpleasure_0-2": 51,
"palaceofpleasure_1-0": 52,
"palaceofpleasure_1-1": 53,
"palaceofpleasure_1-2": 54,
"palaceofpleasure_2-0": 55,
"palaceofpleasure_2-1": 56,
"palaceofpleasure_2-2": 57,
"palaceofpleasure_3-0": 58,
"palaceofpleasure_3-1": 59,
"palaceofpleasure_3-2": 60,
"crashedship_entrance": 61,
"crashedship_entrance_notop": 62,
"chunk_door": 18,
"chunk_ground": 16,
"chunk_air": 17,
"cache": 14,
"ghistroom": 15
}
for (let i = 0; i < 0xF; ++i) {
for (let j = 0; j < 8; ++j) {
items[`setroom${i}-${j}`] = 141;
}
}
const bestiary = {
"snake": 219,
"bat": 223,
"caveman": 224,
"spider": 220,
"hangspider": 221,
"giantspider": 222,
"hornedlizard": 229,
"mole": 230,
"critterdungbeetle": 330,
"mantrap": 232,
"tikiman": 233,
"witchdoctor": 234,
"mosquito": 236,
"monkey": 237,
"critterbutterfly": 331,
"robot": 239,
"firebug": 240,
"imp": 242,
"lavamander": 243,
"vampire": 244,
"crittersnail": 332,
"crocman": 246,
"cobra": 247,
"sorceress": 249,
"cat": 250,
"necromancer": 251,
"leprechaun": 309,
"critterlocust": 336,
"jiangshi": 259,
"fish": 261,
"octopus": 262,
"hermitcrab": 263,
"female_jiangshi": 260,
"crabman": 310,
"critterfish": 333,
"critteranchovy": 334,
"crittercrab": 335,
"ufo": 265,
"landmine": 438,
"springtrap": 73,
"yeti": 267,
"critterpenguin": 337,
"critterfirefly": 338,
"olmite": 275,
"critterdrone": 339,
"frog": 282,
"firefrog": 283,
"tadpole": 286,
"giantfly": 287,
"critterslime": 340,
"bee": 277,
};
const chances = {
"arrowtrap_chance": 0,
"totemtrap_chance": 1,
"pushblock_chance": 2,
"snap_trap_chance": 3,
"jungle_spear_trap_chance": 4,
"spike_ball_chance": 5,
"chain_blocks_chance": 6,
"crusher_trap_chance": 7,
"liontrap_chance": 8,
"lasertrap_chance": 9,
"sparktrap_chance": 10,
"bigspeartrap_chance": 11,
"stickytrap_chance": 12,
"skulldrop_chance": 13,
"eggsac_chance": 14,
"minister_chance": 15,
"beehive_chance": 16,
"leprechaun_chance": 17
}
const textures = {};
const texture_cache = {};
const image_cache = {};
function AddTextures(category, code, path, tWidth, tHeight, width, height, x, y, _width, _height) {
textures[code] = [path, tWidth, tHeight, width, height, x, y, _width, _height]
}
class Texture {
constructor(img, x, y, width, height, tWidth, tHeight) {
[this.img, this.x, this.y, this.width, this.height, this.tWidth, this.tHeight] = [img, x, y, width, height, tWidth, tHeight];
}
draw(ctx, x, y, sx, sy) {
ctx.drawImage(this.img, this.x + sx, this.y + sy, this.width, this.height, x, y, this.width, this.height);
}
};
async function LoadTexture(code) {
let cache;
if (cache = texture_cache[code])
return cache;
if (!textures[code])
return;
const [path, tWidth, tHeight, w, h, x, y, _width, _height] = textures[code];
const img = await loadPath(path);
cache = texture_cache[code] = new Texture(img, x, y,
w,
h,
tWidth, tHeight);
return cache;
}
function loadPath(path) {
return new Promise((resolve, reject) => {
if (!image_cache[path]) {
const img = new Image();
img.src = 'Textures/' + path;
img.onload = () => resolve(img);
img.onerror = () => reject();
image_cache[path] = img;
} else {
const img = image_cache[path];
if (img.complete)
resolve(img);
else
img.addEventListener('load', () => resolve(img))
}
});
}
AddTextures(1, 1, "loading.png", 256, 256, 256, 256, 0, 0, 0, 0);
AddTextures(1, 2, "saving.png", 128, 128, 128, 128, 0, 0, 0, 0);
AddTextures(2, 3, "splash0.png", 1920, 1080, 1920, 1080, 0, 0, 0, 0);
AddTextures(2, 4, "splash1.png", 1920, 1080, 1920, 1080, 0, 0, 0, 0);
AddTextures(2, 5, "splash2.png", 1024, 256, 1024, 256, 0, 0, 0, 0);
AddTextures(4, 6, "fontfirasans.png", 512, 512, 512, 512, 0, 0, 0, 0);
AddTextures(3, 7, "fontyorkten.png", 512, 512, 512, 512, 0, 0, 0, 0);
AddTextures(4, 8, "fontmono.png", 256, 256, 64, 64, 0, 0, 0, 0);
AddTextures(1, 9, "fontdebug.png", 512, 512, 512, 512, 0, 0, 0, 0);
AddTextures(5, 53, "hud.png", 512, 512, 64, 64, 0, 0, 0, 0);
AddTextures(5, 54, "hud.png", 512, 512, 32, 32, 0, 128, 0x100, 0x40);
AddTextures(5, 55, "hud.png", 512, 512, 128, 128, 0, 0, 0, 0);
AddTextures(4, 56, "hud_text.png", 1024, 512, 1024, 128, 0, 0, 0, 0);
AddTextures(3, 57, "hud_controller_buttons.png", 1280, 1280, 128, 128, 0, 0, 0, 0);
AddTextures(3, 58, "hud_controller_buttons.png", 1280, 1280, 128, 128, 0, 0, 0, 0);
AddTextures(3, 59, "hud_controller_buttons.png", 1280, 1280, 128, 128, 0, 384, 0, 0);
AddTextures(3, 60, "hud_controller_buttons.png", 1280, 1280, 128, 128, 0, 768, 0, 0);
AddTextures(3, 61, "hud_controller_buttons.png", 1280, 1280, 128, 128, 0, 1152, 0, 0);
AddTextures(9, 62, "keyboard_buttons", 3072, 1024, 256, 256, 0, 0, 0, 0);
AddTextures(3, 87, "floor_surface.png", 1536, 1536, 128, 128, 0, 0, 0, 0);
AddTextures(3, 88, "base_eggship.png", 1024, 1024, 384, 384, 0, 0, 0, 0);
AddTextures(3, 89, "base_eggship.png", 1024, 1024, 384, 16, 640, 752, 0x180, 0x10);
AddTextures(3, 90, "base_eggship.png", 1024, 1024, 128, 128, 0, 0, 0, 0);
AddTextures(3, 91, "base_eggship.png", 1024, 1024, 128, 256, 384, 0, 0x80, 0x100);
AddTextures(3, 92, "base_eggship.png", 1024, 1024, 256, 256, 0, 0, 0, 0);
AddTextures(3, 93, "base_eggship.png", 1024, 1024, 348, 128, 512, 384, 0, 0);
AddTextures(3, 94, "base_eggship2.png", 1024, 1024, 384, 384, 0, 0, 0, 0);
AddTextures(3, 95, "base_eggship2.png", 1024, 1024, 256, 256, 0, 0, 0, 0);
AddTextures(3, 96, "base_eggship2.png", 1024, 1024, 512, 128, 512, 384, 0x200, 0x100);
AddTextures(3, 97, "base_eggship3.png", 1024, 1024, 384, 384, 384, 384, 0x100, 0);
AddTextures(3, 98, "base_eggship3.png", 1024, 1024, 384, 640, 0, 0, 0, 0);
AddTextures(3, 99, "base_eggship3.png", 1024, 1024, 128, 128, 0, 0, 0, 0);
AddTextures(3, 100, "base_eggship3.png", 1024, 1024, 256, 256, 0, 0, 0, 0);
AddTextures(3, 101, "base_skynight.png", 512, 512, 512, 512, 0, 0, 0, 0);
AddTextures(3, 102, "base_surface.png", 1024, 1024, 1024, 256, 0, 0, 0, 0);
AddTextures(3, 103, "base_surface.png", 1024, 1024, 512, 256, 0, 0, 0, 0);
AddTextures(3, 104, "base_surface2.png", 1024, 1024, 1024, 512, 0, 0, 0, 0);
AddTextures(3, 105, "deco_basecamp.png", 2048, 2048, 512, 512, 0, 0, 0, 0);
AddTextures(3, 106, "deco_basecamp.png", 2048, 2048, 128, 128, 0, 0, 0, 0);
AddTextures(3, 107, "deco_basecamp.png", 2048, 2048, 256, 128, 0, 0, 0, 0);
AddTextures(3, 108, "deco_basecamp.png", 2048, 2048, 256, 512, 0, 0, 0, 0);
AddTextures(3, 109, "deco_basecamp.png", 2048, 2048, 256, 256, 0, 0, 0, 0);
AddTextures(3, 110, "deco_basecamp.png", 2048, 2048, 256, 256, 0, 1408, 0, 0);
AddTextures(3, 111, "deco_basecamp.png", 2048, 2048, 896, 512, 0, 1024, 0, 0);
AddTextures(3, 112, "deco_basecamp.png", 2048, 2048, 256, 256, 896, 1024, 0x100, 0x200);
AddTextures(3, 113, "deco_tutorial.png", 1024, 1024, 512, 256, 0, 0, 0, 0);
AddTextures(3, 114, "deco_tutorial.png", 1024, 1024, 256, 256, 0, 512, 0, 0);
AddTextures(4, 10, "menu_title.png", 1920, 1080, 1920, 1080, 0, 0, 0, 0);
AddTextures(4, 11, "menu_titlegal.png", 1024, 1024, 1024, 1024, 0, 0, 0, 0);
AddTextures(4, 12, "main_body.png", 512, 512, 512, 512, 0, 0, 0, 0);
AddTextures(4, 13, "main_dirt.png", 1024, 256, 1024, 256, 0, 0, 0, 0);
AddTextures(4, 14, "main_door.png", 512, 1024, 512, 1024, 0, 0, 0, 0);
AddTextures(4, 15, "main_doorback.png", 1024, 1024, 1024, 1024, 0, 0, 0, 0);
AddTextures(4, 16, "main_doorframe.png", 1280, 1080, 1280, 1080, 0, 0, 0, 0);
AddTextures(4, 17, "main_fore1.png", 512, 1080, 512, 1080, 0, 0, 0, 0);
AddTextures(4, 18, "main_fore2.png", 768, 1080, 768, 1080, 0, 0, 0, 0);
AddTextures(4, 19, "main_head.png", 512, 512, 512, 512, 0, 0, 0, 0);
AddTextures(4, 20, "menu_disp.png", 1408, 768, 1024, 256, 192, 0, 0, 0);
AddTextures(4, 21, "menu_disp.png", 1408, 768, 128, 256, 0, 0, 0, 0);
AddTextures(4, 22, "menu_disp.png", 1408, 768, 1408, 256, 0, 256, 0, 0);
AddTextures(4, 23, "menu_charsel.png", 1920, 1080, 1920, 1080, 0, 0, 0, 0);
AddTextures(4, 24, "menu_chardoor.png", 512, 512, 512, 512, 0, 0, 0, 0);
AddTextures(4, 25, "menu_generic.png", 1920, 1080, 1920, 1080, 0, 0, 0, 0);
AddTextures(4, 26, "menu_cave1.png", 1920, 1080, 1920, 1080, 0, 0, 0, 0);
AddTextures(4, 27, "menu_cave2.png", 1920, 1080, 1920, 1080, 0, 0, 0, 0);
AddTextures(4, 28, "menu_brick1.png", 1920, 1080, 1920, 1080, 0, 0, 0, 0);
AddTextures(4, 29, "menu_brick2.png", 1920, 1080, 1920, 1080, 0, 0, 0, 0);
AddTextures(4, 30, "menu_basic.png", 1280, 1280, 1280, 1280, 0, 0, 0, 0);
AddTextures(4, 31, "menu_basic.png", 1280, 1280, 64, 64, 0, 0, 0, 0);
AddTextures(4, 32, "menu_basic.png", 1280, 1280, 128, 128, 0, 0, 0, 0);
AddTextures(4, 33, "menu_basic.png", 1280, 1280, 256, 128, 0, 0, 0, 0);
AddTextures(4, 34, "menu_basic.png", 1280, 1280, 512, 128, 384, 640, 0, 0);
AddTextures(4, 35, "menu_basic.png", 1280, 1280, 384, 128, 896, 640, 0, 0);
AddTextures(4, 36, "menu_basic.png", 1280, 1280, 128, 128, 768, 768, 0, 0);
AddTextures(4, 37, "menu_header.png", 1280, 1280, 1280, 1280, 0, 0, 0, 0);
AddTextures(4, 38, "menu_leader.png", 1280, 1280, 128, 128, 0, 0, 0, 0);
AddTextures(4, 39, "menu_leader.png", 1280, 1280, 1152, 128, 0, 0, 0, 0);
AddTextures(4, 40, "menu_leader.png", 1280, 1280, 256, 128, 0, 640, 0, 0);
AddTextures(4, 41, "menu_leader.png", 1280, 1280, 640, 384, 256, 640, 0, 0);
AddTextures(4, 42, "menu_deathmatch.png", 1920, 1080, 1920, 1080, 0, 0, 0, 0);
AddTextures(4, 43, "menu_deathmatch2.png", 1280, 1280, 128, 128, 0, 0, 0, 0);
AddTextures(4, 44, "menu_deathmatch3.png", 1024, 1024, 1024, 1024, 0, 0, 0, 0);
AddTextures(4, 45, "menu_deathmatch4.png", 1280, 1280, 1280, 1280, 0, 0, 0, 0);
AddTextures(4, 46, "menu_deathmatch5.png", 1280, 1280, 1280, 1280, 0, 0, 0, 0);
AddTextures(4, 47, "menu_deathmatch5.png", 1280, 1280, 128, 128, 0, 0, 0, 0);
AddTextures(4, 48, "menu_deathmatch5.png", 1280, 1280, 192, 128, 0, 0, 0, 0);
AddTextures(4, 49, "menu_deathmatch5.png", 1280, 1280, 32, 32, 0, 768, 0x360, 0x20);
AddTextures(4, 50, "menu_deathmatch6.png", 1920, 1080, 1920, 1080, 0, 0, 0, 0);
AddTextures(4, 51, "menu_online.png", 1920, 1080, 1920, 1080, 0, 0, 0, 0);
AddTextures(7, 52, "menu_tunnel.png", 512, 1152, 512, 384, 0, 0, 0, 0);
AddTextures(7, 63, "journal_pagetorn.png", 1024, 1024, 1024, 1024, 0, 0, 0, 0);
AddTextures(4, 64, "journal_back.png", 2048, 1024, 2048, 1024, 0, 0, 0, 0);
AddTextures(4, 65, "journal_pageflip.png", 2048, 1024, 2048, 1024, 0, 0, 0, 0);
AddTextures(4, 66, "journal_select.png", 640, 96, 640, 96, 0, 0, 0, 0);
AddTextures(4, 67, "journal_stickers.png", 800, 800, 80, 80, 0, 0, 0, 0);
AddTextures(4, 68, "journal_stickers.png", 800, 800, 80, 80, 0, 160, 0, 0);
AddTextures(4, 69, "journal_stickers.png", 800, 800, 160, 160, 0, 480, 0, 0);
AddTextures(7, 70, "journal_top_main.png", 2048, 1024, 2048, 1024, 0, 0, 0, 0);
AddTextures(7, 71, "journal_top_entry.png", 2048, 1024, 2048, 1024, 0, 0, 0, 0);
AddTextures(7, 72, "journal_top_gameover.png", 2048, 1024, 2048, 1024, 0, 0, 0, 0);
AddTextures(4, 73, "journal_top_profile.png", 2048, 1024, 2048, 1024, 0, 0, 0, 0);
AddTextures(7, 74, "journal_entry_bg.png", 1280, 1280, 320, 320, 0, 0, 0, 0);
AddTextures(4, 75, "journal_entry_place.png", 2560, 1280, 640, 320, 0, 0, 0, 0);
AddTextures(7, 76, "journal_entry_mons.png", 1600, 960, 160, 160, 0, 0, 0, 0);
AddTextures(7, 77, "journal_entry_mons_big.png", 1600, 1920, 320, 320, 0, 0, 0, 0);
AddTextures(7, 78, "journal_entry_people.png", 1600, 800, 160, 160, 0, 0, 0, 0);
AddTextures(7, 79, "journal_entry_people.png", 1600, 800, 320, 320, 640, 480, 0, 0);
AddTextures(7, 80, "journal_entry_items.png", 1600, 1600, 160, 160, 0, 0, 0, 0);
AddTextures(7, 81, "journal_elements.png", 512, 512, 192, 96, 0, 0, 0, 0);
AddTextures(7, 82, "journal_elements.png", 512, 512, 64, 64, 0, 32, 0, 0);
AddTextures(7, 83, "journal_entry_traps.png", 1600, 1600, 160, 160, 0, 0, 0, 0);
AddTextures(7, 84, "journal_entry_traps.png", 1600, 1600, 160, 320, 0, 640, 0, 0);
AddTextures(7, 85, "journal_entry_traps.png", 1600, 1600, 320, 320, 0, 1280, 0, 0);
AddTextures(7, 86, "journal_story.png", 1024, 2048, 1024, 2048, 0, 0, 0, 0);
AddTextures(3, 115, "floor_cave.png", 1536, 1536, 128, 128, 0, 0, 0, 0);
AddTextures(7, 116, "floor_cave.png", 1536, 1536, 128, 256, 0, 128, 0, 0);
AddTextures(7, 117, "floor_cave.png", 1536, 1536, 384, 320, 0, 896, 0x180, 0x280);
AddTextures(7, 118, "floor_cave.png", 1536, 1536, 256, 256, 1024, 768, 0, 0);
AddTextures(7, 119, "floor_cave.png", 1536, 1536, 256, 256, 1280, 768, 0, 0);
AddTextures(5, 120, "deco_cave.png", 1536, 1536, 512, 512, 0, 0, 0, 0);
AddTextures(7, 121, "deco_cave.png", 1536, 1536, 512, 640, 0, 0, 0, 0);
AddTextures(3, 122, "bg_cave.png", 512, 512, 512, 512, 0, 0, 0, 0);
AddTextures(7, 123, "floor_cave.png", 1536, 1536, 128, 128, 1280, 640, 0x80, 0x80);
AddTextures(7, 124, "floor_jungle.png", 1536, 1536, 128, 128, 0, 0, 0, 0);
AddTextures(7, 125, "floor_jungle.png", 1536, 1536, 384, 320, 0, 896, 0x180, 0x280);
AddTextures(7, 126, "floor_jungle.png", 1536, 1536, 256, 256, 1024, 768, 0, 0);
AddTextures(7, 127, "deco_jungle.png", 1536, 1536, 512, 512, 0, 0, 0, 0);
AddTextures(7, 128, "deco_jungle.png", 1536, 1536, 512, 640, 0, 0, 0, 0);
AddTextures(7, 129, "bg_jungle.png", 512, 512, 512, 512, 0, 0, 0, 0);
AddTextures(7, 130, "floor_jungle.png", 1536, 1536, 128, 128, 1280, 640, 0x80, 0x80);
AddTextures(7, 131, "floor_volcano.png", 1536, 1536, 128, 128, 0, 0, 0, 0);
AddTextures(7, 132, "floor_volcano.png", 1536, 1536, 256, 128, 0, 0, 0, 0);
AddTextures(7, 133, "floor_volcano.png", 1536, 1536, 384, 320, 0, 896, 0x180, 0x280);
AddTextures(7, 134, "floor_volcano.png", 1536, 1536, 256, 256, 1024, 768, 0, 0);
AddTextures(7, 135, "deco_volcano.png", 1536, 1536, 512, 512, 0, 0, 0, 0);
AddTextures(7, 136, "deco_volcano.png", 1536, 1536, 512, 640, 0, 0, 0, 0);
AddTextures(7, 137, "deco_volcano.png", 1536, 1536, 512, 384, 0, 640, 0, 0);
AddTextures(7, 138, "deco_volcano.png", 1536, 1536, 512, 512, 0, 1024, 0, 0);
AddTextures(7, 139, "bg_volcano.png", 512, 512, 512, 512, 0, 0, 0, 0);
AddTextures(7, 140, "floor_volcano.png", 1536, 1536, 128, 128, 1280, 640, 0x80, 0x80);
AddTextures(7, 141, "deco_jungle.png", 1536, 1536, 384, 320, 0, 640, 0x180, 0x280);
AddTextures(7, 142, "floorstyled_stone.png", 1280, 1280, 256, 256, 1024, 768, 0, 0);
AddTextures(7, 143, "bg_stone.png", 512, 512, 512, 512, 0, 0, 0, 0);
AddTextures(7, 144, "floorstyled_stone.png", 1280, 1280, 128, 128, 512, 768, 0x80, 0x80);
AddTextures(7, 145, "floor_temple.png", 1536, 1536, 128, 128, 0, 0, 0, 0);
AddTextures(7, 146, "floor_temple.png", 1536, 1536, 384, 320, 0, 896, 0x180, 0x280);
AddTextures(7, 147, "floor_temple.png", 1536, 1536, 256, 256, 1024, 768, 0, 0);
AddTextures(7, 148, "deco_temple.png", 1536, 1536, 512, 512, 0, 0, 0, 0);
AddTextures(7, 149, "deco_temple.png", 1536, 1536, 512, 640, 0, 0, 0, 0);
AddTextures(7, 150, "bg_temple.png", 512, 512, 512, 512, 0, 0, 0, 0);
AddTextures(7, 151, "floor_temple.png", 1536, 1536, 128, 128, 1280, 640, 0x80, 0x80);
AddTextures(7, 152, "floor_temple.png", 1536, 1536, 384, 320, 512, 0, 0x200, 0x280);
AddTextures(7, 153, "floor_tidepool.png", 1536, 1536, 128, 128, 0, 0, 0, 0);
AddTextures(7, 154, "floor_tidepool.png", 1536, 1536, 128, 256, 0, 128, 0, 0);
AddTextures(7, 155, "floor_tidepool.png", 1536, 1536, 256, 256, 0, 0, 0, 0);
AddTextures(7, 156, "floor_tidepool.png", 1536, 1536, 384, 320, 0, 896, 0x180, 0x280);
AddTextures(7, 157, "floor_tidepool.png", 1536, 1536, 256, 256, 1024, 768, 0, 0);
AddTextures(7, 158, "deco_tidepool.png", 1536, 1536, 512, 512, 0, 0, 0, 0);
AddTextures(7, 159, "deco_tidepool.png", 1536, 1536, 512, 640, 0, 0, 0, 0);
AddTextures(7, 160, "bg_tidepool.png", 512, 512, 512, 512, 0, 0, 0, 0);
AddTextures(7, 161, "floor_tidepool.png", 1536, 1536, 128, 128, 1280, 640, 0x80, 0x80);
AddTextures(7, 162, "floor_ice.png", 1536, 1536, 128, 128, 0, 0, 0, 0);
AddTextures(7, 163, "floor_ice.png", 1536, 1536, 384, 320, 0, 896, 0x180, 0x280);
AddTextures(7, 164, "floor_ice.png", 1536, 1536, 256, 256, 1024, 768, 0, 0);
AddTextures(7, 165, "deco_ice.png", 1536, 1536, 512, 512, 0, 0, 0, 0);
AddTextures(7, 166, "deco_ice.png", 1536, 1536, 512, 640, 0, 0, 0, 0);
AddTextures(7, 167, "deco_ice.png", 1536, 1536, 256, 256, 0, 640, 0, 0);
AddTextures(7, 168, "deco_ice.png", 1536, 1536, 512, 640, 0, 896, 0, 0);
AddTextures(7, 169, "bg_ice.png", 512, 512, 512, 512, 0, 0, 0, 0);
AddTextures(7, 170, "floor_ice.png", 1536, 1536, 128, 128, 1280, 640, 0x80, 0x80);
AddTextures(7, 171, "floor_ice.png", 1536, 1536, 256, 256, 384, 1152, 0x100, 0x100);
AddTextures(7, 172, "floor_babylon.png", 1536, 1536, 128, 128, 0, 0, 0, 0);
AddTextures(7, 173, "floor_babylon.png", 1536, 1536, 384, 320, 0, 896, 0x180, 0x280);
AddTextures(7, 174, "floor_babylon.png", 1536, 1536, 256, 256, 1024, 768, 0, 0);
AddTextures(7, 175, "floor_babylon.png", 1536, 1536, 256, 256, 384, 1024, 0x100, 0x200);
AddTextures(7, 176, "deco_babylon.png", 1536, 1536, 512, 512, 0, 0, 0, 0);
AddTextures(7, 177, "deco_babylon.png", 1536, 1536, 512, 640, 0, 0, 0, 0);
AddTextures(7, 178, "deco_babylon.png", 1536, 1536, 256, 128, 0, 0, 0, 0);
AddTextures(7, 180, "bg_babylon.png", 512, 512, 512, 512, 0, 0, 0, 0);
AddTextures(7, 181, "floor_babylon.png", 1536, 1536, 128, 128, 1280, 640, 0x80, 0x80);
AddTextures(7, 179, "items_ushabti.png", 1536, 1536, 128, 128, 0, 0, 0, 0);
AddTextures(7, 182, "floor_sunken.png", 1536, 1536, 128, 128, 0, 0, 0, 0);
AddTextures(7, 183, "floor_sunken.png", 1536, 1536, 256, 128, 0, 0, 0, 0);
AddTextures(7, 184, "floor_sunken.png", 1536, 1536, 256, 128, 384, 896, 0, 0);
AddTextures(7, 185, "floor_sunken.png", 1536, 1536, 384, 320, 0, 896, 0x180, 0x280);
AddTextures(7, 186, "floor_sunken.png", 1536, 1536, 256, 256, 1024, 768, 0, 0);
AddTextures(7, 187, "deco_eggplant.png", 1536, 1536, 384, 320, 0, 0, 0x180, 0x140);
AddTextures(7, 188, "deco_sunken.png", 1536, 1536, 512, 512, 0, 0, 0, 0);
AddTextures(7, 189, "deco_sunken.png", 1536, 1536, 512, 640, 0, 0, 0, 0);
AddTextures(7, 190, "deco_sunken.png", 1536, 1536, 256, 768, 0, 640, 0, 0);
AddTextures(7, 191, "deco_sunken.png", 1536, 1536, 128, 128, 256, 640, 0, 0);
AddTextures(7, 192, "bg_sunken.png", 512, 512, 512, 512, 0, 0, 0, 0);
AddTextures(7, 193, "floor_sunken.png", 1536, 1536, 128, 128, 1280, 640, 0x80, 0x80);
AddTextures(7, 194, "floor_sunken.png", 1536, 1536, 384, 320, 512, 0, 0x200, 0x280);
AddTextures(7, 195, "floor_sunken.png", 1536, 1536, 64, 64, 768, 1408, 0, 0);
AddTextures(7, 196, "bg_duat.png", 1024, 1024, 1024, 256, 0, 0, 0, 0);
AddTextures(7, 197, "floorstyled_duat.png", 1280, 1280, 128, 128, 512, 768, 0x80, 0x80);
AddTextures(7, 198, "bg_duat.png", 1024, 1024, 512, 256, 0, 0, 0, 0);
AddTextures(7, 199, "bg_duat.png", 1024, 1024, 128, 256, 512, 0, 0, 0);
AddTextures(7, 200, "bg_duat2.png", 1024, 1024, 1024, 512, 0, 0, 0, 0);
AddTextures(7, 201, "deco_temple.png", 1536, 1536, 512, 640, 0, 640, 0, 0);
AddTextures(7, 202, "floor_eggplant.png", 1536, 1536, 128, 128, 0, 0, 0, 0);
AddTextures(7, 203, "floor_eggplant.png", 1536, 1536, 256, 256, 0, 0, 0, 0);
AddTextures(7, 204, "floor_eggplant.png", 1536, 1536, 384, 320, 0, 896, 0x180, 0x280);
AddTextures(7, 205, "floor_eggplant.png", 1536, 1536, 256, 256, 1024, 768, 0, 0);
AddTextures(7, 206, "floor_eggplant.png", 1536, 1536, 256, 256, 1280, 768, 0, 0);
AddTextures(7, 207, "deco_eggplant.png", 1536, 1536, 512, 512, 0, 0, 0, 0);
AddTextures(7, 208, "bg_eggplant.png", 512, 512, 512, 512, 0, 0, 0, 0);
AddTextures(7, 209, "floor_eggplant.png", 1536, 1536, 128, 128, 1280, 640, 0x80, 0x80);
AddTextures(7, 210, "floorstyled_beehive.png", 1280, 1280, 128, 128, 0, 0, 0, 0);
AddTextures(7, 211, "bg_beehive.png", 512, 512, 512, 512, 0, 0, 0, 0);
AddTextures(7, 212, "floorstyled_beehive.png", 1280, 1280, 256, 256, 1024, 768, 0, 0);
AddTextures(7, 213, "deco_cosmic.png", 2048, 1536, 512, 512, 0, 0, 0, 0);
AddTextures(7, 214, "deco_cosmic.png", 2048, 1536, 128, 256, 0, 1280, 0, 0);
AddTextures(7, 215, "deco_cosmic.png", 2048, 1536, 128, 256, 0, 1024, 0, 0);
AddTextures(5, 216, "floorstyled_wood.png", 1280, 1280, 128, 128, 0, 0, 0, 0);
AddTextures(5, 217, "floorstyled_wood.png", 1280, 1280, 128, 256, 0, 0, 0, 0);
AddTextures(5, 218, "floorstyled_wood.png", 1280, 1280, 256, 256, 0, 0, 0, 0);
AddTextures(5, 219, "floorstyled_wood.png", 1280, 1280, 256, 256, 1024, 768, 0, 0);
AddTextures(5, 220, "floorstyled_wood.png", 1280, 1280, 256, 256, 1024, 512, 0, 0);
AddTextures(7, 221, "floorstyled_stone.png", 1280, 1280, 128, 128, 0, 0, 0, 0);
AddTextures(7, 222, "floorstyled_stone.png", 1280, 1280, 256, 128, 1024, 128, 0, 0);
AddTextures(7, 223, "floorstyled_stone.png", 1280, 1280, 256, 256, 0, 0, 0, 0);
AddTextures(7, 224, "floorstyled_stone.png", 1280, 1280, 256, 256, 1024, 768, 0, 0);
AddTextures(7, 225, "floorstyled_temple.png", 1280, 1280, 128, 128, 0, 0, 0, 0);
AddTextures(7, 226, "floorstyled_temple.png", 1280, 1280, 256, 384, 0, 0, 0, 0);
AddTextures(7, 227, "floorstyled_temple.png", 1280, 1280, 256, 256, 1024, 768, 0, 0);
AddTextures(7, 228, "floorstyled_pagoda.png", 1280, 1280, 128, 128, 0, 0, 0, 0);
AddTextures(7, 229, "floorstyled_pagoda.png", 1280, 1280, 128, 256, 0, 0, 0, 0);
AddTextures(7, 230, "floorstyled_pagoda.png", 1280, 1280, 256, 256, 1024, 768, 0, 0);
AddTextures(7, 231, "floorstyled_babylon.png", 1280, 1280, 128, 128, 0, 0, 0, 0);
AddTextures(7, 232, "floorstyled_babylon.png", 1280, 1280, 128, 256, 0, 0, 0, 0);
AddTextures(7, 233, "floorstyled_babylon.png", 1280, 1280, 256, 128, 0, 0, 0, 0);
AddTextures(7, 234, "floorstyled_babylon.png", 1280, 1280, 896, 128, 384, 1024, 0, 0);
AddTextures(7, 235, "floorstyled_babylon.png", 1280, 1280, 256, 256, 1024, 768, 0, 0);
AddTextures(7, 236, "floorstyled_sunken.png", 1280, 1280, 128, 128, 0, 0, 0, 0);
AddTextures(7, 237, "floorstyled_sunken.png", 1280, 1280, 256, 128, 0, 0, 0, 0);
AddTextures(7, 238, "floorstyled_sunken.png", 1280, 1280, 896, 128, 384, 1024, 0, 0);
AddTextures(7, 239, "floorstyled_sunken.png", 1280, 1280, 256, 256, 1024, 768, 0, 0);
AddTextures(7, 240, "floorstyled_vlad.png", 1280, 1280, 128, 128, 0, 0, 0, 0);
AddTextures(7, 241, "floorstyled_vlad.png", 1280, 1280, 128, 256, 0, 0, 0, 0);
AddTextures(7, 242, "floorstyled_vlad.png", 1280, 1280, 256, 384, 0, 0, 0, 0);
AddTextures(7, 243, "floorstyled_vlad.png", 1280, 1280, 256, 256, 1024, 768, 0, 0);
AddTextures(7, 244, "floorstyled_vlad.png", 1280, 1280, 128, 256, 1024, 384, 0x80, 0x100);
AddTextures(7, 245, "bg_vlad.png", 512, 512, 512, 512, 0, 0, 0, 0);
AddTextures(7, 246, "floorstyled_gold.png", 1280, 1280, 128, 128, 0, 0, 0, 0);
AddTextures(7, 247, "floorstyled_gold.png", 1280, 1280, 128, 256, 0, 0, 0, 0);
AddTextures(7, 248, "floorstyled_gold.png", 1280, 1280, 256, 256, 0, 0, 0, 0);
AddTextures(7, 249, "floorstyled_gold.png", 1280, 1280, 256, 256, 1024, 768, 0, 0);
AddTextures(7, 250, "floorstyled_gold_normal.png", 1280, 1280, 128, 128, 0, 0, 0, 0);
AddTextures(7, 251, "deco_gold.png", 1536, 1536, 512, 512, 0, 0, 0, 0);
AddTextures(7, 252, "deco_gold.png", 1536, 1536, 512, 640, 0, 0, 0, 0);
AddTextures(7, 253, "deco_gold.png", 1536, 1536, 384, 320, 0, 640, 0x180, 0x280);
AddTextures(7, 254, "bg_gold.png", 512, 512, 512, 512, 0, 0, 0, 0);
AddTextures(7, 255, "floorstyled_gold.png", 1280, 1280, 128, 128, 512, 768, 0x80, 0x80);
AddTextures(7, 256, "floorstyled_mothership.png", 1280, 1280, 128, 128, 0, 0, 0, 0);
AddTextures(7, 257, "bg_mothership.png", 512, 512, 512, 512, 0, 0, 0, 0);
AddTextures(7, 258, "floorstyled_duat.png", 1280, 1280, 128, 128, 0, 0, 0, 0);
AddTextures(7, 259, "floorstyled_palace.png", 1280, 1280, 128, 128, 0, 0, 0, 0);
AddTextures(7, 260, "floorstyled_palace.png", 1280, 1280, 256, 256, 1024, 768, 0, 0);
AddTextures(7, 261, "floorstyled_palace.png", 1280, 1280, 384, 256, 512, 1024, 0, 0);
AddTextures(7, 262, "floorstyled_palace.png", 1280, 1280, 256, 384, 768, 640, 0, 0);
AddTextures(7, 263, "floorstyled_guts.png", 1280, 1280, 128, 128, 0, 0, 0, 0);
AddTextures(7, 264, "deco_extra.png", 1536, 1536, 512, 640, 0, 0, 0, 0);
AddTextures(7, 265, "deco_extra.png", 1536, 1536, 512, 768, 0, 640, 0, 0);
AddTextures(5, 266, "floormisc.png", 1024, 1024, 128, 128, 0, 0, 0, 0);
AddTextures(5, 267, "floormisc.png", 1024, 1024, 256, 256, 0, 0, 0, 0);
AddTextures(5, 268, "border_main.png", 1024, 1024, 128, 128, 0, 0, 0, 0);
AddTextures(7, 269, "border_main.png", 1024, 1024, 256, 256, 0, 0, 0x100, 0x300);
AddTextures(3, 270, "char_yellow.png", 2048, 2048, 128, 128, 0, 0, 0, 0);
AddTextures(4, 271, "char_magenta.png", 2048, 2048, 128, 128, 0, 0, 0, 0);
AddTextures(4, 272, "char_cyan.png", 2048, 2048, 128, 128, 0, 0, 0, 0);
AddTextures(4, 273, "char_black.png", 2048, 2048, 128, 128, 0, 0, 0, 0);
AddTextures(4, 274, "char_cinnabar.png", 2048, 2048, 128, 128, 0, 0, 0, 0);
AddTextures(4, 275, "char_green.png", 2048, 2048, 128, 128, 0, 0, 0, 0);
AddTextures(4, 276, "char_olive.png", 2048, 2048, 128, 128, 0, 0, 0, 0);
AddTextures(4, 277, "char_white.png", 2048, 2048, 128, 128, 0, 0, 0, 0);
AddTextures(4, 278, "char_cerulean.png", 2048, 2048, 128, 128, 0, 0, 0, 0);
AddTextures(4, 279, "char_blue.png", 2048, 2048, 128, 128, 0, 0, 0, 0);
AddTextures(4, 280, "char_lime.png", 2048, 2048, 128, 128, 0, 0, 0, 0);
AddTextures(4, 281, "char_lemon.png", 2048, 2048, 128, 128, 0, 0, 0, 0);
AddTextures(4, 282, "char_iris.png", 2048, 2048, 128, 128, 0, 0, 0, 0);
AddTextures(4, 283, "char_gold.png", 2048, 2048, 128, 128, 0, 0, 0, 0);
AddTextures(4, 284, "char_red.png", 2048, 2048, 128, 128, 0, 0, 0, 0);
AddTextures(4, 285, "char_pink.png", 2048, 2048, 128, 128, 0, 0, 0, 0);
AddTextures(4, 286, "char_violet.png", 2048, 2048, 128, 128, 0, 0, 0, 0);
AddTextures(4, 287, "char_gray.png", 2048, 2048, 128, 128, 0, 0, 0, 0);
AddTextures(4, 288, "char_khaki.png", 2048, 2048, 128, 128, 0, 0, 0, 0);
AddTextures(4, 289, "char_orange.png", 2048, 2048, 128, 128, 0, 0, 0, 0);
AddTextures(7, 290, "char_hired.png", 2048, 2048, 128, 128, 0, 0, 0, 0);
AddTextures(7, 291, "char_eggchild.png", 2048, 2048, 128, 128, 0, 0, 0, 0);
AddTextures(3, 292, "monsters_pets.png", 1536, 1536, 128, 128, 0, 0, 0, 0);
AddTextures(4, 293, "monstersbasic01.png", 2048, 2048, 128, 128, 0, 0, 0, 0);
AddTextures(7, 294, "monstersbasic02.png", 2048, 2048, 128, 128, 0, 0, 0, 0);
AddTextures(7, 295, "monstersbasic03.png", 2048, 2048, 128, 128, 0, 0, 0, 0);
AddTextures(7, 296, "monsters01.png", 2048, 2048, 128, 128, 0, 0, 0, 0);
AddTextures(7, 297, "monsters02.png", 2048, 2048, 128, 128, 0, 0, 0, 0);
AddTextures(7, 298, "monsters03.png", 2048, 2048, 128, 128, 0, 0, 0, 0);
AddTextures(7, 299, "monsters03.png", 2048, 2048, 256, 128, 0, 0, 0, 0);
AddTextures(7, 300, "monstersbig01.png", 2048, 2048, 256, 256, 0, 0, 0, 0);
AddTextures(7, 301, "monstersbig02.png", 2048, 2048, 256, 256, 0, 0, 0, 0);
AddTextures(7, 302, "monstersbig02.png", 2048, 2048, 256, 384, 512, 1024, 0, 0);
AddTextures(7, 303, "monstersbig03.png", 2048, 2048, 256, 256, 0, 0, 0, 0);
AddTextures(7, 304, "monstersbig04.png", 2048, 2048, 256, 256, 0, 0, 0, 0);
AddTextures(7, 305, "monstersbig04.png", 2048, 2048, 128, 256, 0, 0, 0, 0);
AddTextures(7, 306, "monstersbig04.png", 2048, 2048, 384, 256, 0, 1792, 0, 0);
AddTextures(7, 307, "monstersbig05.png", 2048, 2048, 256, 256, 0, 0, 0, 0);
AddTextures(7, 308, "monstersbig05.png", 2048, 2048, 256, 128, 0, 0, 0, 0);
AddTextures(7, 310, "monstersbig05.png", 2048, 2048, 384, 384, 0, 1664, 0, 0);
AddTextures(7, 311, "monstersbig05.png", 2048, 2048, 128, 384, 0, 1280, 0, 0);
AddTextures(7, 312, "monstersbig05.png", 2048, 2048, 128, 128, 0, 896, 0, 0);
AddTextures(7, 313, "monstersbig06.png", 2048, 2048, 256, 256, 640, 0, 0x500, 0x800);
AddTextures(7, 314, "monstersbig06.png", 2048, 2048, 640, 768, 0, 0, 0x280, 0x600);
AddTextures(7, 315, "monstersbig06.png", 2048, 2048, 512, 640, 1536, 256, 0x200, 0x280);
AddTextures(7, 316, "monstersbig06.png", 2048, 2048, 256, 256, 640, 896, 0x500, 0x100);
AddTextures(7, 317, "monstersbig06.png", 2048, 2048, 256, 384, 640, 256, 0, 0);
AddTextures(7, 318, "monstersbig06.png", 2048, 2048, 128, 384, 896, 256, 0, 0);
AddTextures(7, 319, "monstersbig06.png", 2048, 2048, 256, 384, 1024, 256, 0, 0);
AddTextures(7, 320, "monstersbig06.png", 2048, 2048, 256, 384, 1280, 256, 0, 0);
AddTextures(7, 321, "monstersbig06.png", 2048, 2048, 256, 256, 640, 640, 0, 0);
AddTextures(7, 322, "monstersbig06.png", 2048, 2048, 256, 256, 0, 1280, 0, 0);
AddTextures(7, 323, "monstersbig06.png", 2048, 2048, 512, 256, 0, 1536, 0, 0);
AddTextures(7, 324, "monsters_ghost.png", 2048, 2048, 256, 256, 0, 0, 0, 0);
AddTextures(7, 325, "monsters_ghost.png", 2048, 2048, 128, 128, 0, 1280, 0, 0);
AddTextures(7, 326, "monsters_olmec.png", 2048, 2048, 512, 512, 0, 0, 0, 0);
AddTextures(7, 327, "monsters_olmec.png", 2048, 2048, 512, 256, 0, 0, 0, 0);
AddTextures(7, 328, "monsters_olmec.png", 2048, 2048, 256, 256, 0, 0, 0, 0);
AddTextures(7, 329, "monsters_olmec.png", 2048, 2048, 256, 256, 0, 128, 0, 0);
AddTextures(7, 330, "monsters_olmec.png", 2048, 2048, 256, 128, 0, 0, 0, 0);
AddTextures(7, 331, "monsters_osiris.png", 2048, 2048, 640, 896, 0, 0, 0, 0);
AddTextures(7, 332, "monsters_osiris.png", 2048, 2048, 384, 384, 0, 896, 0, 0);
AddTextures(7, 333, "monsters_osiris.png", 2048, 2048, 384, 384, 0, 1280, 0, 0);
AddTextures(7, 334, "monsters_osiris.png", 2048, 2048, 128, 128, 1920, 1664, 0x80, 0x180);
AddTextures(7, 335, "monsters_osiris.png", 2048, 2048, 384, 128, 1536, 1152, 0, 0);
AddTextures(7, 336, "monsters_tiamat.png", 2048, 2048, 256, 384, 0, 0, 0, 0);
AddTextures(7, 337, "monsters_tiamat.png", 2048, 2048, 384, 384, 0, 0, 0, 0);
AddTextures(7, 338, "monsters_tiamat.png", 2048, 2048, 128, 384, 384, 384, 0, 0);
AddTextures(7, 339, "monsters_tiamat.png", 2048, 2048, 128, 256, 1536, 1152, 0, 0);
AddTextures(7, 340, "monsters_tiamat.png", 2048, 2048, 256, 256, 1280, 1152, 0, 0);
AddTextures(7, 341, "monsters_tiamat.png", 2048, 2048, 128, 640, 1920, 1408, 0, 0);
AddTextures(7, 342, "monsters_tiamat.png", 2048, 2048, 1152, 640, 768, 1408, 0, 0);
AddTextures(7, 343, "monsters_tiamat.png", 2048, 2048, 512, 512, 768, 896, 0, 0);
AddTextures(7, 344, "monsters_tiamat.png", 2048, 2048, 768, 1280, 0, 768, 0, 0);
AddTextures(7, 345, "monsters_yama.png", 1280, 1280, 256, 384, 1024, 0, 0, 0);
AddTextures(7, 346, "monsters_yama.png", 1280, 1280, 1024, 1280, 0, 0, 0, 0);
AddTextures(7, 347, "monsters_yama.png", 1280, 1280, 256, 512, 1024, 768, 0, 0);
AddTextures(7, 348, "monsters_hundun.png", 1280, 1280, 384, 512, 0, 0, 0, 0);
AddTextures(7, 349, "monsters_hundun.png", 1280, 1280, 128, 256, 384, 0, 0x80, 0x100);
AddTextures(7, 350, "monsters_hundun.png", 1280, 1280, 128, 256, 384, 256, 0x80, 0x100);
AddTextures(7, 351, "monsters_hundun.png", 1280, 1280, 256, 256, 512, 0, 0x300, 0x200);
AddTextures(7, 352, "monsters_hundun.png", 1280, 1280, 128, 128, 0, 512, 0x500, 0x100);
AddTextures(7, 353, "monsters_hundun.png", 1280, 1280, 384, 384, 0, 768, 0, 0);
AddTextures(7, 354, "monstersbig04.png", 2048, 2048, 128, 128, 1792, 256, 0x100, 0x100);
AddTextures(7, 355, "monsters02.png", 2048, 2048, 128, 128, 640, 640, 0x300, 0x80);
AddTextures(7, 356, "monsters02.png", 2048, 2048, 128, 128, 768, 1664, 0x300, 0x80);
AddTextures(3, 357, "items.png", 2048, 2048, 128, 128, 0, 0, 0, 0);
AddTextures(7, 358, "mounts.png", 2048, 2048, 128, 128, 0, 0, 0x800, 0x100);
AddTextures(5, 359, "fx_explosion.png", 1024, 1024, 256, 256, 0, 0, 0, 0);
AddTextures(4, 360, "fx_small.png", 1024, 1024, 128, 128, 0, 0, 0, 0);
AddTextures(5, 361, "fx_small2.png", 1024, 1024, 128, 128, 0, 0, 0, 0);
AddTextures(4, 362, "fx_small3.png", 1024, 1024, 128, 128, 0, 0, 0, 0);
AddTextures(4, 363, "fx_big.png", 1024, 1024, 256, 256, 0, 0, 0, 0);
AddTextures(4, 364, "fx_rubble.png", 1024, 1280, 128, 128, 0, 0, 0, 0);
AddTextures(7, 365, "fx_ankh.png", 2048, 2048, 512, 768, 0, 0, 0, 0);
AddTextures(7, 366, "fx_ankh.png", 2048, 2048, 256, 256, 0, 1536, 0x800, 0x200);
AddTextures(5, 367, "shadows.png", 1024, 256, 256, 256, 0, 0, 0, 0);
AddTextures(7, 368, "coffins.png", 1024, 768, 256, 256, 0, 0, 0x200, 0x100);
AddTextures(7, 369, "coffins.png", 1024, 768, 256, 256, 0, 256, 0x200, 0x100);
AddTextures(7, 370, "coffins.png", 1024, 768, 256, 256, 0, 512, 0x200, 0x100);
AddTextures(7, 371, "coffins.png", 1024, 768, 256, 256, 512, 0, 0x200, 0x100);
AddTextures(7, 372, "coffins.png", 1024, 768, 256, 256, 512, 256, 0x200, 0x100);
AddTextures(4, 373, "credits.png", 1024, 1024, 256, 256, 0, 0, 0, 0);
AddTextures(4, 374, "credits.png", 1024, 1024, 128, 128, 0, 512, 0, 0);
AddTextures(9, 375, "liquidgradient_water", 1, 1, 1, 1, 0, 0, 0, 0);
AddTextures(9, 376, "liquidgradient_eggplant_water", 1, 1, 1, 1, 0, 0, 0, 0);
AddTextures(9, 377, "liquidgradient_lava", 1, 1, 1, 1, 0, 0, 0, 0);
AddTextures(7, 378, "noise0.png", 512, 512, 512, 512, 0, 0, 0, 0);
AddTextures(7, 379, "noise1.png", 512, 512, 512, 512, 0, 0, 0, 0);
AddTextures(3, 380, "bayer8.png", 8, 8, 8, 8, 0, 0, 0, 0);
AddTextures(3, 381, "lut_original.png", 512, 512, 512, 512, 0, 0, 0, 0);
AddTextures(5, 382, "lut_backlayer.png", 512, 512, 512, 512, 0, 0, 0, 0);
AddTextures(7, 383, "lut_blackmarket.png", 512, 512, 512, 512, 0, 0, 0, 0);
AddTextures(7, 384, "lut_vlad.png", 512, 512, 512, 512, 0, 0, 0, 0);
AddTextures(7, 385, "lut_icecaves.png", 512, 512, 512, 512, 0, 0, 0, 0);
AddTextures(7, 386, "shine.png", 512, 512, 512, 512, 0, 0, 0, 0);
AddTextures(8, 387, "OldTextures/ai.png", 64, 128, 16, 16, 0, 0, 0, 0);
const specific_textures = {
"DwellingArea": {
10: 367,
9: 122,
8: 121,
7: 119,
6: 118,
5: 116,
4: 123
},
"JungleArea": {
10: 368,
9: 128,
8: 127,
7: 126,
6: 125,
5: 124,
4: 129
},
"VolcanoArea": {
10: 367,
9: 137,
8: 136,
7: 135,
6: 134,
5: 132,
4: 140
},
"OlmecArea": {
10: 367,
9: 129,
8: 128,
7: 143,
6: 142,
5: 125,
4: 144
},
"TempleArea": {
10: 368,
9: 150,
8: 149,
7: 148,
6: 147,
5: 146,
4: 151
},
"TidepoolArea": {
10: 367,
9: 160,
8: 159,
7: 158,
6: 157,
5: 154,
4: 161
},
"IceCavesArea": {
10: 367,
9: 167,
8: 166,
7: 165,
6: 164,
5: 163,
4: 170
},
"BabylonArea": {
10: 367,
9: 178,
8: 177,
7: 175,
6: 174,
5: 173,
4: 181
},
"SunkenCityArea": {
10: 367,
9: 190,
8: 189,
7: 187,
6: 186,
5: 183,
4: 193
},
"CityOfGoldArea": {
10: 369,
9: 251,
8: 250,
7: 148,
6: 252,
5: 146,
4: 253
},
"AbzuArea": {
10: 367,
9: 160,
8: 159,
7: 158,
6: 157,
5: 154,
4: 161
},
"TiamatArea": {
10: 367,
9: 178,
8: 177,
7: 175,
6: 174,
5: 154,
4: 181
},
"EggplantArea": {
10: 367,
9: -1,
8: 208,
7: 206,
6: 205,
5: 203,
4: 209
},
"HundunArea": {
10: 367,
9: 190,
8: 189,
7: 187,
6: 186,
5: 183,
4: 193
},
"BasecampArea": {
10: 367,
9: 122,
8: 121,
7: 119,
6: 118,
5: 116,
4: 123
}
};
export default { blocks, items, bestiary, chances, LoadTexture, textures, specific_textures };
// For debugging
window.datasheet = this;
| 43,866
|
https://github.com/kokoye2007/converter/blob/master/index.php
|
Github Open Source
|
Open Source
|
MIT
| 2,014
|
converter
|
kokoye2007
|
PHP
|
Code
| 1,129
| 4,201
|
<?php include_once('./view.php'); ?>
<?php include_once('./header.php'); ?>
<?php
//var_dump($font_options);
?>
<header role="banner">
<div class="container">
<h1 class="text-center gray-light">Myanmar Font Converter</h1>
<nav class="navbar navbar-inverse" role="navigation">
<ul class="nav navbar-nav nav-pills">
<li><a href="#home" data-toggle="tab"><span class="glyphicon glyphicon-home"> Home</span></a></li>
<li><a href="#uploadsect" data-toggle="tab"><span class="glyphicon glyphicon-upload"> Upload</span></a></li>
<li><a href="#about" data-toggle="tab"><span class="glyphicon glyphicon-info-sign"> About</span></a></li>
<li><a href="#help" data-toggle="tab"><span class="glyphicon glyphicon-question-sign"> Help</span></a></li>
</ul>
</nav>
</div>
</header>
<div class="container hide-time">
<section class="alert alert-info">
<p id="message">
<?php if(isset($time)){ echo $time;} ?>
</p>
</section>
</div>
<section id="myTabContent" class="tab-content">
<section class="tab-pane fade in active" id="home">
<div class="container">
<form id="converter" class="form-horizontal" role="form" enctype="multipart/form-data" action="" method="POST">
<div class="row">
<fieldset id="input-set" class="col-xs-6">
<legend>Input</legend>
<div class="control-group">
<label for="input" class="control-label">Input Text</label>
<div class="controls">
<textarea name="input" id="input" rows="10" class="form-control input-xlarge textareaH" placeholder="" style="font-family:<?php echo $ifontfamily; ?> "></textarea>
</div>
</div>
<div class="input-group">
<label for="ifont" class="control-label">Select Input Font : </label>
<select name="ifont" id="ifont">
<?php
foreach($font_options['ifont'] as $name){
if(isset($ichecked) && $ichecked == $name){
echo "<option value='$name' id='$name' selected='selected'>".ucwords($name)."</option>";
}elseif($name == 'ayar'){
echo "<option value='$name' id='$name' selected='selected'>".ucwords($name)."</option>";
}else{
echo "<option value='$name' id='$name'>".ucwords($name)."</option>";
}
}
?>
</select>
</div>
</fieldset>
<fieldset id="output-set" class="col-xs-6">
<legend>Output</legend>
<div class="control-group">
<label for="output" class="control-label">Output Text</label>
<div class="controls">
<textarea rows="10" class="panel-body form-control textareaH" id="output" style="font-family:<?php echo $ofontfamily; ?> " contenteditable><?php if(isset($output_text) && ($output_text != '')){ echo $output_text;}else{ echo "Copy output text from here!";}?></textarea>
</div>
</div>
<div class="input-group">
<label for="ofont" class="control-label">Select Output Font : </label>
<select name="ofont" id="ofont">
<?php
foreach($font_options['ofont'] as $name){
if(isset($ochecked) && $ochecked == $name){
echo "<option value='$name' id='$name' selected='selected'>".ucwords($name)."</option>";
}elseif($name == 'myanmar3'){
echo "<option value='$name' id='$name' selected='selected'>".ucwords($name)."</option>";
}else{
echo "<option value='$name' id='$name'>".ucwords($name)."</option>";
}
}
?>
</select>
</div>
</fieldset>
</div>
<div class="clearfix visible-xs"></div>
<fieldset id="control-set1">
<div id="controls">
<div class="input-groups">
<label for="en_zwsp" class="control-label checkbox-inline">
<input type="checkbox" name="en_zwsp" id="en_zwsp">
Zero-Width-Space</label>
<p class="help-block">Selecting this will add Zero-Width-Space unicode character according to Myanmar word break rules.</p>
</div>
</div>
</fieldset>
<fieldset id="control-set2">
<div id="ascii-controls">
<div class="input-groups">
<label for="spelling_check" class="control-label checkbox-inline">
<input type="checkbox" name="spelling_check" id="spelling_check">
Check English Words automatically</label>
<label for="text-only" class="control-label checkbox-inline">
<input type="checkbox" name="text-only" id="text-only" checked="checked">
Text only input</label>
<label for="suggested" class="control-label checkbox-inline">
<input type="checkbox" name="suggested" id="suggested">
Use user suggested words list. <span class="text-danger">Use with care!</span></label>
</div>
<div class="input-group">
<label for="exceptions">Suggest</label>
<input type="text" name="exceptions" id="exceptions" class="form-control">
<p class="help-block">Enter words list seperated by comma to ignore in convertion! If your word is less than 4 letters, please use at least 2 words combined. <br>For Example: if your want to ignore the word "you" or "I" from the sentence "I love you.", use "I love" or "love you." or the whole sentence "I love you."</p>
</div>
</div>
<input type="submit" name="submit" id="submit" class="btn btn-primary" value="Convert">
</fieldset>
</form>
</div>
</section>
<section class="tab-pane fade" id="uploadsect">
<div class="container">
<form id="uploadform" class="form-horizontal" role="form" enctype="multipart/form-data" action="" method="POST">
<div class="row">
<fieldset id="input-set" class="col-xs-6">
<legend>Input</legend>
<div class="input-group">
<select name="ifont" id="uifont">
<?php
foreach($font_options['ifont'] as $name){
if(isset($ichecked) && $ichecked == $name){
echo "<option value='$name' id='$name' selected='selected'>".ucwords($name)."</option>";
}elseif($name == 'ayar'){
echo "<option value='$name' id='$name' selected='selected'>".ucwords($name)."</option>";
}else{
echo "<option value='$name' id='$name'>".ucwords($name)."</option>";
}
}
?>
</select>
<label for="ifont" class="control-label">Input Font</label>
</div>
</fieldset>
<fieldset id="output-set" class="col-xs-6">
<legend>Output</legend>
<div class="input-group">
<select name="ofont" id="uofont">
<?php
foreach($font_options['ofont'] as $name){
if(isset($ochecked) && $ochecked == $name){
echo "<option value='$name' id='$name' selected='selected'>".ucwords($name)."</option>";
}elseif($name == 'myanmar3'){
echo "<option value='$name' id='$name' selected='selected'>".ucwords($name)."</option>";
}else{
echo "<option value='$name' id='$name'>".ucwords($name)."</option>";
}
}
?>
</select>
<label for="ofont" class="control-label">Output Font</label>
</div>
</fieldset>
</div>
<div class="clearfix visible-xs"></div>
<fieldset id="upload-set">
<legend>File Upload</legend>
<input type="file" name="inputfile" value="browse" class="input-file" id="inputfile">
</fieldset>
<fieldset id="control-set3">
<div id="controls">
<div class="input-groups">
<label for="en_zwsp" class="control-label checkbox-inline">
<input type="checkbox" name="en_zwsp" id="en_zwsp">
Add Zero-Width-Space</label>
<p class="help-block">Selecting this will add Zero-Width-Space unicode character according to Myanmar word break rules.</p>
</div>
</div>
</fieldset>
<fieldset id="control-set4">
<div id="ascii-controls">
<div class="input-groups">
<label for="spelling_check" class="control-label checkbox-inline">
<input type="checkbox" name="spelling_check" id="spelling_check">
Check English Words automatically</label>
<label for="text-only" class="control-label checkbox-inline">
<input type="checkbox" name="text-only" id="text-only" checked="checked">
Text only input</label>
<label for="suggested" class="control-label checkbox-inline">
<input type="checkbox" name="suggested" id="suggested">
Use user suggested words list</label>
</div>
<div class="input-group">
<label for="exceptions">Exceptions</label>
<input type="text" name="exceptions" id="exceptions" class="form-control">
<p class="help-block">Enter words list seperated by comma to ignore in convertion! If your word is less than 4 letters, please use at least 2 words combined. <br>For Example: if your want to ignore the word "you" or "I" from the sentence "I love you.", use "I love" or "love you." or the whole sentence "I love you."</p>
</div>
</div>
<button type="submit" name="submit" id="submit" class="btn btn-primary">Convert</button>
</fieldset>
</form>
</div>
</section>
<section class="tab-pane fade" id="about">
<div class="container">
<h3>About</h3>
<div class="panel">
This is the fastest and most realiable converter ever for Burmese Fonts encodings.
</div>
<h4>License</h4>
<div class="panel">This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.</div>
<h4>Details</h4>
<div class="panel">Name: Myanmar Font Converter<br>
Web URI: <a href="http://converter.myanmapress.com">http://converter.myanmapress.com</a><br>
Description: Use to convert ASCII and Unicode fonts vice verse.<br>
Version: 2.0<br>
Author: Sithu Thwin<br>
Author URI: <a href="http://www.thwin.net/">http://www.thwin.net/</a><br>
License: GPLv2 or later<br>
</div>
<h4>Instructions</h4>
<p>For detail instructions, use Help tab section</p>
</div>
</section>
<section class="tab-pane fade" id="help">
<div class="container">
<h4>ASCII controls</h4>
<div class="panel">
<p>
When converting from ASCII based fonts, you have some options to choose. (3 checkboxs and 1 text input box)
</p>
<p>
1st checkbox (check English Words automatically) is to check English words and Burmese words when converting mixed content of English and Burmese.
</p>
<p>2nd checkbox ( Text only input) is checked by default. It needs to be unchecked if you are converting html/xml contents. But converting time will take longer than text only contents if you unchecked this.</p>
<p>3rd checkbox (Use user suggested words) is to use user suggested word list dictionary when checking between English and Burmese words. All user suggested words list are come from below text box and saved on server.</p>
<p>Suggest (Textbox) is to suggest English words. All suggested words are ignored from converting (which means substitution English alphabet with Burmese alphabet will not happen for English words). So all suggested English words are remain unchanged when converting from ASCII fonts. Important! You need to use phrase instead only one word if your word is less than 4 letters.</p>
</div>
</div>
</section>
</section>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title"><?php if(isset($error_message) || isset($type_error)){echo 'Error';}else{ echo 'Output Results';} ?></h4>
</div>
<div class="modal-body" id="error">
<?php if(isset($error_message)){echo $error_message;} ?>
<?php if(isset($type_error)){echo $type_error;} ?>
</div>
<!--textarea row="10" class="modal-body form-control" name="ajax_output" id="ajax_output" contenteditable></textarea-->
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<?php include_once('./footer.php'); ?>
| 50,776
|
https://github.com/dongdapeng110/SharpDevelopTest/blob/master/data/templates/project/VB/WPFAssemblyInfo.vb
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
SharpDevelopTest
|
dongdapeng110
|
Visual Basic
|
Code
| 131
| 269
|
#Region "Imports directives"
Imports System.Resources
Imports System.Windows
#End Region
' In order to begin building localizable applications, set
' <UICulture>CultureYouAreCodingWith</UICulture> in your .vbproj file
' inside a <PropertyGroup>. For example, if you are using US english
' in your source files, set the <UICulture> to en-US. Then uncomment
' the NeutralResourceLanguage attribute below. Update the "en-US" in
' the line below to match the UICulture setting in the project file.
'<Assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)>
' themeDictionaryLocation = where theme specific resource dictionaries are located
' (used if a resource is not found in the page,
' or application resource dictionaries)
' genericDictionaryLocation = where the generic resource dictionary is located
' (used if a resource is not found in the page,
' app, or any theme specific resource dictionaries)
<Assembly: ThemeInfo(ResourceDictionaryLocation.None, ResourceDictionaryLocation.SourceAssembly)>
| 4,016
|
https://github.com/TecSecret/BrazilCustomerAttributes/blob/master/Config/Backend/Prefixoptions.php
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
BrazilCustomerAttributes
|
TecSecret
|
PHP
|
Code
| 209
| 682
|
<?php
namespace TecSecret\BrazilCustomerAttributes\Config\Backend;
use Magento\Framework\App\Cache\TypeListInterface;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\App\Config\Value as ConfigValue;
use Magento\Framework\Data\Collection\AbstractDb;
use Magento\Framework\Model\Context;
use Magento\Framework\Model\ResourceModel\AbstractResource;
use Magento\Framework\Registry;
use Magento\Framework\Serialize\SerializerInterface;
/**
*
* Class to render prefix options attribute
*
*
* NOTICE OF LICENSE
*
* @category SystemCode
* @package Systemcode_BrazilCustomerAttributes
* @author Eduardo Diogo Dias <[email protected]>
* @copyright System Code LTDA-ME
* @license http://opensource.org/licenses/osl-3.0.php
*/
class Prefixoptions extends ConfigValue
{
/**
* Json Serializer
*
* @var SerializerInterface
*/
protected $serializer;
/**
* Prefixoptions constructor.
* @param SerializerInterface $serializer
* @param Context $context
* @param Registry $registry
* @param ScopeConfigInterface $config
* @param TypeListInterface $cacheTypeList
* @param AbstractResource|null $resource
* @param AbstractDb|null $resourceCollection
* @param array $data
*/
public function __construct(
SerializerInterface $serializer,
Context $context,
Registry $registry,
ScopeConfigInterface $config,
TypeListInterface $cacheTypeList,
AbstractResource $resource = null,
AbstractDb $resourceCollection = null,
array $data = []
) {
$this->serializer = $serializer;
parent::__construct($context, $registry, $config, $cacheTypeList, $resource, $resourceCollection, $data);
}
/**
* Prepare data before save
*
* @return void
*/
public function beforeSave()
{
/** @var array $value */
$value = $this->getValue();
unset($value['__empty']);
$encodedValue = $this->serializer->serialize($value);
$this->setValue($encodedValue);
}
/**
* Process data after load
*
* @return void
*/
protected function _afterLoad()
{
/** @var string $value */
$value = $this->getValue();
if($value){
$decodedValue = $this->serializer->unserialize($value);
$this->setValue($decodedValue);
}
}
}
| 28,856
|
https://github.com/mjalaf/IgniteTheTour/blob/master/DEV - Building your Applications for the Cloud/DEV10/src/inventory-service/start-docker.sh
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
IgniteTheTour
|
mjalaf
|
Shell
|
Code
| 10
| 43
|
#!/bin/bash
set -e
dotnet user-secrets set 'ConnectionStrings:InventoryContext' '${SQLDB_CONNECTION_STRING}'
dotnet run
| 8,450
|
https://github.com/ebptwllc/eXpand/blob/master/Xpand/Xpand.ExpressApp.Modules/Scheduler.Web/Controllers/WebDashboardRefreshController.cs
|
Github Open Source
|
Open Source
|
MS-PL
| 2,022
|
eXpand
|
ebptwllc
|
C#
|
Code
| 193
| 685
|
using System;
using System.Linq;
using DevExpress.Data.Filtering;
using DevExpress.ExpressApp;
using DevExpress.ExpressApp.Editors;
using DevExpress.ExpressApp.Scheduler.Web;
using DevExpress.ExpressApp.Web.Editors;
using Xpand.Persistent.Base.General.Controllers.Dashboard;
namespace Xpand.ExpressApp.Scheduler.Web.Controllers {
public sealed class WebDashboardRefreshController : ViewController<DashboardView> {
protected override void OnViewControlsCreated() {
base.OnViewControlsCreated();
foreach (var result in View.Items.OfType<DashboardViewItem>()) {
result.ControlCreated += ResultOnControlCreated;
}
}
void ResultOnControlCreated(object sender, EventArgs eventArgs) {
var viewItem = (DashboardViewItem)sender;
viewItem.ControlCreated-=ResultOnControlCreated;
var listView = viewItem.InnerView as ListView;
if (listView != null) {
var schedulerEditor = listView.Editor as ASPxSchedulerListEditor;
if (schedulerEditor != null) {
schedulerEditor.ResourceDataSourceCreating += schedulerEditor_ResourceDataSourceCreating;
}
}
}
void schedulerEditor_ResourceDataSourceCreating(object sender, DevExpress.ExpressApp.Scheduler.ResourceDataSourceCreatingEventArgs e) {
foreach (var result in View.Items.OfType<DashboardViewItem>()) {
var listView = result.InnerView as ListView;
if (listView != null && listView.Editor == sender) {
var model = result.Model as IModelDashboardViewItemEx;
if (model != null && model.Filter != null) {
var filterView = GetViewById(model.Filter.DataSourceView.Id);
if (filterView != null && filterView.ObjectTypeInfo.Type == e.ResourceType) {
e.Handled = true;
e.DataSource = WebDataSource(e.ResourceType, filterView);
return;
}
}
}
}
}
WebDataSource WebDataSource(Type resourceType, ListView filterView) {
var criteria = new InOperator(filterView.ObjectTypeInfo.KeyMember.Name,
filterView.SelectedObjects.Cast<object>().Select(o => ObjectSpace.GetKeyValue(o)));
return new WebDataSource(ObjectSpace, Application.TypesInfo.FindTypeInfo(resourceType), ObjectSpace.CreateCollection(resourceType, criteria));
}
private ListView GetViewById(string id) {
return View.Items.OfType<DashboardViewItem>().Select(vi => vi.InnerView).FirstOrDefault(v => v != null && v.Id == id) as ListView;
}
}
}
| 851
|
https://github.com/NovasomIndustries/Utils-2019.01/blob/master/rock/app/carmachine/music/middleWidget/musicitemgroupwidget.cpp
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
Utils-2019.01
|
NovasomIndustries
|
C++
|
Code
| 91
| 1,152
|
#include "musicitemgroupwidget.h"
#include <QHBoxLayout>
musicItemGroupWidget::musicItemGroupWidget(QWidget *parent):baseWidget(parent)
{
m_islove=false;
QHBoxLayout *hlyout=new QHBoxLayout;
m_btnLove=new flatButton(this);
m_btnLove->setFixedSize(16,16);
m_btnDel=new flatButton(this);
m_btnDel->setFixedSize(16,16);
m_btnMore=new flatButton(this);
m_btnMore->setFixedSize(16,16);
m_btnMovie=new flatButton(this);
m_btnMovie->setFixedSize(16,16);
m_btnLove->setStyleSheet("QPushButton{border-image:url(:/image/middlewidget/btn_love (1).png);}"
"QPushButton:hover{border-image:url(:/image/middlewidget/btn_love (2).png);}"
"QPushButton:pressed{border-image:url(:/image/middlewidget/btn_love (3).png);}");
m_btnDel->setStyleSheet("QPushButton{border-image:url(:/image/middlewidget/btn_del (1).png);}"
"QPushButton:hover{border-image:url(:/image/middlewidget/btn_del (2).png);}"
"QPushButton:pressed{border-image:url(:/image/middlewidget/btn_del (3).png);}");
m_btnMore->setStyleSheet("QPushButton{border-image:url(:/image/middlewidget/btn_more (1).png);}"
"QPushButton:hover{border-image:url(:/image/middlewidget/btn_more (2).png);}"
"QPushButton:pressed{border-image:url(:/image/middlewidget/btn_more (3).png);}");
m_btnMovie->setStyleSheet("QPushButton{border:NULL;background-image:url(:/image/middlewidget/btn_mv (2).png);}"
"QPushButton:hover{border:NULL;background-image:url(:/image/middlewidget/btn_mv (1).png);}"
"QPushButton:pressed{border:NULL;background-image:url(:/image/middlewidget/btn_mv (3).png);}");
hlyout->addWidget(m_btnMovie,0,Qt::AlignCenter);
hlyout->addWidget(m_btnLove,0,Qt::AlignCenter);
hlyout->addWidget(m_btnDel,0,Qt::AlignCenter);
hlyout->addWidget(m_btnMore,0,Qt::AlignCenter);
hlyout->addSpacing(14);
hlyout->setSpacing(5);
hlyout->setContentsMargins(0,0,0,0);
setLayout(hlyout);
connect(m_btnLove,SIGNAL(clicked(bool)),this,SLOT(slot_btnloveclicked()));
}
void musicItemGroupWidget::setLoved()
{
m_islove=true;
m_btnLove->setStyleSheet("QPushButton{border-image:url(:/image/middlewidget/btn_islove (1).png);}"
"QPushButton:hover{border-image:url(:/image/middlewidget/btn_islove (2).png);}"
"QPushButton:pressed{border-image:url(:/image/middlewidget/btn_islove (3).png);}");
}
void musicItemGroupWidget::slot_btnloveclicked()
{
if(m_islove)
{
m_btnLove->setStyleSheet("QPushButton{border-image:url(:/image/middlewidget/btn_love (1).png);}"
"QPushButton:hover{border-image:url(:/image/middlewidget/btn_love (2).png);}"
"QPushButton:pressed{border-image:url(:/image/middlewidget/btn_love (3).png);}");
}
else
{
m_btnLove->setStyleSheet("QPushButton{border-image:url(:/image/middlewidget/btn_islove (1).png);}"
"QPushButton:hover{border-image:url(:/image/middlewidget/btn_islove (2).png);}"
"QPushButton:pressed{border-image:url(:/image/middlewidget/btn_islove (3).png);}");
}
m_islove=!m_islove;
}
| 15,343
|
https://github.com/EAxelGM/SchoolNotes-BackEnd/blob/master/resources/views/mails/notificar_multiplo_clips.blade.php
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
SchoolNotes-BackEnd
|
EAxelGM
|
Blade
|
Code
| 275
| 1,075
|
@extends('layouts.mailWarnBan')
@section('asunto')
¡Felicidades {{$data['name']}}, por llegar a los {{$data['clips']}} clips!
@endsection
@section('cuerpo1')
Estamos muy contentos de que estes usando de la plataforma SchoolNotes.
@endsection
@section('cuerpo2')
Sin mas que decir gracias por ser un usuario activo, recuerda que muy pronto tendremos muchas sospresas mas, asi que nunca olvides invitar a mas de tus amigos para ganar mas Clips!
<br><br>
@if($data['codigo_creador'] != null)
No olvides compartir tu codigo de creador <a href="https://schoolnotes.live/editar-perfil">{{$data['codigo_creador']['codigo']}}</a> para ganar mas clips al momento de que un usuario se registre, y/o hagan una compra.
@else
Hemos notado que aun no has creado tu codigo de creador, deberias crear uno ahora mismo, es muy sencillo, solo da <a href="https://schoolnotes.live/editar-perfil">Clic Aqui</a> y crea tu codigo de creador para empezarlo a compartir y asi ganaras clips al momento de que alguien se registra o realiza una compra usando tu codigo de creador!
@endif
@endsection
@section('despedida')
¡Nunca pares de aprender!, El equipo de SchoolNotes te da las Gracias por seguir con nosotros.
@endsection
@section('iconoEmpresa')
<a target="_blank">
<img src="{{$imagenes['icono']}}" alt style="display: block;" width="40">
</a>
@endsection
@section('nombreEmpresa')
SchooNotes
@endsection
@section('descripcionEmpresa')
[email protected]
@endsection
@section('facebook')
<!--a target="_blank">
<img title="Facebook" src="https://tlr.stripocdn.email/content/assets/img/social-icons/circle-white/facebook-circle-white.png" alt="Fb" width="24" height="24">
</a-->
@endsection
@section('twitter')
<!--a target="_blank" href>
<img title="Twitter" src="https://tlr.stripocdn.email/content/assets/img/social-icons/circle-white/twitter-circle-white.png" alt="Tw" width="24" height="24">
</a-->
@endsection
@section('instagram')
<!--a target="_blank" href>
<img title="Instagram" src="https://tlr.stripocdn.email/content/assets/img/social-icons/circle-white/instagram-circle-white.png" alt="Inst" width="24" height="24">
</a-->
@endsection
@section('linkedin')
<!--a target="_blank" href>
<img title="Linkedin" src="https://tlr.stripocdn.email/content/assets/img/social-icons/circle-white/linkedin-circle-white.png" alt="In" width="24" height="24">
</a-->
@endsection
@section('footer1')
[email protected]
@endsection
@section('footer2')
Este mensaje fue enviado desde la empresa SchoolNotes
@endsection
@section('footer3')
<!--a target="_blank" href="https://viewstripo.email/">Preferencias</!--a> |
<a target="_blank" href="https://viewstripo.email/">Browser</a> |
<a target="_blank" href="https://viewstripo.email/">Forward</a> |
<a-- target="_blank" class="unsubscribe">Unsubscribe</a-->
@endsection
@section('copyrigth')
Copyright © 2020 <strong>SchoolNotes</strong>, Todos los derechos reservados
@endsection
@section('logo2')
<a target="_blank" href="#">
<img src="{{$imagenes['book']}}" alt width="125">
</a>
@endsection
| 28,011
|
https://github.com/ssokssok/metricbeat/blob/master/docs/modules/tlabasset/patch.asciidoc
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,019
|
metricbeat
|
ssokssok
|
AsciiDoc
|
Code
| 44
| 152
|
////
This file is generated! See scripts/docs_collector.py
////
[[metricbeat-metricset-tlabasset-patch]]
=== tlabasset patch metricset
experimental[]
include::../../../module/tlabasset/patch/_meta/docs.asciidoc[]
==== Fields
For a description of each field in the metricset, see the
<<exported-fields-tlabasset,exported fields>> section.
Here is an example document generated by this metricset:
[source,json]
----
include::../../../module/tlabasset/patch/_meta/data.json[]
----
| 45,388
|
https://github.com/Munirahul/sample-001/blob/master/SnacksDetails.java
|
Github Open Source
|
Open Source
|
MIT
| null |
sample-001
|
Munirahul
|
Java
|
Code
| 70
| 248
|
import java.util.Scanner;
public class SnacksDetails {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the no of pizzas bought:");
int p = input.nextInt();
System.out.println("Enter the no of puffs bought:");
int u = input.nextInt();
System.out.println("Enter the no of cool drinks bought:");
int c = input.nextInt();
System.out.println("Bill Details");
System.out.println("No of pizzas:"+p);
System.out.println("No of puffs:"+u);
System.out.println("No of cooldrinks::"+c);
System.out.println("Total price="+(p*100 + u*20 + c*10));
System.out.println("ENJOY THE SHOW!!!");
}
}
| 13,801
|
https://github.com/p4fpga/p4fpga/blob/master/src/bsv/library/SharedBuff.bsv
|
Github Open Source
|
Open Source
|
BSD-2-Clause
| 2,021
|
p4fpga
|
p4fpga
|
Bluespec
|
Code
| 590
| 2,085
|
// Copyright (c) 2015 Cornell University.
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use, copy,
// modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
// BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// NOTE:
// - This module stores packet in FIFO order with no guarantees on per-port fairness.
// - Access-control module provides per-port fairness, which is outside the packet buffer.
import BRAM::*;
import FIFO::*;
import FIFOF::*;
import GetPut::*;
import Vector::*;
import Connectable::*;
import ConnectalBram::*;
import ConnectalMemory::*;
import MemTypes::*;
import SharedBuffMemServer::*;
import SharedBuffMemServerInternal::*;
import SharedBuffMMU::*;
import MemMgmt::*;
import PhysMemSlaveFromBram::*;
import Ethernet::*;
import DbgDefs::*;
import ConnectalConfig::*;
`include "ConnectalProjectConfig.bsv"
// FIXME: Client#(Bit#(EtherLen), Maybe#(PktId))
// FIXME: Server#(Bit#(EtherLen), Maybe#(PktId))
interface MemAllocServer;
interface Put#(Bit#(EtherLen)) mallocReq;
interface Get#(Maybe#(PktId)) mallocDone;
endinterface
interface MemAllocClient;
interface Get#(Bit#(EtherLen)) mallocReq;
interface Put#(Maybe#(PktId)) mallocDone;
endinterface
// FIXME: Client#(PktId, Bool)
// FIXME: Server#(PktId, Bool)
interface MemFreeServer;
interface Put#(PktId) freeReq;
interface Get#(Bool) freeDone;
endinterface
interface MemFreeClient;
interface Get#(PktId) freeReq;
interface Put#(Bool) freeDone;
endinterface
instance Connectable#(MemAllocClient, MemAllocServer);
module mkConnection#(MemAllocClient client, MemAllocServer server)(Empty);
mkConnection(client.mallocReq, server.mallocReq);
mkConnection(server.mallocDone, client.mallocDone);
endmodule
endinstance
instance Connectable#(MemFreeClient, MemFreeServer);
module mkConnection#(MemFreeClient client, MemFreeServer server)(Empty);
mkConnection(client.freeReq, server.freeReq);
mkConnection(server.freeDone, client.freeDone);
endmodule
endinstance
interface SharedBuffer#(numeric type addrWidth, numeric type busWidth, numeric type nMasters);
interface MemServerRequest memServerRequest;
method MemMgmtDbgRec dbg;
endinterface
module mkSharedBuffer#(Vector#(numReadClients, MemReadClient#(busWidth)) readClients
,Vector#(numFreeClients, MemFreeClient) memFreeClients
,Vector#(numWriteClients, MemWriteClient#(busWidth)) writeClients
,Vector#(numAllocClients, MemAllocClient) memAllocClients
,MemServerIndication memServerInd
`ifdef DEBUG
,MemMgmtIndication memTestInd
,MMUIndication mmuInd
`endif
)(SharedBuffer#(addrWidth, busWidth, nMasters))
provisos(Add#(TLog#(TDiv#(busWidth, 8)), e__, 8)
,Add#(TLog#(TDiv#(busWidth, 8)), f__, BurstLenSize)
,Add#(c__, addrWidth, 64)
,Add#(d__, addrWidth, MemOffsetSize)
,Add#(numWriteClients, a__, TMul#(TDiv#(numWriteClients, nMasters),nMasters))
,Add#(numReadClients, b__, TMul#(TDiv#(numReadClients, nMasters),nMasters))
,Add#(numAllocClients, b__, TMul#(TDiv#(numAllocClients, nMasters),nMasters))
,Mul#(TDiv#(busWidth, TDiv#(busWidth, 8)), TDiv#(busWidth, 8), busWidth)
,Mul#(TDiv#(busWidth, ByteEnableSize), ByteEnableSize, busWidth)
,Add#(DataBusWidth, 0, busWidth)
);
MemMgmt#(addrWidth, numAllocClients, numReadClients) alloc <- mkMemMgmt(
`ifdef DEBUG
memTestInd
,mmuInd
`endif
);
MemServer#(addrWidth, busWidth, nMasters) dma <- mkMemServer(readClients, writeClients, cons(alloc.mmu, nil), memServerInd);
// TODO: use two ports to improve throughput
BRAM_Configure bramConfig = defaultValue;
bramConfig.latency = 2;
`ifdef BYTE_ENABLES
BRAM1PortBE#(Bit#(addrWidth), Bit#(busWidth), ByteEnableSize) memBuff <- mkBRAM1ServerBE(bramConfig);
Vector#(nMasters, PhysMemSlave#(addrWidth, busWidth)) memSlaves <- replicateM(mkPhysMemSlaveFromBramBE(memBuff.portA));
`else
BRAM1Port#(Bit#(addrWidth), Bit#(busWidth)) memBuff <- ConnectalBram::mkBRAM1Server(bramConfig);
Vector#(nMasters, PhysMemSlave#(addrWidth, busWidth)) memSlaves <- replicateM(mkPhysMemSlaveFromBram(memBuff.portA));
`endif
mkConnection(dma.masters, memSlaves);
FIFO#(MemMgmtAllocResp#(numAllocClients)) mallocDoneFifo <- mkFIFO;
rule fill_malloc_done;
let v <- alloc.mallocDone.get;
mallocDoneFifo.enq(v);
endrule
Vector#(numAllocClients, MemAllocServer) memAllocServers = newVector;
for (Integer i=0; i<valueOf(numAllocClients); i=i+1) begin
memAllocServers[i] = (interface MemAllocServer;
interface Put mallocReq;
method Action put(Bit#(EtherLen) req);
alloc.mallocReq.put(MemMgmtAllocReq{req: req, clients:fromInteger(i)});
endmethod
endinterface
interface Get mallocDone;
method ActionValue#(Maybe#(PktId)) get if (mallocDoneFifo.first.clients == fromInteger(i));
mallocDoneFifo.deq;
return mallocDoneFifo.first.id;
endmethod
endinterface
endinterface);
end
Vector#(numFreeClients, MemFreeServer) memFreeServers = newVector;
for (Integer i=0; i<valueOf(numFreeClients); i=i+1) begin
memFreeServers[i] = (interface MemFreeServer;
interface Put freeReq;
method Action put(PktId id);
alloc.freeReq.put(MemMgmtFreeReq{id: id, clients: fromInteger(i)});
endmethod
endinterface
interface Get freeDone;
method ActionValue#(Bool) get;
return True;
endmethod
endinterface
endinterface);
end
mkConnection(memAllocClients, memAllocServers);
mkConnection(memFreeClients, memFreeServers);
interface MemServerRequest memServerRequest = dma.request;
method MemMgmtDbgRec dbg = alloc.dbg;
endmodule
| 36,377
|
https://github.com/puzzlet/flask/blob/master/flask/testsuite/subclassing.py
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,021
|
flask
|
puzzlet
|
Python
|
Code
| 96
| 353
|
# -*- coding: utf-8 -*-
"""
flask.testsuite.subclassing
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Test that certain behavior of flask can be customized by
subclasses.
:copyright: (c) 2011 by Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""
import flask
import unittest
from io import StringIO
from logging import StreamHandler
from flask.testsuite import FlaskTestCase
class FlaskSubclassingTestCase(FlaskTestCase):
def test_suppressed_exception_logging(self):
class SuppressedFlask(flask.Flask):
def log_exception(self, exc_info):
pass
out = StringIO()
app = SuppressedFlask(__name__)
app.logger_name = 'flask_tests/test_suppressed_exception_logging'
app.logger.addHandler(StreamHandler(out))
@app.route('/')
def index():
1/0
rv = app.test_client().get('/')
self.assert_equal(rv.status_code, 500)
self.assertTrue(b'Internal Server Error' in rv.data)
err = out.getvalue()
self.assert_equal(err, '')
def suite():
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(FlaskSubclassingTestCase))
return suite
| 25,606
|
https://github.com/Getrajer/NugetUmbraco/blob/master/ActiveIS.UmbracoForms.Loqate/Helpers/GetFormHelper.cs
|
Github Open Source
|
Open Source
|
MIT
| null |
NugetUmbraco
|
Getrajer
|
C#
|
Code
| 60
| 220
|
using System;
using System.Collections.Generic;
using Umbraco.Core;
using Umbraco.Core.Composing;
using Umbraco.Forms.Core.Data.Storage;
using Umbraco.Forms.Core.Models;
namespace ActiveIS.UmbracoForms.Loqate.Helpers
{
public static class FormHelper
{
public static Form GetForm(Guid id)
{
var formService = Current.Factory.GetInstance<IFormStorage>();
var form = formService.GetForm(id);
return form;
}
public static IEnumerable<Field> GetAllFormFields(Guid id)
{
var formService = Current.Factory.GetInstance<IFormStorage>();
var form = formService.GetForm(id);
var allFormFields = form.AllFields;
return allFormFields;
}
}
}
| 21,397
|
https://github.com/stokei-company/categories-service/blob/master/src/modules/categories/controllers/index.ts
|
Github Open Source
|
Open Source
|
MIT
| null |
categories-service
|
stokei-company
|
TypeScript
|
Code
| 13
| 27
|
import { CategoryController } from "./category.controller";
export const Controllers = [
CategoryController,
];
| 17,093
|
https://github.com/lulock/dota/blob/master/planner/elements/CompetenceElement.lua
|
Github Open Source
|
Open Source
|
MIT
| null |
dota
|
lulock
|
Lua
|
Code
| 166
| 371
|
--------------------------------------------------------------------------------------
-- NOTE: this class has not been tested yet --
-- --
-- this is the CompetenceElement class which extends PlanElement --
-- an Competence is an aggregate defined by: --
-- . unique name identifier --
-- . list of Senses that trigger an Action, ActionPattern, or Competence --
-- . element --
-- --
-- tick() checks Senses and only: --
-- . ticks element if all senses are satisfied --
-- for more on POSH Competences see: --
-- http://www.cs.bath.ac.uk/~jjb/web/BOD/AgeS02/node11.html --
--------------------------------------------------------------------------------------
CompetenceElement = Class{__includes = PlanElement}
function CompetenceElement:init(name, senses, element)
self.name = name --string name
self.senses = senses --list of senses
self.element = element --should probably be renamed to element or something
end
function CompetenceElement:tick()
--print('in competence element', self.name, 'with child element', self.element.name)
for _,sense in pairs(self.senses) do --check all conditions
if not sense:tick() then
--print('competence element sense returned failure')
return FAILURE
end
end
--print('competence element ticking trigger element', self.element.name)
return self.element:tick() --tick trigger element only if all conditions satisfied
end
| 11,812
|
https://github.com/Steve-Tod/STFC3/blob/master/code/data/KineticsTVDataset.py
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
STFC3
|
Steve-Tod
|
Python
|
Code
| 381
| 1,768
|
import os
import logging
import numpy as np
import torch
from torchvision import transforms
import kornia.augmentation as K
from data.aug import RandomResizedCropHFilp, get_transform
from data.aug_official import get_train_transforms, IMG_MEAN, IMG_STD
from data.kinetics import Kinetics400
from data.utils import *
logger = logging.getLogger('base')
class KineticsTVDataset(torch.utils.data.Dataset):
# for CRWFCN, return a sequence
# add color augmentation
def __init__(self, opt):
super().__init__()
self.opt = opt
self.data_dir = opt['root']
self.is_train = opt['phase'] == 'train'
self.seq_len = opt['seq_len']
self.frame_rate = opt['frame_rate']
self.clips_per_video = opt['clips_per_video']
self.feature_size = opt['feature_size']
self.affine_th = opt['affine_th']
self.frame_size = opt['frame_size']
self.to_image = transforms.ToPILImage()
opt['same_on_batch'] = True
self.aug = RandomResizedCropHFilp(opt)
print(self.aug)
self.color_aug = get_transform(opt['color_aug'])
print(self.color_aug)
self.normalize = K.Normalize(mean=torch.Tensor(IMG_MEAN), std=torch.Tensor(IMG_STD))
self.denormalize = K.Denormalize(mean=torch.Tensor(IMG_MEAN), std=torch.Tensor(IMG_STD))
self.feature_mask = torch.ones(1, 1, self.feature_size,
self.feature_size)
assert self.is_train
# no norm
transform_train = get_train_transforms(opt, norm=False)
if opt['metadata'] is not None:
dataset, _ = torch.load(opt['metadata'])
if dataset.video_clips.video_paths[0].startswith(self.data_dir):
video_paths = dataset.video_clips.video_paths
else:
video_paths = []
for p in dataset.video_clips.video_paths:
new_p = '/'.join(p.split('/')[-3:])
new_p = os.path.join(self.data_dir, new_p)
video_paths.append(new_p)
cached = dict(video_paths=video_paths,
video_fps=dataset.video_clips.video_fps,
video_pts=dataset.video_clips.video_pts)
else:
cached = None
self.Kinetics400 = Kinetics400(
self.data_dir,
step_between_clips=1,
frames_per_clip=self.seq_len,
frame_rate=self.frame_rate,
extensions=('mp4'),
transform=transform_train,
_precomputed_metadata=cached)
if opt['label_size'] is None:
label_size = self.feature_size
else:
label_size = opt['label_size']
self.label = generate_neighbour_label(label_size,
label_size,
opt['dist_type'],
opt['rad']).float()
def __getitem__(self, idx, return_orig=False):
data = self.Kinetics400[idx]
x, orig = data[0]
x = torch.from_numpy(x).float() / 255.0
x = x.permute(0, 3, 1, 2)
T, C, H, W = x.shape
assert C == 3
# color augmentation
x, x_backward = self.augment(x)
frames_forward, affine_mat_forward = self.aug(x)
frames_backward, affine_mat_backward = self.aug(x_backward)
frames = torch.cat((frames_forward, frames_backward), dim=0)
frames = self.normalize(frames)
affine_mat_backward_inv = torch.inverse(affine_mat_backward[0])
affine_mat_f2b = torch.matmul(affine_mat_forward[0], affine_mat_backward_inv)
affine_mat_f2b = affine_mat_f2b[:2]
affine_grid = torch.nn.functional.affine_grid(
theta=affine_mat_f2b.unsqueeze(0),
size=(1, 1, self.feature_size, self.feature_size),
align_corners=True)
feature_mask = torch.nn.functional.grid_sample(self.feature_mask,
affine_grid,
align_corners=True)
feature_mask_b = feature_mask > self.affine_th
feature_mask_b = feature_mask_b.view(-1).float()
if return_orig:
return frames, affine_mat_f2b, self.label, feature_mask_b, orig
else:
return frames, affine_mat_f2b, self.label, feature_mask_b
def augment(self, frames):
frames_aug = []
frames_aug_back = []
if isinstance(self.color_aug, tuple):
for t in range(frames.size(0)):
frames_aug.append(self.color_aug[0](frames[t]))
for t in reversed(range(frames.size(0))):
frames_aug_back.append(self.color_aug[1](frames[t]))
elif self.color_aug is None:
return frames, frames.flip(0)
else:
for t in range(frames.size(0)):
frames_aug.append(self.color_aug(frames[t]))
for t in reversed(range(frames.size(0))):
frames_aug_back.append(self.color_aug(frames[t]))
return torch.stack(frames_aug, dim=0), torch.stack(frames_aug_back, dim=0)
def detrans(self, tensor):
img_list = []
for i in range(tensor.size(0)):
img_tensor = tensor[i] # 3, 256, 256
mean = torch.Tensor(IMG_MEAN)
mean = mean.float().view(3, 1, 1)
std = torch.Tensor(IMG_STD)
std = std.float().view(3, 1, 1)
img_tensor = img_tensor * std + mean
img_list.append(self.to_image(img_tensor))
return img_list
def __len__(self):
return len(self.Kinetics400)
| 37,079
|
https://github.com/goodeggs/express-domain-middleware/blob/master/test/index.js
|
Github Open Source
|
Open Source
|
MIT
| null |
express-domain-middleware
|
goodeggs
|
JavaScript
|
Code
| 57
| 231
|
var assert = require('assert');
var omf = require('omf');
var app = require(__dirname + '/app');
var isValidResponse = function(statusCode) {
return function(res) {
res.has.statusCode(statusCode);
res.is.json();
it('has id in body', function() {
var body = JSON.parse(this.response.body);
assert(body.id);
assert.equal(typeof body.id, 'number');
});
};
};
omf(app, function(app) {
app.get('/', isValidResponse(200));
app.get('/async', isValidResponse(200));
app.get('/timeout-error', isValidResponse(500));
app.get('/file-error', isValidResponse(500));
app.get('/closed-error', isValidResponse(200));
app.get('/', isValidResponse(200));
});
| 12,315
|
https://github.com/ViolaPsch/MIQ/blob/master/tests/testthat/apps/MIQ_en_num-items-8/app.R
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
MIQ
|
ViolaPsch
|
R
|
Code
| 5
| 28
|
library(psychTestR)
library(MIQ)
MIQ_standalone(num_items = 8)
| 30,448
|
https://github.com/etcpwd1960/market/blob/master/src/components/molecules/Wallet/Network.tsx
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
market
|
etcpwd1960
|
TSX
|
Code
| 176
| 471
|
import React, { useState, useEffect, ReactElement } from 'react'
import { useOcean } from '../../../providers/Ocean'
import Status from '../../atoms/Status'
import { ConfigHelper, ConfigHelperConfig } from '@oceanprotocol/lib'
import styles from './Network.module.css'
import Badge from '../../atoms/Badge'
import Tooltip from '../../atoms/Tooltip'
import { useWeb3 } from '../../../providers/Web3'
export default function Network(): ReactElement {
const { networkId, networkDisplayName, isTestnet } = useWeb3()
const { config } = useOcean()
const networkIdConfig = (config as ConfigHelperConfig).networkId
const [isEthMainnet, setIsEthMainnet] = useState<boolean>()
const [isSupportedNetwork, setIsSupportedNetwork] = useState<boolean>()
useEffect(() => {
// take network from user when present,
// otherwise use the default configured one of app
const network = networkId || networkIdConfig
const isEthMainnet = network === 1
setIsEthMainnet(isEthMainnet)
// Check networkId against ocean.js ConfigHelper configs
// to figure out if network is supported.
const isSupportedNetwork = Boolean(new ConfigHelper().getConfig(network))
setIsSupportedNetwork(isSupportedNetwork)
}, [networkId, networkIdConfig])
return !isEthMainnet && networkDisplayName ? (
<div className={styles.network}>
{!isSupportedNetwork && (
<Tooltip content="No Ocean Protocol contracts are deployed to this network.">
<Status state="error" className={styles.warning} />
</Tooltip>
)}
<span className={styles.name}>{networkDisplayName}</span>
{isTestnet && <Badge label="Test" className={styles.badge} />}
</div>
) : null
}
| 30,617
|
https://github.com/github188/tunnel/blob/master/tunnel-core/src/main/java/dll/struct/hw/PU_PTZ_PRESET_FREEZE.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
tunnel
|
github188
|
Java
|
Code
| 137
| 584
|
package dll.struct;
import com.sun.jna.NativeLong;
import com.sun.jna.Pointer;
import com.sun.jna.Structure;
import java.util.Arrays;
import java.util.List;
/**
* <i>native declaration : D:\HWPuSDK.h</i><br>
* This file was autogenerated by <a href="http://jnaerator.googlecode.com/">JNAerator</a>,<br>
* a tool written by <a href="http://ochafik.com/">Olivier Chafik</a> that <a href="http://code.google.com/p/jnaerator/wiki/CreditsAndLicense">uses a few opensource projects.</a>.<br>
* For help, please visit <a href="http://nativelibs4java.googlecode.com/">NativeLibs4Java</a> , <a href="http://rococoa.dev.java.net/">Rococoa</a>, or <a href="http://jna.dev.java.net/">JNA</a>.
*/
public class PU_PTZ_PRESET_FREEZE extends Structure {
/** \u901a\u9053ID */
public NativeLong ulChannelID;
/** \u4f7f\u80fd */
public boolean bFreezeEnable;
public PU_PTZ_PRESET_FREEZE() {
super();
}
protected List<String> getFieldOrder() {
return Arrays.asList("ulChannelID", "bFreezeEnable");
}
/**
* @param ulChannelID \u901a\u9053ID<br>
* @param bFreezeEnable \u4f7f\u80fd
*/
public PU_PTZ_PRESET_FREEZE(NativeLong ulChannelID, boolean bFreezeEnable) {
super();
this.ulChannelID = ulChannelID;
this.bFreezeEnable = bFreezeEnable;
}
public PU_PTZ_PRESET_FREEZE(Pointer peer) {
super(peer);
}
public static class ByReference extends PU_PTZ_PRESET_FREEZE implements Structure.ByReference {
};
public static class ByValue extends PU_PTZ_PRESET_FREEZE implements Structure.ByValue {
};
}
| 44,086
|
https://github.com/linggao/anax/blob/master/agreementbot/persistence.go
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
anax
|
linggao
|
Go
|
Code
| 2,945
| 8,186
|
package agreementbot
import (
"encoding/json"
"errors"
"fmt"
"github.com/boltdb/bolt"
"github.com/golang/glog"
"github.com/open-horizon/anax/policy"
"time"
)
const AGREEMENTS = "agreements"
type Agreement struct {
CurrentAgreementId string `json:"current_agreement_id"` // unique
Org string `json:"org"` // the org in which the policy exists that was used to make this agreement
DeviceId string `json:"device_id"` // the device id we are working with, immutable after construction
HAPartners []string `json:"ha_partners"` // list of HA partner device IDs
AgreementProtocol string `json:"agreement_protocol"` // immutable after construction - name of protocol in use
AgreementProtocolVersion int `json:"agreement_protocol_version"` // version of protocol in use - New in V2 protocol
AgreementInceptionTime uint64 `json:"agreement_inception_time"` // immutable after construction
AgreementCreationTime uint64 `json:"agreement_creation_time"` // device responds affirmatively to proposal
AgreementFinalizedTime uint64 `json:"agreement_finalized_time"` // agreement is seen in the blockchain
AgreementTimedout uint64 `json:"agreement_timeout"` // agreement was not finalized before it timed out
ProposalSig string `json:"proposal_signature"` // The signature used to create the agreement - from the producer
Proposal string `json:"proposal"` // JSON serialization of the proposal
ProposalHash string `json:"proposal_hash"` // Hash of the proposal
ConsumerProposalSig string `json:"consumer_proposal_sig"` // Consumer's signature of the proposal
Policy string `json:"policy"` // JSON serialization of the policy used to make the proposal
PolicyName string `json:"policy_name"` // The name of the policy for this agreement, policy names are unique
CounterPartyAddress string `json:"counter_party_address"` // The blockchain address of the counterparty in the agreement
DataVerificationURL string `json:"data_verification_URL"` // The URL to use to ensure that this agreement is sending data.
DataVerificationUser string `json:"data_verification_user"` // The user to use with the DataVerificationURL
DataVerificationPW string `json:"data_verification_pw"` // The pw of the data verification user
DataVerificationCheckRate int `json:"data_verification_check_rate"` // How often to check for data
DataVerificationMissedCount uint64 `json:"data_verification_missed_count"` // Number of data verification misses
DataVerificationNoDataInterval int `json:"data_verification_nodata_interval"` // How long to wait before deciding there is no data
DisableDataVerificationChecks bool `json:"disable_data_verification_checks"` // disable data verification checks, assume data is being sent.
DataVerifiedTime uint64 `json:"data_verification_time"` // The last time that data verification was successful
DataNotificationSent uint64 `json:"data_notification_sent"` // The timestamp for when data notification was sent to the device
MeteringTokens uint64 `json:"metering_tokens"` // Number of metering tokens from proposal
MeteringPerTimeUnit string `json:"metering_per_time_unit"` // The time units of tokens per, from the proposal
MeteringNotificationInterval int `json:"metering_notify_interval"` // The interval of time between metering notifications (seconds)
MeteringNotificationSent uint64 `json:"metering_notification_sent"` // The last time a metering notification was sent
MeteringNotificationMsgs []string `json:"metering_notification_msgs"` // The last metering messages that were sent, oldest at the end
Archived bool `json:"archived"` // The record is archived
TerminatedReason uint `json:"terminated_reason"` // The reason the agreement was terminated
TerminatedDescription string `json:"terminated_description"` // The description of why the agreement was terminated
BlockchainType string `json:"blockchain_type"` // The name of the blockchain type that is being used (new V2 protocol)
BlockchainName string `json:"blockchain_name"` // The name of the blockchain being used (new V2 protocol)
BlockchainOrg string `json:"blockchain_org"` // The name of the blockchain org being used (new V2 protocol)
BCUpdateAckTime uint64 `json:"blockchain_update_ack_time"` // The time when the producer ACked our update ot him (new V2 protocol)
NHMissingHBInterval int `json:"missing_heartbeat_interval"` // How long a heartbeat can be missing until it is considered missing (in seconds)
NHCheckAgreementStatus int `json:"check_agreement_status"` // How often to check that the node agreement entry still exists in the exchange (in seconds)
Pattern string `json:"pattern"` // The pattern used to make the agreement
}
func (a Agreement) String() string {
return fmt.Sprintf("Archived: %v, "+
"CurrentAgreementId: %v, "+
"Org: %v, "+
"AgreementProtocol: %v, "+
"AgreementProtocolVersion: %v, "+
"DeviceId: %v, "+
"HA Partners: %v, "+
"AgreementInceptionTime: %v, "+
"AgreementCreationTime: %v, "+
"AgreementFinalizedTime: %v, "+
"AgreementTimedout: %v, "+
"ProposalSig: %v, "+
"ProposalHash: %v, "+
"ConsumerProposalSig: %v, "+
"Policy Name: %v, "+
"CounterPartyAddress: %v, "+
"DataVerificationURL: %v, "+
"DataVerificationUser: %v, "+
"DataVerificationCheckRate: %v, "+
"DataVerificationMissedCount: %v, "+
"DataVerificationNoDataInterval: %v, "+
"DisableDataVerification: %v, "+
"DataVerifiedTime: %v, "+
"DataNotificationSent: %v, "+
"MeteringTokens: %v, "+
"MeteringPerTimeUnit: %v, "+
"MeteringNotificationInterval: %v, "+
"MeteringNotificationSent: %v, "+
"MeteringNotificationMsgs: %v, "+
"TerminatedReason: %v, "+
"TerminatedDescription: %v, "+
"BlockchainType: %v, "+
"BlockchainName: %v, "+
"BlockchainOrg: %v, "+
"BCUpdateAckTime: %v, "+
"NHMissingHBInterval: %v, "+
"NHCheckAgreementStatus: %v, "+
"Pattern: %v",
a.Archived, a.CurrentAgreementId, a.Org, a.AgreementProtocol, a.AgreementProtocolVersion, a.DeviceId, a.HAPartners,
a.AgreementInceptionTime, a.AgreementCreationTime, a.AgreementFinalizedTime,
a.AgreementTimedout, a.ProposalSig, a.ProposalHash, a.ConsumerProposalSig, a.PolicyName, a.CounterPartyAddress,
a.DataVerificationURL, a.DataVerificationUser, a.DataVerificationCheckRate, a.DataVerificationMissedCount, a.DataVerificationNoDataInterval,
a.DisableDataVerificationChecks, a.DataVerifiedTime, a.DataNotificationSent,
a.MeteringTokens, a.MeteringPerTimeUnit, a.MeteringNotificationInterval, a.MeteringNotificationSent, a.MeteringNotificationMsgs,
a.TerminatedReason, a.TerminatedDescription, a.BlockchainType, a.BlockchainName, a.BlockchainOrg, a.BCUpdateAckTime,
a.NHMissingHBInterval, a.NHCheckAgreementStatus, a.Pattern)
}
// private factory method for agreement w/out persistence safety:
func agreement(agreementid string, org string, deviceid string, policyName string, bcType string, bcName string, bcOrg string, agreementProto string, pattern string, nhPolicy policy.NodeHealth) (*Agreement, error) {
if agreementid == "" || agreementProto == "" {
return nil, errors.New("Illegal input: agreement id or agreement protocol is empty")
} else {
return &Agreement{
CurrentAgreementId: agreementid,
Org: org,
DeviceId: deviceid,
HAPartners: []string{},
AgreementProtocol: agreementProto,
AgreementProtocolVersion: 0,
AgreementInceptionTime: uint64(time.Now().Unix()),
AgreementCreationTime: 0,
AgreementFinalizedTime: 0,
AgreementTimedout: 0,
ProposalSig: "",
Proposal: "",
ProposalHash: "",
ConsumerProposalSig: "",
Policy: "",
PolicyName: policyName,
CounterPartyAddress: "",
DataVerificationURL: "",
DataVerificationUser: "",
DataVerificationPW: "",
DataVerificationCheckRate: 0,
DataVerificationNoDataInterval: 0,
DisableDataVerificationChecks: false,
DataVerifiedTime: 0,
DataNotificationSent: 0,
MeteringTokens: 0,
MeteringPerTimeUnit: "",
MeteringNotificationInterval: 0,
MeteringNotificationSent: 0,
MeteringNotificationMsgs: []string{"", ""},
Archived: false,
TerminatedReason: 0,
TerminatedDescription: "",
BlockchainType: bcType,
BlockchainName: bcName,
BlockchainOrg: bcOrg,
BCUpdateAckTime: 0,
NHMissingHBInterval: nhPolicy.MissingHBInterval,
NHCheckAgreementStatus: nhPolicy.CheckAgreementStatus,
Pattern: pattern,
}, nil
}
}
func AgreementAttempt(db *bolt.DB, agreementid string, org string, deviceid string, policyName string, bcType string, bcName string, bcOrg string, agreementProto string, pattern string, nhPolicy policy.NodeHealth) error {
if agreement, err := agreement(agreementid, org, deviceid, policyName, bcType, bcName, bcOrg, agreementProto, pattern, nhPolicy); err != nil {
return err
} else if err := PersistNew(db, agreement.CurrentAgreementId, bucketName(agreementProto), &agreement); err != nil {
return err
} else {
return nil
}
}
func AgreementUpdate(db *bolt.DB, agreementid string, proposal string, policy string, dvPolicy policy.DataVerification, defaultCheckRate uint64, hash string, sig string, protocol string, agreementProtoVersion int) (*Agreement, error) {
if agreement, err := singleAgreementUpdate(db, agreementid, protocol, func(a Agreement) *Agreement {
a.AgreementCreationTime = uint64(time.Now().Unix())
a.Proposal = proposal
a.ProposalHash = hash
a.ConsumerProposalSig = sig
a.Policy = policy
a.AgreementProtocolVersion = agreementProtoVersion
a.DisableDataVerificationChecks = !dvPolicy.Enabled
if dvPolicy.Enabled {
a.DataVerificationURL = dvPolicy.URL
a.DataVerificationUser = dvPolicy.URLUser
a.DataVerificationPW = dvPolicy.URLPassword
a.DataVerificationCheckRate = dvPolicy.CheckRate
if a.DataVerificationCheckRate == 0 {
a.DataVerificationCheckRate = int(defaultCheckRate)
}
a.DataVerificationNoDataInterval = dvPolicy.Interval
a.DataVerifiedTime = uint64(time.Now().Unix())
a.MeteringTokens = dvPolicy.Metering.Tokens
a.MeteringPerTimeUnit = dvPolicy.Metering.PerTimeUnit
a.MeteringNotificationInterval = dvPolicy.Metering.NotificationIntervalS
}
return &a
}); err != nil {
return nil, err
} else {
return agreement, nil
}
}
func AgreementMade(db *bolt.DB, agreementId string, counterParty string, signature string, protocol string, hapartners []string, bcType string, bcName string, bcOrg string) (*Agreement, error) {
if agreement, err := singleAgreementUpdate(db, agreementId, protocol, func(a Agreement) *Agreement {
a.CounterPartyAddress = counterParty
a.ProposalSig = signature
a.HAPartners = hapartners
a.BlockchainType = bcType
a.BlockchainName = bcName
a.BlockchainOrg = bcOrg
return &a
}); err != nil {
return nil, err
} else {
return agreement, nil
}
}
func AgreementBlockchainUpdate(db *bolt.DB, agreementId string, consumerSig string, hash string, counterParty string, signature string, protocol string) (*Agreement, error) {
if agreement, err := singleAgreementUpdate(db, agreementId, protocol, func(a Agreement) *Agreement {
a.ConsumerProposalSig = consumerSig
a.ProposalHash = hash
a.CounterPartyAddress = counterParty
a.ProposalSig = signature
return &a
}); err != nil {
return nil, err
} else {
return agreement, nil
}
}
func AgreementBlockchainUpdateAck(db *bolt.DB, agreementId string, protocol string) (*Agreement, error) {
if agreement, err := singleAgreementUpdate(db, agreementId, protocol, func(a Agreement) *Agreement {
a.BCUpdateAckTime = uint64(time.Now().Unix())
return &a
}); err != nil {
return nil, err
} else {
return agreement, nil
}
}
func AgreementFinalized(db *bolt.DB, agreementid string, protocol string) (*Agreement, error) {
if agreement, err := singleAgreementUpdate(db, agreementid, protocol, func(a Agreement) *Agreement {
a.AgreementFinalizedTime = uint64(time.Now().Unix())
return &a
}); err != nil {
return nil, err
} else {
return agreement, nil
}
}
func AgreementTimedout(db *bolt.DB, agreementid string, protocol string) (*Agreement, error) {
if agreement, err := singleAgreementUpdate(db, agreementid, protocol, func(a Agreement) *Agreement {
a.AgreementTimedout = uint64(time.Now().Unix())
return &a
}); err != nil {
return nil, err
} else {
return agreement, nil
}
}
func DataVerified(db *bolt.DB, agreementid string, protocol string) (*Agreement, error) {
if agreement, err := singleAgreementUpdate(db, agreementid, protocol, func(a Agreement) *Agreement {
a.DataVerifiedTime = uint64(time.Now().Unix())
return &a
}); err != nil {
return nil, err
} else {
return agreement, nil
}
}
func DataNotVerified(db *bolt.DB, agreementid string, protocol string) (*Agreement, error) {
if agreement, err := singleAgreementUpdate(db, agreementid, protocol, func(a Agreement) *Agreement {
a.DataVerificationMissedCount += 1
return &a
}); err != nil {
return nil, err
} else {
return agreement, nil
}
}
func DataNotification(db *bolt.DB, agreementid string, protocol string) (*Agreement, error) {
if agreement, err := singleAgreementUpdate(db, agreementid, protocol, func(a Agreement) *Agreement {
a.DataNotificationSent = uint64(time.Now().Unix())
return &a
}); err != nil {
return nil, err
} else {
return agreement, nil
}
}
func MeteringNotification(db *bolt.DB, agreementid string, protocol string, mn string) (*Agreement, error) {
if agreement, err := singleAgreementUpdate(db, agreementid, protocol, func(a Agreement) *Agreement {
a.MeteringNotificationSent = uint64(time.Now().Unix())
if len(a.MeteringNotificationMsgs) == 0 {
a.MeteringNotificationMsgs = []string{"", ""}
}
a.MeteringNotificationMsgs[1] = a.MeteringNotificationMsgs[0]
a.MeteringNotificationMsgs[0] = mn
return &a
}); err != nil {
return nil, err
} else {
return agreement, nil
}
}
func (a *Agreement) NodeHealthInUse() bool {
return a.NHMissingHBInterval != 0 || a.NHCheckAgreementStatus != 0
}
func (a *Agreement) FinalizedWithinTolerance(tolerance uint64) bool {
tolerate := uint64(time.Now().Unix()) - tolerance
return a.AgreementFinalizedTime > tolerate
}
func ArchiveAgreement(db *bolt.DB, agreementid string, protocol string, reason uint, desc string) (*Agreement, error) {
if agreement, err := singleAgreementUpdate(db, agreementid, protocol, func(a Agreement) *Agreement {
a.Archived = true
a.TerminatedReason = reason
a.TerminatedDescription = desc
return &a
}); err != nil {
return nil, err
} else {
return agreement, nil
}
}
// no error on not found, only nil
func FindSingleAgreementByAgreementId(db *bolt.DB, agreementid string, protocol string, filters []AFilter) (*Agreement, error) {
filters = append(filters, IdAFilter(agreementid))
if agreements, err := FindAgreements(db, filters, protocol); err != nil {
return nil, err
} else if len(agreements) > 1 {
return nil, fmt.Errorf("Expected only one record for agreementid: %v, but retrieved: %v", agreementid, agreements)
} else if len(agreements) == 0 {
return nil, nil
} else {
return &agreements[0], nil
}
}
// no error on not found, only nil
func FindSingleAgreementByAgreementIdAllProtocols(db *bolt.DB, agreementid string, protocols []string, filters []AFilter) (*Agreement, error) {
filters = append(filters, IdAFilter(agreementid))
for _, protocol := range protocols {
if agreements, err := FindAgreements(db, filters, protocol); err != nil {
return nil, err
} else if len(agreements) > 1 {
return nil, fmt.Errorf("Expected only one record for agreementid: %v, but retrieved: %v", agreementid, agreements)
} else if len(agreements) == 0 {
continue
} else {
return &agreements[0], nil
}
}
return nil, nil
}
func singleAgreementUpdate(db *bolt.DB, agreementid string, protocol string, fn func(Agreement) *Agreement) (*Agreement, error) {
if agreement, err := FindSingleAgreementByAgreementId(db, agreementid, protocol, []AFilter{}); err != nil {
return nil, err
} else if agreement == nil {
return nil, fmt.Errorf("Unable to locate agreement id: %v", agreementid)
} else {
updated := fn(*agreement)
return updated, persistUpdatedAgreement(db, agreementid, protocol, updated)
}
}
// does whole-member replacements of values that are legal to change during the course of an agreement's life
func persistUpdatedAgreement(db *bolt.DB, agreementid string, protocol string, update *Agreement) error {
return db.Update(func(tx *bolt.Tx) error {
if b, err := tx.CreateBucketIfNotExists([]byte(AGREEMENTS + "-" + protocol)); err != nil {
return err
} else {
current := b.Get([]byte(agreementid))
var mod Agreement
if current == nil {
return fmt.Errorf("No agreement with given id available to update: %v", agreementid)
} else if err := json.Unmarshal(current, &mod); err != nil {
return fmt.Errorf("Failed to unmarshal agreement DB data: %v", string(current))
} else {
// This code is running in a database transaction. Within the tx, the current record is
// read and then updated according to the updates within the input update record. It is critical
// to check for correct data transitions within the tx .
if mod.AgreementCreationTime == 0 { // 1 transition from zero to non-zero
mod.AgreementCreationTime = update.AgreementCreationTime
}
if mod.AgreementFinalizedTime == 0 { // 1 transition from zero to non-zero
mod.AgreementFinalizedTime = update.AgreementFinalizedTime
}
if mod.AgreementTimedout == 0 { // 1 transition from zero to non-zero
mod.AgreementTimedout = update.AgreementTimedout
}
if mod.CounterPartyAddress == "" { // 1 transition from empty to non-empty
mod.CounterPartyAddress = update.CounterPartyAddress
}
if mod.Proposal == "" { // 1 transition from empty to non-empty
mod.Proposal = update.Proposal
}
if mod.ProposalHash == "" { // 1 transition from empty to non-empty
mod.ProposalHash = update.ProposalHash
}
if mod.ConsumerProposalSig == "" { // 1 transition from empty to non-empty
mod.ConsumerProposalSig = update.ConsumerProposalSig
}
if mod.Policy == "" { // 1 transition from empty to non-empty
mod.Policy = update.Policy
}
if mod.ProposalSig == "" { // 1 transition from empty to non-empty
mod.ProposalSig = update.ProposalSig
}
if mod.DataVerificationURL == "" { // 1 transition from empty to non-empty
mod.DataVerificationURL = update.DataVerificationURL
}
if mod.DataVerificationUser == "" { // 1 transition from empty to non-empty
mod.DataVerificationUser = update.DataVerificationUser
}
if mod.DataVerificationPW == "" { // 1 transition from empty to non-empty
mod.DataVerificationPW = update.DataVerificationPW
}
if mod.DataVerificationCheckRate == 0 { // 1 transition from zero to non-zero
mod.DataVerificationCheckRate = update.DataVerificationCheckRate
}
if mod.DataVerificationMissedCount < update.DataVerificationMissedCount { // Valid transitions must move forward
mod.DataVerificationMissedCount = update.DataVerificationMissedCount
}
if mod.DataVerificationNoDataInterval == 0 { // 1 transition from zero to non-zero
mod.DataVerificationNoDataInterval = update.DataVerificationNoDataInterval
}
if !mod.DisableDataVerificationChecks { // 1 transition from false to true
mod.DisableDataVerificationChecks = update.DisableDataVerificationChecks
}
if mod.DataVerifiedTime < update.DataVerifiedTime { // Valid transitions must move forward
mod.DataVerifiedTime = update.DataVerifiedTime
}
if mod.DataNotificationSent < update.DataNotificationSent { // Valid transitions must move forward
mod.DataNotificationSent = update.DataNotificationSent
}
if len(mod.HAPartners) == 0 { // 1 transition from empty array to non-empty
mod.HAPartners = update.HAPartners
}
if mod.MeteringTokens == 0 { // 1 transition from zero to non-zero
mod.MeteringTokens = update.MeteringTokens
}
if mod.MeteringPerTimeUnit == "" { // 1 transition from empty to non-empty
mod.MeteringPerTimeUnit = update.MeteringPerTimeUnit
}
if mod.MeteringNotificationInterval == 0 { // 1 transition from zero to non-zero
mod.MeteringNotificationInterval = update.MeteringNotificationInterval
}
if mod.MeteringNotificationSent < update.MeteringNotificationSent { // Valid transitions must move forward
mod.MeteringNotificationSent = update.MeteringNotificationSent
}
if len(mod.MeteringNotificationMsgs) == 0 || mod.MeteringNotificationMsgs[0] == update.MeteringNotificationMsgs[1] { // msgs must move from new to old in the array
mod.MeteringNotificationMsgs = update.MeteringNotificationMsgs
}
if !mod.Archived { // 1 transition from false to true
mod.Archived = update.Archived
}
if mod.TerminatedReason == 0 { // 1 valid transition from zero to non-zero
mod.TerminatedReason = update.TerminatedReason
}
if mod.TerminatedDescription == "" { // 1 transition from empty to non-empty
mod.TerminatedDescription = update.TerminatedDescription
}
if mod.BlockchainType == "" { // 1 transition from empty to non-empty
mod.BlockchainType = update.BlockchainType
}
if mod.BlockchainName == "" { // 1 transition from empty to non-empty
mod.BlockchainName = update.BlockchainName
}
if mod.BlockchainOrg == "" { // 1 transition from empty to non-empty
mod.BlockchainOrg = update.BlockchainOrg
}
if mod.AgreementProtocolVersion == 0 { // 1 transition from empty to non-empty
mod.AgreementProtocolVersion = update.AgreementProtocolVersion
}
if mod.BCUpdateAckTime == 0 { // 1 transition from zero to non-zero
mod.BCUpdateAckTime = update.BCUpdateAckTime
}
if serialized, err := json.Marshal(mod); err != nil {
return fmt.Errorf("Failed to serialize agreement record: %v", mod)
} else if err := b.Put([]byte(agreementid), serialized); err != nil {
return fmt.Errorf("Failed to write record with key: %v", agreementid)
} else {
glog.V(2).Infof("Succeeded updating agreement record to %v", mod)
}
}
}
return nil
})
}
func DeleteAgreement(db *bolt.DB, pk string, protocol string) error {
if pk == "" {
return fmt.Errorf("Missing required arg pk")
} else {
return db.Update(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(bucketName(protocol)))
if b == nil {
return fmt.Errorf("Unknown bucket: %v", bucketName(protocol))
} else if existing := b.Get([]byte(pk)); existing == nil {
glog.Errorf("Warning: record deletion requested, but record does not exist: %v", pk)
return nil // handle already-deleted agreement as success
} else {
var record Agreement
if err := json.Unmarshal(existing, &record); err != nil {
glog.Errorf("Error deserializing agreement: %v. This is a pre-deletion warning message function so deletion will still proceed", record)
} else if record.CurrentAgreementId != "" && !record.Archived {
glog.Warningf("Warning! Deleting an agreement record with an agreement id, this operation should only be done after cancelling on the blockchain.")
}
}
return b.Delete([]byte(pk))
})
}
}
func UnarchivedAFilter() AFilter {
return func(e Agreement) bool { return !e.Archived }
}
func ArchivedAFilter() AFilter {
return func(e Agreement) bool { return e.Archived }
}
func IdAFilter(id string) AFilter {
return func(a Agreement) bool { return a.CurrentAgreementId == id }
}
func DevPolAFilter(deviceId string, policyName string) AFilter {
return func(a Agreement) bool { return a.DeviceId == deviceId && a.PolicyName == policyName }
}
type AFilter func(Agreement) bool
func FindAgreements(db *bolt.DB, filters []AFilter, protocol string) ([]Agreement, error) {
agreements := make([]Agreement, 0)
readErr := db.View(func(tx *bolt.Tx) error {
if b := tx.Bucket([]byte(bucketName(protocol))); b != nil {
b.ForEach(func(k, v []byte) error {
var a Agreement
if err := json.Unmarshal(v, &a); err != nil {
glog.Errorf("Unable to deserialize db record: %v", v)
} else {
if !a.Archived {
glog.V(5).Infof("Demarshalled agreement in DB: %v", a)
}
exclude := false
for _, filterFn := range filters {
if !filterFn(a) {
exclude = true
}
}
if !exclude {
agreements = append(agreements, a)
}
}
return nil
})
}
return nil // end the transaction
})
if readErr != nil {
return nil, readErr
} else {
return agreements, nil
}
}
func PersistNew(db *bolt.DB, pk string, bucket string, record interface{}) error {
if pk == "" || bucket == "" {
return fmt.Errorf("Missing required args, pk and/or bucket")
} else {
writeErr := db.Update(func(tx *bolt.Tx) error {
if b, err := tx.CreateBucketIfNotExists([]byte(bucket)); err != nil {
return err
} else if existing := b.Get([]byte(pk)); existing != nil {
return fmt.Errorf("Bucket %v already contains record with primary key: %v", bucket, pk)
} else if bytes, err := json.Marshal(record); err != nil {
return fmt.Errorf("Unable to serialize record %v. Error: %v", record, err)
} else if err := b.Put([]byte(pk), bytes); err != nil {
return fmt.Errorf("Unable to write to record to bucket %v. Primary key of record: %v", bucket, pk)
} else {
glog.V(2).Infof("Succeeded writing record identified by %v in %v", pk, bucket)
return nil
}
})
return writeErr
}
}
func bucketName(protocol string) string {
return AGREEMENTS + "-" + protocol
}
| 37,724
|
https://github.com/studiosok/Normal/blob/master/src/Components/Communication/Tail.tsx
|
Github Open Source
|
Open Source
|
MIT
| null |
Normal
|
studiosok
|
TypeScript
|
Code
| 47
| 141
|
import React from 'react';
import Quiz from '../Quiz/QuizBody';
const Tail = (props) => {
return (
<div className="Container">
<div id="topBottomMargin">
<h2>Tail Talk</h2>
<div>
<p>~Summary text about body language specifically related to the tail~</p>
</div>
</div>
<div className="Main">
<Quiz {...props} />
</div>
</div>
);
};
export default Tail;
| 10,954
|
https://github.com/GIANTCRAB/dota-2-lua-abilities/blob/master/scripts/vscripts/lua_abilities/ogre_magi_ignite_lua/modifier_ogre_magi_ignite_lua.lua
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
dota-2-lua-abilities
|
GIANTCRAB
|
Lua
|
Code
| 214
| 875
|
-- Created by Elfansoer
--[[
Ability checklist (erase if done/checked):
- Scepter Upgrade
- Break behavior
- Linken/Reflect behavior
- Spell Immune/Invulnerable/Invisible behavior
- Illusion behavior
- Stolen behavior
]]
--------------------------------------------------------------------------------
modifier_ogre_magi_ignite_lua = class({})
--------------------------------------------------------------------------------
-- Classifications
function modifier_ogre_magi_ignite_lua:IsHidden()
return false
end
function modifier_ogre_magi_ignite_lua:IsDebuff()
return true
end
function modifier_ogre_magi_ignite_lua:IsStunDebuff()
return false
end
function modifier_ogre_magi_ignite_lua:IsPurgable()
return true
end
--------------------------------------------------------------------------------
-- Initializations
function modifier_ogre_magi_ignite_lua:OnCreated( kv )
-- references
self.slow = self:GetAbility():GetSpecialValueFor( "slow_movement_speed_pct" )
local damage = self:GetAbility():GetSpecialValueFor( "burn_damage" )
if not IsServer() then return end
local interval = 1
-- precache damage
self.damageTable = {
victim = self:GetParent(),
attacker = self:GetCaster(),
damage = damage,
damage_type = self:GetAbility():GetAbilityDamageType(),
ability = self, --Optional.
}
-- ApplyDamage(damageTable)
-- Start interval
self:StartIntervalThink( interval )
end
function modifier_ogre_magi_ignite_lua:OnRefresh( kv )
-- references
self.slow = self:GetAbility():GetSpecialValueFor( "slow_movement_speed_pct" )
local damage = self:GetAbility():GetSpecialValueFor( "burn_damage" )
if not IsServer() then return end
-- update damage
self.damageTable.damage = damage
end
function modifier_ogre_magi_ignite_lua:OnRemoved()
end
function modifier_ogre_magi_ignite_lua:OnDestroy()
end
--------------------------------------------------------------------------------
-- Modifier Effects
function modifier_ogre_magi_ignite_lua:DeclareFunctions()
local funcs = {
MODIFIER_PROPERTY_MOVESPEED_BONUS_PERCENTAGE,
}
return funcs
end
function modifier_ogre_magi_ignite_lua:GetModifierMoveSpeedBonus_Percentage()
return self.slow
end
--------------------------------------------------------------------------------
-- Interval Effects
function modifier_ogre_magi_ignite_lua:OnIntervalThink()
-- apply damage
ApplyDamage( self.damageTable )
-- play effects
local sound_cast = "Hero_OgreMagi.Ignite.Damage"
EmitSoundOn( sound_cast, self:GetParent() )
end
--------------------------------------------------------------------------------
-- Graphics & Animations
function modifier_ogre_magi_ignite_lua:GetEffectName()
return "particles/units/heroes/hero_ogre_magi/ogre_magi_ignite_debuff.vpcf"
end
function modifier_ogre_magi_ignite_lua:GetEffectAttachType()
return PATTACH_ABSORIGIN_FOLLOW
end
| 1,088
|
https://github.com/jantunez14/merlin/blob/master/tools/festvox/src/st/build_st.scm
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,019
|
merlin
|
jantunez14
|
Scheme
|
Code
| 925
| 2,623
|
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; ;;;
;;; Carnegie Mellon University ;;;
;;; and Alan W Black and Kevin Lenzo ;;;
;;; Copyright (c) 1998-2002 ;;;
;;; All Rights Reserved. ;;;
;;; ;;;
;;; Permission is hereby granted, free of charge, to use and distribute ;;;
;;; this software and its documentation without restriction, including ;;;
;;; without limitation the rights to use, copy, modify, merge, publish, ;;;
;;; distribute, sublicense, and/or sell copies of this work, and to ;;;
;;; permit persons to whom this work is furnished to do so, subject to ;;;
;;; the following conditions: ;;;
;;; 1. The code must retain the above copyright notice, this list of ;;;
;;; conditions and the following disclaimer. ;;;
;;; 2. Any modifications must be clearly marked as such. ;;;
;;; 3. Original authors' names are not deleted. ;;;
;;; 4. The authors' names are not used to endorse or promote products ;;;
;;; derived from this software without specific prior written ;;;
;;; permission. ;;;
;;; ;;;
;;; CARNEGIE MELLON UNIVERSITY AND THE CONTRIBUTORS TO THIS WORK ;;;
;;; DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ;;;
;;; ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT ;;;
;;; SHALL CARNEGIE MELLON UNIVERSITY NOR THE CONTRIBUTORS BE LIABLE ;;;
;;; FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES ;;;
;;; WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN ;;;
;;; AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ;;;
;;; ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF ;;;
;;; THIS SOFTWARE. ;;;
;;; ;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; ;;;
;;; Code for converting festvox setup files to SphinxTrain files ;;;
;;; for auto-labelling ;;;
;;; ;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;(cond
; ((probe_file "festvox/build_clunits.scm")
; (load "festvox/build_clunits.scm"))
; ((probe_file "festvox/build_ldom.scm")
; (load "festvox/build_ldom.scm")))
(define (st_setup datafile vname)
(st_phonedictrans datafile vname)
)
(define (st_phones vname)
(let ((ofd (fopen (format nil "st/etc/%s.phone" vname) "w")))
(mapcar
(lambda (p) (format ofd "%s\n" (car p)))
(cadr (assoc 'phones (PhoneSet.description))))
(fclose ofd)))
(define (add_to_list i list)
(cond
((member_string i list)
list)
(t
(cons i list))))
(define (ennicen_word w)
(let ((ws (format nil "%s" w))
(lets nil) (p 0))
(while (< p (length ws))
(if (string-matches (substring ws p 1) "[A-Za-z0-9]")
(set! lets (cons (substring ws p 1) lets))
(set! lets (cons "Q" lets)))
(set! p (+ 1 p)))
(if (> (length lets) 20) ;; long word names can confuse sphinx
(set! lets (list "x" (length lets) "Q")))
(apply
string-append
(reverse lets))))
(defvar wordlist nil)
(define (add_word_to_list name d)
(let ((w wordlist))
(if (string-matches name "[A-Z0-9][A-Z0-9]*")
(set! nicename name)
(set! nicename (ennicen_word (upcase name))))
(set! entry (assoc_string nicename wordlist))
(if entry
(begin
(set! subentry (assoc_string d (cdr entry)))
(if subentry
(if (string-equal "1" (cadr subentry))
(car entry)
(format nil "%s%d" (car entry) (cadr subentry)))
(begin
(set-cdr! ;; new homograph
entry
(cons
(list d (+ 1 (cadr (cadr entry))))
(cdr entry)))
(format nil "%s%d" (car entry) (cadr (cadr entry))))))
(begin ;; new word
(set! wordlist ;; new word
(cons
(list nicename (list d 1)) wordlist))
nicename))))
; (while (and
; w (not (string-equal d (cadr (car w)))))
; (set! w (cdr w)))
; (if w
; (caar w)
; (begin
; (set! wordname (format nil "%s%d" nicename wordn))
; (set! wordlist
; (cons (list wordname d) wordlist))
; (set! wordn (+ 1 wordn))
; wordname))))
(define (make_nicephone s)
"(make_nicephone s)
Sphinx can't deal with phone names distinguished only by case, so
if the phones have any upper case they are prepend CAP."
(let ((n))
(if (string-matches (item.name s) ".*[A-Z].*")
(set! n (string-append "CAP" (item.name s)))
(set! n (item.name s)))
n))
(define (st_phonedictrans datafile vname)
(let ((words nil) (phones nil) (wordn 0)
(silence (car (cadr (car (PhoneSet.description '(silences))))))
(pfd (fopen (format nil "st/etc/%s.phone" vname) "w"))
(dfd (fopen (format nil "st/etc/%s.dic" vname) "w"))
(ffd (fopen (format nil "st/etc/%s.filler" vname) "w"))
(ifd (fopen (format nil "st/etc/%s.fileids" vname) "w" ))
(tfd (fopen (format nil "st/etc/%s.transcription" vname) "w"))
)
(mapcar
(lambda (p)
(format t "%s\n" (car p))
(let ((u (Utterance Text "")))
(set! pron "")
(set! u (utt.load nil (format nil "prompt-utt/%s.utt" (car p))))
(format ifd "%s\n" (car p))
(format tfd "<s>")
(mapcar
(lambda (s)
; (format t "ph %s - %s\n" (item.name s) pron)
; (format t "qqq %l %l %l %l\n"
; (item.relation s 'SylStructure)
; (null (item.prev (item.relation.parent s "SylStructure")))
; (null (item.relation.prev s "SylStructure"))
; (not (string-equal "" pron)))
(if (and (null (item.prev (item.relation.parent s "SylStructure")))
(null (item.relation.prev s "SylStructure"))
(not (string-equal "" pron)))
(begin
(format tfd " %s" (add_word_to_list
maybewordname
pron))
(set! pron ""))
)
(cond
; ((and (string-equal (item.name s) silence)
; (not (string-equal (item.feat s "p.name") silence)))
; (format tfd " <sil>"))
((not (string-equal (item.name s) silence))
(set! maybewordname
(item.feat s "R:SylStructure.parent.parent.name"))
(set! nicephone (make_nicephone s))
(set! phones (add_to_list nicephone phones))
(set! pron (format nil "%s %s" pron nicephone))
; (format t "pron is %s\n" pron)
)
(t
nil)))
(utt.relation.items u 'Segment))
(if (not (string-equal "" pron))
(format tfd " %s" (add_word_to_list maybewordname pron)))
(format tfd " </s> (%s)\n" (car p)))
)
(load datafile t))
(fclose tfd)
(mapcar
(lambda (l)
(mapcar
(lambda (ss)
(if (> (cadr ss) 1)
(format dfd "%s%d %s\n" (car l) (cadr ss) (car ss))
(format dfd "%s %s\n" (car l) (car ss))))
(reverse (cdr l))))
wordlist)
(fclose dfd)
(set! sfd (fopen "etc/mysilence" "w"))
(format sfd "%s\n" silence)
(fclose sfd)
(mapcar
(lambda (p)
(if (not (string-equal silence p))
(format pfd "%s\n" p)))
phones)
(format pfd "SIL\n") ;; SphinxTrain requires silence as "SIL"
(fclose pfd)
(format ffd "<s> SIL\n")
(format ffd "</s> SIL\n")
(format ffd "<sil> SIL\n")
(fclose ffd)
))
| 39,220
|
https://github.com/simonlovesyou/AutoRobot/blob/master/test/actions/index.js
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
AutoRobot
|
simonlovesyou
|
JavaScript
|
Code
| 16
| 35
|
import scripts from './scripts';
import app from './app';
module.exports = () => {
app();
scripts();
}
| 50,604
|
https://github.com/mszpila/tachoserver/blob/master/src/user/domain/dto/UploadDocumentDto.ts
|
Github Open Source
|
Open Source
|
MIT
| null |
tachoserver
|
mszpila
|
TypeScript
|
Code
| 14
| 36
|
export class UploadDocumentDto {
readonly frontUrl: string;
readonly backUrl: string;
readonly selfieUrl: string;
}
| 16,613
|
https://github.com/waixxt3213/Brickjoon/blob/master/Brickjoon_Src/Bronze2/11721.cpp
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
Brickjoon
|
waixxt3213
|
C++
|
Code
| 41
| 100
|
#include <iostream>
using namespace std;
int main()
{
string str;
cin >> str;
for (int i = 0; i < str.length(); i++)
{
cout << str.at(i);
if ((i + 1)%10 == 0)
{
cout << '\n';
}
}
}
// solved
| 47,924
|
https://github.com/Ghislain1/zoe-fb-app/blob/master/src/app/shared/models/app-user.ts
|
Github Open Source
|
Open Source
|
MIT
| 2,018
|
zoe-fb-app
|
Ghislain1
|
TypeScript
|
Code
| 125
| 443
|
export interface User {
name: string;
email: string;
firstname: String;
lastname: String;
id: Number;
isAdmin: boolean;
generateAvatar(): string;
}
export class AppUser {
public email: String;
public id: Number;
public firstname: String;
public lastname: String;
public avatar?: string;
public flags?: String[];
public settings?: Object;
constructor(user: User) {
this.email = user['email'] || '';
this.id = user['id'] || -1;
this.firstname = user['firstname'] || '';
this.lastname = user['lastname'] || '';
this.flags = this.flags || [];
this.settings = this.settings || {};
this.avatar = this.generateAvatar() || '';
}
public generateAvatar(): string {
const colors = [
'#c62828',
'#ad1457',
'#6a1b9a',
'#4527a0',
'#283593',
'#1565c0',
'#0277bd',
'#00838f',
'#2e7d32',
'#558b2f',
'#9e9d24',
'#f9a825',
'#ff8f00',
'#ef6c00',
'#d84315'
];
return (
'https://dummyimage.com/60x60/' +
colors[Math.round(Math.random() * (colors.length - 1))].substr(1) +
'/ffffff&text=' +
this.firstname[0] +
this.lastname[0]
);
}
}
| 936
|
https://github.com/pulumi/pulumi-alicloud/blob/master/sdk/dotnet/ThreatDetection/Inputs/HoneypotProbeHoneypotBindListGetArgs.cs
|
Github Open Source
|
Open Source
|
Apache-2.0, MPL-2.0, BSD-3-Clause
| 2,023
|
pulumi-alicloud
|
pulumi
|
C#
|
Code
| 116
| 414
|
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AliCloud.ThreatDetection.Inputs
{
public sealed class HoneypotProbeHoneypotBindListGetArgs : global::Pulumi.ResourceArgs
{
[Input("bindPortLists")]
private InputList<Inputs.HoneypotProbeHoneypotBindListBindPortListGetArgs>? _bindPortLists;
/// <summary>
/// List of listening ports.See the following `Block BindPortList`.
/// </summary>
public InputList<Inputs.HoneypotProbeHoneypotBindListBindPortListGetArgs> BindPortLists
{
get => _bindPortLists ?? (_bindPortLists = new InputList<Inputs.HoneypotProbeHoneypotBindListBindPortListGetArgs>());
set => _bindPortLists = value;
}
/// <summary>
/// Honeypot ID.
/// </summary>
[Input("honeypotId")]
public Input<string>? HoneypotId { get; set; }
public HoneypotProbeHoneypotBindListGetArgs()
{
}
public static new HoneypotProbeHoneypotBindListGetArgs Empty => new HoneypotProbeHoneypotBindListGetArgs();
}
}
| 47,243
|
https://github.com/y8gao/elapp/blob/master/main.js
|
Github Open Source
|
Open Source
|
MIT
| null |
elapp
|
y8gao
|
JavaScript
|
Code
| 198
| 720
|
const {
app,
BrowserWindow,
ipcMain,
dialog,
nativeTheme
} = require('electron')
const { menu } = require('./menu')
const Store = require('electron-store');
const store = new Store();
const isWindows = process.platform === "win32";
function createWindow() {
nativeTheme.themeSource = store.get('theme-mode', 'system')
const win = new BrowserWindow({
width: 800,
height: 600,
minHeight:480,
minWidth: 640,
frame: false,
webPreferences: {
nodeIntegration: true,
}
})
ipcMain.handle('btn-minimize:click', () => {
if (win.minimizable) {
win.minimize()
}
})
ipcMain.handle('btn-maximize:click', () => {
if (win.maximizable) {
if (!win.isMaximized()) {
win.maximize()
} else {
win.unmaximize()
}
}
})
ipcMain.handle('btn-close:click', () => {
if (process.platform !== 'darwin') {
win.close()
}
})
ipcMain.on(`display-app-menu`, function (e, args) {
if (isWindows && win) {
menu.popup({
window: win,
x: args.x,
y: args.y
});
}
});
win.on('maximize', () => {
win.webContents.send('win-size:changed', 'maximize')
})
win.on('unmaximize', () => {
win.webContents.send('win-size:changed', 'unmaximize')
})
win.loadFile('index.html')
}
ipcMain.handle('dark-mode:set', (event, mode) => {
if (-1 != ['system', 'dark', 'light'].indexOf(mode)) {
nativeTheme.themeSource = mode
store.set('theme-mode', mode)
}
})
ipcMain.handle('open-dialog:file', () => {
return dialog.showOpenDialog({
properties: ['openFile', 'multiSelections'],
filters: [{
name: 'Images',
extensions: ['jpg', 'png', 'gif']
}]
})
})
app.whenReady().then(createWindow)
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow()
}
})
| 34,070
|
https://github.com/gamers4everlasting/efsolIntranceproject/blob/master/src/Domain/Enums/QuestionTypes.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
efsolIntranceproject
|
gamers4everlasting
|
C#
|
Code
| 32
| 76
|
namespace CleanArchitecture.Domain.Enums
{
public enum QuestionTypes
{
SingleLineTextBox, // will render a textbox
DateTimePicker, // will render a text area
YesOrNo, //will render a checkbox
SingleSelect, //will render a dropdownlist
}
}
| 49,726
|
https://github.com/ns7381/DAG_ML/blob/master/static/app/common/ui/datatables.js
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
DAG_ML
|
ns7381
|
JavaScript
|
Code
| 2,897
| 10,743
|
/**
* 表格初始化
*/
define([
'App', 'jquery', 'jq/dataTables-bs3', 'jq/dataTables/addon/fixedColumns', 'bs/tooltip'
], function(App, $) {
var window = window || this || {},
document = document || window.document || {};
var $doc = $(document);
var CELL_WIDTH = {
'check': 16,
'opt': "8em",
'opt-2': '6em',
'opt-1': '4em',
'datetime': "10em",
'date': "5em",
'time': "4em",
'name': "15em",
'ip': "8em",
'host': "11em"
};
var cellWidth = function(key) {
var w;
key = $.trim(key);
if (key) {
w = CELL_WIDTH[key] || key;
}
return w;
};
// 全局 dataTable 设置
if ($.fn.dataTable) {
$.extend(true, $.fn.dataTable.defaults, {
"dom": 'rt<"table-bottom clearfix"<"pull-left"il><"pull-right"p>>',
"language": {
"processing": '<i class="fa fa-spinner fa-spin"></i> 正在加载...',
"loadingRecords": '<i class="fa fa-spinner fa-spin"></i> 正在加载...',
"search": '_INPUT_<a class="btn-search"><i class="fa fa-search"></i></a>',
"lengthMenu": "每页显示 _MENU_ 条",
"info": "显示第 _START_~_END_ 条记录 / 共 <span class='nums'>_TOTAL_</span> 条",
"infoEmpty": "显示 0 条记录",
"paginate": {
"previous": '<i class="fa fa-angle-left"></i>',
"next": '<i class="fa fa-angle-right"></i>'
},
"paginationType": "two_button",
"emptyTable": '<div class="text-center"><i class="fa fa-info-circle text-warning"></i> 没有记录</div>',
"zeroRecords": '<div class="text-center"><i class="fa fa-info-circle text-warning"></i> 没有查询到符合条件的记录</div>',
"infoFiltered": ""//"(总 _MAX_ 条)"
}
});
}
/**
* 使用 dataTables 组件初始化表格
* @param tableSelector
* 表格选择器 或 表格的jQuery对象
* @param options
* 初始化表格时的配置项,若为零配置此参数可忽略,后一个参数往前提
* @param complete
* 初始化后的回调方法,此参数也可直接写在options中,对应键是initComplete
* function($table, settings, json) {
* // do something
* }
* @returns dataTable API实例,为 NULL 则表示表格未找到或未初始化成功
*/
var initDataTable = function(tableSelector, options, complete) {
if($.isFunction(options)) {
complete = options;
options = null;
}
if(tableSelector != null) {
var $table;
try {
if (tableSelector instanceof $) {
$table = tableSelector;
} else {
$table = $(tableSelector);
}
} catch (e) {
$table = null;
}
if (!$table || !$table.length) return null;
var tableId = $table.attr('id');
if (tableId) {
$table.siblings('.table-top:first').attr('id', tableId + "_top");
}
var th_num = $table.find("thead th").length;
if ($table.find("tfoot")) {
var td_num = $table.find("tfoot td").length;
if (td_num > 0) {
if (th_num > td_num) {
$table.find("tfoot td:last").attr("colspan",th_num-td_num+1);
} else if (th_num < td_num) {
$table.find("thead th:last").attr("colspan",td_num-th_num+1);
}
}
}
// init options
if(options && $.isFunction(options.initComplete)) {
complete = options.initComplete;
delete options.initComplete;
}
var baseOptions = {
'autoWidth': true,
'ordering': false, // 禁用排序
'processing': true, // 显示加载效果
// 保存表格状态
/*
'stateSave' : true,
'stateSaveCallback': function(settings, data) {
$(settings.nTable).data('saveData.dt', data);
},
'stateLoadCallback': function(settings) {
return $(settings.nTable).data('saveData.dt');
},
*/
// 设置显示滚动条
'scrollX': true,
'scrollCollapse': true,
'createdRow': function (row, data, index) {
var $row = $(row), rowApi = this.api().row(index);
$row.attr('index', data.id || index).data('rowData.dt', rowApi.data());
var btnOptSelector = ".btn-opt, .btn-opt a, .btn-opt ~ .dropdown a";
$row.find(btnOptSelector).each(function () {
$(this).data('row.dt', rowApi);
});
$row.on("click", btnOptSelector, rowApi, function (e) {
if (!$(this).data('row.dt')) {
$(this).data('row.dt', e.data);
}
});
$row.on('mouseleave', '.btn-opt', function(e) {
$('.tooltip').hide();
});
$row = null;
rowApi = null;
},
'initComplete': function () {
var tableApi = this.api(),
settings = this.fnSettings();
if (!settings) return false;
var firstColumn = settings.aoColumns[0];
if (firstColumn && !firstColumn.orderable) {
$(firstColumn.nTh).removeClass("sorting sorting_asc sorting_desc").addClass(firstColumn.sSortingClass || "sorting_disabled");
}
var $table = $(settings.nTable),
$tBody = $(settings.nTBody),
$tableWrapper = $(settings.nTableWrapper),
$tableTop = $tableWrapper.siblings(".table-top"),
$tableBottom = $tableWrapper.find(".table-bottom");
if ($tBody.children().length <= 0) {
$tableWrapper.addClass("no-body");
} else {
$tableWrapper.removeClass("no-body");
}
settings.sTableId && $tableTop.attr('id', settings.sTableId + "_top");
$(".btn-reload", $tableTop).off("click").on("click", function (e) {
$table.reloadTable();
});
$(".btn-search", $tableTop).off("click").on('click', function () {
var $search = $(this).siblings('input[type="search"],input.input-search');
tableApi.search($search.val()).draw();
});
$(".table-filter", $tableTop).each(function (i, el) {
var $el = $(this);
$el.data('valueOrg', $el.val());
if ($el.is("select")) {
$el.off("change").on('change', function (e) {
tableApi.search($(this).val()).draw();
});
} else if ($el.is('input[type="search"],input.input-search')) {
$el.off("keypress").on('keypress', function (e) {
if (e.keyCode == 13) {
tableApi.search($(this).val()).draw();
}
});
}
});
var args = [];
$.each(arguments, function (i, arg) {
args.push(arg);
});
args.unshift($table);
$.isFunction(complete) && complete.apply(this, args);
},
'drawCallback': function (settings) {
settings = settings || this.fnSettings();
var $tableWrapper = $(settings.nTableWrapper),
$table = $(settings.nTable),
$tableBody = $(settings.nTBody);
if ($("td.dataTables_empty", $tableBody).length) {
$(".dataTables_processing", $tableWrapper).hide();
}
}
};
options = $.extend(true, {}, baseOptions, options);
var dataSrc = options.dataSrc;
delete options.dataSrc;
if (options.ajax && options.ajax.dataSrc == null && dataSrc != null) {
options.ajax.dataSrc = dataSrc;
}
// 表格列权限控制
var hiddenColumns = [];
$table.find('th[data-permission], td[data-permission]').each(function() {
var $this = $(this), index = $this.index();
if (!App.permission.has($this.data('permission')) && $.inArray(index, hiddenColumns) == -1) {
hiddenColumns.push(index);
}
index = null;
$this = null;
});
var columnsDef = [], targets, i, j, k;
if (options.columnDefs) {
if ($.isArray(options.columnDefs)) {
var columnDef;
for (i=0; i<options.columnDefs.length; i++) {
columnDef = options.columnDefs[i];
if (columnDef && $.isArray(targets = columnDef.targets)) {
delete columnDef.targets;
for (j=0; j<targets.length; j++) {
k = targets[j];
columnsDef[k] = $.extend({}, columnsDef[k], columnDef);
}
}
}
}
delete options.columnDefs;
}
if (columnsDef.length && !options.columns) {
options.columns = columnsDef;
}
if ($.isArray(options.columns)) {
var columnOpt,
className, regexpCellW = /cell-(\w+)(?:-(\d+))?/, match,
_cellWidth, _cellMinWidth, _render = null;
for (i=0; i<options.columns.length; i++) {
columnOpt = $.extend({}, columnsDef[i], options.columns[i]);
// visible
if ($.inArray(i, hiddenColumns) > -1) {
columnOpt.visible = false;
}
// class to width
if (columnOpt.class != null) {
className = $.trim(columnOpt.class);
if (className && (match = className.match(regexpCellW)) != null) {
_cellWidth = cellWidth(match[1]);
if (_cellWidth === match[1]) {
if (match[2] != null) {
if (match[1] == "percent") {
_cellWidth = match[2] + '%';
} else {
_cellWidth = match[2] + match[1];
}
} else {
_cellWidth = '';
}
}
if (_cellWidth) {
columnOpt.width = _cellWidth;
}
}
}
// width
if (columnOpt.width != null) {
_cellWidth = columnOpt.width;
}
if (typeof _cellWidth === "string") {
_cellWidth = cellWidth(_cellWidth);
columnOpt.width = _cellWidth;
}
_cellWidth = null;
// minWidth
if (columnOpt.minWidth != null) {
_cellMinWidth = columnOpt.minWidth;
}
if (typeof _cellMinWidth === "string") {
_cellMinWidth = cellWidth(_cellMinWidth);
columnOpt.minWidth = _cellMinWidth;
}
_cellMinWidth = null;
// render
if (typeof columnOpt.render === "function") {
_render = columnOpt.render;
}
columnOpt.render = function(data, type, rowData, cellApi) {
var settings = cellApi.settings || {},
columns = settings.aoColumns || [],
colSettings = columns[cellApi.col] || {};
var render = colSettings.mRender || {};
render = render.__render__;
if (typeof render === "function") {
data = render.apply(this, arguments);
}
if (data != null && typeof data === "string") {
data = App.permission.compile(data);
}
return data;
};
columnOpt.render.__render__ = _render;
_render = null;
options.columns[i] = columnOpt;
}
}
// 表格错误处理
if ($.fn.dataTableExt) {
$.fn.dataTableExt.errMode = function(table, errCode, errText) {
var errMsg = 'DataTables Error: table id="' + $table.selector+'"';
if (typeof errCode === "string" && !/^\d+$/.test(errCode)) {
errMsg += (" - " + errCode);
} else {
if (errCode == 3) {
errMsg += " has already been initialised.";
} else {
errMsg = errText.replace("warning:", "Error:");
}
}
$doc.trigger($.Event("error.dt"), errMsg);
};
}
var tableApi = $table.DataTable(options);
if (!tableApi) return null;
var settings = tableApi.settings()[0];
if (settings) {
var $tbody = $(settings.nTBody),
$tableWrapper = $(settings.nTableWrapper);
if ($tbody.children().length <= 0) {
$tableWrapper.addClass("no-body");
} else {
$tableWrapper.removeClass("no-body");
}
}
// 第一列包含选择框时,固定显示第一列
var checkSelector = 'input[type="checkbox"], input[type="radio"]',
hasCheck = false;
if (
$(".dataTables_scrollHead table>thead>tr>th:first", $table.parents(".dataTables_wrapper")).find(checkSelector).length
) {
hasCheck = true;
} else {
var firstColumnOption = $.extend({}, $.isArray(options.columns) && options.columns.length ? options.columns[0] : null),
$firstColumnContent;
if (typeof firstColumnOption.defaultContent === "string") {
$firstColumnContent = $(firstColumnOption.defaultContent);
} else if (typeof firstColumnOption.render === "function") {
try {
$firstColumnContent = $(firstColumnOption.render.call(tableApi, '', '', {}, {col:0, row: 0}));
} catch (e) {
$firstColumnContent = $([]);
}
}
if ($firstColumnContent && $firstColumnContent.find(checkSelector).length) {
hasCheck = true;
}
}
new $.fn.dataTable.FixedColumns(tableApi, {
leftColumns: hasCheck ? 1 : 0,
drawCallback: function(leftObj, rightObj) {
var dtSettings = this.s.dt;
var $tableWrapper = $(dtSettings.nTableWrapper),
$table = $(dtSettings.nTable),
$tableHead = $(dtSettings.nTHead),
$tableBody = $(dtSettings.nTBody),
$tableScroll = $(".dataTables_scroll", $tableWrapper),
$tableLeftHead = $(leftObj.header),
$tableLeftBody = $(leftObj.body),
$tableLeft = $tableLeftHead.parents(".DTFC_LeftWrapper:first"),
$tableRightHead = $(rightObj.header),
$tableRightBody = $(rightObj.body),
$tableRight = $tableRightHead.parents(".DTFC_RightWrapper:first");
// last-child
$('tr:last-child', $tableBody)
.add($('tbody > tr:last-child', $tableLeftBody))
.add($('tbody > tr:last-child', $tableRightBody))
.addClass('last-child');
$('th:last-child', $tableHead)
.add($('td:last-child', $tableBody))
.add($('th:last-child, td:last-child', $tableLeftHead))
.add($('th:last-child, td:last-child', $tableLeftBody))
.add($('th:last-child, td:last-child', $tableRightHead))
.add($('th:last-child, td:last-child', $tableRightBody))
.addClass('last-child');
// class cell-check
if (hasCheck) {
$('th:first-child', $tableHead)
.add($('td:first-child', $tableBody))
.add($('th:first-child, td:first-child', $tableLeftHead))
.add($('th:first-child, td:first-child', $tableLeftBody))
.add($('th:first-child, td:first-child', $tableRightHead))
.add($('th:first-child, td:first-child', $tableRightBody))
.addClass('cell-check');
}
var tableApi = $table.dataTable().api();
var checkboxSelector = 'input[type="checkbox"]';
var getFirstCellCheckbox = function($wrapper) {
var $checkbox = $([]);
if ($wrapper && $wrapper instanceof $) {
$wrapper.find("tr").each(function() {
$checkbox = $checkbox.add($(this).children("th:first, td:first").find(checkboxSelector));
});
}
return $checkbox;
};
// content table checkbox
getFirstCellCheckbox($tableScroll).iCheck({
checkboxClass: "icheckbox-info"
}).on('ifChecked', {$tbody: $tableBody}, function (e) {
if ($(this).hasClass('selectAll')) {
var $tbody = e.data.$tbody;
getFirstCellCheckbox($tbody).iCheck('check');
}
}).on('ifUnchecked', {$tbody: $tableBody}, function (e) {
var $this = $(this);
$this.removeAttr("checked");
if ($this.hasClass('selectAll')) {
var $tbody = e.data.$tbody;
getFirstCellCheckbox($tbody).iCheck('uncheck').removeAttr('checked');
}
});
// content table radio
var radioSelector = 'input[type="radio"]';
$(radioSelector, $tableScroll).iCheck({
radioClass: "iradio-info"
}).on('ifUnchecked', function (e) {
$(this).removeAttr('checked');
});
// tooltip
$('[data-toggle="tooltip"]', $tableScroll).tooltip({container: "#page-main .page-content:first"});
// left table checkbox
$(checkboxSelector, $tableLeft).iCheck({
checkboxClass: "icheckbox-info"
}).on('ifChecked', {$tbody: $tableLeftBody}, function (e) {
var $this = $(this);
if ($this.hasClass('selectAll')) {
var $tbody = e.data.$tbody;
getFirstCellCheckbox($tableHead).iCheck('check');
getFirstCellCheckbox($tbody).iCheck('check');
} else {
var $tr = $this.parents("tr:first"),
$td = $this.parents("td:first"),
rowIndex = $tr.index(),
columnIndex = $td.index(),
settings = tableApi.settings()[0];
if (!(settings.oFeatures.bServerSide && settings.oFeatures.bPaginate)) {
rowIndex = tableApi.page() * tableApi.page.len() + rowIndex;
}
var $cell = $(tableApi.cell(rowIndex, columnIndex).node());
$(checkboxSelector, $cell).iCheck('check');
}
}).on('ifUnchecked', {$tbody: $tableLeftBody}, function (e) {
var $this = $(this);
$this.removeAttr("checked");
if ($this.hasClass('selectAll')) {
var $tbody = e.data.$tbody;
getFirstCellCheckbox($tableHead).iCheck('uncheck');
getFirstCellCheckbox($tbody).iCheck('uncheck');
} else {
var $tr = $this.parents("tr:first"),
$td = $this.parents("td:first"),
rowIndex = $tr.index(),
columnIndex = $td.index(),
settings = tableApi.settings()[0];
if (!(settings.oFeatures.bServerSide && settings.oFeatures.bPaginate)) {
rowIndex = tableApi.page() * tableApi.page.len() + rowIndex;
}
var $cell = $(tableApi.cell(rowIndex, columnIndex).node());
$(checkboxSelector, $cell).iCheck('uncheck').removeAttr('checked');
}
});
// left table radio
$(radioSelector, $tableLeft).iCheck({
radioClass: "iradio-info"
}).on('ifChecked', {$tbody: $tableLeftBody}, function (e) {
var $this = $(this),
$tr = $this.parents("tr:first"),
$td = $this.parents("td:first"),
rowIndex = $tr.index(),
columnIndex = $td.index(),
settings = tableApi.settings()[0];
if (!(settings.oFeatures.bServerSide && settings.oFeatures.bPaginate)) {
rowIndex = tableApi.page() * tableApi.page.len() + rowIndex;
}
var $cell = $(tableApi.cell(rowIndex, columnIndex).node());
$(radioSelector, $cell).iCheck('check');
}).on('ifUnchecked', {$tbody: $tableLeftBody}, function (e) {
var $this = $(this),
$tr = $this.parents("tr:first"),
$td = $this.parents("td:first"),
rowIndex = $tr.index(),
columnIndex = $td.index(),
settings = tableApi.settings()[0];
if (!(settings.oFeatures.bServerSide && settings.oFeatures.bPaginate)) {
rowIndex = tableApi.page() * tableApi.page.len() + rowIndex;
}
$this.removeAttr('checked');
var $cell = $(tableApi.cell(rowIndex, columnIndex).node());
$(radioSelector, $cell).iCheck('uncheck').removeAttr('checked');
});
// hover
$('tr', $tableBody).hover(function() {
var $tr = $(this), rowIndex = $tr.index();
var $fixedTr = $('tbody>tr:eq('+rowIndex+')', $tableLeftBody);
$fixedTr = $fixedTr.add($('tbody>tr:eq('+rowIndex+')', $tableRightBody));
$fixedTr.addClass('hover');
}, function() {
var $tr = $(this), rowIndex = $tr.index();
var $fixedTr = $('tbody>tr:eq('+rowIndex+')', $tableLeftBody);
$fixedTr = $fixedTr.add($('tbody>tr:eq('+rowIndex+')', $tableRightBody));
$fixedTr.removeClass('hover');
});
$('tbody>tr', $tableLeftBody).add($('tbody>tr', $tableRightBody)).hover(function() {
var $tr = $(this), rowIndex = $tr.index();
$('tr:eq('+rowIndex+')', $tableBody).addClass('hover');
}, function() {
var $tr = $(this), rowIndex = $tr.index();
$('tr:eq('+rowIndex+')', $tableBody).removeClass('hover');
});
// tooltip
$('[data-toggle="tooltip"]', $tableLeft).tooltip({container: "#page-main .page-content:first"});
$('[data-toggle="tooltip"]', $tableRight).tooltip({container: "#page-main .page-content:first"});
// dropdown
initDropdown($tableWrapper);
}
});
return tableApi;
}
return null;
};
function initDropdown($wrapper) {
var toggleFlag = "toggled";
if ($wrapper && $wrapper instanceof $ && !$wrapper.data(toggleFlag)) {
var backdrop = '.dropdown-backdrop';
var toggle = '[data-toggle="dropdown"]';
var dataKey = 'menu.ui.dropdown';
function dropdownToggle(e) {
var $this = $(e.currentTarget || e.target);
if ($this.is('.disabled, :disabled')) return false;
var $parent = getParent($this);
var $menu = $this.data(dataKey);
var isActive = $menu ? true : false;
clearMenus();
if (!isActive) {
if ('ontouchstart' in document.documentElement && !$parent.closest('.navbar-nav').length) {
// if mobile we use a backdrop because click events don't delegate
$('<div class="dropdown-backdrop"/>').appendTo($wrapper).on('click', clearMenus);
}
var $dropDownMenu = $this.siblings(".dropdown-menu:first");
$this.data(dataKey, ($menu = $dropDownMenu.clone(true)));
$menu.appendTo($wrapper).hide();
$menu.find("a").off("click").on("click", function(e) {
if (!this.href || (this.href && (
~this.baseURI.indexOf(this.href) || !/^https?:\/\//.test(this.href))
)) {
if (this.hash) {
$.History.setHash(this.hash);
} else if (this.href && !/^javascript:/.test(this.href)) {
window.location.assign(this.href);
} else if(!$(this).is(":disabled")) {
var index = $(this).parents("li:first").index(),
indexA = $(this).index();
$dropDownMenu.find('li:eq('+index+') ' + 'a:eq('+indexA+')').trigger("click");
}
return false;
}
});
$menu.css($.extend({display: "block", right: "auto"}, getMenuPos($this, $menu)));
var relatedTarget = { relatedTarget: $this[0] };
$parent.trigger(e = $.Event('show.bs.dropdown', relatedTarget));
if (e.isDefaultPrevented()) return;
$this
.trigger('focus')
.attr('aria-expanded', 'true');
$parent
.trigger('shown.bs.dropdown', relatedTarget)
}
return false;
}
function clearMenus(e) {
if (e && e.which === 3) return;
$(backdrop).remove();
$wrapper.find(toggle).removeData(dataKey).each(function() {
var $this = $(this);
var $parent = getParent($this);
var relatedTarget = { relatedTarget: this };
if (!$this.data(dataKey)) return;
$parent.trigger(e = $.Event('hide.bs.dropdown', relatedTarget));
if (e.isDefaultPrevented()) return;
$this.attr('aria-expanded', 'false');
$parent.trigger('hidden.bs.dropdown', relatedTarget);
});
$wrapper.children(".dropdown-menu").remove();
}
function getParent($this) {
var selector = $this.attr('data-target');
if (!selector) {
selector = $this.attr('href');
selector = selector && /#[A-Za-z]/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, ''); // strip for ie7
}
var $parent = selector && $(selector);
return $parent && $parent.length ? $parent : $this.parent();
}
function getMenuPos($this, $menu) {
var $pageMain = $('#page-main'),
posMain = $pageMain.offset(),
mainH = $pageMain.innerHeight();
var posTarget = $this.offset(),
posWrapper = $wrapper.offset(),
thisW = $this.outerWidth(),
thisH = $this.outerHeight(),
menuW = $menu.outerWidth(),
menuH = $menu.outerHeight(),
pos = {};
var posLeft2Wrapper = posTarget.left - posWrapper.left,
posWrapperTop2Main = posWrapper.top - posMain.top,
posTop2Wrapper = posTarget.top - posWrapper.top,
posTop2Main = posTop2Wrapper + posWrapperTop2Main;
if (mainH > menuH + posTop2Main) {
var thisHalfW = thisW / 2;
$menu.removeClass("left left-top left-bottom");
pos.top = posTop2Wrapper + thisH;
pos.left = posLeft2Wrapper - (menuW - thisW) + thisHalfW;
} else {
var thisHalfH = thisH / 2,
menuHalfH = menuH / 2;
pos.left = posLeft2Wrapper - menuW - 7;
var posTopMiddle2Main = posTop2Main + thisHalfH;
if (posTopMiddle2Main >= menuH/2 && mainH - posTopMiddle2Main >= menuH/2) {
$menu.addClass("left");
pos.top = posTop2Wrapper - menuHalfH + thisHalfH - 6;
} else if (posTopMiddle2Main < menuH/2) {
$menu.addClass("left-top");
pos.top = posTop2Wrapper - 6;
} else {
$menu.addClass("left-bottom");
pos.top = posTop2Wrapper - menuH + thisH;
}
}
return pos;
}
$(document).on('click.bs.dropdown.data-api', clearMenus);
$wrapper
.on('click.bs.dropdown.data-api', clearMenus)
.on('click.bs.dropdown.data-api', toggle, dropdownToggle)
.on('keydown.bs.dropdown.data-api', toggle, dropdownToggle)
.data(toggleFlag, true);
}
}
/**
* 判断是否是dataTable
*/
$.fn.isDataTable = function() {
var flag;
this.each(function() {
var $this = $(this);
if (!$this.is("table") || !$.fn.dataTable.isDataTable(this)) {
flag = false;
return false;
} else {
flag = true;
}
});
return !!flag;
};
/**
* 使用dataTable插件后的表格刷新重新加载
* @param ajax {String|Object}
* 使用新的ajax配置项。
* 为字符串时将作为新的请求地址。
* 为对象时,如果含有属性url及相应值,同$.ajax配置项规则。否则,作为新的请求参数
* @param clear {Boolean}
* 是否清空查询条件、当前页数等状态,默认为false
* @returns {$.fn}
*/
$.fn.reloadTable = function (ajax, clear) {
this.each(function() {
var $this = $(this);
if (typeof clear !== "boolean") {
clear = !!clear;
}
var tableApi = $this.dataTable().api(),
settings = tableApi.settings()[0],
$tableWrapper = $(settings.nTableWrapper),
$tableTop = $tableWrapper.siblings(".table-top"),
$tableHead = $tableWrapper.find(".DTFC_LeftHeadWrapper:first table:first");
var dataSrc = settings.ajax ? settings.ajax.dataSrc : null;
if (!$tableHead.length) {
$tableHead = $(settings.nTHead);
}
if (settings.oFeatures.bServerSide || settings.ajax) {
var sVal = '';
if (clear) {
$(".table-filter", $tableTop).each(function (i, el) {
var $el = $(this);
var valOrg = $el.data('valueOrg');
typeof valOrg != "undefined" && $el.val(valOrg);
$el = null;
});
} else {
sVal = $('input[type="search"],input.input-search', $tableTop).val();
}
if (!settings.oFeatures.bServerSide) {
tableApi.search(sVal);
}
if (ajax != null) {
if (!$.isFunction(ajax) && !$.isPlainObject(ajax)) {
ajax = {url: ajax};
}
if (settings.ajax && !$.isFunction(settings.ajax)) {
if (ajax.url) {
tableApi.ajax.url(App.getFullUrl(ajax.url));
settings.ajax.data = ajax.data;
} else {
settings.ajax.data = ajax;
}
} else {
settings.ajax = ajax;
}
if (dataSrc != null) {
settings.ajax.dataSrc = dataSrc;
}
}
tableApi.ajax.reload(null, clear);
$('input[type="checkbox"]', $tableHead).iCheck("uncheck");
} else {
App.go();
}
});
$('.tooltip').hide();
return this;
};
/**
* 获取datatable选中行数据
* @returns [
* {
* api, // 当前table的api对象
* nTable, // 当前table的dom对象
* nTr, // 当前行dom对象
* row, // 当前行的api对象
* data // 当前行的数据
* }
* ]
*/
$.fn.getTableSelected = function() {
var selected;
this.each(function() {
var $this = $(this);
if (!$this.isDataTable()) {
return true;
}
var tableApi = $this.dataTable().api();
var settings = tableApi.settings()[0];
var $rows = tableApi.rows().nodes().to$();
$rows.each(function() {
var $row = $(this),
$checkCell = $('td:first, th:first', $row);
var $check = $checkCell.find('input[type="checkbox"], input[type="radio"]');
if ($check.prop('checked') || $check.attr('checked') === "checked") {
var $tr = $check.parents("tr:first"),
rowIndex = $tr.index();
if (!(settings.oFeatures.bServerSide && settings.oFeatures.bPaginate)) {
rowIndex = tableApi.page() * tableApi.page.len() + rowIndex;
}
var rowApi = tableApi.row(rowIndex);
var obj = {
api: tableApi,
nTable: $this.get(0),
nTr: $tr.get(0),
row: rowApi,
data: rowApi.data()
};
!selected && (selected = []);
selected.push(obj);
}
});
});
return selected;
};
var DataTables = {
init: initDataTable,
parseAjax: function(context, $table, url, param) {
var self = context || this || {};
try {
if (!($table instanceof $)) {
$table = $($table);
}
return function(data, callback, settings) {
if (self.ajax && $.isFunction(self.ajax.send)) {
return self.ajax.send(
DataTables.parseUrl($table, url, param),
function(err, resp) {
if (err) {
App.onError(err, function(err) {
App.assignError(err, {level: 'app'});
});
callback(DataTables.parseResult($table));
} else {
callback(DataTables.parseResult($table, resp));
}
}
);
} else {
callback(DataTables.parseResult($table));
}
};
} catch (e) {}
return null;
},
parseUrl: function($table, url, param) {
if ($.fn.dataTable.isDataTable($table)) {
try {
if (!($table instanceof $)) {
$table = $($table);
}
var tableApi = $table.dataTable().api();
if (tableApi) {
var parseUrl = function(url, level) {
level = level || 0;
if (level > 1000) return url;
if ($.isArray(url)) {
level = level + 1;
url = [].concat(url);
$.each(url, function(i, _url) {
url[i] = parseUrl(_url, level);
});
} else if (url != null) {
if (typeof url !== "object") {
url = {name: url};
} else {
url = $.extend({}, url);
}
url.args = url.args || {};
url.data = $.extend({}, url.data, DataTables.parseParam($table, param));
url.args = $.extend({pageNo: tableApi.page() + 1, pageSize: tableApi.page.len()}, url.args, url.data);
}
return url;
};
url = parseUrl(url);
}
} catch (e) {}
}
return url;
},
parseParam: function($table, params) {
var _params;
if (params) {
_params = $.extend({}, params);
}
if ($.fn.dataTable.isDataTable($table)) {
try {
if (!($table instanceof $)) {
$table = $($table);
}
var settings = $table.fnSettings() || {};
// 前端处理搜索关键字的转换
var $tableWrapper = $(settings.nTableWrapper),
$tableTop = $tableWrapper.siblings(".table-top"),
$tableFilter = $tableTop.find(".table-filter").add($table.prev().find(".dataTables_filter").find("select,input"));
_params = _params || {};
$tableFilter.each(function(){
var filterKey = $(this).attr('name'),
filterVal = $(this).val();
_params[filterKey] = filterVal;
});
} catch (e) {}
}
return _params;
},
parseResult: function($table, data) {
var result = {};
var dataSrc, settings = {};
if ($.fn.dataTable.isDataTable($table)) {
try {
if (!($table instanceof $)) {
$table = $($table);
}
settings = $table.fnSettings() || {};
if (settings.ajax && settings.ajax.dataSrc) {
dataSrc = settings.ajax.dataSrc;
}
} catch (e) {}
}
data = data || {};
var _data = [];
if ($.isFunction(dataSrc)) {
_data = data.result || data;
try {
_data = dataSrc(_data);
if (_data && !$.isArray(_data) && typeof _data === "object") {
data = _data;
_data = data.result || data[dataSrc] || data;
}
} catch (e) {
_data = [];
$doc.trigger($.Event("error.dt"), 'dataSrc - ' + e.message);
}
dataSrc = 'data';
} else {
dataSrc = $.trim(dataSrc);
dataSrc = dataSrc || 'data';
_data = data.result || data[dataSrc] || data;
if ($.isFunction(settings.ajax)) {
dataSrc = 'data';
}
}
_data = _data || [];
var recordsTotal = data.totalCount || _data.length || 0,
recordsFiltered = data.totalCount || _data.length || 0;
result[dataSrc] = _data;
result['recordsTotal'] = recordsTotal;
result['recordsFiltered'] = recordsFiltered;
return result;
},
width: cellWidth
};
return DataTables;
});
| 41,977
|
https://github.com/labeeb8/MyMedicationList/blob/master/MyMedicationList/UserListViewController.h
|
Github Open Source
|
Open Source
|
MIT
| 2,013
|
MyMedicationList
|
labeeb8
|
Objective-C
|
Code
| 56
| 201
|
//
// UserListViewController.h
// MyMedicationList
// National Library of Medicine
// Code available in the public domain
//
#import <UIKit/UIKit.h>
#import "HomeScreenDelegate.h"
#import "ImportViewController.h"
@interface UserListViewController : UITableViewController
@property (assign,nonatomic) id <HomeScreenDelegate> delegate;
@property (retain, nonatomic) IBOutlet UITableViewCell *genderTableViewCell;
@property (nonatomic,retain) IBOutlet UIView *bluetoothActionView;
@property (retain,nonatomic) ImportViewController *importViewController;
- (void)presentModalImportViewController;
- (void)dismissModalImportViewController;
- (void) migrateToCoreData;
@end
| 40,631
|
https://github.com/LK26/outline-client/blob/master/third_party/shadowsocks-libev/libcork/include/libcork/helpers/errors.h
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,022
|
outline-client
|
LK26
|
C
|
Code
| 491
| 1,254
|
/* -*- coding: utf-8 -*-
* ----------------------------------------------------------------------
* Copyright © 2011-2012, RedJack, LLC.
* All rights reserved.
*
* Please see the COPYING file in this distribution for license
* details.
* ----------------------------------------------------------------------
*/
#ifndef LIBCORK_HELPERS_ERRORS_H
#define LIBCORK_HELPERS_ERRORS_H
/* This header is *not* automatically included when you include
* libcork/core.h, since we define some macros that don't include a
* cork_ or CORK_ prefix. Don't want to pollute your namespace unless
* you ask for it! */
#include <libcork/core/allocator.h>
#include <libcork/core/attributes.h>
#include <libcork/core/error.h>
#if !defined(CORK_PRINT_ERRORS)
#define CORK_PRINT_ERRORS 0
#endif
#if !defined(CORK_PRINT_ERROR)
#if CORK_PRINT_ERRORS
#include <stdio.h>
#define CORK_PRINT_ERROR_(func, file, line) \
fprintf(stderr, "---\nError in %s (%s:%u)\n %s\n", \
(func), (file), (unsigned int) (line), \
cork_error_message());
#define CORK_PRINT_ERROR() CORK_PRINT_ERROR_(__func__, __FILE__, __LINE__)
#else
#define CORK_PRINT_ERROR() /* do nothing */
#endif
#endif
/* A bunch of macros for calling a function that returns an error. If
* an error occurs, it will automatically be propagated out as the
* result of your own function. With these macros, you won't have a
* check to check or modify the error condition; it's returned as-is.
*
* XZ_check
*
* where:
*
* X = what happens if an error occurs
* "e" = jump to the "error" label
* "rY" = return a default error result (Y defined below)
* "x" = return an error result that you specify
*
* Y = your return type
* "i" = int
* "p" = some pointer type
*
* Z = the return type of the function you're calling
* "e" = use cork_error_occurred() to check
* "i" = int
* "p" = some pointer type
*
* In all cases, we assume that your function has a cork_error parameter
* called "err".
*/
/* jump to "error" label */
#define ee_check(call) \
do { \
(call); \
if (CORK_UNLIKELY(cork_error_occurred())) { \
CORK_PRINT_ERROR(); \
goto error; \
} \
} while (0)
#define ei_check(call) \
do { \
int __rc = (call); \
if (CORK_UNLIKELY(__rc != 0)) { \
CORK_PRINT_ERROR(); \
goto error; \
} \
} while (0)
#define ep_check(call) \
do { \
const void *__result = (call); \
if (CORK_UNLIKELY(__result == NULL)) { \
CORK_PRINT_ERROR(); \
goto error; \
} \
} while (0)
/* return specific error code */
#define xe_check(result, call) \
do { \
(call); \
if (CORK_UNLIKELY(cork_error_occurred())) { \
CORK_PRINT_ERROR(); \
return result; \
} \
} while (0)
#define xi_check(result, call) \
do { \
int __rc = (call); \
if (CORK_UNLIKELY(__rc != 0)) { \
CORK_PRINT_ERROR(); \
return result; \
} \
} while (0)
#define xp_check(result, call) \
do { \
const void *__result = (call); \
if (CORK_UNLIKELY(__result == NULL)) { \
CORK_PRINT_ERROR(); \
return result; \
} \
} while (0)
/* return default error code */
#define rie_check(call) xe_check(-1, call)
#define rii_check(call) xi_check(__rc, call)
#define rip_check(call) xp_check(-1, call)
#define rpe_check(call) xe_check(NULL, call)
#define rpi_check(call) xi_check(NULL, call)
#define rpp_check(call) xp_check(NULL, call)
#endif /* LIBCORK_HELPERS_ERRORS_H */
| 4,382
|
https://github.com/Zycon42/ShadingMethods/blob/master/src/utils/ArrayRef.h
|
Github Open Source
|
Open Source
|
MIT
| 2,014
|
ShadingMethods
|
Zycon42
|
C++
|
Code
| 251
| 651
|
/**
* @file ArrayRef.h
*
* @author Jan Dušek <[email protected]>
* @date 2013
*/
#ifndef ARRAY_REF_H
#define ARRAY_REF_H
#include <vector>
#include <cstddef>
#include <cassert>
/**
* Convenient class for passing non-const references to arrays.
* Use this class to pass arrays to functions, it's intended to
* pass by value, don't worry its just pointer and size.
*/
template <typename T>
class ArrayRef
{
public:
typedef T value_type;
typedef T* pointer;
typedef size_t size_type;
ArrayRef(pointer ptr, size_type n) : ptr(ptr), n(n) { }
ArrayRef(std::vector<T>& vec) : ptr(vec.data()), n(vec.size()) { }
pointer data() {
return ptr;
}
const pointer data() const {
return ptr;
}
size_type size() const {
return n;
}
value_type& operator[](size_type i) {
assert(i < n);
return ptr[i];
}
const value_type& operator[](size_type i) const {
assert(i < n);
return ptr[i];
}
private:
T* ptr;
size_type n;
};
/**
* Convenient class for passing const references to arrays.
* Use this class to pass arrays to functions, it's intended to
* pass by value, don't worry its just pointer and size.
*/
template <typename T>
class ConstArrayRef
{
public:
typedef T value_type;
typedef T* pointer;
typedef size_t size_type;
ConstArrayRef(const pointer ptr, size_type n) : ptr(ptr), n(n) { }
ConstArrayRef(const std::vector<T>& vec) : ptr(vec.data()), n(vec.size()) { }
ConstArrayRef(ConstArrayRef<T>& other) : ptr(other.data()), n(other.size()) { }
const pointer data() const {
return ptr;
}
size_type size() const {
return n;
}
const value_type& operator[](size_type i) const {
assert(i < n);
return ptr[i];
}
private:
const T* ptr;
size_type n;
};
#endif // !ARRAY_REF_H
| 11,294
|
https://github.com/padmaja-22/CP/blob/master/Data Structures/Linked List/detectAndCountLoop.cpp
|
Github Open Source
|
Open Source
|
MIT
| null |
CP
|
padmaja-22
|
C++
|
Code
| 115
| 513
|
#include <iostream>
#include <algorithm>
using namespace std;
class Node{
public:
Node* next;
int data;
};
void insertInto(Node** head_ref,int new_data){
Node* new_node=new Node();
Node* last=(*head_ref);
new_node->data=new_data;
new_node->next=NULL;
if(*head_ref==NULL){
*head_ref=new_node;
return;
}
while(last->next!=NULL){
last=last->next;
}
last->next=new_node;
return;
}
void printList(Node* node){
while(node!=NULL){
cout<<node->data<<" ";
node=node->next;
}
}
int countNodes(Node* n){
int cnt=1;
Node* temp=n;
while(temp->next!=n){
temp=temp->next;
cnt++;
}
return cnt;
}
int detectAndCount(Node* ptr){
Node *slow=ptr, *fast=ptr;
while(slow && fast && fast->next){
slow=slow->next;
fast=fast->next->next;
if(slow==fast){
return countNodes(slow);
}
}
return 0;
}
int main(){
Node* head=NULL;//starting with an empty list;
insertInto(&head,1);
insertInto(&head,2);
insertInto(&head,3);
insertInto(&head,4);
insertInto(&head,5);
insertInto(&head,6);
insertInto(&head,7);
cout<<"Linkedlist created : ";
printList(head);
cout<<endl;
head->next->next->next->next->next->next=head; //creating a loop
cout<<"Number of elements in loop : "<<detectAndCount(head);
return 0;
}
| 29,989
|
https://github.com/mobxtel/FinalProcurement/blob/master/src/AppBundle/Entity/BiznesFushaOperimi.php
|
Github Open Source
|
Open Source
|
MIT
| null |
FinalProcurement
|
mobxtel
|
PHP
|
Code
| 175
| 754
|
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* BiznesFushaOperimi
*
* @ORM\Table(name="biznes_fusha_operimi", indexes={@ORM\Index(name="IDX_A648114F8B3BE709", columns={"fusha_operimi_id"}), @ORM\Index(name="IDX_A648114F90860C3E", columns={"biznes_id"})})
* @ORM\Entity
*/
class BiznesFushaOperimi
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* @var \AppBundle\Entity\FushaOperimi
*
* @ORM\ManyToOne(targetEntity="AppBundle\Entity\FushaOperimi")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="fusha_operimi_id", referencedColumnName="id")
* })
*/
private $fushaOperimi;
/**
* @var \AppBundle\Entity\Biznes
*
* @ORM\ManyToOne(targetEntity="AppBundle\Entity\Biznes")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="biznes_id", referencedColumnName="id")
* })
*/
private $biznes;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set fushaOperimi
*
* @param \AppBundle\Entity\FushaOperimi $fushaOperimi
*
* @return BiznesFushaOperimi
*/
public function setFushaOperimi(\AppBundle\Entity\FushaOperimi $fushaOperimi = null)
{
$this->fushaOperimi = $fushaOperimi;
return $this;
}
/**
* Get fushaOperimi
*
* @return \AppBundle\Entity\FushaOperimi
*/
public function getFushaOperimi()
{
return $this->fushaOperimi;
}
/**
* Set biznes
*
* @param \AppBundle\Entity\Biznes $biznes
*
* @return BiznesFushaOperimi
*/
public function setBiznes(\AppBundle\Entity\Biznes $biznes = null)
{
$this->biznes = $biznes;
return $this;
}
/**
* Get biznes
*
* @return \AppBundle\Entity\Biznes
*/
public function getBiznes()
{
return $this->biznes;
}
}
| 41,847
|
https://github.com/zhangwei9757/xiaocaibao/blob/master/game6/guild/src/main/java/com/tumei/model/GroupBean.java
|
Github Open Source
|
Open Source
|
LicenseRef-scancode-unknown-license-reference, Apache-2.0
| 2,018
|
xiaocaibao
|
zhangwei9757
|
Java
|
Code
| 2,603
| 9,559
|
package com.tumei.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.google.common.base.Strings;
import com.tumei.common.RemoteService;
import com.tumei.common.fight.*;
import com.tumei.common.group.GroupMessage;
import com.tumei.common.group.GroupRoleMessage;
import com.tumei.common.group.GroupSceneRoleStruct;
import com.tumei.common.group.GroupSimpleStruct;
import com.tumei.common.utils.Defs;
import com.tumei.common.utils.ErrCode;
import com.tumei.common.utils.RandomUtil;
import com.tumei.common.utils.TimeUtil;
import com.tumei.common.webio.AwardStruct;
import com.tumei.common.webio.BattleResultStruct;
import com.tumei.controller.GroupService;
import com.tumei.controller.struct.*;
import com.tumei.controller.struct.notify.GroupTextNotifyStruct;
import com.tumei.modelconf.GroupConf;
import com.tumei.modelconf.GuildraidConf;
import com.tumei.modelconf.Readonly;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;
import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Consumer;
import static com.tumei.common.utils.Defs.*;
/**
* Created by leon on 2016/11/5.
*/
@Document(collection = "Groups")
public class GroupBean {
static final Log log = LogFactory.getLog(GroupBean.class);
@JsonIgnore
@Id
private String objectId;
@Field("id")
private Long id;
private String name = "";
private int icon;
private boolean dirty;
/**
* 创建时间
*/
private Date create;
/**
* 公会所在服务器
*/
private int zone;
/**
* 今日贡献总数值
*/
private int progress;
/**
* 加入公会的方案
* 0: 自动加入
* 1: 需要审批
* 2: 拒绝加入
*/
private int approval;
/**
* 军团贡献
*/
private int contrib;
/**
* 军团等级
*/
private int level = 1;
/**
* 军团经验
*/
private int exp;
/**
* 总军团经验
*/
private int allExp;
/**
* 军团描述
*/
private String desc = "";
/**
* 内部公告
*/
private String notify = "";
private HashMap<Long, GroupRole> roles = new HashMap<>();
/**
* 待审批成员
*/
private List<GroupPreRole> preRoles = new ArrayList<>();
/**
* 按照服务器分块的成员列表, 不会保存到数据库
*/
private HashMap<Integer, List<GroupRole>> zoneRoles = new HashMap<>();
/**
* 需要广播全体的消息
*/
private List<String> messages = new ArrayList<>();
private int flushDay;
private GroupScene scene = new GroupScene();
/**
* 消息记录,登录公会的时候返回以前的100条老消息
*/
private List<String> notifys = new ArrayList<>();
public GroupBean() {
arrangeZoneRoles();
}
/**
* 搜寻是否有需要广播的信息
*/
public synchronized void update() {
if (messages.size() > 0) {
String text = String.join("\n", messages);
messages.clear();
if (Strings.isNullOrEmpty(text)) {
return;
}
GroupTextNotifyStruct n = new GroupTextNotifyStruct(text);
try {
zoneRoles.forEach((server, grs) -> {
n.addUsers(grs);
RemoteService.getInstance().notifyGroup(server, n);
});
} catch (Exception ex) {
}
}
}
public synchronized GroupScene getScene() {
return scene;
}
public void setScene(GroupScene scene) {
this.scene = scene;
}
public int getFlushDay() {
return flushDay;
}
public void setFlushDay(int flushDay) {
this.flushDay = flushDay;
}
public String getObjectId() {
return objectId;
}
public void setObjectId(String objectId) {
this.objectId = objectId;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getIcon() {
return icon;
}
public void setIcon(int icon) {
this.icon = icon;
}
public int getApproval() {
return approval;
}
public void setApproval(int approval) {
this.approval = approval;
}
public HashMap<Long, GroupRole> getRoles() {
return roles;
}
public void setRoles(HashMap<Long, GroupRole> roles) {
this.roles = roles;
}
public synchronized int getProgress() {
return progress;
}
public void setProgress(int progress) {
this.progress = progress;
}
public int getContrib() {
return contrib;
}
public void setContrib(int contrib) {
this.contrib = contrib;
}
public int getLevel() {
return level;
}
public void setLevel(int level) {
this.level = level;
}
public int getExp() {
return exp;
}
public void setExp(int exp) {
this.exp = exp;
}
public int getZone() {
return zone;
}
public void setZone(int zone) {
this.zone = zone;
}
public Date getCreate() {
return create;
}
public void setCreate(Date create) {
this.create = create;
}
public List<GroupPreRole> getPreRoles() {
return preRoles;
}
public void setPreRoles(List<GroupPreRole> preRoles) {
this.preRoles = preRoles;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getNotify() {
return notify;
}
public void setNotify(String notify) {
this.notify = notify;
}
public List<String> getNotifys() {
return notifys;
}
public void setNotifys(List<String> notifys) {
this.notifys = notifys;
}
public static GroupBean create(long id) {
GroupBean gb = new GroupBean();
gb.id = id;
gb.zone = (int) (id % 1000);
gb.create = new Date();
return gb;
}
/*********** 需要同步的操作 ***************/
/**
* 增加公会经验
*
* @param _exp
*/
public synchronized void addExp(int _exp) {
exp += _exp;
allExp += _exp;
GroupService.getInstance().submitExpRank(id, allExp);
while (true) {
GroupConf gc = Readonly.getInstance().findGroup(level);
if (gc == null || gc.exp == 0 || exp < gc.exp) {
break;
}
else {
exp -= gc.exp;
++level;
report(TimeUtil.nowString() + "|在全体成员的努力下,公会达到" + Defs.getColorString(5, level+"") + "级");
}
}
}
public synchronized String join(GroupRoleMessage grm) {
GroupConf gc = Readonly.getInstance().findGroup(level);
if (roles.size() >= gc.num) {
return "公会成员已满";
}
if (approval == 2 && roles.size() > 0) {
return "拒绝加入";
}
else if (approval == 1 && roles.size() > 0) {
if (preRoles.size() >= 15) {
return "申请人数过多";
}
// 删除重复的
preRoles.removeIf((_gpr) -> _gpr.id == grm.id);
GroupPreRole gpr = new GroupPreRole(grm);
preRoles.add(gpr);
return "等待审批";
}
else {
if (roles.values().stream().filter((rr) -> {
return (rr.id == grm.id);
}).count() > 0) {
return "已经加入该公会";
}
long other = GroupService.getInstance().tryGroup(grm.id, id);
if (other != 0) {
return "other:" + other;
}
GroupRole gr = new GroupRole(grm);
if (roles.size() == 0) {
gr.setLord();
}
gr.last = LocalDateTime.now();
roles.put(gr.id, gr);
List<GroupRole> tmp = zoneRoles.getOrDefault(getZone(gr.id), null);
if (tmp == null) {
tmp = new ArrayList<>();
zoneRoles.put(getZone(gr.id), tmp);
}
tmp.add(gr);
report(TimeUtil.nowString() + "|玩家" + Defs.getColorString(5, gr.name) + "加入公会.");
}
return "";
}
public synchronized String approveJoin(GroupPreRole gpr, GroupRole leader) {
GroupConf gc = Readonly.getInstance().findGroup(level);
if (roles.size() >= gc.num) {
return "公会成员已满";
}
long other = GroupService.getInstance().tryGroup(gpr.id, id);
if (other != 0) {
return "玩家已经加入其它公会";
}
GroupRole gr = new GroupRole(gpr);
gr.last = LocalDateTime.now();
roles.put(gr.id, gr);
List<GroupRole> tmp = zoneRoles.getOrDefault(getZone(gr.id), null);
if (tmp == null) {
tmp = new ArrayList<>();
zoneRoles.put(getZone(gr.id), tmp);
}
tmp.add(gr);
report(TimeUtil.nowString() + "|玩家" + Defs.getColorString(1, gr.name) + "被官员" + Defs.getColorString(5, leader.name) + "批准加入公会.");
return "";
}
private int getZone(long id) {
return (int) (id % 1000);
}
/**
* 根据roles里的数据,按照角色所在服务器进行整理
*/
protected void arrangeZoneRoles() {
zoneRoles.clear();
for (GroupRole gr : roles.values()) {
long id = gr.id;
List<GroupRole> tmp = zoneRoles.getOrDefault(getZone(id), null);
if (tmp == null) {
tmp = new ArrayList<>();
zoneRoles.put(getZone(id), tmp);
}
tmp.add(gr);
}
}
/**
* 删除成员的缓存
*
* @param id
*/
private void remove(long id) {
roles.remove(id);
List<GroupRole> tmp = zoneRoles.getOrDefault(getZone(id), null);
if (tmp != null) {
tmp.removeIf((r) -> {
return (r.id == id);
});
}
GroupService.getInstance().leaveGroup(id, getId());
}
public synchronized String leave(long id) {
GroupRole role = roles.getOrDefault(id, null);
if (role != null) {
if (roles.size() > 1) {
// 会长离开公会,副会长继承,没有副会长不准离开
if (role.isLord()) {
Optional<GroupRole> opt = roles.values().stream().filter((r) -> {
return r.isVp();
}).findFirst();
if (!opt.isPresent()) {
return "至少有一名副会长,才能离开公会";
}
else {
// 设定为会长
opt.get().setLord();
}
}
}
remove(id);
report(TimeUtil.nowString() + "|公会成员" + Defs.getColorString(5, role.name) + "离开公会.");
}
return "";
}
/**
* 根据公会当前信息,返回公会传递数据的结构
*
* @return
*/
public synchronized GroupMessage createBody() {
GroupMessage gm = new GroupMessage();
gm.gid = getId();
gm.name = getName();
gm.icon = getIcon();
gm.zone = getZone();
if (create != null) {
gm.create = create.getTime();
}
gm.desc = getDesc();
gm.notify = getNotify();
gm.contrib = getContrib();
gm.approval = getApproval();
gm.level = getLevel();
gm.exp = getExp();
getRoles().values().stream().forEach((role) -> {
gm.roles.add(role.createGroupRoleMessage());
});
getPreRoles().stream().forEach((role) -> {
gm.pres.add(role.createGroupRoleMessage());
});
return gm;
}
/**
* 查找公会,公会推荐的时候返回的结构
*
* @return
*/
public synchronized GroupSimpleStruct createSimpleBody() {
GroupSimpleStruct gss = new GroupSimpleStruct();
gss.gid = getId();
gss.name = getName();
gss.icon = getIcon();
gss.count = getRoles().size();
gss.level = getLevel();
gss.desc = getDesc();
gss.zone = getZone();
Optional<GroupRole> opt = getRoles().values().stream().filter((r) -> {
return r.isLord();
}).findFirst();
opt.ifPresent((r) -> {
gss.lord = r.name;
gss.lordlvl = r.level;
});
return gss;
}
public synchronized String getLeaderName() {
Optional<GroupRole> opt = roles.values().stream().filter((r) -> {
return r.isLord();
}).findFirst();
if (opt.isPresent()) {
return opt.get().name;
}
return "";
}
public synchronized boolean isDirty() {
return dirty;
}
public synchronized void setDirty(boolean dirty) {
this.dirty = dirty;
}
public synchronized void save(Consumer<GroupBean> func) {
if (dirty) {
dirty = false;
func.accept(this);
}
}
/**
* 修改公会加入的方式
*
* @param role 操作者
* @param mode 方案
* @return
*/
public synchronized String modifyApproval(long role, int mode) {
if (mode < 0 || mode > 2) {
return ErrCode.未知参数.name();
}
GroupRole gr = roles.getOrDefault(role, null);
if (gr == null || !gr.isLord()) {
return "没有权限";
}
approval = mode;
report(TimeUtil.nowString() + "|管理员" + Defs.getColorString(5, gr.name) + "修改公会审批方式.");
return "";
}
/**
* 修改公会公告
*
* @param role
* @param desc
* @return
*/
public synchronized String modifyDesc(long role, String desc) {
if (desc == null || desc.length() > 255) {
return "公告内容非法";
}
GroupRole gr = roles.getOrDefault(role, null);
if (gr == null || !gr.isLord()) {
return "没有权限";
}
this.desc = desc;
report(TimeUtil.nowString() + "|管理员" + Defs.getColorString(5, gr.name) + "修改宣言");
return "";
}
public synchronized String modifyNotify(long role, String desc) {
if (desc == null || desc.length() > 255) {
return "公告内容非法";
}
GroupRole gr = roles.getOrDefault(role, null);
if (gr == null || !gr.isLord()) {
return "没有权限";
}
this.notify = desc;
report(TimeUtil.nowString() + "|管理员" + Defs.getColorString(5, gr.name) + "修改通知");
return "";
}
/***
* 报告发生的事件给所有成员所在的服务器
*/
public synchronized void report(String text) {
messages.add(text);
while (notifys.size() > 200) {
notifys.remove(0);
}
notifys.add(text);
}
/**
* 报告玩家通过审批,加入公会
*
* @param role
*/
public synchronized void reportApproval(long role) {
RemoteService.getInstance().notifyApproval((int) (role % 1000), this.id, role);
}
/**
* 修改成员的权限级别
*
* @param role 操作者
* @param target 被操作者
* @param mode 1:提升 2:降低
* @return
*/
public synchronized String modify(long role, long target, int mode) {
if (mode < 1 || mode > 2) {
return ErrCode.未知参数.name();
}
GroupRole gr = roles.getOrDefault(role, null);
GroupRole tr = roles.getOrDefault(target, null);
if (gr == null || tr == null || role == target || !gr.isLord()) {
return "没有权限";
}
if (mode == 1) { // 提升
if (tr.isVp()) { // 副会长提升的时候,会长需要下降
gr.setVp();
tr.setLord();
}
else {
// 检查副团长的个数
if (roles.values().stream().filter((r) -> {
return r.isVp();
}).count() >= 4) {
return "副会长个数已达上限";
}
tr.setVp();
}
}
else {
tr.setNormal();
}
return "";
}
/**
* 审批成员
*
* @param role 审批人
* @param target 被审批人
* @param mode 1:同意 2:拒绝
* @return
*/
public synchronized String approve(long role, long target, int mode) {
if (mode < 1 || mode > 2) {
return ErrCode.未知参数.name();
}
GroupRole gr = roles.getOrDefault(role, null);
Optional<GroupPreRole> opt = preRoles.stream().filter((r) -> {
return (r.id == target);
}).findFirst();
if (!opt.isPresent()) {
return "审批对象不存在";
}
GroupPreRole tr = opt.get();
if (gr == null || role == target || !gr.isVpAbove()) {
return "没有权限";
}
if (roles.values().stream().anyMatch((r) -> {
return (r.id == target);
})) {
// 审批对象已经存在成员列表中,直接和拒绝流程一样,江这次审批记录删除即刻。
mode = 2;
}
if (mode == 1) { // 同意
String rtn = approveJoin(tr, gr); // 审批成功才删除这个申请
preRoles.remove(tr);
if (Strings.isNullOrEmpty(rtn)) {
reportApproval(tr.id);
}
return rtn;
}
else { // 拒绝
preRoles.remove(tr);
}
return "";
}
/**
* @param role
* @param target
* @return
*/
public synchronized String kick(long role, long target) {
GroupRole gr = roles.getOrDefault(role, null);
GroupRole tr = roles.getOrDefault(target, null);
if (gr == null || role == target || !gr.isVpAbove()) {
return "没有权限";
} else if (tr == null) {
return "操作对象不在公会中";
}
if (tr.isVpAbove()) {
return "官员不能被踢";
}
remove(target);
report(TimeUtil.nowString() + "|公会成员" + Defs.getColorString(1, tr.name) + "被官员" + Defs.getColorString(5, gr.name) + "踢出公会.");
return "";
}
/**
* 弹劾团长
* <p>
* 1. 副团长或者贡献排名前5个成员才能进行弹劾
* 2. 团长最近登录时间是在五天前
* 3. 弹劾成功后,立刻成为新的团长
*
* @param role
* @return
*/
public synchronized String impeach(long role) {
GroupRole gr = roles.getOrDefault(role, null);
if (gr == null) {
return "成员不存在";
}
if (gr.isLord()) {
return "会长不能弹劾";
}
if (!gr.isVp()) {
// 在非副会长的情况下,检查是否贡献为前5
List<GroupRole> tmp = new ArrayList<>(roles.values());
Collections.sort(tmp, (o1, o2) -> {
if (o1.cb > o2.cb) {
return -1;
}
else if (o1.cb < o2.cb) {
return 1;
}
return 0;
});
int n = 5;
if (n > tmp.size()) {
n = tmp.size();
}
boolean found = false;
for (int i = 0; i < 5; ++i) {
if (tmp.get(i).id == role) {
found = true;
break;
}
}
if (!found) {
return "只有副会长或者历史贡献排名前五的成员才能弹劾离线五天以上的会长";
}
}
// 检查团长是否离线超过五天
GroupRole leader = roles.values().stream().filter((r) -> {
return r.isLord();
}).findFirst().get();
// 当前时间减去5天,如果在会长上次登录时间之后,表示会长超过5天未登录, 否则不能弹劾
if (!LocalDateTime.now().minusDays(5).isAfter(leader.last)) {
return "会长5天内登录过,不可被弹劾";
}
// 弹劾会长,提升自己
leader.setNormal();
gr.setLord();
report(TimeUtil.nowString() + "|会长" + Defs.getColorString(1, leader.name) + "被玩家" + Defs.getColorString(5, gr.name) + "成功弹劾.");
return "";
}
public synchronized boolean logon(GroupRoleMessage grm) {
GroupRole gr = roles.getOrDefault(grm.id, null);
if (gr == null) {
return false;
}
gr.logon(grm);
return true;
}
/**
* 贡献
*
* @param role
* @param pg
* @param _exp
* @param cb
* @return
*/
public synchronized String donate(long role, int pg, int _exp, int cb) {
GroupRole gr = roles.get(role);
if (gr == null) {
return "玩家已经不在该公会中";
}
flush();
gr.cbs += cb;
gr.cb += cb;
addExp(_exp);
progress += pg;
String mode = String.format(绿色字段, "普通捐献");
if (pg >= 5) {
mode = String.format(紫色字段, "高级捐献");
} else if (pg >= 3){
mode = String.format(蓝色字段, "中级捐献");
}
report("1|" + TimeUtil.nowString() + "|" + Defs.getColorString(5, gr.name) + ":进行了一次" + mode + ".");
return "";
}
/**
* 刷新成员的当日贡献和公会进度
*/
public synchronized void flush() {
int today = TimeUtil.getToday();
if (today != flushDay) {
flushDay = today;
progress = 0;
roles.forEach((rid, gr) -> gr.flush());
// 如果当前副本章节未通过,则恢复所有战斗力,否则建立下一关的战斗力
scene.reset();
GroupService.getInstance().submitSceneRank(id, scene.scene);
dirty = true;
}
}
public synchronized void flushToScene(int sc) {
progress = 0;
roles.forEach((rid, gr) -> gr.flush());
// 如果当前副本章节未通过,则恢复所有战斗力,否则建立下一关的战斗力
scene.scene = sc;
scene.reset();
GroupService.getInstance().submitSceneRank(id, scene.scene);
dirty = true;
}
/**
* 是否可以进行公会副本战斗
* @return
*/
public synchronized boolean canFight() {
// 1. 判断时间 早上10点到晚上10点
if (LocalDateTime.now().getHour() < 10) {
return false;
}
return true;
}
// 获取指定副本关卡,指定阵营的奖励
public synchronized List<AwardStruct> getSceneAwards(int idx) {
List<AwardStruct> rtn = new ArrayList<>();
scene.awards.get(idx).forEach(as -> {
rtn.add(new AwardStruct(as.id, as.count));
});
return rtn;
}
public synchronized AwardStruct randomSceneAwards(int idx) {
List<AwardStruct> awards = scene.awards.get(idx);
int find = (RandomUtil.getRandom() % awards.size());
return awards.remove(find);
}
/**
* 公会请求战斗
*
* @param bs
* @param index
* @param rl
*/
public synchronized void callFight(GroupRole role, HerosStruct bs, int index, BattleResultStruct rl) {
List<DirectHeroStruct> peers = scene.peers.get(index - 1);
// 如果对手全部死亡了,直接返回结束
if (peers.stream().noneMatch((dhs) -> dhs.life > 0)) {
rl.result = "关卡Boss已经被其他成员击杀";
} else {
SceneFightStruct arg = new SceneFightStruct();
arg.hss = bs;
arg.right = peers;
arg.isBoss = true;
GroupSceneRoleStruct gsrs = scene.roles.get(role.id);
if (gsrs == null) {
gsrs = new GroupSceneRoleStruct();
gsrs.name = role.name;
gsrs.icon = role.icon;
scene.roles.put(role.id, gsrs);
}
GuildraidConf grc = Readonly.getInstance().findGuildraid(scene.scene);
rl.rCon = RandomUtil.getBetween(grc.reward1[0], grc.reward1[1]);
try {
FightResult r = GroupService.getInstance().callRemote(RemoteService::callFight, arg);
if (r == null) {
rl.result = "战斗服务器维护中";
} else {
++gsrs.count;
rl.data = r.data;
if (r.win < 1) {
rl.result = "战斗出错";
} else {// 胜利,就是击杀
if (r.win == 1) {
rl.kill = 1;
}
long harm = 0;
long total = 0;
for (int j = 0; j < peers.size(); ++j) {
DirectHeroStruct shs = peers.get(j);
if (shs != null) {
long l = r.lifes.get(j);
// log.info("英雄(" + shs.hero + ") life:" + shs.life + " 现在:" + l);
harm = harm + (shs.life - l);
shs.life = l;
total += shs.life;
}
}
if (gsrs.harm < harm) {
gsrs.harm = harm;
}
rl.harm = harm;
int rt = (int)(100.0f - (total * 100f) / scene.totals.get(index - 1));
if (rt < 0) {
rt = 0;
} else if (rt > 100) {
rt = 100;
rl.kill = 1; // 如果扣除都血量满足条件,也算胜利
}
log.info(this.id + ": 玩家(" + role.name + ") 战斗,血量为:" + total + ",最大血量:" + scene.totals.get(index - 1) + " 进度:" + rt);
scene.progress[index-1] = rt;
if (rl.kill == 1) { // 击杀 奖励判定
if (scene.firstKill[index-1] == 0) {
scene.firstKill[index-1] = 1;
rl.kill = 2;
log.info(this.id + ": 玩家(" + role.name + ") 首次击杀boss(" + index + ") 获得经验:" + grc.reward5 + " 原来等级经验:" + this.level + "," + this.exp);
this.addExp(grc.reward5);
} else {
log.info(this.id + ": 玩家(" + role.name + ") 非首次击杀boss(" + index + ") 不能获得经验:" + grc.reward5);
}
role.cb += rl.rCon + grc.reward2;
role.cbs += rl.rCon + grc.reward2;
this.contrib += grc.reward2 + rl.rCon;
log.info(this.id + ": 玩家(" + role.name + ") 获得贡献:" + (rl.rCon + grc.reward2));
report("2|" + TimeUtil.nowString() + "|" + scene.scene + "|" + index + "|" + Defs.getColorString(5, role.name));
} else {
role.cb += rl.rCon;
role.cbs += rl.rCon;
this.contrib += rl.rCon;
log.info(this.id + ": 玩家(" + role.name + ") 获得贡献:" + rl.rCon);
}
this.dirty = true;
}
}
} catch (Exception ex) {
log.error("错误原因:" + ex.getMessage());
ex.printStackTrace();
rl.result = "战斗出错";
}
}
}
}
| 1,099
|
https://github.com/Tory-Xu/TYNavBarStyle/blob/master/TYNavBarStyle/Classes/UINavigationController+TYNavBarStyle.h
|
Github Open Source
|
Open Source
|
MIT
| null |
TYNavBarStyle
|
Tory-Xu
|
C
|
Code
| 62
| 297
|
//
// UINavigationController+TYNavBarStyle.h
// Legend
//
// Created by yons on 17/6/8.
// Copyright © 2017年 congacademy. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "TYNavBarTintEngine.h"
@interface UINavigationController (TYNavBarStyle)
/**
* 导航栏颜色,并设置状态栏相应样色
*
* @param style `TYNavBarStyle`
*/
- (void)lg_setNavigationBarStyle:(TYNavBarStyle)style;
/**
* 导航栏返回按钮样式
*
* 如果需要隐藏返回按钮,实现如下:
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[self.navigationItem setHidesBackButton:YES];
}
*
* @param style `TYNavBarStyle`
*/
- (void)lg_setNavigationBarBackItemStyle:(TYNavBarStyle)style;
@end
| 49,742
|
https://github.com/ipinfo/java/blob/master/src/main/java/io/ipinfo/api/model/ASN.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,023
|
java
|
ipinfo
|
Java
|
Code
| 136
| 318
|
package io.ipinfo.api.model;
public class ASN {
private final String asn;
private final String name;
private final String domain;
private final String route;
private final String type;
public ASN(
String asn,
String name,
String domain,
String route,
String type
) {
this.asn = asn;
this.name = name;
this.domain = domain;
this.route = route;
this.type = type;
}
public String getAsn() {
return asn;
}
public String getName() {
return name;
}
public String getDomain() {
return domain;
}
public String getRoute() {
return route;
}
public String getType() {
return type;
}
@Override
public String toString() {
return "ASN{" +
"asn='" + asn + '\'' +
", name='" + name + '\'' +
", domain='" + domain + '\'' +
", route='" + route + '\'' +
", type='" + type + '\'' +
'}';
}
}
| 14,030
|
https://github.com/kuriyummy/ITMO_ICT_WebDevelopment_2021-2022/blob/master/students/K33401/laboratory_works/Dorofeeva_Arina/Lr3 + Lr4/DjangoLr4/axolotols_back/axolotls_app/serializers.py
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
ITMO_ICT_WebDevelopment_2021-2022
|
kuriyummy
|
Python
|
Code
| 28
| 86
|
from rest_framework import serializers
from .models import *
class VideoSerializer(serializers.ModelSerializer):
class Meta:
model = VideoOfUser
fields = "__all__"
class LinkToVideoSerializer(serializers.ModelSerializer):
class Meta:
model = LinkToVideo
fields = "__all__"
| 41,175
|
https://github.com/elafarge/opentelemetry-collector-contrib/blob/master/exporter/googlecloudpubsubexporter/watermark_test.go
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,022
|
opentelemetry-collector-contrib
|
elafarge
|
Go
|
Code
| 344
| 1,553
|
// Copyright The OpenTelemetry Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package googlecloudpubsubexporter
import (
"testing"
"time"
"github.com/stretchr/testify/assert"
"go.opentelemetry.io/collector/model/pdata"
)
var (
tsRef = time.Date(2022, 11, 28, 12, 0, 0, 0, time.UTC)
tsBefore30s = tsRef.Add(-30 * time.Second)
tsBefore1m = tsRef.Add(-1 * time.Minute)
tsBefore5m = tsRef.Add(-5 * time.Minute)
tsAfter30s = tsRef.Add(30 * time.Second)
tsAfter5m = tsRef.Add(5 * time.Minute)
)
var metricsData = func() pdata.Metrics {
d := pdata.NewMetrics()
metric := d.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics().AppendEmpty()
metric.SetDataType(pdata.MetricDataTypeHistogram)
metric.Histogram().DataPoints().AppendEmpty().SetTimestamp(pdata.NewTimestampFromTime(tsAfter30s))
metric = d.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics().AppendEmpty()
metric.SetDataType(pdata.MetricDataTypeSummary)
metric.Summary().DataPoints().AppendEmpty().SetTimestamp(pdata.NewTimestampFromTime(tsAfter5m))
metric = d.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics().AppendEmpty()
metric.SetDataType(pdata.MetricDataTypeGauge)
metric.Gauge().DataPoints().AppendEmpty().SetTimestamp(pdata.NewTimestampFromTime(tsRef))
metric = d.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics().AppendEmpty()
metric.SetDataType(pdata.MetricDataTypeSum)
metric.Sum().DataPoints().AppendEmpty().SetTimestamp(pdata.NewTimestampFromTime(tsBefore30s))
metric = d.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics().AppendEmpty()
metric.SetDataType(pdata.MetricDataTypeExponentialHistogram)
metric.ExponentialHistogram().DataPoints().AppendEmpty().SetTimestamp(pdata.NewTimestampFromTime(tsBefore5m))
return d
}()
var tracesData = func() pdata.Traces {
d := pdata.NewTraces()
span := d.ResourceSpans().AppendEmpty().ScopeSpans().AppendEmpty().Spans().AppendEmpty()
span.SetStartTimestamp(pdata.NewTimestampFromTime(tsRef))
span = d.ResourceSpans().AppendEmpty().ScopeSpans().AppendEmpty().Spans().AppendEmpty()
span.SetStartTimestamp(pdata.NewTimestampFromTime(tsBefore30s))
span = d.ResourceSpans().AppendEmpty().ScopeSpans().AppendEmpty().Spans().AppendEmpty()
span.SetStartTimestamp(pdata.NewTimestampFromTime(tsBefore5m))
return d
}()
var logsData = func() pdata.Logs {
d := pdata.NewLogs()
log := d.ResourceLogs().AppendEmpty().ScopeLogs().AppendEmpty().LogRecords().AppendEmpty()
log.SetTimestamp(pdata.NewTimestampFromTime(tsRef))
log = d.ResourceLogs().AppendEmpty().ScopeLogs().AppendEmpty().LogRecords().AppendEmpty()
log.SetTimestamp(pdata.NewTimestampFromTime(tsBefore30s))
log = d.ResourceLogs().AppendEmpty().ScopeLogs().AppendEmpty().LogRecords().AppendEmpty()
log.SetTimestamp(pdata.NewTimestampFromTime(tsBefore5m))
return d
}()
func TestCurrentMetricsWatermark(t *testing.T) {
out := currentMetricsWatermark(metricsData, tsRef, time.Minute)
assert.Equal(t, tsRef, out)
}
func TestCurrentTracesWatermark(t *testing.T) {
out := currentTracesWatermark(tracesData, tsRef, time.Minute)
assert.Equal(t, tsRef, out)
}
func TestCurrentLogsWatermark(t *testing.T) {
out := currentLogsWatermark(logsData, tsRef, time.Minute)
assert.Equal(t, tsRef, out)
}
func TestEarliestMetricsWatermarkInDrift(t *testing.T) {
out := earliestMetricsWatermark(metricsData, tsRef, time.Hour)
assert.Equal(t, tsBefore5m, out)
}
func TestEarliestMetricsWatermarkOutDrift(t *testing.T) {
out := earliestMetricsWatermark(metricsData, tsRef, time.Minute)
assert.Equal(t, tsBefore1m, out)
}
func TestEarliestLogsWatermarkInDrift(t *testing.T) {
out := earliestLogsWatermark(logsData, tsRef, time.Hour)
assert.Equal(t, tsBefore5m, out)
}
func TestEarliestLogsWatermarkOutDrift(t *testing.T) {
out := earliestLogsWatermark(logsData, tsRef, time.Minute)
assert.Equal(t, tsBefore1m, out)
}
func TestEarliestTracessWatermarkInDrift(t *testing.T) {
out := earliestTracesWatermark(tracesData, tsRef, time.Hour)
assert.Equal(t, tsBefore5m, out)
}
func TestEarliestTracesWatermarkOutDrift(t *testing.T) {
out := earliestTracesWatermark(tracesData, tsRef, time.Minute)
assert.Equal(t, tsBefore1m, out)
}
| 13,227
|
https://github.com/nrs011/steady/blob/master/frontend-apps/src/main/webapp/helpers/transpiled/basePriorityQueueES5.js
|
Github Open Source
|
Open Source
|
BSD-3-Clause, Apache-2.0, MIT
| 2,020
|
steady
|
nrs011
|
JavaScript
|
Code
| 344
| 892
|
/*
* This file is part of Eclipse Steady.
*
* 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.
*
* SPDX-License-Identifier: Apache-2.0
* SPDX-FileCopyrightText: Copyright (c) 2018-2020 SAP SE or an SAP affiliate company and Eclipse Steady contributors
*/
"use strict";
var _createClass = (function() {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function(Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
})();
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var BasePriorityQueue = (function() {
function BasePriorityQueue() {
_classCallCheck(this, BasePriorityQueue);
this._queue = [];
this._processed = []; // array of ids
}
BasePriorityQueue.prototype.enqueue = function enqueue(run, options) {
options = Object.assign(
{
priority: 0,
id: null
},
options
);
var element = { priority: options.priority, id: options.id, run: run };
if (this.size && this._queue[this.size - 1].priority >= options.priority) {
this._queue.push(element);
return;
}
var index = lowerBound(this._queue, element, function(a, b) {
return b.priority - a.priority;
});
this._queue.splice(index, 0, element);
};
BasePriorityQueue.prototype.dequeue = function dequeue() {
var item = this._queue.shift();
this._processed.push(item.id);
return item.run;
};
BasePriorityQueue.prototype.isPending = function isPending(id) {
return this._queue.some(function(item) {
return item.id === id;
});
};
BasePriorityQueue.prototype.isProcessed = function isProcessed(id) {
return this._processed.indexOf(id) >= 0;
};
BasePriorityQueue.prototype.isInserted = function isInserted(id) {
return this.isPending(id) || this.isProcessed(id);
};
_createClass(BasePriorityQueue, [
{
key: "size",
get: function get() {
return this._queue.length;
}
}
]);
return BasePriorityQueue;
})();
| 19,655
|
https://github.com/jlahteen/juhta.net/blob/master/src/Juhta.Net.LibraryManagement/IConfigurableLibrary.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
juhta.net
|
jlahteen
|
C#
|
Code
| 107
| 229
|
//
// Juhta.NET, Copyright (c) 2017 Juha Lähteenmäki
//
// This source code may be used, modified and distributed under the terms of
// the MIT license. Please refer to the LICENSE.txt file for details.
//
using Microsoft.Extensions.Configuration;
namespace Juhta.Net.LibraryManagement
{
/// <summary>
/// Defines an interface for such configurable libraries whose configuration is done with a JSON, XML or INI
/// configuration.
/// </summary>
public interface IConfigurableLibrary : IConfigurableLibraryBase
{
#region Methods
/// <summary>
/// Initializes the library based on a specified configuration.
/// </summary>
/// <param name="config">Specifies an <see cref="IConfigurationRoot"/> object containing a configuration for
/// the library.</param>
void InitializeLibrary(IConfigurationRoot config);
#endregion
}
}
| 45,059
|
https://github.com/dac09/react-redux-weather/blob/master/src/routes.js
|
Github Open Source
|
Open Source
|
MIT
| 2,016
|
react-redux-weather
|
dac09
|
JavaScript
|
Code
| 32
| 103
|
import React from 'react';
import { Route, IndexRoute } from 'react-router';
import CoreLayout from './layouts/CoreLayout/CoreLayout'
import HomePage from './containers/HomePage/'
export default (
<Route path="/" component={CoreLayout}>
<IndexRoute component={HomePage}/>
<Route path="home"
component={HomePage}/>
</Route>
);
| 35,228
|
https://github.com/mleventh/compressive-sensing-page/blob/master/cs-intro-gh-pages 2/node_modules/mathlib/src/Screen3D/prototype/drawGrid.ts
|
Github Open Source
|
Open Source
|
MIT
| 2,015
|
compressive-sensing-page
|
mleventh
|
TypeScript
|
Code
| 219
| 760
|
/**
* Draws the grid.
*
* @return {Screen3D}
*/
drawGrid() {
if (!this.options.grid) {
return this;
}
var _this = this,
gridDrawer = function (opts, rotX, rotY) {
var i, ii, tickX, tickY, lines, circles, rays,
size = 10,
grid = new THREE.Object3D(),
color = new THREE.Color(opts.color);
if (opts.type === 'cartesian') {
tickX = 'x' in opts.tick ? opts.tick.x : opts.tick.y;
tickY = 'z' in opts.tick ? opts.tick.z : opts.tick.y;
lines = new THREE.Shape();
for (i = -size; i <= size; i += tickX) {
lines.moveTo(-size, i);
lines.lineTo(size, i);
}
for (i = -size; i <= size; i += tickY) {
lines.moveTo(i, -size);
lines.lineTo(i, size);
}
grid.add(new THREE.Line(lines.createPointsGeometry(),
new THREE.LineBasicMaterial({color: color}),
THREE.LinePieces));
grid.rotation.x = rotX;
grid.rotation.y = rotY;
_this.scene.add(grid);
}
else if (opts.type === 'polar') {
circles = new THREE.Shape();
rays = new THREE.Shape();
for (i = 0; i <= size; i += opts.tick.r) {
circles.moveTo(i, 0);
circles.absarc(0, 0, i, 0, 2 * Math.PI + 0.001, false);
}
grid.add(new THREE.Line(circles.createPointsGeometry(),
new THREE.LineBasicMaterial({color: color})));
for (i = 0, ii = 2 * Math.PI; i < ii; i += opts.angle) {
rays.moveTo(0, 0);
rays.lineTo(size * Math.cos(i), size * Math.sin(i));
}
grid.add(new THREE.Line(rays.createPointsGeometry(), new THREE.LineBasicMaterial({color: color})));
grid.rotation.x = rotX;
grid.rotation.y = rotY;
_this.scene.add(grid);
}
};
gridDrawer(this.options.grid.xy, 0, 0);
gridDrawer(this.options.grid.xz, Math.PI / 2, 0);
gridDrawer(this.options.grid.yz, 0, Math.PI / 2);
return this;
}
| 46,381
|
https://github.com/usgs-coupled/iriclib-test/blob/master/h5cgnsfile.h
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
iriclib-test
|
usgs-coupled
|
C++
|
Code
| 147
| 577
|
#ifndef H5CGNSFILE_H
#define H5CGNSFILE_H
#include "h5cgnsfilesolutionwriter.h"
#include "iriclib_global.h"
#include <string>
namespace iRICLib {
class H5CgnsBase;
class H5CgnsFileSolutionReader;
class H5CgnsFileSolutionWriter;
class H5CgnsZone;
class IRICLIBDLL H5CgnsFile
{
public:
enum class Mode {
Create,
OpenModify,
OpenReadOnly
};
H5CgnsFile(const std::string& fileName, Mode mode, const std::string& resultFolder = "result");
~H5CgnsFile();
int open();
int close();
Mode mode() const;
std::string fileName() const;
std::string tmpFileName() const; // temporary file used to read result while running
std::string resultFolder() const;
int baseNum() const;
H5CgnsBase* base();
H5CgnsBase* base(int dim);
H5CgnsBase* baseById(int bid);
H5CgnsBase* ccBase() const;
bool baseExists(int dim) const;
int zoneNum() const;
H5CgnsZone* zoneById(int zid);
int writeTime(double time);
int writeIteration(int iteration);
int setSolutionId(int solutionId);
int copyGridsTo(H5CgnsFile* target);
int flush();
int getGridId(H5CgnsZone* zone, int* gridId);
int lastGridId(int* id);
H5CgnsFileSolutionReader* solutionReader();
H5CgnsFileSolutionWriter* solutionWriter();
void setWriterMode(H5CgnsFileSolutionWriter::Mode mode);
private:
class Impl;
Impl* impl;
public:
friend class H5CgnsBase;
};
} // namespace iRICLib
#ifdef _DEBUG
#include "private/h5cgnsfile_impl.h"
#endif // _DEBUG
#endif // H5CGNSFILE_H
| 21,776
|
https://github.com/Trazalog/traz-prod-assetplanner/blob/master/assets/props/gps.js
|
Github Open Source
|
Open Source
|
LicenseRef-scancode-unknown-license-reference, MIT
| 2,023
|
traz-prod-assetplanner
|
Trazalog
|
JavaScript
|
Code
| 117
| 320
|
navigator.geolocation.getCurrentPosition(success, error, options);
function obtenerPosicion() {
debugger;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success, error, options);
return (lat && lon);
} else {
console.log('GSP | No Activado');
return false;
}
}
var options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};
var lat = false;
var lon = false;
var ac = false;
var accMax = parseInt($('#gps-acc').val());
function success(pos) {
var crd = pos.coords;
if ((crd.accuracy != null) || (cdr.acurrary < accMax)) {
lat = crd.latitude;
lon = crd.longitude;
ac = crd.accuracy;
} else {
lat = false;
lon = false;
ac = false;
}
};
function error(err) {
console.log('GPS | ERROR(' + err.code + '): ' + err.message);
lat = false;
lon = false;
ac = false;
};
| 10,769
|
https://github.com/jph/lumberg/blob/master/lib/lumberg/cpanel/zone_edit.rb
|
Github Open Source
|
Open Source
|
MIT
| 2,016
|
lumberg
|
jph
|
Ruby
|
Code
| 853
| 1,561
|
module Lumberg
module Cpanel
# Public: This module allows users to modify their domains
class ZoneEdit < Base
# Public: Retrieve a list of your account's zones and zone file contents.
#
# Returns Hash API Response
def list
perform_request({ api_function: 'fetchzones' })
end
# Public: Add an A, CNAME, or TXT record to a zone file, specified by
# line number
#
# options - Hash options for API call params (default: {})
# :domain - String addon domain for which yo wish to add an entry
# :name - String name of the record, aka subdomain
# :type - String type of the record you wish to add to the zone file.
# Acceptable values include A, CNAME or TXT
# :txt - String text you wish to contain in your TXT record. Required
# parameter when you specify "TXT" in the :type parameter
# (default: '')
# :cname - String required parameter when you specify CNAME in the
# :type parameter (default: '')
# :address - String ip address to map to the subdomain. (default: '')
# :ttl - Integer time to live in seconds (default: 0)
# :class - String class to be used for the record. Ordinarily this
# parameter is not required (default: '')
#
# Returns Hash API response.
def create(options = {})
options[:txtdata] = options.delete(:txt)
perform_request({ api_function: 'add_zone_record' }.merge(options))
end
# Public: Show dns zone for a domain
#
# options - Hash options for API call params (default: {})
# :domain - String domain that corresponds to the zone file you wish to
# show
# :get_custom_entries - Boolean parameter. Entering a value of "1" will
# cause the function to return only non-essential
# A and CNAME records. These will include www.*,
# ftp.*, mail.* and localhost.* (default: '')
# :keys - String parameter that may contain a serie of values, all of
# which act the same way. Each value searches the data
# structure, like a grep, for a single hash (line of the zone
# file). Acceptable values include: line, ttl, name, class,
# address, type, txtdata, preference and exchange.
#
# Returns Hash API response.
def show(options = {})
options[:customonly] = options.delete(:get_custom_entries)
perform_request({ api_function: 'fetchzone' }.merge(options))
end
# Public: Revert a zone file to its original state.
#
# options - Hash options for API call params (default: {})
# :domain - String domain that corresponds to the zone file you wish to
# revert
#
# Returns Hash API response
def reset(options = {})
perform_request({ api_function: 'resetzone' })
end
# Public: Edit an A, CNAME, or TXT record in a zone file, specified by
# line number. This function works nicely with "show" method to easily
# fetch line number and record information.
#
# options - Hash options for API call params (default: {})
# :domain - String domain that corresponds to the zone you wish to edit
# :line - Integer line number of the zone file you wish to edit
# :type - The type fo record you wish to add to the zone file.
# Acceptable values include A, CNAME or TXT. Each type of
# record requires a specific parameter
# :txt - String text you wish to contain in your TXT record. Required
# parameter when you specify "TXT" in the :type parameter
# (default: '')
# :cname - String required parameter when you specify CNAME in the
# :type parameter (default: '')
# :address - String ip address to map to the subdomain. (default: '')
# :ttl - Integer time to live in seconds (default: 0)
# :class - String class to be used for the record. Ordinarily this
# parameter is not required (default: '')
#
# Returns Hash API response.
def edit(options = {})
options[:Line] = options.delete(:line)
options[:txtdata] = options.delete(:txt)
perform_request({ api_function: 'edit_zone_record' }.merge(options))
end
# Public: Remove lines from a DNS zone file. You may only remove A, TXT,
# and CNAME records with this function.
#
# options - Hash options for API call params (default: {})
# :domain - String domain that corresponds to the zone you wish to
# remove a line
# :line - Integer line number of the zone file you wish to remove. Use
# "show" method to obtain the line number of a record
#
# Returns Hash API response.
def remove(options = {})
perform_request({ api_function: 'remove_zone_record' }.merge(options))
end
# Public: Retrieve a list of domains, created within cPanel, associated
# with your cPanel account.
#
# options - Hash options for API call params (default: {})
# :domain - String domain parameter which allows you to append one
# domain name to the end of the resulting output
# (default: '')
#
# Returns Hash API response.
def show_domains(options = {})
perform_request({ api_function: 'fetch_cpanel_generated_domains' })
end
# Public: Retrieve a list of zone modifications for a specific domain.
#
# options - Hash options for API call params (default: {})
# :domain - String domain whose zone modifications you wish to view
#
# Returns Hash API response.
def modifications_for(options = {})
perform_request({ api_function: 'fetchzone_records' }.merge(options))
end
end
end
end
| 38,654
|
https://github.com/emaycn/emay-store/blob/master/src/test/java/cn/emay/store/file/FileMapTest.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
emay-store
|
emaycn
|
Java
|
Code
| 307
| 927
|
package cn.emay.store.file;
import cn.emay.store.file.map.FileMap;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
/**
* @author Frank
*/
public class FileMapTest {
private FileMap map;
@Before
public void pre() {
long time;
map = new FileMap("./emaytest/filemap", 5, 12 * 1024 * 1024, 1024 * 1024);
time = System.currentTimeMillis();
System.out.println("load ok\t" + (System.currentTimeMillis() - time));
}
@After
public void after() {
map.close();
map.delete();
}
@Test
public void testMap() throws InterruptedException {
String key0 = "这个是KEY";
String value0 = "这个是VALUE,这个是VALUE,这个是VALUE";
int total = 10000 * 100;
long time = System.currentTimeMillis();
/*
* 测试put
*/
for (int i = 0; i < total; i++) {
String key = key0 + i;
String value = value0 + i;
map.put(key, value);
}
System.out.println("测试put\t" + (System.currentTimeMillis() - time));
time = System.currentTimeMillis();
Assert.assertEquals(map.size(), total);
for (int i = 0; i < total; i++) {
String key = key0 + i;
String value = value0 + i;
Assert.assertEquals(map.get(key), value);
}
System.out.println("测试put ok\t" + (System.currentTimeMillis() - time));
time = System.currentTimeMillis();
/*
* 测试覆盖
*/
for (int i = 0; i < total; i++) {
String key = key0 + i;
String value = value0 + i + i;
map.put(key, value);
}
System.out.println("测试覆盖\t" + (System.currentTimeMillis() - time));
time = System.currentTimeMillis();
Assert.assertEquals(map.size(), total);
for (int i = 0; i < total; i++) {
String key = key0 + i;
String value = value0 + i + i;
Assert.assertEquals(map.get(key), value);
}
System.out.println("测试覆盖 ok\t" + (System.currentTimeMillis() - time));
time = System.currentTimeMillis();
System.out.println("ishas 111" + map.exists(key0 + "111"));
/*
* 测试删除
*/
for (int i = 0; i < total; i++) {
String key = key0 + i;
map.remove(key);
}
System.out.println("测试删除\t" + (System.currentTimeMillis() - time));
Assert.assertEquals(map.size(), 0);
for (int i = 0; i < total; i++) {
String key = key0 + i;
Assert.assertNull(map.get(key));
}
System.out.println("测试删除 ok\t" + (System.currentTimeMillis() - time));
System.out.println("ishas 111" + map.exists(key0 + "111"));
Thread.sleep(6L * 1000L);
}
}
| 10,588
|
https://github.com/ostertagi/chartflo/blob/master/lib/src/timeseries/timeseries.dart
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
chartflo
|
ostertagi
|
Dart
|
Code
| 326
| 1,027
|
import 'package:charts_flutter/flutter.dart' as charts;
import 'package:flutter/material.dart';
import '../models/chart_datapoint.dart';
import '../models/resample.dart';
import 'build_tschart.dart';
import 'timeframe.dart';
class _TimeSerieChartState extends State<TimeSerieChart> {
_TimeSerieChartState(
{@required this.dataset,
this.showPoints = false,
this.showArea = false,
this.showLine = true,
this.resample,
this.textColor = Colors.black,
this.fontSize = 14,
this.lineColor = Colors.blue,
this.axisColor = Colors.grey})
: assert(dataset != null),
assert(dataset.length > 1),
_dataset = dataset;
final Color textColor;
final Color axisColor;
final int fontSize;
final Resample resample;
final Map<DateTime, num> dataset;
final bool showPoints;
final bool showArea;
final bool showLine;
final Color lineColor;
final _dataPoints = <ChartDataPoint<DateTime, num>>[];
final _seriesList = <charts.Series<dynamic, DateTime>>[];
Map<DateTime, num> _dataset;
bool _ready = false;
@override
void initState() {
// print("DATASET $dataset");
super.initState();
if (resample != null) {
_dataset = TimeFrame.resample(
dataset: dataset,
resampleMethod: resample.method,
timePeriod: resample.timePeriod);
}
_dataset.forEach((date, val) {
_dataPoints.add(ChartDataPoint<DateTime, num>(x: date, y: val));
});
_seriesList.addAll([
charts.Series<ChartDataPoint<DateTime, num>, DateTime>(
id: "1",
//seriesColor: lineColor,
domainFn: (ChartDataPoint<DateTime, num> dataPoint, _) => dataPoint.x,
measureFn: (ChartDataPoint<DateTime, num> dataPoint, _) => dataPoint.y,
data: _dataPoints,
)
]);
setState(() => _ready = true);
}
@override
Widget build(BuildContext context) {
return _ready
? buildFcTimeriesChart(_seriesList, fontSize, textColor, lineColor,
axisColor, showPoints, showArea, showLine, true)
: const Center(child: CircularProgressIndicator());
}
}
/// A timeseries line chart
class TimeSerieChart extends StatefulWidget {
/// Provide a dataset
const TimeSerieChart(
{@required this.dataset,
this.showPoints = false,
this.showArea = false,
this.showLine = true,
this.resample,
this.textColor = Colors.black,
this.fontSize = 14,
this.lineColor = Colors.blue,
this.axisColor = Colors.black});
/// The dataset to chart
final Map<DateTime, num> dataset;
/// Show the points on the chart
final bool showPoints;
/// Show the area of the chart
final bool showArea;
/// Show the line
final bool showLine;
/// Resample method
final Resample resample;
/// The text labels color
final Color textColor;
/// The line color
final Color lineColor;
/// The axis line color
final Color axisColor;
/// The text label font size in poits
final int fontSize;
@override
_TimeSerieChartState createState() => _TimeSerieChartState(
dataset: dataset,
showPoints: showPoints,
showArea: showArea,
showLine: showLine,
textColor: textColor,
fontSize: fontSize,
lineColor: lineColor,
axisColor: axisColor,
resample: resample);
}
| 6,518
|
https://github.com/briangriffey/glass-full-activity/blob/master/build.gradle
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,014
|
glass-full-activity
|
briangriffey
|
Gradle
|
Code
| 49
| 196
|
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:0.6.3'
}
}
apply plugin: 'android'
android {
compileSdkVersion "Google Inc.:Glass Development Kit Sneak Peek:15"
buildToolsVersion "18.0.1"
sourceSets {
main.java.srcDirs = ['src']
main.res.srcDirs = ['res']
main.manifest.srcFile 'AndroidManifest.xml'
}
defaultConfig {
minSdkVersion 14
targetSdkVersion 18
}
}
repositories {
mavenCentral()
}
| 38,985
|
https://github.com/Xinerki/Story/blob/master/missions/marker_display.lua
|
Github Open Source
|
Open Source
|
MIT
| 2,017
|
Story
|
Xinerki
|
Lua
|
Code
| 277
| 2,481
|
missions = {}
function missions.renderMissionMarkers()
for i,v in ipairs(getElementsByType('marker')) do
if getElementData(v,"story.isMissionMarker") then
local x,y,z=getElementPosition(v)
local isUsed=getElementData(v,"story.isMissionMarkerUsed")
local usedBy=getElementData(v,"story.missionMarkerUsedBy")
if getDistanceBetweenPoints3D( x,y,z,getElementPosition(localPlayer) ) < 10 then
local x,y=getScreenFromWorldPosition( x,y,z+2 )
local outline=2
local scale=2
r,g,b=getMarkerColor(v)
if x and y and getElementDimension(v) == getElementDimension(localPlayer) then
x=x*2
if getElementData(v, "story.isMissionMarker1P") then
if isUsed then
dxDrawText(getElementData(v,"story.missionMarkerName").."\n1 Player".."\nCurrently played by: "..getPlayerName(usedBy),x+outline,y-outline,0,0,tocolor(0,0,0,255),scale,"default-bold","center")
dxDrawText(getElementData(v,"story.missionMarkerName").."\n1 Player".."\nCurrently played by: "..getPlayerName(usedBy),x-outline,y+outline,0,0,tocolor(0,0,0,255),scale,"default-bold","center")
dxDrawText(getElementData(v,"story.missionMarkerName").."\n1 Player".."\nCurrently played by: "..getPlayerName(usedBy),x+outline,y+outline,0,0,tocolor(0,0,0,255),scale,"default-bold","center")
dxDrawText(getElementData(v,"story.missionMarkerName").."\n1 Player".."\nCurrently played by: "..getPlayerName(usedBy),x-outline,y-outline,0,0,tocolor(0,0,0,255),scale,"default-bold","center")
dxDrawText(getElementData(v,"story.missionMarkerName").."\n1 Player".."\nCurrently played by: "..getPlayerName(usedBy),x,y,0,0,tocolor(r,g,b,255),scale,"default-bold","center")
else
dxDrawText(getElementData(v,"story.missionMarkerName").."\n1 Player".."\nAvailable to play.",x+outline,y-outline,0,0,tocolor(0,0,0,255),scale,"default-bold","center")
dxDrawText(getElementData(v,"story.missionMarkerName").."\n1 Player".."\nAvailable to play.",x-outline,y+outline,0,0,tocolor(0,0,0,255),scale,"default-bold","center")
dxDrawText(getElementData(v,"story.missionMarkerName").."\n1 Player".."\nAvailable to play.",x+outline,y+outline,0,0,tocolor(0,0,0,255),scale,"default-bold","center")
dxDrawText(getElementData(v,"story.missionMarkerName").."\n1 Player".."\nAvailable to play.",x-outline,y-outline,0,0,tocolor(0,0,0,255),scale,"default-bold","center")
dxDrawText(getElementData(v,"story.missionMarkerName").."\n1 Player".."\nAvailable to play.",x,y,0,0,tocolor(r,g,b,255),scale,"default-bold","center")
end
end
if getElementData(v, "story.isMissionMarker2P") and not getElementData(v, "story.isPlayer1inMission") then
dxDrawText(getElementData(v,"story.missionMarkerName").."\n2 Players".."\nAvailable to play.",x+outline,y-outline,0,0,tocolor(0,0,0,255),scale,"default-bold","center")
dxDrawText(getElementData(v,"story.missionMarkerName").."\n2 Players".."\nAvailable to play.",x-outline,y+outline,0,0,tocolor(0,0,0,255),scale,"default-bold","center")
dxDrawText(getElementData(v,"story.missionMarkerName").."\n2 Players".."\nAvailable to play.",x+outline,y+outline,0,0,tocolor(0,0,0,255),scale,"default-bold","center")
dxDrawText(getElementData(v,"story.missionMarkerName").."\n2 Players".."\nAvailable to play.",x-outline,y-outline,0,0,tocolor(0,0,0,255),scale,"default-bold","center")
dxDrawText(getElementData(v,"story.missionMarkerName").."\n2 Players".."\nAvailable to play.",x,y,0,0,tocolor(r,g,b,255),scale,"default-bold","center")
end
if getElementData(v, "story.isMissionMarker2P") and getElementData(v, "story.isPlayer1inMission") and not getElementData(v, "story.isPlayer2inMission") then
dxDrawText(getElementData(v,"story.missionMarkerName").."\n2 Players".."\nWaiting for player 2: "..getPlayerName(getElementData(v, "story.player1")),x+outline,y+outline,0,0,tocolor(0,0,0,255),scale,"default-bold","center")
dxDrawText(getElementData(v,"story.missionMarkerName").."\n2 Players".."\nWaiting for player 2: "..getPlayerName(getElementData(v, "story.player1")),x-outline,y-outline,0,0,tocolor(0,0,0,255),scale,"default-bold","center")
dxDrawText(getElementData(v,"story.missionMarkerName").."\n2 Players".."\nWaiting for player 2: "..getPlayerName(getElementData(v, "story.player1")),x+outline,y-outline,0,0,tocolor(0,0,0,255),scale,"default-bold","center")
dxDrawText(getElementData(v,"story.missionMarkerName").."\n2 Players".."\nWaiting for player 2: "..getPlayerName(getElementData(v, "story.player1")),x-outline,y+outline,0,0,tocolor(0,0,0,255),scale,"default-bold","center")
dxDrawText(getElementData(v,"story.missionMarkerName").."\n2 Players".."\nWaiting for player 2: "..getPlayerName(getElementData(v, "story.player1")),x,y,0,0,tocolor(r,g,b,255),scale,"default-bold","center")
end
if getElementData(v, "story.isMissionMarker2P") and getElementData(v, "story.isPlayer1inMission") and getElementData(v, "story.isPlayer2inMission") then
dxDrawText(getElementData(v,"story.missionMarkerName").."\n2 Players".."\nCurrently played by: [P1]"..getPlayerName(getElementData(v, "story.player1")).." and [P2]"..getPlayerName(getElementData(v, "story.player2")),x+outline,y+outline,0,0,tocolor(0,0,0,255),scale,"default-bold","center")
dxDrawText(getElementData(v,"story.missionMarkerName").."\n2 Players".."\nCurrently played by: [P1]"..getPlayerName(getElementData(v, "story.player1")).." and [P2]"..getPlayerName(getElementData(v, "story.player2")),x-outline,y-outline,0,0,tocolor(0,0,0,255),scale,"default-bold","center")
dxDrawText(getElementData(v,"story.missionMarkerName").."\n2 Players".."\nCurrently played by: [P1]"..getPlayerName(getElementData(v, "story.player1")).." and [P2]"..getPlayerName(getElementData(v, "story.player2")),x+outline,y-outline,0,0,tocolor(0,0,0,255),scale,"default-bold","center")
dxDrawText(getElementData(v,"story.missionMarkerName").."\n2 Players".."\nCurrently played by: [P1]"..getPlayerName(getElementData(v, "story.player1")).." and [P2]"..getPlayerName(getElementData(v, "story.player2")),x-outline,y+outline,0,0,tocolor(0,0,0,255),scale,"default-bold","center")
dxDrawText(getElementData(v,"story.missionMarkerName").."\n2 Players".."\nCurrently played by: [P1]"..getPlayerName(getElementData(v, "story.player1")).." and [P2]"..getPlayerName(getElementData(v, "story.player2")),x,y,0,0,tocolor(r,g,b,255),scale,"default-bold","center")
end
end
--dxDrawText( string text, float left, float top [, float right=left, float bottom=top, int color=white, float scale=1, mixed font="default", string alignX="left", string alignY="top", bool clip=false, bool wordBreak=false, bool postGUI=false, bool colorCoded=false, bool subPixelPositioning=false, float fRotation=0, float fRotationCenterX=0, float fRotationCenterY=0 ] )
end
end
end
end
| 48,154
|
https://github.com/m0c1-us/PowerToys/blob/master/src/common/shared_constants.h
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
PowerToys
|
m0c1-us
|
C
|
Code
| 44
| 98
|
#pragma once
#include "common.h"
namespace CommonSharedConstants
{
// Flag that can be set on an input event so that it is ignored by Keyboard Manager
const ULONG_PTR KEYBOARDMANAGER_INJECTED_FLAG = 0x1;
// Fake key code to represent VK_WIN.
inline const DWORD VK_WIN_BOTH = 0x104;
}
| 37,430
|
https://github.com/damaki/SPARKNaCl/blob/master/tests/core3.adb
|
Github Open Source
|
Open Source
|
BSD-2-Clause, BSD-3-Clause
| 2,022
|
SPARKNaCl
|
damaki
|
Ada
|
Code
| 184
| 597
|
with SPARKNaCl; use SPARKNaCl;
with SPARKNaCl.Core; use SPARKNaCl.Core;
with SPARKNaCl.Debug; use SPARKNaCl.Debug;
with SPARKNaCl.Hashing; use SPARKNaCl.Hashing;
with Interfaces; use Interfaces;
procedure Core3
is
Second_Key : constant Salsa20_Key :=
Construct ((16#dc#, 16#90#, 16#8d#, 16#da#,
16#0b#, 16#93#, 16#44#, 16#a9#,
16#53#, 16#62#, 16#9b#, 16#73#,
16#38#, 16#20#, 16#77#, 16#88#,
16#80#, 16#f3#, 16#ce#, 16#b4#,
16#21#, 16#bb#, 16#61#, 16#b9#,
16#1c#, 16#bd#, 16#4c#, 16#3e#,
16#66#, 16#25#, 16#6c#, 16#e4#));
Nonce_Suffix : constant Bytes_8 :=
(16#82#, 16#19#, 16#e0#, 16#03#, 16#6b#, 16#7a#, 16#0b#, 16#37#);
C : constant Bytes_16 :=
(16#65#, 16#78#, 16#70#, 16#61#, 16#6e#, 16#64#, 16#20#, 16#33#,
16#32#, 16#2d#, 16#62#, 16#79#, 16#74#, 16#65#, 16#20#, 16#6b#);
Input : Bytes_16 := (others => 0);
Output : Byte_Seq (0 .. (2 ** 22 - 1));
H : Bytes_64;
Pos : I32;
begin
Input (0 .. 7) := Nonce_Suffix;
Pos := 0;
loop
loop
Salsa20 (Output (Pos .. Pos + 63),
Input,
Second_Key,
C);
Pos := Pos + 64;
Input (8) := Input (8) + 1;
exit when Input (8) = 0;
end loop;
Input (9) := Input (9) + 1;
exit when Input (9) = 0;
end loop;
Hash (H, Output);
DH ("Hash is", H);
end Core3;
| 31,741
|
https://github.com/pooja-gera/TheWireUsChallenge/blob/master/Competitive Programming/Day 29/SourceCode.cpp
|
Github Open Source
|
Open Source
|
MIT
| null |
TheWireUsChallenge
|
pooja-gera
|
C++
|
Code
| 43
| 103
|
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin>>n;
long long int a[n] , s = 0 ;
for( int i = 0 ; i < n ; i++ )
{ cin>>a[i];
s += a[i] ;
}
cout<<s;
return 0;
}
| 8,854
|
https://github.com/Vrashq/BabylonJs_Rendu/blob/master/css/_base.scss
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
BabylonJs_Rendu
|
Vrashq
|
SCSS
|
Code
| 22
| 69
|
html, body {
padding: 0;
margin: 0;
overflow: hidden;
cursor: crosshair;
color: white;
font-family: airstrike_boldbold, Arial sans-serif;
}
button {
cursor:pointer;
}
| 13,484
|
https://github.com/awgur11/niceoptica/blob/master/resources/views/layouts/site/store/filters-checkboxes.blade.php
|
Github Open Source
|
Open Source
|
MIT
| null |
niceoptica
|
awgur11
|
PHP
|
Code
| 491
| 2,106
|
@if(isset($catalog) && $catalog->filters->where('active', 1)->count() > 0)
<style type="text/css">
.form-check-label{
/* Base for label styling */
}
[type="checkbox"]:not(:checked),
[type="checkbox"]:checked {
position: absolute;
left: -9999px;
}
[type="checkbox"]:not(:checked) + label,
[type="checkbox"]:checked + label {
position: relative;
padding-left: 1.95em;
cursor: pointer;
}
/* checkbox aspect */
[type="checkbox"]:not(:checked) + label:before,
[type="checkbox"]:checked + label:before {
content: '';
position: absolute;
left: 0; top: 0;
width: 1.25em; height: 1.25em;
border: 1px solid #ccc;
transition: 0.5s;
background: #fff;
border-radius: 0px;
box-shadow: inset 0 1px 3px rgba(0,0,0,.1);
}
[type="checkbox"]:checked + label:before{
border: 1px solid #c7003d;
}
/* checked mark aspect */
[type="checkbox"]:not(:checked) + label:after,
[type="checkbox"]:checked + label:after {
content: '\2713\0020';
position: absolute;
top: .15em; left: .22em;
font-size: 1.3em;
line-height: 0.8;
color: #c7003d;
transition: all .2s;
font-family: 'Lucida Sans Unicode', 'Arial Unicode MS', Arial;
}
/* checked mark aspect changes */
[type="checkbox"]:not(:checked) + label:after {
opacity: 0;
transform: scale(0);
}
[type="checkbox"]:checked + label:after {
opacity: 1;
transform: scale(1);
}
/* disabled checkbox */
[type="checkbox"]:disabled:not(:checked) + label:before,
[type="checkbox"]:disabled:checked + label:before {
box-shadow: none;
border-color: #bbb;
background-color: #ddd;
}
[type="checkbox"]:disabled:checked + label:after {
color: #999;
}
[type="checkbox"]:disabled + label {
color: #aaa;
}
/* accessibility */
[type="checkbox"]:checked:focus + label:before,
[type="checkbox"]:not(:checked):focus + label:before {
// border: 2px dotted blue;
}
/* hover style just for information */
label:hover:before {
border: 1px solid #d25912!important;
}
.filters-top-head{
font-family: fnormal;
color: #000;
letter-spacing: 2px;
font-size: 16px;
font-weight: 600;
padding-bottom: 5px;
}
#filters-block{
padding: 0 0 5px;
background: #fff;
z-index: 99999999;
}
.filter-title{
padding: 15px;
font-family: fnormal;
font-size: 14px;
text-transform: uppercase;
border-top: 1px solid #3481be;
font-weight: 100;
margin-bottom: 10px;
background:#5bb3e634 ;
}
.filter-title i{
cursor: pointer;
}
.filter-body{
//padding: 5px;
border:1px solid #fff;
//margin-bottom: 15px;
max-height: 400px;
overflow: auto;
}
#filter-button-block{
padding: 15px;
text-align: center;
}
.filter-body label{
font-weight: 100;
font-family: fnormal;
font-size: 13px;
}
.filter-body::-webkit-scrollbar {
width: 4px;
}
.filter-body::-webkit-scrollbar-track {
box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);
background-color: #5bb3e634;
}
.filter-body::-webkit-scrollbar-thumb {
background-color: #3481be;
outline: 1px solid slategrey;
}
@media screen and (max-width: 992px){
#filters-block{
position: fixed;
height: 100vh;
overflow: auto;
top: 0;
left: 0;
z-index: 999999;
width: 100%;
transform: translateX(-150%);
transition: 0.5s ease-in;
border-right: 1px solid #3481be;
}
#filters-block.show-filters{
transform: translateX(0);
transition: 0.6s;
}
}
</style>
<form method="GET" action="{{ url()->current() }}" name="order-filters-form" id="order-filters-form">
<div id="filters-block">
<div class="d-lg-none p-2 text-right">
<div class="btn btn-sm btn-outline-danger d-lg-none mb-3" id="hide-filters-button">
<i class="fas fa-arrow-left"></i>
</div>
</div>
@foreach($catalog->filters->where('active', 1) as $filter)
<div class="filter-block">
<div class="filter-title d-flex justify-content-between">
<b>{{ $filter->language->title ?? null }}</b> <span class="show-filters-button" data-toggle="collapse" data-target="#filter-{{ $filter->id }}"><i class="fas fa-chevron-down"></i></span>
</div>
<div class="filter-body collapse px-2 px-lg-0" id="filter-{{ $filter->id }}">
@foreach($catalog->fvalues->where('filter_id', $filter->id) as $fvalue)
<p>
<input type="checkbox" class="form-check-input" name="filter-{{ $filter->id }}[]" value="{{ $fvalue->id }}-{{ $fvalue->language->title ?? null }}"
@if(app("request")->has('filter-'.$filter->id) && in_array($fvalue->id, app('request')->input('filter-'.$filter->id))) checked @endif id="fvalue-{{ $fvalue->id }}">
<label class="form-check-label" for="fvalue-{{ $fvalue->id }}">{{ $fvalue->language->title ?? null }}</label>
</p>
@endforeach
</div>
</div>
@endforeach
<div id="filter-button-block">
<button class="btn btn-danger">@lang('Apply')</button>
</div>
</div>
</form>
@endif
<script type="text/javascript">
$(function(){
$('.show-filters-button').first().click();
})
$(document).on('click', '#show-filters-button', function(){
$('#filters-block').addClass('show-filters');
});
$(document).on('click', '#hide-filters-button', function(){
$('#filters-block').removeClass('show-filters');
});
</script>
<script type="text/javascript">
$(document).on('click', '.show-filters-button', function(){
if($(this).hasClass('collapsed'))
$(this).html('<i class="fas fa-chevron-down"></i>');
else
$(this).html('<i class="fas fa-chevron-up"></i>');
})
</script>
| 26,222
|
https://github.com/kingsdigitallab/tvof-django/blob/master/tvof/cms/migrations/0010_auto_20180509_1800.py
|
Github Open Source
|
Open Source
|
MIT
| null |
tvof-django
|
kingsdigitallab
|
Python
|
Code
| 114
| 408
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.10 on 2018-05-09 17:00
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('cms', '0009_auto_20180509_1742'),
]
operations = [
migrations.AddField(
model_name='blogpost',
name='title_fr',
field=models.CharField(blank=True, default=b'', help_text="The page title as you'd like it to be seen by the public", max_length=255, verbose_name=b'Title'),
),
migrations.AddField(
model_name='homepage',
name='title_fr',
field=models.CharField(blank=True, default=b'', help_text="The page title as you'd like it to be seen by the public", max_length=255, verbose_name=b'Title'),
),
migrations.AddField(
model_name='indexpage',
name='title_fr',
field=models.CharField(blank=True, default=b'', help_text="The page title as you'd like it to be seen by the public", max_length=255, verbose_name=b'Title'),
),
migrations.AddField(
model_name='richtextpage',
name='title_fr',
field=models.CharField(blank=True, default=b'', help_text="The page title as you'd like it to be seen by the public", max_length=255, verbose_name=b'Title'),
),
]
| 50,785
|
https://github.com/everlost/audio_miner/blob/master/frontend/lib/services/auth.service.js
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
audio_miner
|
everlost
|
JavaScript
|
Code
| 116
| 309
|
import { fetchWrapper } from "../network/fetch-wrapper";
import { store } from "../client_state/store";
import { setUser, clearUser } from "../client_state/user";
/**
* contains methods related to user authentication.
* some methods act as a middleware between components and the fetchWrapper to manage client-side user state
*/
export const authService = {
login,
refreshToken,
logout,
signUp,
};
function login(username, password) {
return fetchWrapper.post(`/login`, { username, password })
.then((user) => {
store.dispatch(setUser(user));
return user;
});
}
function logout() {
return fetchWrapper.get(`/logout`)
.then((resp) => {
store.dispatch(clearUser());
return resp;
});
}
function refreshToken() {
return fetchWrapper.get(`/refresh_token`)
.then((user) => {
store.dispatch(setUser(user));
return user;
});
}
function signUp(username, password) {
return fetchWrapper.post(`/signup`, { username, password })
.then((result) => {
return result;
});
}
| 4,244
|
https://github.com/muyoumumumu/QuShuChe/blob/master/app/src/main/java/com/muyoumumumu/QuShuChe/ui/acitivity/Tongji_Shiju.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,020
|
QuShuChe
|
muyoumumumu
|
Java
|
Code
| 339
| 3,006
|
package com.muyoumumumu.QuShuChe.ui.acitivity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;
import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.HorizontalBarChart;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.muyoumumumu.QuShuChe.R;
import com.muyoumumumu.QuShuChe.model.bean.Mnn;
import java.util.ArrayList;
public class Tongji_Shiju extends AppCompatActivity {
TextView show1,show2,show3,show4,show5,show6,show7,show8;
int red_time=10000;
//设置取得各时距的链表
public static ArrayList<Object> arg_zhixing_obj,arg_zuozhuan_obj,arg_youzhuan_obj,arg_diaotou_obj;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.shiju_tongji);
show1=(TextView)findViewById(R.id.showresult5s);
show2=(TextView)findViewById(R.id.showresult6s);
show3=(TextView)findViewById(R.id.showresult7s);
show4=(TextView)findViewById(R.id.showresult8s);
show5=(TextView)findViewById(R.id.showresult5ss);
show6=(TextView)findViewById(R.id.showresult6ss);
show7=(TextView)findViewById(R.id.showresult7ss);
show8=(TextView)findViewById(R.id.showresult8ss);
String name= Mnn. getInstance().getName_mark()[0];
//得到链表
arg_zhixing_obj= Main_activity.shiju_main(name,"直行",red_time);
arg_zuozhuan_obj= Main_activity.shiju_main(name,"左转",red_time);
arg_youzhuan_obj= Main_activity.shiju_main(name,"右转",red_time);
arg_diaotou_obj= Main_activity.shiju_main(name,"掉头",red_time);
//都是有效的时距 10s以内的
ArrayList<Integer>arg_zhixing=(ArrayList<Integer>) arg_zhixing_obj.get(2);
ArrayList<Integer>arg_zuozhuan=(ArrayList<Integer>) arg_zuozhuan_obj.get(2);
ArrayList<Integer>arg_youzhuan=(ArrayList<Integer>) arg_youzhuan_obj.get(2);
ArrayList<Integer>arg_diaotou=(ArrayList<Integer>) arg_diaotou_obj.get(2);
int num1=0,num2=0,num3=0,num4=0;
for(int i=0;i<arg_zhixing.size();i++) {
num1+=arg_zhixing.get(i);
}for(int i=0;i<arg_zuozhuan.size();i++) {
num2+=arg_zuozhuan.get(i);
}for(int i=0;i<arg_youzhuan.size();i++) {
num3+=arg_youzhuan.get(i);
}for(int i=0;i<arg_diaotou.size();i++) {
num4+=arg_diaotou.get(i);
}
show1.setText("直行: "+ ((float)(num1/arg_zhixing.size()/100))/10+" s");
show2.setText("左转: "+ ((float)(num2/arg_zuozhuan.size()/100))/10+" s");
show3.setText("右转: "+ ((float)(num3/arg_youzhuan.size()/100))/10+" s");
show4.setText("掉头: "+ ((float)(num4/arg_diaotou.size()/100))/10+" s");
//筛选,5s,,可能出现0
int size_zhixing=0,num_zhixing=0;
for(int i=0;i<arg_zhixing.size();i++){
if(arg_zhixing.get(i)<=5000){
size_zhixing++;
num_zhixing+=arg_zhixing.get(i);
}
}
//筛选,5s
int size_zuozhuan=0,num_zuozhuan=0;
for(int i=0;i<arg_zuozhuan.size();i++){
if(arg_zuozhuan.get(i)<=5000){
size_zuozhuan++;
num_zuozhuan+=arg_zuozhuan.get(i);
}
}
//筛选,5s,
int size_youzhuan=0,num_youzhuan=0;
for(int i=0;i<arg_youzhuan.size();i++){
if(arg_youzhuan.get(i)<=5000){
size_youzhuan++;
num_youzhuan+=arg_youzhuan.get(i);
}
}
//筛选,5s
int size_diaotou=0,num_diaotou=0;
for(int i=0;i<arg_diaotou.size();i++){
if(arg_diaotou.get(i)<=5000){
size_diaotou++;
num_diaotou+=arg_diaotou.get(i);
}
}
//如果视距都大于5s将会测不出饱和流量的
int a1=(size_zhixing!=1)?num_zhixing/size_zhixing:1000000000;
int a2=(size_zuozhuan!=1)?num_zuozhuan/size_zuozhuan:1000000000;
int a3=(size_youzhuan!=1)?num_youzhuan/size_youzhuan:1000000000;
int a4=(size_diaotou!=1)?num_diaotou/size_diaotou:1000000000;
show5.setText("直行: "+ 3600000/a1 +" pcu/h");
show6.setText("左转: "+ 3600000/a2 +" pcu/h");
show7.setText("右转: "+ 3600000/a3 +" pcu/h");
show8.setText("掉头: "+ 3600000/a4 +" pcu/h");
//画图表===================================================================================
HorizontalBarChart barChart1 = (HorizontalBarChart) findViewById(R.id.BarChart_shiju_1);
HorizontalBarChart barChart2 = (HorizontalBarChart) findViewById(R.id.BarChart_shiju_2);
assert barChart1 != null;
barChart1.animateY(3000, Easing.EasingOption.EaseInCubic);
assert barChart2 != null;
barChart2.animateY(3000, Easing.EasingOption.EaseInCubic);
barChart1.getAxisRight().setEnabled(false);
barChart2.getAxisRight().setEnabled(false);
barChart1.getXAxis().setDrawGridLines(false);
barChart2.getXAxis().setDrawGridLines(false);
barChart1.getLegend().setEnabled(false);
barChart2.getLegend().setEnabled(false);
barChart1.setDescription("");
barChart2.setDescription("");
ArrayList<String> xVals = new ArrayList<>();
xVals.add("直行");
xVals.add("左转");
xVals.add("右转");
xVals.add("掉头");
ArrayList<BarEntry> yVals_1 = new ArrayList<>();
ArrayList<BarEntry> yVals_2 = new ArrayList<>();
yVals_1.add(new BarEntry(((float)num1/arg_zhixing.size())/1000,0));
yVals_1.add(new BarEntry(((float)num2/arg_zuozhuan.size())/1000,1));
yVals_1.add(new BarEntry(((float)num3/arg_youzhuan.size())/1000,2));
yVals_1.add(new BarEntry(((float)num4/arg_diaotou.size())/1000,3));
yVals_2.add(new BarEntry(3600000/a1,0));
yVals_2.add(new BarEntry(3600000/a2,1));
yVals_2.add(new BarEntry(3600000/a3,2));
yVals_2.add(new BarEntry(3600000/a4,3));
BarDataSet barset1,barset2;
barset1 = new BarDataSet(yVals_1,"平均车头时距");
barset1.setColors(getColors());
barset2 = new BarDataSet(yVals_2,"饱和流率");
barset2.setColors(getColors());
BarData bardata1,bardata2;
bardata1=new BarData(xVals,barset1);
bardata2=new BarData(xVals,barset2);
barChart1.setData(bardata1);
barChart2.setData(bardata2);
//===============================================================================================
Button very_tinme = (Button) findViewById(R.id.btn_very_import_time);
OnClickListener listener=new OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(Tongji_Shiju.this, ChartActivity_2.class));
}
};
assert very_tinme != null;
very_tinme.setOnClickListener(listener);}
//设置颜色
private int[] getColors() {
//设置色块数量
int stacksize = 4;
// have as many colors as stack-values per entry
int[] colors = new int[stacksize];
System.arraycopy(ColorTemplate.MYZIDINGYI_COLORS_4, 0, colors, 0, stacksize);
return colors;
}
}
| 36,137
|
https://github.com/oozoofrog/swift/blob/master/test/multifile/batch-mode-llvmIRHash-consistency.swift
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
swift
|
oozoofrog
|
Swift
|
Code
| 131
| 336
|
// Ensure that the LLVMIR hash of the 2nd compilation in batch mode
// is consistent no matter if the first one generates code or not.
// This test fails in some configurations.
// REQUIRES: rdar_62338337
// RUN: %empty-directory(%t)
// RUN: echo 'public enum E: Error {}' >%t/main.swift
// RUN: echo >%t/other.swift
// RUN: touch -t 201901010101 %t/*.swift
// RUN: cd %t; %target-swift-frontend -c -g -enable-batch-mode -module-name main -primary-file ./main.swift -primary-file other.swift
// RUN: cp %t/main{,-old}.o
// RUN: cp %t/other{,-old}.o
// RUN: echo 'public enum E: Error {}' >%t/main.swift
// RUN: echo >%t/other.swift
// RUN: cd %t; %target-swift-frontend -c -g -enable-batch-mode -module-name main -primary-file ./main.swift -primary-file other.swift
// Ensure that code generation was not performed for other.swift
// RUN: ls -t %t | %FileCheck %s
// CHECK: other.swift
// CHECK: other.o
| 9,564
|
https://github.com/MartinNovak83/omnius/blob/master/application/FSS.Omnius.Modules/Entitron/Service/ConditionalFilteringService.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
omnius
|
MartinNovak83
|
C#
|
Code
| 286
| 949
|
using System;
using System.Collections.Generic;
using FSS.Omnius.Modules.Entitron.Entity.Tapestry;
using FSS.Omnius.Modules.Tapestry;
using FSS.Omnius.Modules.Entitron.DB;
namespace FSS.Omnius.Modules.Entitron.Service
{
public class ConditionalFilteringService
{
public static bool MatchConditionSets(ICollection<TapestryDesignerConditionSet> conditionSets, DBItem entitronRow, Dictionary<string, object> tapestryVars)
{
bool result = true;
foreach (var conditionSet in conditionSets)
{
if (conditionSet.SetRelation == "AND")
result = result && matchConditionSet(conditionSet, entitronRow, tapestryVars);
else if (conditionSet.SetRelation == "OR")
result = result || matchConditionSet(conditionSet, entitronRow, tapestryVars);
}
return result;
}
private static bool matchConditionSet(TapestryDesignerConditionSet conditionSet, DBItem entitronRow, Dictionary<string, object> tapestryVars)
{
bool result = true;
foreach (var condition in conditionSet.Conditions)
{
if (condition.Relation == "AND")
result = result && matchCondition(condition, entitronRow, tapestryVars);
else if (condition.Relation == "OR")
result = result || matchCondition(condition, entitronRow, tapestryVars);
}
return result;
}
private static bool matchCondition(TapestryDesignerCondition condition, DBItem entitronRow, Dictionary<string, object> tapestryVars)
{
object leftOperand;
if (condition.Variable[0] == '#')
{
var parsedObjectLeft = KeyValueString.ParseValue(condition.Variable.Substring(1), tapestryVars);
if (parsedObjectLeft == null)
return false;
leftOperand = parsedObjectLeft;
}
else
leftOperand = entitronRow[condition.Variable];
var parsedObjectRight = KeyValueString.ParseValue(condition.Value, tapestryVars);
if (parsedObjectRight == null)
return false;
object value = parsedObjectRight;
switch (condition.Operator)
{
case "==":
if (leftOperand is bool && value is bool)
return (bool)leftOperand == (bool)value;
else if (leftOperand is bool)
return ((bool)leftOperand ? "true" : "false") == value.ToString();
else
return leftOperand.ToString() == value.ToString();
case "!=":
if (leftOperand is bool && value is bool)
return (bool)leftOperand != (bool)value;
else if (leftOperand is bool)
return ((bool)leftOperand ? "true" : "false") != value.ToString();
else
return leftOperand.ToString() != value.ToString();
case ">":
return Convert.ToInt64(leftOperand) > Convert.ToInt64(value);
case ">=":
return Convert.ToInt64(leftOperand) >= Convert.ToInt64(value);
case "<":
return Convert.ToInt64(leftOperand) < Convert.ToInt64(value);
case "<=":
return Convert.ToInt64(leftOperand) <= Convert.ToInt64(value);
case "is empty":
return value.ToString().Length == 0;
case "is not empty":
return value.ToString().Length > 0;
case "contains":
return ((string)leftOperand).Contains(value.ToString());
case "is in":
return ((List<object>)value).Contains(leftOperand);
}
return true;
}
}
}
| 4,797
|
https://github.com/PixelOfDeath/glCompact/blob/master/include/glCompact/SurfaceFormat.hpp
|
Github Open Source
|
Open Source
|
MIT
| null |
glCompact
|
PixelOfDeath
|
C++
|
Code
| 614
| 3,075
|
#pragma once
#include <cstdint> //C++11
#include <glCompact/MemorySurfaceFormat.hpp>
namespace glCompact {
struct SurfaceFormatDetail;
class SurfaceFormat {
friend class SurfaceInterface;
friend class TextureInterface;
friend class Frame;
friend class PipelineInterface;
friend class RenderBufferInterface;
public:
enum FormatEnum {
R8_UNORM = 1,
R8_SNORM,
R8_UINT,
R8_SINT,
R16_UNORM,
R16_SNORM,
R16_UINT,
R16_SINT,
R32_UINT,
R32_SINT,
R16_SFLOAT,
R32_SFLOAT,
R8G8_UNORM,
R8G8_SNORM,
R8G8_UINT,
R8G8_SINT,
R16G16_UNORM,
R16G16_SNORM,
R16G16_UINT,
R16G16_SINT,
R32G32_UINT,
R32G32_SINT,
R16G16_SFLOAT,
R32G32_SFLOAT,
//R8G8B8_UNORM,
//R8G8B8_SNORM,
//R8G8B8_UINT,
//R8G8B8_SINT,
//R16G16B16_UNORM,
//R16G16B16_SNORM,
//R16G16B16_UINT,
//R16G16B16_SINT,
//R32G32B32_UNORM,
//R32G32B32_SNORM,
//R16G16B16_SFLOAT,
//R32G32B32_SFLOAT,
R8G8B8A8_UNORM,
R8G8B8A8_SNORM,
R8G8B8A8_UINT,
R8G8B8A8_SINT,
R16G16B16A16_UNORM,
R16G16B16A16_SNORM,
R16G16B16A16_UINT,
R16G16B16A16_SINT,
R32G32B32A32_UINT,
R32G32B32A32_SINT,
R16G16B16A16_SFLOAT,
R32G32B32A32_SFLOAT,
//core support for sampling, rasterization, image access, sparse
B10G11R11_UFLOAT_PACK32,
R10G10B10A2_UNORM_PACK32,
R10G10B10A2_UINT_PACK32,
//core support for sampling, rasterization
R5G5B5A1_UNORM_PACK16, //GL_RGB5_A1
R5G6B5_UNORM_PACK16, //GL_RGB565
R4G4B4A4_UNORM_PACK16, //GL_RGBA4
//core support for sampling, sparse
E5B9G9R9_UFLOAT_PACK32, //GL_RGB9_E5 unsigned RGB9 values with shared 5 bit exponent
//core support for sampling
R3G3B2_UNORM_PACK8, //GL_R3_G3_B2 Not supported by vulkan!
R4G4B4_UNORM, //GL_RGB4 Not supported by vulkan!
R5G5B5_UNORM, //GL_RGB5 Not supported by vulkan!
R10G10B10_UNORM, //GL_RGB10 Not supported by vulkan!
R12G12B12_UNORM, //GL_RGB12 Not supported by vulkan!
R2G2B2A2_UNORM_PACK8, //GL_RGBA2 Not supported by vulkan!
R12G12B12A12_UNORM, //GL_RGBA12 Not supported by vulkan!
//sRGB formats TODO: how do this formats interact with MemorySurfaceFormat?
R8G8B8_SRGB, //GL_SRGB8,
R8G8B8A8_SRGB, //GL_SRGB8_ALPHA8
//depth
D16_UNORM,
D24_UNORM,
D32_UNORM,
D32_SFLOAT,
//depth stencil (Many drivers only support FBOs with depth and stencil via this combinaton formats!)
D24_UNORM_S8_UINT,
D32_SFLOAT_S8_UINT,
//stencil index (sadly only supported as core relatively late in OpenGL), VK only supports 8bit stencil formats. Maybe copy for simplicity/bug hit prevention?
//S1_UINT,
//S4_UINT,
S8_UINT,
//S16_UINT,
//Compressed Formats
//Except ASTC, all compressed formats use blocks of 4x4 pixels
//S3 Texture Compression (S3TC)
//GL_EXT_texture_compression_s3tc (Not core, ubiquitous extension)
//GL_EXT_texture_compression_dxt1
//GL_NV_texture_compression_vtc (VTC 3D texture compression) is S3TC for 3d textures
//The original S3TC comes in 6 variants (ignoring sRGB), OpenGL only implements 4 of them!
//BC1 (DXT1) without alpha
//BC1 (DXT1) 1-bit alpha <- (RGB values pre-multiplied with alpha, an alpha bit 0 means RGB is black!)
//BC2 (DXT2) Explicit alpha <- NOT in OpenGL (RGB values pre-multiplied with alpha value)
//BC2 (DXT3) Explicit alpha
//BC3 (DXT4) Interpolated alpha <- NOT in OpenGL (RGB values pre-multiplied with alpha value)
//BC3 (DXT5) Interpolated alpha
BC1_RGB_UNORM_BLOCK, //BC1 (DXT1)
BC1_RGBA_UNORM_BLOCK, //BC1 (DXT1) with alpha bit
BC2_UNORM_BLOCK, //BC2 (DXT3)
BC3_UNORM_BLOCK, //BC3 (DXT5)
//GL_EXT_texture_compression_s3tc_srgb (Not core)
BC1_RGB_SRGB_BLOCK, //BC1 (DXT1)
BC1_RGBA_SRGB_BLOCK, //BC1 (DXT1) with alpha bit
BC2_SRGB_BLOCK, //BC2 (DXT3)
BC3_SRGB_BLOCK, //BC3 (DXT5)
//Red Green Texture Compression (RGTC)
//GL_ARB_texture_compression_rgtc (Core since 3.0)
//RG formats have sepperate interpolation, so they can be used for e.g. normals without artefacting
BC4_UNORM_BLOCK, //unsigned R
BC4_SNORM_BLOCK, //signed R
BC5_UNORM_BLOCK, //unsigned RG
BC5_SNORM_BLOCK, //signed RG
//BPTC
//GL_EXT_texture_compression_bptc
//GL_ARB_texture_compression_bptc (Core since 4.2)
BC6H_UFLOAT_BLOCK,
BC6H_SFLOAT_BLOCK,
BC7_UNORM_BLOCK,
BC7_SRGB_BLOCK,
//Ericsson Texture Compression (ETC2/EAC)
//ETC2 is basically ETC1, but making use of some previous unused bit paterns for new modes
ETC2_R8G8B8_UNORM_BLOCK, //RGB ETC2
ETC2_R8G8B8_SRGB_BLOCK, //RGB ETC2 with sRGB encoding
ETC2_R8G8B8A1_UNORM_BLOCK, //RGB ETC2 with punch-through alpha
ETC2_R8G8B8A1_SRGB_BLOCK, //RGB ETC2 with punch-through alpha and sRGB
ETC2_R8G8B8A8_UNORM_BLOCK, //RGBA ETC2
ETC2_R8G8B8A8_SRGB_BLOCK, //RGBA ETC2 with sRGB encoding
EAC_R11_UNORM_BLOCK, //Unsigned R11 EAC
EAC_R11_SNORM_BLOCK, //Signed R11 EAC
EAC_R11G11_UNORM_BLOCK, //Unsigned RG11 EAC
EAC_R11G11_SNORM_BLOCK, //Signed RG11 EAC
//Adaptable Scalable Texture Compression (ASTC)
//GL_KHR_texture_compression_astc_hdr (high dynamic range) (Core since 4.3)
//GL_KHR_texture_compression_astc_ldr (low dynamic range) and GL_KHR_texture_compression_astc_sliced_3d
//GL_OES_texture_compression_astc
//
//GL_EXT_texture_compression_astc_decode_mode,
//GL_EXT_texture_compression_astc_decode_mode_rgb9e5 (adds extra decode precision format GL_RGB9_E5)
ASTC_4x4_UNORM_BLOCK,
ASTC_4x4_SRGB_BLOCK,
ASTC_5x4_UNORM_BLOCK,
ASTC_5x4_SRGB_BLOCK,
ASTC_5x5_UNORM_BLOCK,
ASTC_5x5_SRGB_BLOCK,
ASTC_6x5_UNORM_BLOCK,
ASTC_6x5_SRGB_BLOCK,
ASTC_6x6_UNORM_BLOCK,
ASTC_6x6_SRGB_BLOCK,
ASTC_8x5_UNORM_BLOCK,
ASTC_8x5_SRGB_BLOCK,
ASTC_8x6_UNORM_BLOCK,
ASTC_8x6_SRGB_BLOCK,
ASTC_8x8_UNORM_BLOCK,
ASTC_8x8_SRGB_BLOCK,
ASTC_10x5_UNORM_BLOCK,
ASTC_10x5_SRGB_BLOCK,
ASTC_10x6_UNORM_BLOCK,
ASTC_10x6_SRGB_BLOCK,
ASTC_10x8_UNORM_BLOCK,
ASTC_10x8_SRGB_BLOCK,
ASTC_10x10_UNORM_BLOCK,
ASTC_10x10_SRGB_BLOCK,
ASTC_12x10_UNORM_BLOCK,
ASTC_12x10_SRGB_BLOCK,
ASTC_12x12_UNORM_BLOCK,
ASTC_12x12_SRGB_BLOCK,
//GL_EXT_texture_compression_latc
//GL_NV_texture_compression_latc (legacy)
//Old LUMINANCE compressed formats - not going to implement this one
};
SurfaceFormat(): formatEnum(static_cast<FormatEnum>(0)){};
SurfaceFormat(FormatEnum formatEnum): formatEnum(formatEnum){}
SurfaceFormat& operator=(FormatEnum formatEnum){
this->formatEnum = formatEnum;
return *this;
}
/*inline bool operator!=(const SurfaceFormat& if1, const SurfaceFormat& if2){
return if1.formatEnum != if2.formatEnum;
}*/
inline operator bool() {
return bool(formatEnum);
}
inline bool operator!=(const SurfaceFormat& surfaceFormat){
return this->formatEnum != surfaceFormat.formatEnum;
}
bool isCopyConvertibleToThisMemorySurfaceFormat(MemorySurfaceFormat memorySurfaceFormat) const;
void throwIfNotCopyConvertibleToThisMemorySurfaceFormat(MemorySurfaceFormat memorySurfaceFormat) const;
private:
FormatEnum formatEnum;
const SurfaceFormatDetail detail() const;
};
}
| 9,453
|
https://github.com/phanluong1997/pro_CI/blob/master/public/cpanel/vendor/apex/ecommerce-dashboard/by-device.js
|
Github Open Source
|
Open Source
|
MIT
| null |
pro_CI
|
phanluong1997
|
JavaScript
|
Code
| 64
| 213
|
var options = {
chart: {
height: 230,
type: 'donut',
},
labels: ['Desktop', 'Tablet', 'Mobile'],
series: [60000, 45000, 15000],
legend: {
position: 'bottom',
},
dataLabels: {
enabled: false
},
stroke: {
width: 10,
colors: ['#eceff3'],
},
colors: ['#da9d46', '#f18024', '#af772b'],
tooltip: {
y: {
formatter: function(val) {
return "$" + val
}
}
},
}
var chart = new ApexCharts(
document.querySelector("#budget"),
options
);
chart.render();
| 747
|
https://github.com/xavierfeltin/mark-code/blob/master/src/main/kotlin/com/hadihariri/markcode/Main.kt
|
Github Open Source
|
Open Source
|
MIT
| 2,017
|
mark-code
|
xavierfeltin
|
Kotlin
|
Code
| 72
| 243
|
package com.hadihariri.markcode
import java.io.File
fun main(args: Array<String>) {
if (args.size < 2) {
println("Usage: <doc_directory> <examples output directory> [-o]")
return
}
val writeExpectedOutput = args.size > 2 && args[2] == "-o"
val chapters = mutableListOf<Chapter>()
File(args[0]).listFiles { _, name -> name.endsWith(".adoc") }.forEach {
val chapterCodeDir = File(args[1], it.nameWithoutExtension )
val chapter = Chapter(it, chapterCodeDir)
chapters.add(chapter)
chapter.process(writeExpectedOutput)
}
if (writeExpectedOutput) {
writeVerifyAllSamples(chapters, File(args[1]))
}
if (chapters.any { it.hasErrors }) {
System.exit(1)
}
}
| 49,887
|
https://github.com/hpsworldwide/Quick/blob/master/src/main/scala/com/scalableQuality/quick/core/valueMapping/ValueMapper.scala
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,020
|
Quick
|
hpsworldwide
|
Scala
|
Code
| 172
| 708
|
package com.scalableQuality.quick.core.valueMapping
import com.scalableQuality.quick.core.valueMapping.errorMessages.ValueMapperErrorMessages
import com.scalableQuality.quick.mantle.constructFromXml._
import com.scalableQuality.quick.mantle.error.UnrecoverableError
import scala.xml.MetaData
class ValueMapper private[core] (
transformations: List[ValueMapperFunction]
) {
def apply(value: Option[String]): Option[String] =
transformations.foldLeft(value) {
(previousVal: Option[String], transformation: ValueMapperFunction) =>
transformation(previousVal)
}
//def contains(valueMapperFunction: ValueMapperFunction): Boolean = transformations.contains(valueMapperFunction)
}
object ValueMapper {
def apply(listOfTransformation: List[ValueMapperFunction]): ValueMapper = {
new ValueMapper(listOfTransformation)
}
// TODO : improve attribute extraction
def apply(elemMetaData: MetaData): Either[UnrecoverableError, ValueMapper] = {
val attributeValues =
AttributesValuesExtractor(elemMetaData, listOfAttributesKeys)
val trimValueAttribute = attributeValues.get(trimKey)
val ignoreCaseValueAttribute = attributeValues.get(ignoreCaseKey)
val classParameters =
validateAttributeValues(trimValueAttribute, ignoreCaseValueAttribute)
classParameters match {
case Right((shouldTrim, shouldIgnoreCase)) =>
val valueMappersFunctions
: List[ValueMapperFunction] = Trim(shouldTrim) ::: ToUpperCase(
shouldIgnoreCase)
val valueMapper = ValueMapper(valueMappersFunctions)
Right(valueMapper)
case Left(errorMessages) =>
ValueMapperErrorMessages.invalidAttributes(errorMessages)
}
}
private def validateAttributeValues(
trimValueAttribute: Either[UnrecoverableError, Boolean],
ignoreCaseValueAttribute: Either[UnrecoverableError, Boolean]
): Either[List[UnrecoverableError], (Boolean, Boolean)] = {
(trimValueAttribute, ignoreCaseValueAttribute) match {
case (Right(trim), Right(ignoreCase)) =>
val classParameters = (trim, ignoreCase)
Right(classParameters)
case _ =>
UnrecoverableError.collectAllErrors(trimValueAttribute,
ignoreCaseValueAttribute)
}
}
private val defaultValueMapperInclusion = Right(false)
private val trimKey = AttributeValueExtractor(
"trimComparisonValue",
AttributeValueConversion.toBoolean,
defaultValueMapperInclusion)
private val ignoreCaseKey = AttributeValueExtractor(
"ignoreComparisonValueCase",
AttributeValueConversion.toBoolean,
defaultValueMapperInclusion)
val listOfAttributesKeys = List(trimKey, ignoreCaseKey)
}
| 48,672
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.