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/Gabriel4256/rv6-benchmark-backup/blob/master/kernel-rs/src/arch/arm/asm.rs
|
Github Open Source
|
Open Source
|
MIT-0
| 2,022
|
rv6-benchmark-backup
|
Gabriel4256
|
Rust
|
Code
| 537
| 1,385
|
//! ARM instructions.
// Dead code is allowed in this file because not all components are used in the kernel.
#![allow(dead_code)]
const DIS_INT: usize = 0x80;
/// Enable device interrupts (IRQ).
///
/// # Safety
///
/// Interrupt handlers must be set properly.
#[inline]
pub unsafe fn intr_on() {
unsafe {
asm!("msr daifclr, #2");
}
}
/// Disable device interrupts (IRQ).
#[inline]
pub fn intr_off() {
// SAFETY: turning interrupt off is safe.
unsafe {
asm!("msr daifset, #2");
}
}
/// Are device interrupts (IRQ) enabled?
#[inline]
pub fn intr_get() -> bool {
let mut x: usize;
unsafe {
asm!("mrs {}, daif", out(reg) x);
}
x & DIS_INT == 0
}
/// Which hart (core) is this?
#[inline]
pub fn cpu_id() -> usize {
let mut x: usize;
unsafe {
asm!("mrs {}, mpidr_el1", out(reg) x);
}
x & 0b11
}
/// get current EL
pub fn r_currentel() -> usize {
let mut x: usize;
unsafe {
asm!("mrs {}, CurrentEL", out(reg) x);
}
(x & 0x0c) >> 2
}
/// read the main id register
pub fn r_midr_el1() -> usize {
let mut x: usize;
unsafe {
asm!("mrs {}, midr_el1", out(reg) x);
}
x
}
/// flush instruction cache
pub fn ic_ialluis() {
unsafe { asm!("ic ialluis") }
}
/// flush TLB
pub fn tlbi_vmalle1() {
unsafe { asm!("tlbi vmalle1") }
}
/// Instruction Synchronization Barrier.
pub fn isb() {
unsafe { asm!("isb") }
}
/// Write to Architectural Feature Access Control Register, EL1
///
/// # Safety
///
/// `x` must contain valid value for cpacr_el1 register.
pub unsafe fn w_cpacr_el1(x: usize) {
unsafe { asm!("msr cpacr_el1, {}", in(reg) x) }
}
/// Write to Monitor Debug System Control Register, EL1
///
/// # Safety
///
/// `x` must contain valid value for mdscr_el1 register.
pub unsafe fn w_mdscr_el1(x: usize) {
if x == 0 {
unsafe { asm!("msr mdscr_el1, xzr") }
}
unsafe { asm!("msr mdscr_el1, {}", in(reg) x) }
}
pub fn r_fpsr() -> usize {
let mut x;
unsafe { asm! ("mrs {}, fpsr", out(reg) x) };
x
}
/// Write to Floating-point Status Register
///
/// # Safety
///
/// `x` must contain valid value for mdscr_el1 register.
pub unsafe fn w_fpsr(x: usize) {
unsafe { asm!("msr fpsr, {}", in(reg) x) }
}
#[derive(Debug)]
pub enum SmcFunctions {
_Version = 0x84000000,
_SuspendAarch64 = 0xc4000001,
_CpuOff = 0x84000002,
CpuOn = 0xc4000003,
_AffinityInfoAarch64 = 0xc4000004,
_Features = 0x8400000A,
_MigInfoType = 0x84000006,
_SystemOff = 0x84000008,
_SystemReset = 0x84000009,
}
/// Secure Monitor call
///
/// # Safety
///
/// Arguments must follow ARM SMC calling convention.
#[no_mangle]
pub unsafe fn smc_call(x0: u64, x1: u64, x2: u64, x3: u64) -> u64 {
let r;
unsafe {
// NOTE: here use hvc for qemu without `virtualization=on`
asm!("hvc #0", inlateout("x0") x0 => r, in("x1") x1, in("x2") x2, in("x3") x3);
}
r
}
pub fn cpu_relax() {
barrier();
}
pub fn r_mpidr() -> usize {
let mut x: usize;
unsafe {
asm!("mrs {}, mpidr_el1", out(reg) x);
}
x
}
pub fn r_icc_ctlr_el1() -> u32 {
let mut x: usize;
unsafe { asm!("mrs {}, icc_ctlr_el1", out(reg) x) };
x as u32
}
pub fn barrier() {
unsafe {
asm!("isb sy");
asm!("dsb sy");
asm!("dsb ishst");
asm!("tlbi vmalle1is");
asm!("dsb ish");
asm!("isb");
}
}
| 41,416
|
https://github.com/ekristen/aws-nuke/blob/master/resources/iam-service-specific-credentials_mock_test.go
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
aws-nuke
|
ekristen
|
Go
|
Code
| 52
| 375
|
package resources
import (
"testing"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/iam"
"github.com/golang/mock/gomock"
"github.com/rebuy-de/aws-nuke/mocks/mock_iamiface"
"github.com/stretchr/testify/assert"
)
func Test_Mock_IAMServiceSpecificCredential_Remove(t *testing.T) {
a := assert.New(t)
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockIAM := mock_iamiface.NewMockIAMAPI(ctrl)
iamServiceSpecificCredential := IAMServiceSpecificCredential{
svc: mockIAM,
name: "user:foobar",
serviceName: "service:foobar",
id: "user:service:foobar",
userName: "user:foobar",
}
mockIAM.EXPECT().DeleteServiceSpecificCredential(gomock.Eq(&iam.DeleteServiceSpecificCredentialInput{
UserName: aws.String(iamServiceSpecificCredential.userName),
ServiceSpecificCredentialId: aws.String(iamServiceSpecificCredential.id),
})).Return(&iam.DeleteServiceSpecificCredentialOutput{}, nil)
err := iamServiceSpecificCredential.Remove()
a.Nil(err)
}
| 22,653
|
https://github.com/seewindcn/pycocos2d/blob/master/pkg/eventlet-0.12.1/eventlet/api.py
|
Github Open Source
|
Open Source
|
MIT
| 2,013
|
pycocos2d
|
seewindcn
|
Python
|
Code
| 617
| 1,943
|
import errno
import sys
import socket
import string
import linecache
import inspect
import warnings
from eventlet.support import greenlets as greenlet, BaseException
from eventlet import hubs
from eventlet import greenthread
from eventlet import debug
from eventlet import Timeout
__all__ = [
'call_after', 'exc_after', 'getcurrent', 'get_default_hub', 'get_hub',
'GreenletExit', 'kill', 'sleep', 'spawn', 'spew', 'switch',
'ssl_listener', 'tcp_listener', 'trampoline',
'unspew', 'use_hub', 'with_timeout', 'timeout']
warnings.warn("eventlet.api is deprecated! Nearly everything in it has moved "
"to the eventlet module.", DeprecationWarning, stacklevel=2)
def get_hub(*a, **kw):
warnings.warn("eventlet.api.get_hub has moved to eventlet.hubs.get_hub",
DeprecationWarning, stacklevel=2)
return hubs.get_hub(*a, **kw)
def get_default_hub(*a, **kw):
warnings.warn("eventlet.api.get_default_hub has moved to"
" eventlet.hubs.get_default_hub",
DeprecationWarning, stacklevel=2)
return hubs.get_default_hub(*a, **kw)
def use_hub(*a, **kw):
warnings.warn("eventlet.api.use_hub has moved to eventlet.hubs.use_hub",
DeprecationWarning, stacklevel=2)
return hubs.use_hub(*a, **kw)
def switch(coro, result=None, exc=None):
if exc is not None:
return coro.throw(exc)
return coro.switch(result)
Greenlet = greenlet.greenlet
def tcp_listener(address, backlog=50):
"""
Listen on the given ``(ip, port)`` *address* with a TCP socket. Returns a
socket object on which one should call ``accept()`` to accept a connection
on the newly bound socket.
"""
warnings.warn("""eventlet.api.tcp_listener is deprecated. Please use eventlet.listen instead.""",
DeprecationWarning, stacklevel=2)
from eventlet import greenio, util
socket = greenio.GreenSocket(util.tcp_socket())
util.socket_bind_and_listen(socket, address, backlog=backlog)
return socket
def ssl_listener(address, certificate, private_key):
"""Listen on the given (ip, port) *address* with a TCP socket that
can do SSL. Primarily useful for unit tests, don't use in production.
*certificate* and *private_key* should be the filenames of the appropriate
certificate and private key files to use with the SSL socket.
Returns a socket object on which one should call ``accept()`` to
accept a connection on the newly bound socket.
"""
warnings.warn("""eventlet.api.ssl_listener is deprecated. Please use eventlet.wrap_ssl(eventlet.listen()) instead.""",
DeprecationWarning, stacklevel=2)
from eventlet import util
import socket
socket = util.wrap_ssl(socket.socket(), certificate, private_key, True)
socket.bind(address)
socket.listen(50)
return socket
def connect_tcp(address, localaddr=None):
"""
Create a TCP connection to address ``(host, port)`` and return the socket.
Optionally, bind to localaddr ``(host, port)`` first.
"""
warnings.warn("""eventlet.api.connect_tcp is deprecated. Please use eventlet.connect instead.""",
DeprecationWarning, stacklevel=2)
from eventlet import greenio, util
desc = greenio.GreenSocket(util.tcp_socket())
if localaddr is not None:
desc.bind(localaddr)
desc.connect(address)
return desc
TimeoutError = greenthread.TimeoutError
trampoline = hubs.trampoline
spawn = greenthread.spawn
spawn_n = greenthread.spawn_n
kill = greenthread.kill
call_after = greenthread.call_after
call_after_local = greenthread.call_after_local
call_after_global = greenthread.call_after_global
class _SilentException(BaseException):
pass
class FakeTimer(object):
def cancel(self):
pass
class timeout(object):
"""Raise an exception in the block after timeout.
Example::
with timeout(10):
urllib2.open('http://example.com')
Assuming code block is yielding (i.e. gives up control to the hub),
an exception provided in *exc* argument will be raised
(:class:`~eventlet.api.TimeoutError` if *exc* is omitted)::
try:
with timeout(10, MySpecialError, error_arg_1):
urllib2.open('http://example.com')
except MySpecialError, e:
print "special error received"
When *exc* is ``None``, code block is interrupted silently.
"""
def __init__(self, seconds, *throw_args):
self.seconds = seconds
if seconds is None:
return
if not throw_args:
self.throw_args = (TimeoutError(), )
elif throw_args == (None, ):
self.throw_args = (_SilentException(), )
else:
self.throw_args = throw_args
def __enter__(self):
if self.seconds is None:
self.timer = FakeTimer()
else:
self.timer = exc_after(self.seconds, *self.throw_args)
return self.timer
def __exit__(self, typ, value, tb):
self.timer.cancel()
if typ is _SilentException and value in self.throw_args:
return True
with_timeout = greenthread.with_timeout
exc_after = greenthread.exc_after
sleep = greenthread.sleep
getcurrent = greenlet.getcurrent
GreenletExit = greenlet.GreenletExit
spew = debug.spew
unspew = debug.unspew
def named(name):
"""Return an object given its name.
The name uses a module-like syntax, eg::
os.path.join
or::
mulib.mu.Resource
"""
toimport = name
obj = None
import_err_strings = []
while toimport:
try:
obj = __import__(toimport)
break
except ImportError, err:
# print 'Import error on %s: %s' % (toimport, err) # debugging spam
import_err_strings.append(err.__str__())
toimport = '.'.join(toimport.split('.')[:-1])
if obj is None:
raise ImportError('%s could not be imported. Import errors: %r' % (name, import_err_strings))
for seg in name.split('.')[1:]:
try:
obj = getattr(obj, seg)
except AttributeError:
dirobj = dir(obj)
dirobj.sort()
raise AttributeError('attribute %r missing from %r (%r) %r. Import errors: %r' % (
seg, obj, dirobj, name, import_err_strings))
return obj
| 11,588
|
https://github.com/STEM-Alliance/RobotCode/blob/master/reuse/src/main/java/org/wfrobotics/reuse/math/HerdAngle.java
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
RobotCode
|
STEM-Alliance
|
Java
|
Code
| 99
| 293
|
package org.wfrobotics.reuse.math;
public class HerdAngle implements WrappedAngle
{
private final double angle;
public HerdAngle(double angle)
{
double a = angle;
a = (((a + 180) % 360) + 360) % 360 - 180; // -180 to 180
if (a == -0)
{
a = 0;
}
this.angle = a;
}
public HerdAngle(HerdAngle clone)
{
this(clone.angle);
}
public double getAngle()
{
return angle;
}
public String toString()
{
return String.format("%.1f\u00b0", angle);
}
public HerdAngle rotate(double angle)
{
return new HerdAngle(this.angle + angle);
}
public HerdAngle rotate(WrappedAngle b)
{
return rotate(b.getAngle());
}
public HerdAngle rotateReverse(WrappedAngle b)
{
return rotate(-b.getAngle());
}
}
| 41,424
|
https://github.com/geekyfox/antiblog/blob/master/README.rdoc
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
antiblog
|
geekyfox
|
RDoc
|
Code
| 76
| 179
|
== The Antiblog
This is the source code for my own very personal
{Antiblog}[https://antiblog.geekyfox.net].
General concept of what "antiblog" is all about is explained in
{this essay}[http://antiblog.geekyfox.net/meta/about],
and previous implementation of this idea (in Haskell)
can be found {here}[https://github.com/geekyfox/antiblog.hs].
== Installation & Usage
This application is not (really) intended for general usage (by anyone
except myself).
If you really want to use it and can't figure out how, feel free to
ask {me}[mailto:ivan.appel@gmail.com] for help directly.
| 16,171
|
https://github.com/lingshanng/tp/blob/master/src/main/java/seedu/address/ui/LessonCard.java
|
Github Open Source
|
Open Source
|
MIT
| null |
tp
|
lingshanng
|
Java
|
Code
| 135
| 486
|
package seedu.address.ui;
import java.util.Comparator;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Region;
import seedu.address.model.lesson.Lesson;
public class LessonCard extends UiPart<Region> {
private static final String FXML = "LessonListCard.fxml";
public final Lesson lesson;
@FXML
private HBox cardPane;
@FXML
private Label lessonId;
@FXML
private Label title;
@FXML
private Label date;
@FXML
private Label time;
@FXML
private Label rates;
@FXML
private FlowPane homeworkList;
/**
* Creates a {@code PersonCode} with the given {@code Person} and index to display.
*/
public LessonCard(Lesson lesson, int displayedIndex) {
super(FXML);
this.lesson = lesson;
lessonId.setText(displayedIndex + ". ");
title.setText(lesson.getSubject() + " (" + lesson.getTypeOfLesson() + ")");
date.setText("Date: " + lesson.getDisplayDate().value);
time.setText("Time: " + lesson.getTimeRange().toString());
rates.setText("Rates: $" + lesson.getLessonRates().toString());
lesson.getHomework().stream()
.sorted(Comparator.comparing(homework -> homework.description))
.forEach(homework -> homeworkList.getChildren()
.add(homeworkLabel(homework.toString())));
}
private Label homeworkLabel(String homework) {
Label label = new Label(homework);
label.setWrapText(true);
return label;
}
}
| 33,799
|
https://github.com/zbolo-wd/nexi_payment/blob/master/.gitignore
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
nexi_payment
|
zbolo-wd
|
Ignore List
|
Code
| 12
| 111
|
.dart_tool/package_config.json
.idea/.gitignore
.idea/modules.xml
.idea/nexi_payment.iml
.idea/vcs.xml
.idea/codeStyles/Project.xml
.idea/libraries/Dart_SDK.xml
.idea/libraries/Flutter_Plugins.xml
.idea/
.dart_tool/package_config_subset
.dart_tool/version
.packages
| 439
|
https://github.com/praging/country-levels/blob/master/scripts/fips_download_csv.sh
|
Github Open Source
|
Open Source
|
CC0-1.0, MIT
| null |
country-levels
|
praging
|
Shell
|
Code
| 31
| 189
|
#!/usr/bin/env bash
set -e
cd "${BASH_SOURCE%/*}/" || exit
cd ../data
mkdir -p fips
wget https://www2.census.gov/programs-surveys/popest/geographies/2018/all-geocodes-v2018.xlsx -O fips/fips.xlsx
wget https://www2.census.gov/programs-surveys/popest/datasets/2010-2019/counties/totals/co-est2019-alldata.csv -O fips/population.csv
xlsx2csv fips/fips.xlsx | tail -n +5 > fips/fips.csv
rm fips/fips.xlsx
| 5,809
|
https://github.com/Septharoth/EndlessClient/blob/master/EOLib/Net/PacketFamily.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
EndlessClient
|
Septharoth
|
C#
|
Code
| 161
| 503
|
namespace EOLib.Net
{
public enum PacketFamily : byte
{
Internal = 0,
Connection = (byte)1,
Account = (byte)2,
Character = (byte)3,
Login = (byte)4,
Welcome = (byte)5,
Walk = (byte)6,
Face = (byte)7,
Chair = (byte)8,
Emote = (byte)9,
Attack = (byte)11,
Spell = (byte)12,
Shop = (byte)13,
Item = (byte)14,
StatSkill = (byte)16,
Global = (byte)17,
Talk = (byte)18,
Warp = (byte)19,
JukeBox = (byte)21,
Players = (byte)22,
Avatar = (byte)23,
Party = (byte)24,
Refresh = (byte)25,
NPC = (byte)26,
AutoRefresh = (byte)27,
AutoRefresh2 = (byte)28,
Appear = (byte)29,
PaperDoll = (byte)30,
Effect = (byte)31,
Trade = (byte)32,
Chest = (byte)33,
Door = (byte)34,
Message = (byte)35,
Bank = (byte)36,
Locker = (byte)37,
Barber = (byte)38,
Guild = (byte)39,
Music = (byte)40,
Sit = (byte)41,
Recover = (byte)42,
Board = (byte)43,
Cast = (byte)44,
Arena = (byte)45,
Priest = (byte)46,
Marriage = (byte)47,
AdminInteract = (byte)48,
Citizen = (byte)49,
Quest = (byte)50,
Book = (byte)51,
Init = (byte)255
}
}
| 41,778
|
https://github.com/mekoidigret/CampusKid/blob/master/resources/ts/app.ts
|
Github Open Source
|
Open Source
|
MIT
| null |
CampusKid
|
mekoidigret
|
TypeScript
|
Code
| 32
| 75
|
import "./bootstrap";
import Vue from "vue";
import router from "./router";
import store from "./store";
import App from "./App.vue";
const app = new Vue({
router,
store,
el: "#app",
render: h => h(App)
});
| 35,946
|
https://github.com/polivbr/pulumi-azure-native/blob/master/sdk/python/pulumi_azure_native/maintenance/v20210401preview/_inputs.py
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
pulumi-azure-native
|
polivbr
|
Python
|
Code
| 971
| 3,967
|
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
from ._enums import *
__all__ = [
'InputLinuxParametersArgs',
'InputPatchConfigurationArgs',
'InputWindowsParametersArgs',
'TaskPropertiesArgs',
]
@pulumi.input_type
class InputLinuxParametersArgs:
def __init__(__self__, *,
classifications_to_include: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None,
package_name_masks_to_exclude: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None,
package_name_masks_to_include: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None):
"""
Input properties for patching a Linux machine.
:param pulumi.Input[Sequence[pulumi.Input[str]]] classifications_to_include: Classification category of patches to be patched
:param pulumi.Input[Sequence[pulumi.Input[str]]] package_name_masks_to_exclude: Package names to be excluded for patching.
:param pulumi.Input[Sequence[pulumi.Input[str]]] package_name_masks_to_include: Package names to be included for patching.
"""
if classifications_to_include is not None:
pulumi.set(__self__, "classifications_to_include", classifications_to_include)
if package_name_masks_to_exclude is not None:
pulumi.set(__self__, "package_name_masks_to_exclude", package_name_masks_to_exclude)
if package_name_masks_to_include is not None:
pulumi.set(__self__, "package_name_masks_to_include", package_name_masks_to_include)
@property
@pulumi.getter(name="classificationsToInclude")
def classifications_to_include(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]:
"""
Classification category of patches to be patched
"""
return pulumi.get(self, "classifications_to_include")
@classifications_to_include.setter
def classifications_to_include(self, value: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]):
pulumi.set(self, "classifications_to_include", value)
@property
@pulumi.getter(name="packageNameMasksToExclude")
def package_name_masks_to_exclude(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]:
"""
Package names to be excluded for patching.
"""
return pulumi.get(self, "package_name_masks_to_exclude")
@package_name_masks_to_exclude.setter
def package_name_masks_to_exclude(self, value: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]):
pulumi.set(self, "package_name_masks_to_exclude", value)
@property
@pulumi.getter(name="packageNameMasksToInclude")
def package_name_masks_to_include(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]:
"""
Package names to be included for patching.
"""
return pulumi.get(self, "package_name_masks_to_include")
@package_name_masks_to_include.setter
def package_name_masks_to_include(self, value: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]):
pulumi.set(self, "package_name_masks_to_include", value)
@pulumi.input_type
class InputPatchConfigurationArgs:
def __init__(__self__, *,
linux_parameters: Optional[pulumi.Input['InputLinuxParametersArgs']] = None,
post_tasks: Optional[pulumi.Input[Sequence[pulumi.Input['TaskPropertiesArgs']]]] = None,
pre_tasks: Optional[pulumi.Input[Sequence[pulumi.Input['TaskPropertiesArgs']]]] = None,
reboot_setting: Optional[pulumi.Input[Union[str, 'RebootOptions']]] = None,
windows_parameters: Optional[pulumi.Input['InputWindowsParametersArgs']] = None):
"""
Input configuration for a patch run
:param pulumi.Input['InputLinuxParametersArgs'] linux_parameters: Input parameters specific to patching Linux machine. For Windows machines, do not pass this property.
:param pulumi.Input[Sequence[pulumi.Input['TaskPropertiesArgs']]] post_tasks: List of post tasks. e.g. [{'source' :'runbook', 'taskScope': 'Resource', 'parameters': { 'arg1': 'value1'}}]
:param pulumi.Input[Sequence[pulumi.Input['TaskPropertiesArgs']]] pre_tasks: List of pre tasks. e.g. [{'source' :'runbook', 'taskScope': 'Global', 'parameters': { 'arg1': 'value1'}}]
:param pulumi.Input[Union[str, 'RebootOptions']] reboot_setting: Possible reboot preference as defined by the user based on which it would be decided to reboot the machine or not after the patch operation is completed.
:param pulumi.Input['InputWindowsParametersArgs'] windows_parameters: Input parameters specific to patching a Windows machine. For Linux machines, do not pass this property.
"""
if linux_parameters is not None:
pulumi.set(__self__, "linux_parameters", linux_parameters)
if post_tasks is not None:
pulumi.set(__self__, "post_tasks", post_tasks)
if pre_tasks is not None:
pulumi.set(__self__, "pre_tasks", pre_tasks)
if reboot_setting is not None:
pulumi.set(__self__, "reboot_setting", reboot_setting)
if windows_parameters is not None:
pulumi.set(__self__, "windows_parameters", windows_parameters)
@property
@pulumi.getter(name="linuxParameters")
def linux_parameters(self) -> Optional[pulumi.Input['InputLinuxParametersArgs']]:
"""
Input parameters specific to patching Linux machine. For Windows machines, do not pass this property.
"""
return pulumi.get(self, "linux_parameters")
@linux_parameters.setter
def linux_parameters(self, value: Optional[pulumi.Input['InputLinuxParametersArgs']]):
pulumi.set(self, "linux_parameters", value)
@property
@pulumi.getter(name="postTasks")
def post_tasks(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['TaskPropertiesArgs']]]]:
"""
List of post tasks. e.g. [{'source' :'runbook', 'taskScope': 'Resource', 'parameters': { 'arg1': 'value1'}}]
"""
return pulumi.get(self, "post_tasks")
@post_tasks.setter
def post_tasks(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['TaskPropertiesArgs']]]]):
pulumi.set(self, "post_tasks", value)
@property
@pulumi.getter(name="preTasks")
def pre_tasks(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['TaskPropertiesArgs']]]]:
"""
List of pre tasks. e.g. [{'source' :'runbook', 'taskScope': 'Global', 'parameters': { 'arg1': 'value1'}}]
"""
return pulumi.get(self, "pre_tasks")
@pre_tasks.setter
def pre_tasks(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['TaskPropertiesArgs']]]]):
pulumi.set(self, "pre_tasks", value)
@property
@pulumi.getter(name="rebootSetting")
def reboot_setting(self) -> Optional[pulumi.Input[Union[str, 'RebootOptions']]]:
"""
Possible reboot preference as defined by the user based on which it would be decided to reboot the machine or not after the patch operation is completed.
"""
return pulumi.get(self, "reboot_setting")
@reboot_setting.setter
def reboot_setting(self, value: Optional[pulumi.Input[Union[str, 'RebootOptions']]]):
pulumi.set(self, "reboot_setting", value)
@property
@pulumi.getter(name="windowsParameters")
def windows_parameters(self) -> Optional[pulumi.Input['InputWindowsParametersArgs']]:
"""
Input parameters specific to patching a Windows machine. For Linux machines, do not pass this property.
"""
return pulumi.get(self, "windows_parameters")
@windows_parameters.setter
def windows_parameters(self, value: Optional[pulumi.Input['InputWindowsParametersArgs']]):
pulumi.set(self, "windows_parameters", value)
@pulumi.input_type
class InputWindowsParametersArgs:
def __init__(__self__, *,
classifications_to_include: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None,
exclude_kbs_requiring_reboot: Optional[pulumi.Input[bool]] = None,
kb_numbers_to_exclude: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None,
kb_numbers_to_include: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None):
"""
Input properties for patching a Windows machine.
:param pulumi.Input[Sequence[pulumi.Input[str]]] classifications_to_include: Classification category of patches to be patched
:param pulumi.Input[bool] exclude_kbs_requiring_reboot: Exclude patches which need reboot
:param pulumi.Input[Sequence[pulumi.Input[str]]] kb_numbers_to_exclude: Windows KBID to be excluded for patching.
:param pulumi.Input[Sequence[pulumi.Input[str]]] kb_numbers_to_include: Windows KBID to be included for patching.
"""
if classifications_to_include is not None:
pulumi.set(__self__, "classifications_to_include", classifications_to_include)
if exclude_kbs_requiring_reboot is not None:
pulumi.set(__self__, "exclude_kbs_requiring_reboot", exclude_kbs_requiring_reboot)
if kb_numbers_to_exclude is not None:
pulumi.set(__self__, "kb_numbers_to_exclude", kb_numbers_to_exclude)
if kb_numbers_to_include is not None:
pulumi.set(__self__, "kb_numbers_to_include", kb_numbers_to_include)
@property
@pulumi.getter(name="classificationsToInclude")
def classifications_to_include(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]:
"""
Classification category of patches to be patched
"""
return pulumi.get(self, "classifications_to_include")
@classifications_to_include.setter
def classifications_to_include(self, value: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]):
pulumi.set(self, "classifications_to_include", value)
@property
@pulumi.getter(name="excludeKbsRequiringReboot")
def exclude_kbs_requiring_reboot(self) -> Optional[pulumi.Input[bool]]:
"""
Exclude patches which need reboot
"""
return pulumi.get(self, "exclude_kbs_requiring_reboot")
@exclude_kbs_requiring_reboot.setter
def exclude_kbs_requiring_reboot(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "exclude_kbs_requiring_reboot", value)
@property
@pulumi.getter(name="kbNumbersToExclude")
def kb_numbers_to_exclude(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]:
"""
Windows KBID to be excluded for patching.
"""
return pulumi.get(self, "kb_numbers_to_exclude")
@kb_numbers_to_exclude.setter
def kb_numbers_to_exclude(self, value: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]):
pulumi.set(self, "kb_numbers_to_exclude", value)
@property
@pulumi.getter(name="kbNumbersToInclude")
def kb_numbers_to_include(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]:
"""
Windows KBID to be included for patching.
"""
return pulumi.get(self, "kb_numbers_to_include")
@kb_numbers_to_include.setter
def kb_numbers_to_include(self, value: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]):
pulumi.set(self, "kb_numbers_to_include", value)
@pulumi.input_type
class TaskPropertiesArgs:
def __init__(__self__, *,
parameters: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None,
source: Optional[pulumi.Input[str]] = None,
task_scope: Optional[pulumi.Input[Union[str, 'TaskScope']]] = None):
"""
Task properties of the software update configuration.
:param pulumi.Input[Mapping[str, pulumi.Input[str]]] parameters: Gets or sets the parameters of the task.
:param pulumi.Input[str] source: Gets or sets the name of the runbook.
:param pulumi.Input[Union[str, 'TaskScope']] task_scope: Global Task execute once when schedule trigger. Resource task execute for each VM.
"""
if parameters is not None:
pulumi.set(__self__, "parameters", parameters)
if source is not None:
pulumi.set(__self__, "source", source)
if task_scope is None:
task_scope = 'Global'
if task_scope is not None:
pulumi.set(__self__, "task_scope", task_scope)
@property
@pulumi.getter
def parameters(self) -> Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]:
"""
Gets or sets the parameters of the task.
"""
return pulumi.get(self, "parameters")
@parameters.setter
def parameters(self, value: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]):
pulumi.set(self, "parameters", value)
@property
@pulumi.getter
def source(self) -> Optional[pulumi.Input[str]]:
"""
Gets or sets the name of the runbook.
"""
return pulumi.get(self, "source")
@source.setter
def source(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "source", value)
@property
@pulumi.getter(name="taskScope")
def task_scope(self) -> Optional[pulumi.Input[Union[str, 'TaskScope']]]:
"""
Global Task execute once when schedule trigger. Resource task execute for each VM.
"""
return pulumi.get(self, "task_scope")
@task_scope.setter
def task_scope(self, value: Optional[pulumi.Input[Union[str, 'TaskScope']]]):
pulumi.set(self, "task_scope", value)
| 5,163
|
https://github.com/stephenmusangeya/FusionLink/blob/master/src/Mocks/SophisDotNetToolkit/sophis/market_data/SSMYieldPoint.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
FusionLink
|
stephenmusangeya
|
C#
|
Code
| 95
| 234
|
// Copyright (c) RXD Solutions. All rights reserved.
// FusionLink is licensed under the MIT license. See LICENSE.txt for details.
using System;
namespace sophis.market_data
{
public class SSMYieldPoint : IDisposable
{
public CSMInfoSup fInfoPtr { get; set; }
public double fYield { get; set; }
public unsafe short fStartDate { get; set; }
public char fType { get; set; }
public int fMaturity { get; set; }
public bool IsPointOfType(eMTypeSegment typeSegment)
{
throw new NotImplementedException();
}
public SSMYieldPoint GetNthElement(int nIndex)
{
throw new NotImplementedException();
}
public void Dispose()
{
throw new NotImplementedException();
}
}
}
| 14,195
|
https://github.com/ninjayoto/kotlintest/blob/master/kotlintest-core/src/main/kotlin/io/kotlintest/extensions/DiscoveryExtension.kt
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,018
|
kotlintest
|
ninjayoto
|
Kotlin
|
Code
| 103
| 202
|
package io.kotlintest.extensions
import io.kotlintest.Description
import io.kotlintest.Spec
/**
* Allows interception of the discovery phase of KotlinTest.
*
* That is, after [Spec] classes have been discovered, but before
* execution begins.
*
* This gives the possibility of filtering the specs seen by
* the Test Runner.
*/
interface DiscoveryExtension {
/**
* Invoked as soon as the discovery phase is complete.
* At that point, the [Spec] classes have been loaded, but
* not yet executed.
*
* @param descriptions the [Description] for each discovered [Spec]
*
* @return the list of filtered specs to use.
*/
fun afterDiscovery(descriptions: List<Description>): List<Description>
}
| 16,788
|
https://github.com/bevacqua/ponymark/blob/master/src/Editor.js
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
ponymark
|
bevacqua
|
JavaScript
|
Code
| 273
| 797
|
'use strict';
var emitter = require('contra/emitter');
var ui = require('./ui');
var util = require('./util');
var position = require('./position');
var PanelCollection = require('./PanelCollection');
var UndoManager = require('./UndoManager');
var UIManager = require('./UIManager');
var CommandManager = require('./CommandManager');
var PreviewManager = require('./PreviewManager');
var defaultsStrings = {
bold: 'Strong <strong> Ctrl+B',
boldexample: 'strong text',
code: 'Code Sample <pre><code> Ctrl+K',
codeexample: 'enter code here',
heading: 'Heading <h1>/<h2> Ctrl+H',
headingexample: 'Heading',
help: 'Markdown Editing Help',
hr: 'Horizontal Rule <hr> Ctrl+R',
image: 'Image <img> Ctrl+G',
imagedescription: 'enter image description here',
italic: 'Emphasis <em> Ctrl+I',
italicexample: 'emphasized text',
link: 'Hyperlink <a> Ctrl+L',
linkdescription: 'enter link description here',
litem: 'List item',
olist: 'Numbered List <ol> Ctrl+O',
quote: 'Blockquote <blockquote> Ctrl+Q',
quoteexample: 'Blockquote',
redo: 'Redo - Ctrl+Y',
redomac: 'Redo - Ctrl+Shift+Z',
ulist: 'Bulleted List <ul> Ctrl+U',
undo: 'Undo - Ctrl+Z'
};
function Editor (postfix, opts) {
var options = opts || {};
if (typeof options.handler === 'function') { //backwards compatible behavior
options = { helpButton: options };
}
options.strings = options.strings || {};
if (options.helpButton) {
options.strings.help = options.strings.help || options.helpButton.title;
}
function getString (identifier) {
return options.strings[identifier] || defaultsStrings[identifier];
}
var api = emitter();
var self = this;
var panels;
self.run = function () {
if (panels) {
return; // already initialized
}
panels = new PanelCollection(postfix);
var commandManager = new CommandManager(getString);
var previewManager = new PreviewManager(panels, function () {
api.emit('refresh');
});
var uiManager;
var undoManager = new UndoManager(function () {
previewManager.refresh();
if (uiManager) { // not available on the first call
uiManager.setUndoRedoButtonStates();
}
}, panels);
uiManager = new UIManager(postfix, panels, undoManager, previewManager, commandManager, options.helpButton, getString);
uiManager.setUndoRedoButtonStates();
api.refresh = function () {
previewManager.refresh(true);
};
api.refresh();
};
self.api = api;
}
module.exports = Editor;
| 29,934
|
https://github.com/androidmalin/EffectiveJava/blob/master/patterns_structural/bridge_patterns/src/main/java/com/example/bridge/pattern/common2/DetailBehaviorA.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
EffectiveJava
|
androidmalin
|
Java
|
Code
| 27
| 95
|
package com.example.bridge.pattern.common2;
public class DetailBehaviorA extends AbstractBehavior {
@Override
public void operation1() {
System.out.println("op-1 from DetailBehaviorA");
}
@Override
public void operation2() {
System.out.println("op-2 from DetailBehaviorA");
}
}
| 20,716
|
https://github.com/cesartputra/bncc/blob/master/resources/views/guest_view/home.blade.php
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
bncc
|
cesartputra
|
Blade
|
Code
| 12
| 64
|
@extends("guest_view/layout")
@section("judul","Home")
@section("content")
Ini Halaman Home<br>
Halo {{$namanya}} <br>
Luasnya {{$luasnya}}
@endsection
| 46,529
|
https://github.com/DioCahyaRa/absensi/blob/master/application/views/Admin/Data_jabatan_v.php
|
Github Open Source
|
Open Source
|
MIT
| null |
absensi
|
DioCahyaRa
|
PHP
|
Code
| 353
| 1,691
|
<?php echo $this->session->flashdata('msg');?>
<?php
if(isset($_SESSION['msg'])){
unset($_SESSION['msg']);
}
?>
<article class="content item-editor-page">
<div class="title-block">
<h3 class="title"> Data Users <span class="sparkline bar" data-type="bar"></span>
</h3>
</div>
<button class="btn btn-success btn-oval" data-toggle="modal" data-target="#tambah_jabatan"><i class="fa fa-pencil"></i>Tambah Jabatan</button>
<div class="table-data-absen">
<table id="example" class="table table-striped table-bordered" style="width:100%">
<thead class="text-center">
<tr>
<th>No</th>
<th>Nama Jabatan</th>
<th>Action</th>
</tr>
</thead>
<tbody class="text-center">
<?php
$no=1;
foreach($jabatan as $u):
?>
<tr>
<td><?= $no++?></td>
<td><?= $u['nama_jabatan'];?></td>
<td>
<button class="btn btn-info btn-oval" data-toggle="modal" data-target="#edit<?= $u['id'];?>"><i class="fa fa-pencil"></i> EDIT</button>
<button class="btn btn-danger btn-oval" data-toggle="modal" data-target="#delete<?= $u['id'];?>"><i class="fa fa-pencil"></i> DELETE</button>
</td>
</tr>
<?php endforeach;?>
</tbody>
</table>
</div>
<!-- Modal Edit Jabatan -->
<?php
$no = 1;
foreach ($jabatan as $u): $no++;
?>
<div class="modal fade" id="edit<?= $u['id'];?>" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-md modal-dialog-centered" role="document">
<div class="modal-content rounded-0">
<div class="modal-body py-0">
<div class="d-flex main-content">
<div class="content-text p-4">
<h3>Form Edit Jabatan</h3>
<p>sesuaikan nama jabatan dengan tepat</p>
<form action="<?= base_url('Admin/Data_jabatan/update_jabatan')?>" method="post">
<div class="form-group">
<label for="name">ID</label>
<input type="text" name="id" class="form-control" value="<?= $u['id']?>" readonly>
</div>
<div class="form-group">
<label for="name">Nama Jabatan</label>
<input type="text" name="nama_jabatan" class="form-control" value="<?= $u['nama_jabatan']?>">
</div>
<button type="submit" class="btn btn-info btn-oval"><i class="fa fa-pencil"></i>Edit Jabatan</button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
<?php endforeach;?>
<!-- Modal Tambah Jabatan -->
<div class="modal fade" id="tambah_jabatan" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-md modal-dialog-centered" role="document">
<div class="modal-content rounded-0">
<div class="modal-body py-0">
<div class="d-flex main-content">
<div class="content-text p-4">
<h3>Form Tambah Jabatan</h3>
<p>Pastikan nama jabatan dengan tepat</p>
<form action="<?= base_url('Admin/Data_jabatan/tambah_jabatan')?>" method="post">
<div class="form-group">
<label for="name">Nama Jabatan</label>
<input type="text" name="nama_jabatan" class="form-control">
</div>
<button type="submit" class="btn btn-info btn-oval"><i class="fa fa-pencil"></i>Tambah Jabatan</button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Modal Delete -->
<?php
$no = 1;
foreach ($jabatan as $u): $no++;
?>
<div class="modal fade" id="delete<?= $u['id'];?>" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-md modal-dialog-centered" role="document">
<div class="modal-content rounded-0">
<div class="modal-body py-0">
<div class="d-flex main-content">
<div class="content-text p-4">
<h3>Apakah anda yakin menghapus data ini ?</h3>
<p>Pastikan kembali nama jabatan yang ingin di hapus!</p>
<form action="<?= base_url('Admin/Data_jabatan/delete_jabatan')?>" method="post">
<div class="form-group">
<label for="name">ID</label>
<input type="text" name="id" class="form-control" value="<?= $u['id']?>" readonly>
</div>
<div class="form-group">
<label for="name">Nama Jabatan</label>
<input type="text" name="nama_jabatan" class="form-control" value="<?= $u['nama_jabatan']?>" readonly>
</div>
<button type="submit" class="btn btn-info btn-oval"><i class="fa fa-pencil"></i>Delete Jabatan</button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
<?php endforeach;?>
</article>
| 11,064
|
https://github.com/teamleadercrm/ui/blob/master/src/components/overviewPage/OverviewPageHeader.tsx
|
Github Open Source
|
Open Source
|
MIT
| 2,023
|
ui
|
teamleadercrm
|
TSX
|
Code
| 77
| 240
|
import React, { ReactNode } from 'react';
import { GenericComponent } from '../../@types/types';
import Box from '../box';
import { BoxProps } from '../box/Box';
import Container from '../container';
import { Heading1 } from '../typography';
export interface OverviewPageHeaderProps extends Omit<BoxProps, 'children'> {
children?: ReactNode;
title: ReactNode;
}
const OverviewPageHeader: GenericComponent<OverviewPageHeaderProps> = ({ children, title, ...others }) => {
return (
<Container
data-teamleader-ui="overview-page-header"
{...others}
display="flex"
marginBottom={5}
paddingTop={7}
justifyContent="space-between"
>
<Heading1 color="teal">{title}</Heading1>
{children && <Box>{children}</Box>}
</Container>
);
};
export default OverviewPageHeader;
| 33,237
|
https://github.com/OnPositive/aml/blob/master/org.aml.raml2java/src/main/java/org/aml/raml2java/BasicAnnotationProcessingConfig.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,019
|
aml
|
OnPositive
|
Java
|
Code
| 158
| 697
|
package org.aml.raml2java;
import java.util.HashSet;
import org.aml.java.mapping.implementsExisting;
import org.aml.java.mapping.skipAnnotation;
import org.aml.typesystem.AbstractType;
public class BasicAnnotationProcessingConfig implements IAnnotationProcessingConfig{
protected HashSet<String>namespacesToSkipDefinition=new HashSet<>();
protected HashSet<String>namespacesToSkipReference=new HashSet<>();
protected HashSet<String>idsToSkipDefinition=new HashSet<>();
protected HashSet<String>idsToSkipReference=new HashSet<>();
protected boolean skipAllDefinitions;
protected boolean skipAllReferences;
public boolean isSkipAllReferences() {
return skipAllReferences;
}
public void setSkipAllReferences(boolean skipAllReferences) {
this.skipAllReferences = skipAllReferences;
}
public boolean isSkipAllDefinitions() {
return skipAllDefinitions;
}
public void setSkipAllDefinitions(boolean skipAllDefinitions) {
this.skipAllDefinitions = skipAllDefinitions;
}
public void addNamespaceToSkipReference(String namespace){
namespacesToSkipReference.add(namespace);
}
public void addNamespaceToSkipDefinition(String namespace){
namespacesToSkipDefinition.add(namespace);
}
public void addIdToSkipReference(String namespace){
idsToSkipReference.add(namespace);
}
public void addIdToSkipDefinition(String namespace){
idsToSkipDefinition.add(namespace);
}
@Override
public boolean skipDefinition(AbstractType t) {
if (t.annotation(skipAnnotation.class, true)!=null){
return true;
}
if (skipAllDefinitions){
return true;
}
String nm=t.getNameSpaceId();
if (namespacesToSkipDefinition.contains(nm)){
return true;
}
String id=nm+"."+t.name();
if (idsToSkipDefinition.contains(id)){
return true;
}
return false;
}
@Override
public boolean skipReference(AbstractType t) {
if (t.annotation(skipAnnotation.class, true)!=null){
return true;
}
if (skipAllReferences){
return true;
}
String nm=t.getNameSpaceId();
if (namespacesToSkipReference.contains(nm)){
return true;
}
String id=nm+"."+t.name();
if (idsToSkipReference.contains(id)){
return true;
}
return false;
}
}
| 14,689
|
https://github.com/faustfizz/rnal/blob/master/android/settings.gradle
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
rnal
|
faustfizz
|
Gradle
|
Code
| 5
| 17
|
rootProject.name = 'rnal'
include ':app'
| 46,427
|
https://github.com/ziadhany/vulnerablecode/blob/master/vulnerabilities/importers/ubuntu.py
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
vulnerablecode
|
ziadhany
|
Python
|
Code
| 180
| 590
|
#
# Copyright (c) nexB Inc. and others. All rights reserved.
# VulnerableCode is a trademark of nexB Inc.
# SPDX-License-Identifier: Apache-2.0
# See http://www.apache.org/licenses/LICENSE-2.0 for the license text.
# See https://github.com/nexB/vulnerablecode for support or download.
# See https://aboutcode.org for more information about nexB OSS projects.
#
import asyncio
import bz2
import logging
import xml.etree.ElementTree as ET
import requests
from vulnerabilities.importer import OvalImporter
from vulnerabilities.package_managers import LaunchpadVersionAPI
logger = logging.getLogger(__name__)
class UbuntuImporter(OvalImporter):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# we could avoid setting translations, and have it
# set by default in the OvalParser, but we don't yet know
# whether all OVAL providers use the same format
self.translations = {"less than": "<"}
self.pkg_manager_api = LaunchpadVersionAPI()
def _fetch(self):
base_url = "https://people.canonical.com/~ubuntu-security/oval"
releases = self.config.releases
for i, release in enumerate(releases, 1):
file_url = f"{base_url}/com.ubuntu.{release}.cve.oval.xml.bz2" # nopep8
logger.info(f"Fetching Ubuntu Oval: {file_url}")
response = requests.get(file_url)
if response.status_code != requests.codes.ok:
logger.error(
f"Failed to fetch Ubuntu Oval: HTTP {response.status_code} : {file_url}"
)
continue
extracted = bz2.decompress(response.content)
yield (
{"type": "deb", "namespace": "ubuntu"},
ET.ElementTree(ET.fromstring(extracted.decode("utf-8"))),
)
logger.info(f"Fetched {i} Ubuntu Oval releases from {base_url}")
def set_api(self, packages):
asyncio.run(self.pkg_manager_api.load_api(packages))
| 10,653
|
https://github.com/scalajs-io/phaser/blob/master/src/main/scala/io/scalajs/dom/html/phaser/component/Destroy.scala
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
phaser
|
scalajs-io
|
Scala
|
Code
| 215
| 428
|
package io.scalajs.dom.html.phaser.component
import scala.scalajs.js
/**
* The Destroy component is responsible for destroying a Game Object.
* @see http://phaser.io/docs/2.6.2/Phaser.Component.Destroy.html
*/
@js.native
//@JSGlobal("Phaser.Component.Destroy")
trait Destroy extends js.Object {
/////////////////////////////////////////////////////////////////////////////////
// Properties
/////////////////////////////////////////////////////////////////////////////////
/**
* As a Game Object runs through its destroy method this flag is set to true,
* and can be checked in any sub-systems or plugins it is being destr
*/
def destroyPhase: Boolean = js.native
/////////////////////////////////////////////////////////////////////////////////
// Methods
/////////////////////////////////////////////////////////////////////////////////
/**
* Destroys the Game Object. This removes it from its parent group, destroys the input, event
* and animation handlers if present and nulls its reference to game, freeing it up for garbage collection.
*
* If this Game Object has the Events component it will also dispatch the onDestroy event.
* You can optionally also destroy the BaseTexture this Game Object is using. Be careful if you've
* more than one Game Object sharing the same BaseTexture.
* @param destroyChildren Should every child of this object have its destroy method called as well?
* @param destroyTexture Destroy the BaseTexture this Game Object is using? Note that if another Game
* Object is sharing the same BaseTexture it will invalidate it.
*/
def destroy(destroyChildren: Boolean, destroyTexture: Boolean): Unit = js.native
def destroy(destroyChildren: Boolean): Unit = js.native
def destroy(): Unit = js.native
}
| 16,017
|
https://github.com/pulumi/pulumi-aws/blob/master/sdk/java/src/main/java/com/pulumi/aws/elasticsearch/inputs/DomainAdvancedSecurityOptionsMasterUserOptionsArgs.java
|
Github Open Source
|
Open Source
|
BSD-3-Clause, Apache-2.0, MPL-2.0
| 2,023
|
pulumi-aws
|
pulumi
|
Java
|
Code
| 550
| 1,502
|
// *** WARNING: this file was generated by pulumi-java-gen. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
package com.pulumi.aws.elasticsearch.inputs;
import com.pulumi.core.Output;
import com.pulumi.core.annotations.Import;
import java.lang.String;
import java.util.Objects;
import java.util.Optional;
import javax.annotation.Nullable;
public final class DomainAdvancedSecurityOptionsMasterUserOptionsArgs extends com.pulumi.resources.ResourceArgs {
public static final DomainAdvancedSecurityOptionsMasterUserOptionsArgs Empty = new DomainAdvancedSecurityOptionsMasterUserOptionsArgs();
/**
* ARN for the main user. Only specify if `internal_user_database_enabled` is not set or set to `false`.
*
*/
@Import(name="masterUserArn")
private @Nullable Output<String> masterUserArn;
/**
* @return ARN for the main user. Only specify if `internal_user_database_enabled` is not set or set to `false`.
*
*/
public Optional<Output<String>> masterUserArn() {
return Optional.ofNullable(this.masterUserArn);
}
/**
* Main user's username, which is stored in the Amazon Elasticsearch Service domain's internal database. Only specify if `internal_user_database_enabled` is set to `true`.
*
*/
@Import(name="masterUserName")
private @Nullable Output<String> masterUserName;
/**
* @return Main user's username, which is stored in the Amazon Elasticsearch Service domain's internal database. Only specify if `internal_user_database_enabled` is set to `true`.
*
*/
public Optional<Output<String>> masterUserName() {
return Optional.ofNullable(this.masterUserName);
}
/**
* Main user's password, which is stored in the Amazon Elasticsearch Service domain's internal database. Only specify if `internal_user_database_enabled` is set to `true`.
*
*/
@Import(name="masterUserPassword")
private @Nullable Output<String> masterUserPassword;
/**
* @return Main user's password, which is stored in the Amazon Elasticsearch Service domain's internal database. Only specify if `internal_user_database_enabled` is set to `true`.
*
*/
public Optional<Output<String>> masterUserPassword() {
return Optional.ofNullable(this.masterUserPassword);
}
private DomainAdvancedSecurityOptionsMasterUserOptionsArgs() {}
private DomainAdvancedSecurityOptionsMasterUserOptionsArgs(DomainAdvancedSecurityOptionsMasterUserOptionsArgs $) {
this.masterUserArn = $.masterUserArn;
this.masterUserName = $.masterUserName;
this.masterUserPassword = $.masterUserPassword;
}
public static Builder builder() {
return new Builder();
}
public static Builder builder(DomainAdvancedSecurityOptionsMasterUserOptionsArgs defaults) {
return new Builder(defaults);
}
public static final class Builder {
private DomainAdvancedSecurityOptionsMasterUserOptionsArgs $;
public Builder() {
$ = new DomainAdvancedSecurityOptionsMasterUserOptionsArgs();
}
public Builder(DomainAdvancedSecurityOptionsMasterUserOptionsArgs defaults) {
$ = new DomainAdvancedSecurityOptionsMasterUserOptionsArgs(Objects.requireNonNull(defaults));
}
/**
* @param masterUserArn ARN for the main user. Only specify if `internal_user_database_enabled` is not set or set to `false`.
*
* @return builder
*
*/
public Builder masterUserArn(@Nullable Output<String> masterUserArn) {
$.masterUserArn = masterUserArn;
return this;
}
/**
* @param masterUserArn ARN for the main user. Only specify if `internal_user_database_enabled` is not set or set to `false`.
*
* @return builder
*
*/
public Builder masterUserArn(String masterUserArn) {
return masterUserArn(Output.of(masterUserArn));
}
/**
* @param masterUserName Main user's username, which is stored in the Amazon Elasticsearch Service domain's internal database. Only specify if `internal_user_database_enabled` is set to `true`.
*
* @return builder
*
*/
public Builder masterUserName(@Nullable Output<String> masterUserName) {
$.masterUserName = masterUserName;
return this;
}
/**
* @param masterUserName Main user's username, which is stored in the Amazon Elasticsearch Service domain's internal database. Only specify if `internal_user_database_enabled` is set to `true`.
*
* @return builder
*
*/
public Builder masterUserName(String masterUserName) {
return masterUserName(Output.of(masterUserName));
}
/**
* @param masterUserPassword Main user's password, which is stored in the Amazon Elasticsearch Service domain's internal database. Only specify if `internal_user_database_enabled` is set to `true`.
*
* @return builder
*
*/
public Builder masterUserPassword(@Nullable Output<String> masterUserPassword) {
$.masterUserPassword = masterUserPassword;
return this;
}
/**
* @param masterUserPassword Main user's password, which is stored in the Amazon Elasticsearch Service domain's internal database. Only specify if `internal_user_database_enabled` is set to `true`.
*
* @return builder
*
*/
public Builder masterUserPassword(String masterUserPassword) {
return masterUserPassword(Output.of(masterUserPassword));
}
public DomainAdvancedSecurityOptionsMasterUserOptionsArgs build() {
return $;
}
}
}
| 4,849
|
https://github.com/Txucishvili/export/blob/master/src/assets/sass/_partails/components/notifications/_notification-box.scss
|
Github Open Source
|
Open Source
|
MIT
| null |
export
|
Txucishvili
|
SCSS
|
Code
| 204
| 769
|
.notification_box {
@include flex;
@include align-items(center);
width: 100%;
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
font-size: 15px;
&.-done {
padding: 8px 14px;
background-color: $oc-green-3;
border: 1px solid $oc-green-6;
color: $oc-white;
}
&.-danger {
padding: 11px 14px;
background-color: $oc-red-4;
border: 1px solid $oc-red-6;
color: $oc-white;
}
}
.appNotifications {
position: absolute;
z-index: 555;
bottom: 0;
right: 0;
padding: 30px;
overflow: hidden;
.notification {
margin: 0 0 10px 0;
background: $oc-gray-1;
@include flex;
@include flex-direction(column);
max-width: 290px;
width: 290px;
border-radius: 4px;
box-shadow: 0px 3px 21px 0px rgba($oc-black, .15);
&.-success {
background-color: $oc-green-4;
border-radius: 4px;
color: $c-white;
}
&.-error {
background-color: $oc-red-4;
border-radius: 4px;
color: $c-white;
}
&.-danger {
background-color: $oc-yellow-4;
border-radius: 4px;
color: $oc-black;
}
&.-gray {
background-color: $oc-gray-3;
border-radius: 4px;
color: $oc-black;
}
.titleLine {
padding: 9px 15px;
display: flex;
font-size: 13px;
border-bottom: 1px solid rgba($oc-white, .17);
.title {
font-size: 14px;
font-family: $SegoeUI-SemiBold;
}
}
.contentside {
padding: 10px 15px;
font-size: 14px;
}
.close {
transition: all .3s ease;
@include flex-all;
cursor: pointer;
outline: none;
&:hover {
color: $oc-red-6;
}
}
animation-name: openNotif;
animation-duration: .3s;
transition: all .3s ease;
&.leaving {
opacity: 0;
transform: translateX(100%);
}
}
}
@keyframes openNotif {
0% {
opacity: .5;
transform: translateX(100px);
}
100% {
opacity: 1;
transform: translateX(0);
}
}
| 30,185
|
https://github.com/GMedian/archerysec/blob/master/osintscan/urls.py
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,021
|
archerysec
|
GMedian
|
Python
|
Code
| 110
| 415
|
# _
# /\ | |
# / \ _ __ ___| |__ ___ _ __ _ _
# / /\ \ | '__/ __| '_ \ / _ \ '__| | | |
# / ____ \| | | (__| | | | __/ | | |_| |
# /_/ \_\_| \___|_| |_|\___|_| \__, |
# __/ |
# |___/
# Copyright (C) 2017-2018 ArcherySec
# This file is part of ArcherySec Project.
from django.conf.urls import url
from osintscan import views
app_name = 'osintscan'
urlpatterns = [
url(r'^domain_osint/$',
views.domain_osint,
name='domain_osint'),
url(r'^sub_domain_search/$',
views.sub_domain_search,
name='sub_domain_search'),
url(r'^domain_list/$',
views.domain_list,
name='domain_list'),
url(r'^del_sub_domain/$',
views.del_sub_domain,
name='del_sub_domain'),
url(r'^osint_whois/$',
views.osint_whois,
name='osint_whois'),
url(r'^whois_info/$',
views.whois_info,
name='whois_info'),
url(r'^del_osint_domain/$',
views.del_osint_domain,
name='del_osint_domain'),
]
| 325
|
https://github.com/lishen2/ProgrammableLED/blob/master/software/src/break_light.c
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
ProgrammableLED
|
lishen2
|
C
|
Code
| 572
| 2,436
|
#include <stdlib.h>
#include "stm32f10x.h"
#include "utils.h"
#include "break_light.h"
#include "xl345.h"
#include "led.h"
#include "app_intf.h"
#include "acc_sensor.h"
#include "power.h"
enum BKL_Status{
BKL_STATUS_CONSTANTSPEED,
BKL_STATUS_DECELERATION,
};
#define BKL_TIMER TIM3
#define BKL_TIM_RCC RCC_APB1Periph_TIM3
#define BKL_TIM_IRQ TIM3_IRQn
#define BKL_TIM_ROUTINE TIM3_IRQHandler
#define BKL_TIMER_DELAY 400
#define BKL_FIFO_LENGTH 12
#define BKL_LED_DECELERATION() LED_SetColor(0xFF00F00F);
#define BKL_LED_CONSTANTSPEED() LED_SetColor(0x00011011);
static s32 g_totalZ = 0;
static s32 g_totalX = 0;
static s32 g_totalY = 0;
static s32 g_count = 0;
static void _BKL_Start(void);
static void _BKL_Stop(void);
struct APP_INTF g_appBreakLight =
{
_BKL_Start,
_BKL_Stop,
};
static void _bklTimerInit(void)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
NVIC_InitTypeDef NVIC_InitStructure;
RCC_APB1PeriphClockCmd(BKL_TIM_RCC, ENABLE);
NVIC_InitStructure.NVIC_IRQChannel = BKL_TIM_IRQ;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 3;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 3;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
TIM_DeInit(BKL_TIMER);
TIM_TimeBaseStructure.TIM_Prescaler = 8000;
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Down;
TIM_TimeBaseInit(BKL_TIMER, &TIM_TimeBaseStructure);
TIM_ClearFlag(BKL_TIMER, TIM_FLAG_Update);
TIM_ITConfig(BKL_TIMER, TIM_IT_Update, ENABLE);
return;
}
static void _bklTimerDeinit(void)
{
NVIC_InitTypeDef NVIC_InitStructure;
NVIC_InitStructure.NVIC_IRQChannel = BKL_TIM_IRQ;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 3;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 3;
NVIC_InitStructure.NVIC_IRQChannelCmd = DISABLE;
NVIC_Init(&NVIC_InitStructure);
TIM_DeInit(BKL_TIMER);
TIM_Cmd(BKL_TIMER, DISABLE);
TIM_ITConfig(BKL_TIMER, TIM_IT_Update, DISABLE);
RCC_APB1PeriphClockCmd(BKL_TIM_RCC, DISABLE);
return;
}
static inline void _displayDeceleration(void)
{
BKL_LED_DECELERATION();
TIM_SetCounter(BKL_TIMER, BKL_TIMER_DELAY);
TIM_Cmd(BKL_TIMER, ENABLE);
return;
}
void BKL_TIM_ROUTINE(void)
{
if(TIM_GetITStatus(BKL_TIMER, TIM_IT_Update) != RESET){
TIM_ClearITPendingBit(BKL_TIMER , TIM_FLAG_Update);
TIM_Cmd(BKL_TIMER, DISABLE);
BKL_LED_CONSTANTSPEED();
}
return;
}
static void _BKLonDataReady(void)
{
s16 x, y, z;
s16 zDiff, xDiff, yDiff;
ACC_ReadAcc(BKL_FIFO_LENGTH, &x, &y, &z);
g_count += 1;
g_totalZ += z;
zDiff = z - g_totalZ/g_count;
g_totalX += x;
xDiff = abs(x - g_totalX/g_count);
g_totalY += y;
yDiff = abs(y - g_totalY/g_count);
// printf("X:%hd,Y:%hd,Z:%hd\r\n", x, y, z);
// printf("Xd:%hd,Yd:%hd,Zd:%hd\r\n", xDiff, yDiff, zDiff);
/* zDiff is positive means we are decelerate */
if ((zDiff >= 23 && xDiff < 19 && yDiff < 19) ||
zDiff >= 50 && xDiff < 90 && yDiff < 90 ||
zDiff >= 90){
_displayDeceleration();
}
if (g_count > 512){
g_count >>= 3;
g_totalZ >>= 3;
g_totalX >>= 3;
g_totalY >>= 3;
}
return;
}
static void _BKLIRQHandler(u8 irq)
{
/* if data is ready */
if (irq & XL345_WATERMARK){
_BKLonDataReady();
}
/* wake up */
if (irq & XL345_ACTIVITY) {
PWR_Restore();
}
/* into low power mode */
if (irq & XL345_INACTIVITY){
PWR_LowPower();
}
return;
}
static void _BKLInitAccSensor(void)
{
u8 buffer[8];
/* add software reset */
buffer[0] = XL345_SOFT_RESET;
XL345_Write(1, XL345_RESERVED1, buffer);
delay_ms(50);
/*--------------------------------------------------
activity - inactivity
--------------------------------------------------*/
/* set up a buffer with all the initialization for activity and inactivity */
buffer[0] = 20; /* THRESH_ACT */
buffer[1] = 5; /* THRESH_INACT */
buffer[2] = 20;/* TIME_INACT (seconds) */
buffer[3] = /* ACT_INACT_CTL */
XL345_ACT_DC
| XL345_ACT_X_ENABLE | XL345_ACT_Y_ENABLE | XL345_ACT_Z_ENABLE
| XL345_INACT_AC | XL345_INACT_X_ENABLE
| XL345_INACT_Y_ENABLE | XL345_INACT_Z_ENABLE;
XL345_Write(4, XL345_THRESH_ACT, buffer);
/*--------------------------------------------------
Power, bandwidth-rate, interupt enabling
--------------------------------------------------*/
/* set up a buffer with all the initization for power*/
buffer[0] = /* BW_RATE */
XL345_RATE_100 | XL345_LOW_NOISE;
buffer[1] = /* POWER_CTL */
XL345_ACT_INACT_SERIAL | XL345_AUTO_SLEEP |
XL345_WAKEUP_8HZ | XL345_MEASURE;
XL345_Write(2, XL345_BW_RATE, buffer);
// set the FIFO control
buffer[0] = XL345_FIFO_MODE_FIFO | // set FIFO mode
0 | // link to INT1
BKL_FIFO_LENGTH; // number of samples
XL345_Write(1, XL345_FIFO_CTL, buffer);
// set data format
buffer[0] = XL345_SPI4WIRE | XL345_INT_HIGH | XL345_10BIT |
XL345_DATA_JUST_RIGHT | XL345_RANGE_2G;
XL345_Write(1, XL345_DATA_FORMAT, buffer);
//set interrupt map
buffer[0] = 0; //all interrupts set to pin INT1
XL345_Write(1, XL345_INT_MAP, buffer);
// turn on the interrupts
buffer[0] = XL345_ACTIVITY | XL345_INACTIVITY |
XL345_WATERMARK;
XL345_Write(1, XL345_INT_ENABLE, buffer);
return;
}
static void _BKLDeinitAccSensor(void)
{
u8 reset = XL345_SOFT_RESET;
/* just reset */
XL345_Write(1, XL345_RESERVED1, &reset);
delay_ms(50);
return;
}
static void _BKL_Start(void)
{
_bklTimerInit();
/* register irq handler to acc module */
ACC_SetIRQHandler(_BKLIRQHandler);
_BKLInitAccSensor();
return;
}
static void _BKL_Stop(void)
{
_BKLDeinitAccSensor();
_bklTimerDeinit();
LED_SetColor(0x00);
return;
}
| 13,280
|
https://github.com/arturek/ILSpy/blob/master/ILSpy/LoadedAssembly.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
ILSpy
|
arturek
|
C#
|
Code
| 664
| 1,896
|
// Copyright (c) 2011 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Threading;
using Mono.Cecil;
namespace ICSharpCode.ILSpy
{
/// <summary>
/// Represents an assembly loaded into ILSpy.
/// </summary>
public sealed class LoadedAssembly
{
readonly Task<AssemblyDefinition> assemblyTask;
readonly AssemblyList assemblyList;
readonly string fileName;
string shortName;
public LoadedAssembly(AssemblyList assemblyList, string fileName)
{
if (assemblyList == null)
throw new ArgumentNullException("assemblyList");
if (fileName == null)
throw new ArgumentNullException("fileName");
this.assemblyList = assemblyList;
this.fileName = fileName;
this.assemblyTask = Task.Factory.StartNew<AssemblyDefinition>(LoadAssembly); // requires that this.fileName is set
this.shortName = Path.GetFileNameWithoutExtension(fileName);
}
public AssemblyDefinition AssemblyDefinition {
get {
try {
return assemblyTask.Result;
} catch (AggregateException) {
return null;
}
}
}
public AssemblyList AssemblyList {
get { return assemblyList; }
}
public string FileName {
get { return fileName; }
}
public string ShortName {
get { return shortName; }
}
public bool IsLoaded {
get { return assemblyTask.IsCompleted; }
}
public bool HasLoadError {
get { return assemblyTask.IsFaulted; }
}
AssemblyDefinition LoadAssembly()
{
// runs on background thread
ReaderParameters p = new ReaderParameters();
p.AssemblyResolver = new MyAssemblyResolver(this);
try {
if (DecompilerSettingsPanel.CurrentDecompilerSettings.UseDebugSymbols) {
SetSymbolSettings(p);
}
return AssemblyDefinition.ReadAssembly(fileName, p);
} finally {
if (p.SymbolStream != null)
p.SymbolStream.Dispose();
}
}
private void SetSymbolSettings(ReaderParameters p)
{
// search for pdb in same directory as dll
string pdbName = Path.Combine(Path.GetDirectoryName(fileName), Path.GetFileNameWithoutExtension(fileName) + ".pdb");
if (File.Exists(pdbName)) {
p.ReadSymbols = true;
p.SymbolStream = File.OpenRead(pdbName);
}
// TODO: use symbol cache, get symbols from microsoft
}
[ThreadStatic]
static int assemblyLoadDisableCount;
public static IDisposable DisableAssemblyLoad()
{
assemblyLoadDisableCount++;
return new DecrementAssemblyLoadDisableCount();
}
sealed class DecrementAssemblyLoadDisableCount : IDisposable
{
bool disposed;
public void Dispose()
{
if (!disposed) {
disposed = true;
assemblyLoadDisableCount--;
}
}
}
sealed class MyAssemblyResolver : IAssemblyResolver
{
readonly LoadedAssembly parent;
public MyAssemblyResolver(LoadedAssembly parent)
{
this.parent = parent;
}
public AssemblyDefinition Resolve(AssemblyNameReference name)
{
var node = parent.LookupReferencedAssembly(name.FullName);
return node != null ? node.AssemblyDefinition : null;
}
public AssemblyDefinition Resolve(AssemblyNameReference name, ReaderParameters parameters)
{
var node = parent.LookupReferencedAssembly(name.FullName);
return node != null ? node.AssemblyDefinition : null;
}
public AssemblyDefinition Resolve(string fullName)
{
var node = parent.LookupReferencedAssembly(fullName);
return node != null ? node.AssemblyDefinition : null;
}
public AssemblyDefinition Resolve(string fullName, ReaderParameters parameters)
{
var node = parent.LookupReferencedAssembly(fullName);
return node != null ? node.AssemblyDefinition : null;
}
}
public LoadedAssembly LookupReferencedAssembly(string fullName)
{
foreach (LoadedAssembly asm in assemblyList.GetAssemblies()) {
if (asm.AssemblyDefinition != null && fullName.Equals(asm.AssemblyDefinition.FullName, StringComparison.OrdinalIgnoreCase))
return asm;
}
if (assemblyLoadDisableCount > 0)
return null;
if (!App.Current.Dispatcher.CheckAccess()) {
// Call this method on the GUI thread.
return (LoadedAssembly)App.Current.Dispatcher.Invoke(DispatcherPriority.Normal, new Func<string, LoadedAssembly>(LookupReferencedAssembly), fullName);
}
var name = AssemblyNameReference.Parse(fullName);
string file = GacInterop.FindAssemblyInNetGac(name);
if (file == null) {
string dir = Path.GetDirectoryName(this.fileName);
if (File.Exists(Path.Combine(dir, name.Name + ".dll")))
file = Path.Combine(dir, name.Name + ".dll");
else if (File.Exists(Path.Combine(dir, name.Name + ".exe")))
file = Path.Combine(dir, name.Name + ".exe");
}
if (file != null) {
return assemblyList.OpenAssembly(file);
} else {
return null;
}
}
public Task ContinueWhenLoaded(Action<Task<AssemblyDefinition>> onAssemblyLoaded, TaskScheduler taskScheduler)
{
return this.assemblyTask.ContinueWith(onAssemblyLoaded, taskScheduler);
}
public void WaitUntilLoaded()
{
assemblyTask.Wait();
}
}
}
| 32,020
|
https://github.com/King0987654/windows2000/blob/master/private/ntos/ps/psquota.c
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
windows2000
|
King0987654
|
C
|
Code
| 1,243
| 4,442
|
/*++
Copyright (c) 1989 Microsoft Corporation
Module Name:
psquota.c
Abstract:
This module implements the quota mechanism for NT
Author:
Mark Lucovsky (markl) 18-Sep-1989
Revision History:
--*/
#include "psp.h"
PEPROCESS_QUOTA_BLOCK
PsChargeSharedPoolQuota(
IN PEPROCESS Process,
IN SIZE_T PagedAmount,
IN SIZE_T NonPagedAmount
)
/*++
Routine Description:
This function charges shared pool quota of the specified pool type
to the specified process's pooled quota block. If the quota charge
would exceed the limits allowed to the process, then an exception is
raised and quota is not charged.
Arguments:
Process - Supplies the process to charge quota to.
PagedAmount - Supplies the amount of paged pool quota to charge.
PagedAmount - Supplies the amount of non paged pool quota to charge.
Return Value:
NULL - Quota was exceeded
NON-NULL - A referenced pointer to the quota block that was charged
--*/
{
KIRQL OldIrql;
SIZE_T NewPoolUsage;
PEPROCESS_QUOTA_BLOCK QuotaBlock;
SIZE_T NewLimit;
ASSERT((Process->Pcb.Header.Type == ProcessObject) || (Process->Pcb.Header.Type == 0));
QuotaBlock = Process->QuotaBlock;
retry_charge:
if ( QuotaBlock != &PspDefaultQuotaBlock ) {
ExAcquireSpinLock(&QuotaBlock->QuotaLock,&OldIrql);
do_charge:
if ( PagedAmount ) {
NewPoolUsage = QuotaBlock->QuotaPoolUsage[PagedPool] + PagedAmount;
//
// See if enough quota exists in the block to satisfy the
// request
//
if ( NewPoolUsage > QuotaBlock->QuotaPoolLimit[PagedPool] ) {
while ( (PspDefaultPagedLimit == 0) && MmRaisePoolQuota(PagedPool,QuotaBlock->QuotaPoolLimit[PagedPool],&NewLimit) ) {
QuotaBlock->QuotaPoolLimit[PagedPool] = NewLimit;
if ( NewPoolUsage <= NewLimit ) {
goto LimitRaised0;
}
}
//DbgPrint("PS: ChargeShared(0) Failed P %8x QB %8x PA %8x NPA %8x\n",Process,QuotaBlock,PagedAmount,NonPagedAmount);DbgBreakPoint();
ExReleaseSpinLock(&QuotaBlock->QuotaLock,OldIrql);
return NULL;
}
LimitRaised0:
if ( NewPoolUsage < QuotaBlock->QuotaPoolUsage[PagedPool] ||
NewPoolUsage < PagedAmount ) {
ExReleaseSpinLock(&QuotaBlock->QuotaLock,OldIrql);
//DbgPrint("PS: ChargeShared(1) Failed P %8x QB %8x PA %8x NPA %8x\n",Process,QuotaBlock,PagedAmount,NonPagedAmount);DbgBreakPoint();
return NULL;
}
QuotaBlock->QuotaPoolUsage[PagedPool] = NewPoolUsage;
if ( NewPoolUsage > QuotaBlock->QuotaPeakPoolUsage[PagedPool] ) {
QuotaBlock->QuotaPeakPoolUsage[PagedPool] = NewPoolUsage;
}
}
if ( NonPagedAmount ) {
NewPoolUsage = QuotaBlock->QuotaPoolUsage[NonPagedPool] + NonPagedAmount;
//
// See if enough quota exists in the block to satisfy the
// request
//
if ( NewPoolUsage > QuotaBlock->QuotaPoolLimit[NonPagedPool] ) {
while ( (PspDefaultNonPagedLimit == 0) && MmRaisePoolQuota(NonPagedPool,QuotaBlock->QuotaPoolLimit[NonPagedPool],&NewLimit) ) {
QuotaBlock->QuotaPoolLimit[NonPagedPool] = NewLimit;
if ( NewPoolUsage <= NewLimit ) {
goto LimitRaised1;
}
}
if ( PagedAmount ) {
QuotaBlock->QuotaPoolUsage[PagedPool] -= PagedAmount;
}
ExReleaseSpinLock(&QuotaBlock->QuotaLock,OldIrql);
//DbgPrint("PS: ChargeShared(2) Failed P %8x QB %8x PA %8x NPA %8x\n",Process,QuotaBlock,PagedAmount,NonPagedAmount);DbgBreakPoint();
return NULL;
}
LimitRaised1:
if ( NewPoolUsage < QuotaBlock->QuotaPoolUsage[NonPagedPool] ||
NewPoolUsage < NonPagedAmount ) {
if ( PagedAmount ) {
QuotaBlock->QuotaPoolUsage[PagedPool] -= PagedAmount;
}
ExReleaseSpinLock(&QuotaBlock->QuotaLock,OldIrql);
//DbgPrint("PS: ChargeShared(3) Failed P %8x QB %8x PA %8x NPA %8x\n",Process,QuotaBlock,PagedAmount,NonPagedAmount);DbgBreakPoint();
return NULL;
}
QuotaBlock->QuotaPoolUsage[NonPagedPool] = NewPoolUsage;
if ( NewPoolUsage > QuotaBlock->QuotaPeakPoolUsage[NonPagedPool] ) {
QuotaBlock->QuotaPeakPoolUsage[NonPagedPool] = NewPoolUsage;
}
}
QuotaBlock->ReferenceCount++;
ExReleaseSpinLock(&QuotaBlock->QuotaLock,OldIrql);
}
else {
//
// Don't do ANY quota operations on the initial system process
//
if ( Process == PsInitialSystemProcess ) {
return (PEPROCESS_QUOTA_BLOCK)1;
}
ExAcquireSpinLock(&PspDefaultQuotaBlock.QuotaLock,&OldIrql);
if ( (QuotaBlock = Process->QuotaBlock) != &PspDefaultQuotaBlock ) {
ExReleaseSpinLock(&PspDefaultQuotaBlock.QuotaLock,OldIrql);
goto retry_charge;
}
goto do_charge;
}
return QuotaBlock;
}
VOID
PsReturnSharedPoolQuota(
IN PEPROCESS_QUOTA_BLOCK QuotaBlock,
IN SIZE_T PagedAmount,
IN SIZE_T NonPagedAmount
)
/*++
Routine Description:
This function returns pool quota of the specified pool type to the
specified process.
Arguments:
QuotaBlock - Supplies the quota block to return quota to.
PagedAmount - Supplies the amount of paged pool quota to return.
PagedAmount - Supplies the amount of non paged pool quota to return.
Return Value:
None.
--*/
{
KIRQL OldIrql;
//
// if we bypassed the quota charge, don't do anything here either
//
if ( QuotaBlock == (PEPROCESS_QUOTA_BLOCK)1 ) {
return;
}
ExAcquireSpinLock(&QuotaBlock->QuotaLock,&OldIrql);
if ( PagedAmount ) {
if ( PagedAmount <= QuotaBlock->QuotaPoolUsage[PagedPool] ) {
QuotaBlock->QuotaPoolUsage[PagedPool] -= PagedAmount;
}
else {
ASSERT(FALSE);
QuotaBlock->QuotaPoolUsage[PagedPool] = 0;
}
}
if ( NonPagedAmount ) {
if ( NonPagedAmount <= QuotaBlock->QuotaPoolUsage[NonPagedPool] ) {
QuotaBlock->QuotaPoolUsage[NonPagedPool] -= NonPagedAmount;
}
else {
ASSERT(FALSE);
QuotaBlock->QuotaPoolUsage[NonPagedPool] = 0;
}
}
QuotaBlock->ReferenceCount--;
if ( QuotaBlock->ReferenceCount == 0 ) {
ExReleaseSpinLock(&QuotaBlock->QuotaLock,OldIrql);
ExFreePool(QuotaBlock);
}
else {
ExReleaseSpinLock(&QuotaBlock->QuotaLock,OldIrql);
}
}
VOID
PsChargePoolQuota(
IN PEPROCESS Process,
IN POOL_TYPE PoolType,
IN SIZE_T Amount
)
/*++
Routine Description:
This function charges pool quota of the specified pool type to
the specified process. If the quota charge would exceed the limits
allowed to the process, then an exception is raised and quota is
not charged.
Arguments:
Process - Supplies the process to charge quota to.
PoolType - Supplies the type of pool quota to charge.
Amount - Supplies the amount of pool quota to charge.
Return Value:
Raises STATUS_QUOTA_EXCEEDED if the quota charge would exceed the
limits allowed to the process.
--*/
{
KIRQL OldIrql;
SIZE_T NewPoolUsage;
PEPROCESS_QUOTA_BLOCK QuotaBlock;
SIZE_T NewLimit;
SIZE_T HardLimit;
ASSERT((Process->Pcb.Header.Type == ProcessObject) || (Process->Pcb.Header.Type == 0));
QuotaBlock = Process->QuotaBlock;
retry_charge:
if ( QuotaBlock != &PspDefaultQuotaBlock ) {
ExAcquireSpinLock(&QuotaBlock->QuotaLock,&OldIrql);
do_charge:
NewPoolUsage = QuotaBlock->QuotaPoolUsage[PoolType] + Amount;
//
// See if enough quota exists in the block to satisfy the
// request
//
if ( NewPoolUsage > QuotaBlock->QuotaPoolLimit[PoolType] ) {
if ( PoolType == PagedPool ) {
HardLimit = PspDefaultPagedLimit;
}
else {
HardLimit = PspDefaultNonPagedLimit;
}
while ( (HardLimit == 0) && MmRaisePoolQuota(PoolType,QuotaBlock->QuotaPoolLimit[PoolType],&NewLimit) ) {
QuotaBlock->QuotaPoolLimit[PoolType] = NewLimit;
if ( NewPoolUsage <= NewLimit ) {
goto LimitRaised2;
}
}
//DbgPrint("PS: ChargePool Failed P %8x QB %8x PT %8x Amount %8x\n",Process,QuotaBlock,PoolType,Amount);DbgBreakPoint();
ExReleaseSpinLock(&QuotaBlock->QuotaLock,OldIrql);
ExRaiseStatus(STATUS_QUOTA_EXCEEDED);
}
LimitRaised2:
if ( NewPoolUsage < QuotaBlock->QuotaPoolUsage[PoolType] ||
NewPoolUsage < Amount ) {
ExReleaseSpinLock(&QuotaBlock->QuotaLock,OldIrql);
ExRaiseStatus(STATUS_QUOTA_EXCEEDED);
}
QuotaBlock->QuotaPoolUsage[PoolType] = NewPoolUsage;
if ( NewPoolUsage > QuotaBlock->QuotaPeakPoolUsage[PoolType] ) {
QuotaBlock->QuotaPeakPoolUsage[PoolType] = NewPoolUsage;
}
NewPoolUsage = Process->QuotaPoolUsage[PoolType] + Amount;
Process->QuotaPoolUsage[PoolType] = NewPoolUsage;
if ( NewPoolUsage > Process->QuotaPeakPoolUsage[PoolType] ) {
Process->QuotaPeakPoolUsage[PoolType] = NewPoolUsage;
}
ExReleaseSpinLock(&QuotaBlock->QuotaLock,OldIrql);
}
else {
if ( Process == PsInitialSystemProcess ) {
return;
}
ExAcquireSpinLock(&PspDefaultQuotaBlock.QuotaLock,&OldIrql);
if ( (QuotaBlock = Process->QuotaBlock) != &PspDefaultQuotaBlock ) {
ExReleaseSpinLock(&PspDefaultQuotaBlock.QuotaLock,OldIrql);
goto retry_charge;
}
goto do_charge;
}
}
VOID
PsReturnPoolQuota(
IN PEPROCESS Process,
IN POOL_TYPE PoolType,
IN SIZE_T Amount
)
/*++
Routine Description:
This function returns pool quota of the specified pool type to the
specified process.
Arguments:
Process - Supplies the process to return quota to.
PoolType - Supplies the type of pool quota to return.
Amount - Supplies the amount of pool quota to return
Return Value:
Raises STATUS_QUOTA_EXCEEDED if the quota charge would exceed the
limits allowed to the process.
--*/
{
KIRQL OldIrql;
PEPROCESS_QUOTA_BLOCK QuotaBlock;
SIZE_T GiveBackLimit;
SIZE_T RoundedUsage;
ASSERT((Process->Pcb.Header.Type == ProcessObject) || (Process->Pcb.Header.Type == 0));
QuotaBlock = Process->QuotaBlock;
retry_return:
if ( QuotaBlock != &PspDefaultQuotaBlock) {
ExAcquireSpinLock(&QuotaBlock->QuotaLock,&OldIrql);
if ( PspDoingGiveBacks ) {
if ( PoolType == PagedPool ) {
GiveBackLimit = MMPAGED_QUOTA_INCREASE;
}
else {
GiveBackLimit = MMNONPAGED_QUOTA_INCREASE;
}
}
else {
GiveBackLimit = 0;
}
do_return:
if ( Amount <= Process->QuotaPoolUsage[PoolType] ) {
Process->QuotaPoolUsage[PoolType] -= Amount;
}
else {
ASSERT(FALSE);
GiveBackLimit = 0;
Process->QuotaPoolUsage[PoolType] = 0;
}
if ( Amount <= QuotaBlock->QuotaPoolUsage[PoolType] ) {
QuotaBlock->QuotaPoolUsage[PoolType] -= Amount;
}
else {
ASSERT(FALSE);
GiveBackLimit = 0;
QuotaBlock->QuotaPoolUsage[PoolType] = 0;
}
if ( GiveBackLimit ) {
if (QuotaBlock->QuotaPoolLimit[PoolType] - QuotaBlock->QuotaPoolUsage[PoolType] > GiveBackLimit ) {
//
// round up the current usage to a page multiple
//
RoundedUsage = ROUND_TO_PAGES(QuotaBlock->QuotaPoolUsage[PoolType]);
//
// Give back the limit minus the rounded usage
//
GiveBackLimit = QuotaBlock->QuotaPoolLimit[PoolType] - RoundedUsage;
QuotaBlock->QuotaPoolLimit[PoolType] -= GiveBackLimit;
MmReturnPoolQuota(PoolType,GiveBackLimit);
}
}
ExReleaseSpinLock(&QuotaBlock->QuotaLock,OldIrql);
}
else {
if ( Process == PsInitialSystemProcess ) {
return;
}
ExAcquireSpinLock(&PspDefaultQuotaBlock.QuotaLock,&OldIrql);
if ( (QuotaBlock = Process->QuotaBlock) != &PspDefaultQuotaBlock) {
ExReleaseSpinLock(&PspDefaultQuotaBlock.QuotaLock,OldIrql);
goto retry_return;
}
GiveBackLimit = 0;
goto do_return;
}
}
VOID
PspInheritQuota(
IN PEPROCESS NewProcess,
IN PEPROCESS ParentProcess
)
{
PEPROCESS_QUOTA_BLOCK QuotaBlock;
KIRQL OldIrql;
if ( ParentProcess ) {
QuotaBlock = ParentProcess->QuotaBlock;
}
else {
QuotaBlock = &PspDefaultQuotaBlock;
}
ExAcquireSpinLock(&QuotaBlock->QuotaLock,&OldIrql);
QuotaBlock->ReferenceCount++;
NewProcess->QuotaBlock = QuotaBlock;
ExReleaseSpinLock(&QuotaBlock->QuotaLock,OldIrql);
}
VOID
MiReturnPageFileQuota (
IN SIZE_T QuotaCharge,
IN PEPROCESS CurrentProcess
);
VOID
PspDereferenceQuota(
IN PEPROCESS Process
)
{
PEPROCESS_QUOTA_BLOCK QuotaBlock;
KIRQL OldIrql;
QuotaBlock = Process->QuotaBlock;
PsReturnPoolQuota(Process,NonPagedPool,Process->QuotaPoolUsage[NonPagedPool]);
PsReturnPoolQuota(Process,PagedPool,Process->QuotaPoolUsage[PagedPool]);
MiReturnPageFileQuota(Process->PagefileUsage,Process);
ExAcquireSpinLock(&QuotaBlock->QuotaLock,&OldIrql);
QuotaBlock->ReferenceCount--;
if ( QuotaBlock->ReferenceCount == 0 ) {
ExReleaseSpinLock(&QuotaBlock->QuotaLock,OldIrql);
ExFreePool(QuotaBlock);
}
else {
ExReleaseSpinLock(&QuotaBlock->QuotaLock,OldIrql);
}
}
| 30,345
|
https://github.com/Mburiah/Android-IP/blob/master/app/src/main/java/com/example/rickmorty/network/RickandmortyApi.java
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
Android-IP
|
Mburiah
|
Java
|
Code
| 18
| 86
|
package com.example.rickmorty.network;
import com.example.rickmorty.models.characters.Response;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Query;
public interface RickandmortyApi {
@GET("character")
Call<Response> getInformation();
}
| 12,350
|
https://github.com/Iamsdt/PSSD/blob/master/app/src/main/java/com/iamsdt/pssd/utils/Constants.kt
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,020
|
PSSD
|
Iamsdt
|
Kotlin
|
Code
| 218
| 662
|
/*
* Developed By Shudipto Trafder
* on 8/17/18 12:39 PM
* Copyright (c) 2018 Shudipto Trafder.
*/
package com.iamsdt.pssd.utils
import android.os.Environment
class Constants {
companion object {
const val DB_NAME = "SS.db"
const val PrivacyPolices = "https://docs.google.com/document/d/1dJOwpVjSbxbhe2KwY1TcYlt-fm882vjybjw1tYLUIuk"
}
object ADD {
const val WORD = "word"
const val DES = "des"
const val DIALOG = "Dialog"
}
object COLOR {
const val colorSp = "colorSp"
const val themeKey = "themeKey"
const val NIGHT_MODE_SP_KEY: String = "NightModeSp"
const val NIGHT_MODE_VALUE_KEY: String = "NightSP"
}
object REMOTE {
const val FB_REMOTE_CONFIG_STORAGE_KEY = "storage_key"
const val USER = "user"
const val ADMIN = "admin"
const val DOWNLOAD_FILE_NAME = "download.json"
const val DOWNLOAD_TAG = "download_tag"
const val SP = "remote_sp"
const val DATE_UPLOAD = "date_upload"
const val DATE_DOWNLOAD = "date_download"
}
object SP {
const val appSp = "App"
const val FIRST_TIME = "first"
const val DATA_INSERT = "data"
const val DATA_RESTORE = "restore"
const val DATA_VOLUME = "volume"
const val UPDATE_4 = "update4"
}
object Settings {
const val EXT = ".ss"
const val SETTING_IMOUT_OPTION_FAVOURITE = "favourite$EXT"
const val SETTING_IMOUT_OPTION_USER = "user$EXT"
val DEFAULT_PATH_STORAGE = Environment.getExternalStorageDirectory()
.absolutePath + "/SSDictionary/"
const val STORAGE_PATH_KEY = "storage"
}
object IO {
const val EXPORT_FAV = "Export_Fav"
const val EXPORT_ADD = "Export_Add"
const val IMPORT_ADD = "IMPORT_Add"
const val IMPORT_FAV = "IMPORT_Fav"
}
}
| 37,123
|
https://github.com/galudino/gof-designpatterns-cpp/blob/master/src/1_structural_patterns/facade/stack_machine_code_generator.h
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
gof-designpatterns-cpp
|
galudino
|
C
|
Code
| 14
| 68
|
#ifndef STACK_MACHINE_CODE_GENERATOR_H
#define STACK_MACHINE_CODE_GENERATOR_H
class stack_machine_code_generator : public code_generator {};
#endif /* STACK_MACHINE_CODE_GENERATOR_H */
| 7,196
|
https://github.com/jeonggyukim/pyathena/blob/master/pyathena/tigress_ncr/hst.py
|
Github Open Source
|
Open Source
|
MIT
| 2,023
|
pyathena
|
jeonggyukim
|
Python
|
Code
| 1,334
| 7,327
|
# read_hst.py
import os
import os.path as osp
import glob
import xarray as xr
import numpy as np
import pandas as pd
from scipy import integrate
import matplotlib.pyplot as plt
import astropy.units as au
import astropy.constants as ac
from ..io.read_hst import read_hst
from ..load_sim import LoadSim
class Hst:
@LoadSim.Decorators.check_pickle_hst
def read_hst(self, savdir=None, force_override=False):
"""Function to read hst and convert quantities to convenient units
"""
par = self.par
u = self.u
domain = self.domain
# volume of resolution element (code unit)
dvol = domain['dx'].prod()
# total volume of domain (code unit)
vol = domain['Lx'].prod()
# Area of domain (code unit)
LxLy = domain['Lx'][0]*domain['Lx'][1]
# Lz
Lz = domain['Lx'][2]
Omega = self.par['problem']['Omega']
if Omega>0:
time_orb = 2*np.pi/Omega*u.Myr # Orbital time in Myr
else:
time_orb = 1.0
try:
if self.par['configure']['new_cooling'] == 'ON':
newcool = True
else:
newcool = False
except KeyError:
newcool = False
nscalars = self.par['configure']['nscalars']
hst = read_hst(self.files['hst'], force_override=force_override)
h = pd.DataFrame()
if self.par['configure']['gas'] == 'mhd':
mhd = True
else:
mhd = False
# Time in code unit
h['time_code'] = hst['time']
# Time in Myr
h['time'] = h['time_code']*u.Myr
h['time_orb'] = h['time']/time_orb
# Time step
h['dt_code'] = hst['dt']
h['dt'] = hst['dt']*u.Myr
# if par['configure']['new_cooling'] == 'ON' and \
# (par['configure']['radps'] == 'ON' or par['configure']['sixray'] == 'ON'):
# for c in ('dt_cool_min','dt_xH2_min','dt_xHII_min'):
# hst[c] *= u.Myr*vol
# Total gas mass in Msun
h['mass'] = hst['mass']*vol*u.Msun
h['mass_sp'] = hst['msp']*vol*u.Msun
for i in range(nscalars):
h[f'mass{i}'] = hst[f'scalar{i}']*vol*u.Msun
if newcool:
h['M_HI'] = h['mass{0:d}'.format(nscalars - 3)]
h['Sigma_HI'] = h['M_HI']/(LxLy*u.pc**2)
h['M_H2'] = 2.0*h['mass{0:d}'.format(nscalars - 2)]
h['Sigma_H2'] = h['M_H2']/(LxLy*u.pc**2)
h['M_HII'] = h['mass'] - h['M_H2'] - h['M_HI']
h['Sigma_HII'] = h['M_HII']/(LxLy*u.pc**2)
# Total outflow mass
if self.test_phase_sep_hst():
self.logger.info("[read_hst]: Reading phase separated history files...")
hph = self.read_hst_phase_all()
hw = self.read_hst_phase(iph=0)
h['massflux_lbd_d'] = hw['Fzm_lower']*u.mass_flux
h['massflux_ubd_d'] = hw['Fzm_upper']*u.mass_flux
h['mass_out'] = (hw['Fzm_upper_dt']-hw['Fzm_lower_dt'])*LxLy*u.Msun
else:
h['massflux_lbd_d'] = hst['F3_lower']*u.mass_flux
h['massflux_ubd_d'] = hst['F3_upper']*u.mass_flux
h['mass_out'] = integrate.cumtrapz(hst['F3_upper'] - hst['F3_lower'], hst['time'], initial=0.0)
h['mass_out'] = h['mass_out']*LxLy*u.Msun
# Mass surface density in Msun/pc^2
h['Sigma_gas'] = h['mass']/(LxLy*u.pc**2)
h['Sigma_sp'] = h['mass_sp']/(LxLy*u.pc**2)
h['Sigma_out'] = h['mass_out']/(LxLy*u.pc**2)
# Calculate (cumulative) SN ejecta mass
# JKIM: only from clustered type II(?)
try:
sn = read_hst(self.files['sn'], force_override=force_override)
t_ = np.array(hst['time'])
Nsn, snbin = np.histogram(sn.time, bins=np.concatenate(([t_[0]], t_)))
h['mass_snej'] = Nsn.cumsum()*self.par['feedback']['MejII'] # Mass of SN ejecta [Msun]
h['Sigma_snej'] = h['mass_snej']/(LxLy*u.pc**2)
except KeyError:
pass
# H mass/surface density in Msun
#h['M_gas'] = h['mass']/u.muH
#h['Sigma_gas'] = h['M_gas']/(LxLy*u.pc**2)
if self.test_phase_sep_hst():
h['H'] = np.sqrt(hw['H2']/hw['mass'])
for ph in ['c','u','w1','w2','h1','h2']:
if ph == 'h1':
phlist = ['WH' + tail for tail in ['MM','IM','NM']]
elif ph == 'h2':
phlist = ['H' + tail for tail in ['MM','IM','NM']]
else:
phlist = [ph.upper() + tail for tail in ['MM','IM','NM']]
h['mf_{}'.format(ph)] = hph['mass'].sel(phase=phlist).sum(dim='phase')/hw['mass']
h['vf_{}'.format(ph)] = hph['vol'].sel(phase=phlist).sum(dim='phase')/hw['vol']
h['H_{}'.format(ph)] = \
np.sqrt(hph['H2'].sel(phase=phlist).sum(dim='phase')/hph['mass'].sel(phase=phlist).sum(dim='phase'))
h['mf_w'] = h['mf_w1'] + h['mf_w2']
h['vf_w'] = h['vf_w1'] + h['vf_w2']
h['H_w'] = np.sqrt((h['H_w1']**2*h['mf_w1'] +
h['H_w2']**2*h['mf_w2'])/
(h['mf_w']))
h['mf_2p'] = h['mf_c'] + h['mf_u'] + h['mf_w']
h['vf_2p'] = h['vf_c'] + h['vf_u'] + h['vf_w']
h['H_2p'] = np.sqrt((h['H_c']**2*h['mf_c'] +
h['H_u']**2*h['mf_u'] +
h['H_w']**2*h['mf_w'])/
(h['mf_2p']))
else:
# Mass, volume fraction, scale height
h['H'] = np.sqrt(hst['H2'] / hst['mass'])
for ph in ['c','u','w','h1','h2']:
h['mf_{}'.format(ph)] = hst['M{}'.format(ph)]/hst['mass']
h['vf_{}'.format(ph)] = hst['V{}'.format(ph)]
h['H_{}'.format(ph)] = \
np.sqrt(hst['H2{}'.format(ph)] / hst['M{}'.format(ph)])
#print(h['mf_c'])
#h['Vmid_2p'] = hst['Vmid_2p']
# mf, vf, H of thermally bistable (cold + unstable + warm) medium
h['mf_2p'] = h['mf_c'] + h['mf_u'] + h['mf_w']
h['vf_2p'] = h['vf_c'] + h['vf_u'] + h['vf_w']
h['H_2p'] = np.sqrt((hst['H2c'] + hst['H2u'] + hst['H2w']) / \
(hst['Mc'] + hst['Mu'] + hst['Mw']))
# Kinetic and magnetic energy
h['KE'] = hst['x1KE'] + hst['x2KE'] + hst['x3KE']
if mhd:
h['ME'] = hst['x1ME'] + hst['x2ME'] + hst['x3ME']
# hst['x2KE'] = hst['x2dke']
for ax in ('1','2','3'):
Ekf = 'x{}KE'.format(ax)
if ax == '2':
Ekf = 'x2dke'
# Mass weighted velocity dispersion??
h['v{}'.format(ax)] = np.sqrt(2*hst[Ekf]/hst['mass'])
if mhd:
h['vA{}'.format(ax)] = \
np.sqrt(2*hst['x{}ME'.format(ax)]/hst['mass'])
if self.test_phase_sep_hst():
phlist = ['C' + tail for tail in ['MM','IM','NM']]
phlist += ['U' + tail for tail in ['MM','IM','NM']]
phlist += ['W1' + tail for tail in ['MM','IM','NM']]
phlist += ['W2' + tail for tail in ['MM','IM','NM']]
m2p = hph['mass'].sel(phase=phlist).sum(dim='phase')
ke2p = hph['x{}KE'.format(ax)].sel(phase=phlist).sum(dim='phase')
h['v{}_2p'.format(ax)] = np.sqrt(2*ke2p/m2p)
else:
h['v{}_2p'.format(ax)] = \
np.sqrt(2*hst['x{}KE_2p'.format(ax)]/hst['mass']/h['mf_2p'])
if self.test_phase_sep_hst():
h['cs'] = np.sqrt(hw['P']/hw['mass'])
h['Pth_mid'] = hst['Pth_mid']*u.pok
h['Pth_mid_2p'] = hst['Pth_mid_2p']*u.pok/hst['Vmid_2p']
h['Pturb_mid'] = hst['Pturb_mid']*u.pok
h['Pturb_mid_2p'] = hst['Pturb_mid_2p']*u.pok/hst['Vmid_2p']
else:
h['cs'] = np.sqrt(hst['P']/hst['mass'])
h['Pth_mid'] = hst['Pth']*u.pok
h['Pth_mid_2p'] = hst['Pth_2p']*u.pok/hst['Vmid_2p']
h['Pturb_mid'] = hst['Pturb']*u.pok
h['Pturb_mid_2p'] = hst['Pturb_2p']*u.pok/hst['Vmid_2p']
# Midplane number density
h['nmid'] = hst['nmid']
h['nmid_2p'] = hst['nmid_2p']/hst['Vmid_2p']
# Star formation rate per area [Msun/kpc^2/yr]
h['sfr10'] = hst['sfr10']
h['sfr40'] = hst['sfr40']
h['sfr100'] = hst['sfr100']
try:
if par['configure']['radps'] == 'ON':
radps = True
else:
radps = False
except KeyError:
radps = False
if radps:
# Total/escaping luminosity in Lsun
ifreq = dict()
for f in ('PH','LW','PE'): #,'PE_unatt'):
try:
ifreq[f] = par['radps']['ifreq_{0:s}'.format(f)]
except KeyError:
pass
for i in range(par['radps']['nfreq']):
for k, v in ifreq.items():
if i == v:
try:
h[f'Ltot_{k}'] = hst[f'Ltot{i}']*vol*u.Lsun
h[f'Lesc_{k}'] = hst[f'Lesc{i}']*vol*u.Lsun
if par['radps']['eps_extinct'] > 0.0:
h[f'Leps_{k}'] = hst[f'Leps{i}']*vol*u.Lsun
try:
h[f'Ldust_{k}'] = hst[f'Ldust{i}']*vol*u.Lsun
except KeyError:
self.logger.info('Ldust not found in hst')
hnu = (par['radps'][f'hnu_{k}']*au.eV).cgs.value
h[f'Qtot_{k}'] = h[f'Ltot_{k}'].values * \
(ac.L_sun.cgs.value)/hnu
h[f'Qesc_{k}'] = h[f'Lesc_{k}'].values * \
(ac.L_sun.cgs.value)/hnu
# Cumulative number of escaped photons
h[f'Qtot_cum_{k}'] = \
integrate.cumtrapz(h[f'Qtot_{k}'], h.time*u.time.cgs.value, initial=0.0)
h[f'Qesc_cum_{k}'] = \
integrate.cumtrapz(h[f'Qesc_{k}'], h.time*u.time.cgs.value, initial=0.0)
# Instantaneous escape fraction
h[f'fesc_{k}'] = h[f'Lesc_{k}']/h[f'Ltot_{k}']
# Cumulative escape fraction
h[f'fesc_cum_{k}'] = \
integrate.cumtrapz(h[f'Lesc_{k}'], h.time, initial=0.0)/\
integrate.cumtrapz(h[f'Ltot_{k}'], h.time, initial=0.0)
h[f'fesc_cum_{k}'].fillna(value=0.0, inplace=True)
except KeyError as e:
pass
#raise e
if 'Ltot_LW' in hst.columns and 'Ltot_PE' in hst.columns:
h['fesc_FUV'] = (hst['Lesc_PE'] + hst['Lesc_LW'])/(hst['Ltot_PE'] + hst['Ltot_LW'])
h['fesc_cum_FUV'] = \
integrate.cumtrapz(hst['Lesc_PE'] + hst['Lesc_LW'], hst.time, initial=0.0)/\
integrate.cumtrapz(hst['Ltot_PE'] + hst['Ltot_LW'], hst.time, initial=0.0)
h[f'fesc_cum_FUV'].fillna(value=0.0, inplace=True)
try:
h['xi_CR0'] = hst['xi_CR0']
except KeyError:
pass
h.index = h['time_code']
self.hst = h
# SN data
try:
if osp.exists(self.files['sn']):
sn = read_hst(self.files['sn'],force_override=force_override)
snr = get_snr(sn['time']*self.u.Myr,hst['time']*self.u.Myr)
self.sn = sn
self.snr = snr/LxLy
except:
pass
return h
def test_phase_sep_hst(self):
fhstph = glob.glob(self.files["hst"].replace(".hst", ".phase*.hst"))
fhstph.sort()
nphase = len(fhstph)
return nphase>0
def read_hst_phase(self, iph=0):
if iph == 0:
f = self.files["hst"].replace(".hst", ".whole.hst")
else:
f = self.files["hst"].replace(".hst", ".phase{}.hst".format(iph))
h = read_hst(f)
h.index = h["time"]
return h.to_xarray()
def read_hst_phase_all(self):
fhstph = glob.glob(self.files["hst"].replace(".hst", ".phase*.hst"))
fhstph.sort()
nphase = len(fhstph)
hstph = xr.Dataset()
for iph in range(1, nphase+1):
phname = self.get_hst_phase_name(iph)
hstph[phname] = self.read_hst_phase(iph).to_array()
hstph = hstph.to_array("phase").to_dataset("variable")
return hstph
def get_hst_phase_name(self, iph):
if iph == 0: return "whole"
thphase = ["C", "U", "W1", "W2", "WH", "H"]
chphase = ["I", "M", "N"]
nthph = len(thphase)
nchph = len(chphase)
if iph > nthph*nchph:
raise KeyError("{} phases are defined, but iph={} is given".format(nthph*nchph,iph))
return thphase[(iph-1) % nthph] + chphase[(iph-1) // nthph] + "M"
def plt_hst_compare(sa, models=None, read_hst_kwargs=dict(savdir=None, force_override=False),
c=['k', 'C0', 'C1', 'C2', 'C3', 'C4', 'C5'],
ncol=3,
lw=[2,2,2,2,2,2,2],
column=['Sigma_gas', 'Sigma_sp', 'Sigma_out',
'sfr10', 'sfr40', 'dt', 'xi_CR0',
'Pturb_mid', 'Pturb_mid_2p',
'Pth_mid', 'Pth_mid_2p',
'H_c','H_u','H_w','H_2p',
'v3_2p','nmid_2p',
'mf_c','mf_u','mf_w'],
xlim=None,
ylim='R8',
figsize=None,
):
if ylim == 'R8':
ylim=dict(Sigma_gas=(5,13),
Sigma_sp=(0,4),
Sigma_out=(0.01,10),
sfr10=(1e-4,4e-2),
sfr40=(1e-4,4e-2),
dt=(1e-4,1e-2),
xi_CR0=(1e-17,1e-15),
Pturb_mid=(1e3,1e5),
Pturb_mid_2p=(1e3,1e5),
Pth_mid=(1e3,1e5),
Pth_mid_2p=(1e3,1e5),
H=(0,1000),
H_c=(0,300),
H_u=(0,300),
H_w=(0,1000),
H_2p=(0,1000),
v3_2p=(0,20.0),
nmid_2p=(1e-1,1e1),
Vmid_2p=(1e-2,1.0),
mf_c=(1e-2,1.0),
mf_u=(1e-2,1.0),
mf_w=(1e-1,1.0),)
elif ylim == 'LGR4':
ylim=dict(Sigma_gas=(0,70),
Sigma_sp=(0,30),
Sigma_out=(0,10),
sfr10=(1e-3,5e-1),
sfr40=(1e-3,5e-1),
dt=(1e-4,1e-2),
xi_CR0=(1e-17,1e-14),
Pturb_mid=(1e3,1e6),
Pturb_mid_2p=(1e3,1e6),
Pth_mid=(1e4,1e6),
Pth_mid_2p=(1e4,1e6),
H=(0,1000),
H_c=(0,400),
H_u=(0,400),
H_w=(0,1000),
H_2p=(0,1000),
v3_2p=(0,40.0),
nmid_2p=(1e-1,1e2),
Vmid_2p=(1e-2,1.0),
mf_c=(1e-2,1.0),
mf_u=(1e-2,1.0),
mf_w=(1e-1,1.0),)
ylabel = dict(Sigma_gas=r'$\Sigma_{\rm gas}\;[M_{\odot}\,{\rm pc}^{-2}]$',
Sigma_sp=r'$\Sigma_{\rm *,formed}\;[M_{\odot}\,{\rm pc}^{-2}]$',
Sigma_out=r'$\Sigma_{\rm of}\;[M_{\odot}\,{\rm pc}^{-2}]$',
sfr10=r'$\Sigma_{\rm SFR,10Myr}\;[M_{\odot}\,{\rm pc}^{-2}]$',
sfr40=r'$\Sigma_{\rm SFR,40Myr}\;[M_{\odot}\,{\rm pc}^{-2}]$',
dt=r'${\rm d}t_{\rm mhd}\;[{\rm Myr}]$',
xi_CR0=r'$\xi_{\rm CR,0}\;[{\rm s}^{-1}]$',
Pturb_mid_2p=r'$P_{\rm turb,mid,2p}\;[{\rm cm}^{-3}\,{\rm K}]$',
Pturb_mid=r'$P_{\rm turb,mid}\;[{\rm cm}^{-3}\,{\rm K}]$',
Pth_mid_2p=r'$P_{\rm thm,mid,2p}\;[{\rm cm}^{-3}\,{\rm K}]$',
Pth_mid=r'$P_{\rm thm,mid}\;[{\rm cm}^{-3}\,{\rm K}]$',
H=r'$H\;[{\rm pc}]$',
H_c=r'$H_{\rm c}\;[{\rm pc}]$',
H_u=r'$H_{\rm u}\;[{\rm pc}]$',
H_w=r'$H_{\rm w}\;[{\rm pc}]$',
H_2p=r'$H_{\rm 2p}\;[{\rm pc}]$',
v3_2p=r'$v_{z,2p}\;[{\rm km}\,{\rm s}^{-1}]$',
nmid_2p=r'$n_{{\rm H,mid,2p}}$',
Vmid_2p=r'$f_{V,{\rm mid,2p}}$',
mf_c=r'$f_{M,{\rm c}}$',
mf_u=r'$f_{M,{\rm u}}$',
mf_w=r'$f_{M,{\rm w}}$',
)
yscale = dict(Sigma_gas='linear',
Sigma_sp='linear',
Sigma_out='log',
sfr10='log',
sfr40='log',
dt='log',
xi_CR0='log',
Pturb_mid_2p='log',
Pturb_mid='log',
Pth_mid_2p='log',
Pth_mid='log',
H='linear',
H_c='linear',
H_u='linear',
H_w='linear',
H_2p='linear',
v3_2p='linear',
nmid_2p='log',
Vmid_2p='log',
mf_c='log',
mf_u='log',
mf_w='log',
)
if models is None:
models = sa.models
nc = ncol
nr = round(len(column)/nc)
if figsize is None:
figsize=(6*nc, 4*nr)
fig, axes = plt.subplots(nr, nc, figsize=figsize,
constrained_layout=True)
axes = axes.flatten()
for i,mdl in enumerate(models):
s = sa.set_model(mdl)
print(mdl)
h = s.read_hst(**read_hst_kwargs)
for j,(ax,col) in enumerate(zip(axes,column)):
if j == 0:
label = mdl
else:
label = '_nolegend_'
try:
ax.plot(h['time'], h[col], c=c[i], lw=lw[i], label=label)
except KeyError:
pass
for j,(ax,col) in enumerate(zip(axes,column)):
ax.set(xlabel=r'${\rm time}\,[{\rm Myr}]$', ylabel=ylabel[col],
yscale=yscale[col], ylim=ylim[col])
if xlim is not None:
ax.set(xlim=xlim)
axes[0].legend(loc='best', fontsize='small')
return fig
def get_snr(sntime,time,tbin='auto',snth=100.):
import xarray as xr
snt = sntime.to_numpy()
t = time.to_numpy()
if tbin == 'auto':
tbin = 0.0
dtbin=0.1
snrmean=0.
while (tbin < 40) & (snrmean < snth):
tbin += dtbin
idx=np.less(snt[np.newaxis,:],t[:,np.newaxis]) & \
np.greater(snt[np.newaxis,:],(t[:,np.newaxis]-tbin))
snr=idx.sum(axis=1)
snrmean=snr.mean()
snr = snr/tbin
else:
idx=np.less(snt[np.newaxis,:],t[:,np.newaxis]) & \
np.greater(snt[np.newaxis,:],(t[:,np.newaxis]-tbin))
snr=idx.sum(axis=1)/tbin
snr=xr.DataArray(snr,coords=[time],dims=['time'])
return snr
| 4,166
|
https://github.com/Andrealr10/gestor/blob/master/application/models/NotificacionModel.php
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
gestor
|
Andrealr10
|
PHP
|
Code
| 122
| 721
|
<?php
class NotificacionModel extends CI_Model
{
function __construct()
{
$this->tabla = "solicitud";
$this->id = "id_solicitud";
}
public function getAll()
{
// return $this->db->get($this->tabla)->result();
$this->db->select('solicitud.*,usuario.username, tipo_solicitud.nombre as tipo');
$this->db->join('usuario', 'usuario.id_usuario = solicitud.id_usuario');
$this->db->join('tipo_solicitud', 'tipo_solicitud.id_tipo_solicitud = solicitud.id_tipo_solicitud');
$this->db->where("solicitud.id_tipo_solicitud = '1'");
$this->db->where('solicitud.estado', 1);
$this->db->order_by('id_solicitud', 'DESC');
return $this->db->get($this->tabla)->result();
}
public function insert($datos)
{
$this->db->insert($this->tabla, $datos);
}
public function getByTipo($tipo)
{
$this->db->select('solicitud.*,usuario.username, tipo_solicitud.nombre as tipo');
$this->db->join('usuario', 'usuario.id_usuario = solicitud.id_usuario');
$this->db->join('tipo_solicitud', 'tipo_solicitud.id_tipo_solicitud = solicitud.id_tipo_solicitud');
$this->db->where('solicitud.id_tipo_solicitud', $tipo);
$this->db->where('solicitud.estado', 1);
return $this->db->get($this->tabla)->result();
}
public function getByEstado($estado)
{
$this->db->select('solicitud.*,usuario.username');
$this->db->join('usuario', 'usuario.id_usuario = solicitud.id_usuario');
$this->db->where('solicitud.estado', $estado);
$this->db->order_by('id_solicitud', 'DESC');
return $this->db->get('solicitud')->result();
}
public function delete($id)
{
$this->db->delete($this->tabla, [$this->id => $id]);
}
public function getById($id)
{
return $this->db->get_where($this->tabla, [$this->id => $id])->row();
}
public function update($data, $id)
{
$this->db->update($this->tabla, $data, [$this->id => $id]);
}
}
| 3,531
|
https://github.com/ldv2001/PrintPrince/blob/master/PrintPrince/PrintPrince/Models/Configuration.cs
|
Github Open Source
|
Open Source
|
MIT, MS-PL
| 2,019
|
PrintPrince
|
ldv2001
|
C#
|
Code
| 131
| 253
|
namespace PrintPrince.Models
{
/// <summary>
/// The model for a configuration.
/// </summary>
/// <remarks>
/// Configurations in Cirrato are settings bound to drivers that can be applied to queues.
/// </remarks>
public class Configuration
{
/// <summary>
/// The name of the configuration.
/// </summary>
/// <remarks>
/// This value is the comment property of the configuration in Cirrato.
/// </remarks>
public string Name { get; set; }
/// <summary>
/// The ID of the configuration in Cirrato.
/// </summary>
public string CirratoID { get; set; }
/// <summary>
/// The name of the driver that the configuration is associated with in Cirrato.
/// </summary>
public string Driver { get; set; }
/// <summary>
/// Creates a new instance of the <see cref="Configuration"/> class.
/// </summary>
public Configuration(){}
}
}
| 12,349
|
https://github.com/Chofito/redux-commons/blob/master/src/orderById.ts
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
redux-commons
|
Chofito
|
TypeScript
|
Code
| 161
| 411
|
import { IdType } from './types';
type OrderByIdConfigurationType = {
fetched?: Array<string>;
replaced?: Array<string>;
idKey?: string;
orderKey?: string;
};
type OrderByIdActionType = {
type: string;
payload: {
order?: Array<IdType>;
};
};
const orderById = (configuration: OrderByIdConfigurationType) => (
state: { [key in IdType]: Array<IdType> } = {},
action: OrderByIdActionType,
): { [key in IdType]: Array<IdType> } => {
const { fetched, replaced, idKey = 'id', orderKey = 'order' } = configuration;
const { payload } = action;
if (fetched != null && fetched.includes(action.type)) {
const order = payload[orderKey];
if (order && order.constructor === Array) {
const objectId = payload[idKey];
const originalOrder = state[objectId] || [];
const stateSet = new Set(originalOrder);
const difference = order.filter(id => !stateSet.has(id));
return {
...state,
[objectId]: [...originalOrder, ...difference],
};
}
}
if (replaced != null && replaced.includes(action.type)) {
const order = payload[orderKey];
if (order && order.constructor === Array) {
const objectId = payload[idKey];
return {
...state,
[objectId]: order,
};
}
}
return state;
};
export default orderById;
| 44,170
|
https://github.com/Souqalmal/kongfig/blob/master/test/apis.js
|
Github Open Source
|
Open Source
|
MIT
| null |
kongfig
|
Souqalmal
|
JavaScript
|
Code
| 369
| 1,248
|
import expect from 'expect.js';
import {apis, plugins} from '../src/core.js';
import {
noop,
createApi,
removeApi,
updateApi,
addApiPlugin,
removeApiPlugin,
updateApiPlugin
} from '../src/actions.js';
describe("apis", () => {
it("should add new api", () => {
var actual = apis([{
"ensure": "present",
"name": "leads",
"attributes": {
"upstream_url": "bar"
}
}])
.map(x => x({hasApi: () => false}));
expect(actual).to.be.eql([
createApi('leads', {upstream_url: "bar"})
]);
});
it("should remove api", () => {
var actual = apis([{
"name": "leads",
"ensure": "removed",
"attributes": {
"upstream_url": "bar"
}
}])
.map(x => x({hasApi: () => true}));
expect(actual).to.be.eql([
removeApi('leads')
]);
});
it("should do no op if api is already removed", () => {
var actual = apis([{
"name": "leads",
"ensure": "removed",
"attributes": {
"upstream_url": "bar"
}
}])
.map(x => x({hasApi: () => false}));
expect(actual).to.be.eql([
noop()
]);
});
it("should update api", () => {
var actual = apis([{
"ensure": "present",
"name": "leads",
"attributes": {
"upstream_url": "bar"
}
}])
.map(x => x({hasApi: () => true, isApiUpToDate: () => false}));
expect(actual).to.be.eql([
updateApi('leads', {upstream_url: "bar"})
]);
});
it("should validate ensure enum", () => {
expect(() => apis([{
"ensure": "not-valid",
"name": "leads"
}])).to.throwException(/Invalid ensure/);
});
it('should add api with plugins', () => {
var actual = apis([{
"ensure": "present",
"name": "leads",
"attributes": {
"upstream_url": "bar"
},
'plugins': [{
"name": 'cors',
"ensure": "present",
'attributes': {
'config.foo': "bar"
}
}]
}]).map(x => x({
hasApi: () => false,
hasPlugin: () => false,
}));
expect(actual).to.be.eql([
createApi('leads', {upstream_url: "bar"}),
addApiPlugin('leads', 'cors', {'config.foo': "bar"})
]);
});
describe("plugins", () => {
it("should add a plugin to an api", () => {
var actual = plugins(
'leads', [{
"name": "cors",
'attributes': {
"config.foo": 'bar'
}}]
).map(x => x({hasPlugin: () => false}));
expect(actual).to.be.eql([
addApiPlugin('leads', 'cors', {"config.foo": 'bar'})
]);
});
it("should remove api plugin", () => {
var actual = plugins(
'leads', [{
"name": "cors",
"ensure": "removed"}]
).map(x => x({
hasPlugin: () => true,
getPluginId: () => 123
}));
expect(actual).to.be.eql([
removeApiPlugin('leads', 123)
]);
});
it('should update api plugin', () => {
var actual = plugins(
'leads', [{
'name': 'cors',
'attributes': {
'config.foo': 'bar'
}}]
).map(x => x({
hasPlugin: () => true,
getPluginId: () => 123,
isApiPluginUpToDate: () => false
}));
expect(actual).to.be.eql([
updateApiPlugin('leads', 123, {'config.foo': 'bar'})
])
});
it("should validate ensure enum", () => {
expect(() => plugins("leads", [{
"ensure": "not-valid",
"name": "leads"
}])).to.throwException(/Invalid ensure/);
});
});
});
| 41,957
|
https://github.com/sameer79/streamline/blob/master/streams/common/src/main/java/com/hortonworks/streamline/streams/common/event/tree/EventInformationTreeNode.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,022
|
streamline
|
sameer79
|
Java
|
Code
| 153
| 353
|
/**
* Copyright 2017 Hortonworks.
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
package com.hortonworks.streamline.streams.common.event.tree;
import com.hortonworks.streamline.streams.common.event.EventInformation;
import java.util.ArrayList;
import java.util.List;
public class EventInformationTreeNode {
private final EventInformation eventInformation;
private final List<EventInformationTreeNode> children;
public EventInformationTreeNode(EventInformation eventInformation) {
this.eventInformation = eventInformation;
this.children = new ArrayList<>();
}
public EventInformation getEventInformation() {
return eventInformation;
}
public void addChild(EventInformationTreeNode child) {
this.children.add(child);
}
public List<EventInformationTreeNode> getChildren() {
return children;
}
}
| 35,354
|
https://github.com/Ubivator/simple-crawler-java-/blob/master/src/main/java/com/soulgalore/crawler/guice/ExecutorServiceProvider.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
simple-crawler-java-
|
Ubivator
|
Java
|
Code
| 198
| 472
|
/******************************************************
* Web crawler
*
*
* Copyright (C) 2012 by Peter Hedenskog (http://peterhedenskog.com)
*
******************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*
*******************************************************
*/
package com.soulgalore.crawler.guice;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.name.Named;
/**
* Provide a Executor service.
*
*/
public class ExecutorServiceProvider implements Provider<ExecutorService> {
/**
* The number of threads used in this executor service.
*/
private final int nrOfThreads;
/**
* Create a new ExecutorServiceProvider.
*
* @param maxNrOfThreads the number of thread in this executor.
*/
@Inject
public ExecutorServiceProvider(
@Named("com.soulgalore.crawler.threadsinworkingpool") int maxNrOfThreads) {
nrOfThreads = maxNrOfThreads;
}
/**
* Get the service.
*
* @return the executor.
*/
public ExecutorService get() {
return Executors.newFixedThreadPool(nrOfThreads);
}
}
| 28,893
|
https://github.com/microsoft/fhir-server/blob/master/src/Microsoft.Health.Fhir.SqlServer/Features/Search/ContinuationToken.cs
|
Github Open Source
|
Open Source
|
MIT, LicenseRef-scancode-generic-cla
| 2,023
|
fhir-server
|
microsoft
|
C#
|
Code
| 281
| 736
|
// -------------------------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// -------------------------------------------------------------------------------------------------
using System;
using System.Globalization;
using System.Text.Json;
namespace Microsoft.Health.Fhir.SqlServer.Features.Search
{
/// <summary>
/// Represents the search continuation token.
/// </summary>
public class ContinuationToken
{
// the token is an array.
private object[] _tokens;
private static readonly JsonSerializerOptions Options = new JsonSerializerOptions() { Converters = { new ContinuationTokenConverter() } };
public ContinuationToken(object[] tokens)
{
_tokens = tokens;
}
public long ResourceSurrogateId
{
get
{
return (long)_tokens[^1];
}
set
{
_tokens[^1] = value;
}
}
public short? ResourceTypeId
{
get
{
if (_tokens.Length < 2)
{
return null;
}
return _tokens[^2] switch
{
short s => s,
long l => (short)l, // deserialization from JSON creates longs
_ => null,
};
}
set
{
_tokens[^2] = value;
}
}
// Currently only a single sort is implemented
public string SortValue
{
get
{
return _tokens.Length > 1 ? _tokens[0] as string : null;
}
}
public string ToJson()
{
return JsonSerializer.Serialize(_tokens);
}
public override string ToString()
{
return ToJson();
}
public static ContinuationToken FromString(string json)
{
if (json == null)
{
return null;
}
if (long.TryParse(json, NumberStyles.None, CultureInfo.InvariantCulture, out var sid))
{
return new ContinuationToken(new object[] { sid });
}
try
{
object[] result = JsonSerializer.Deserialize<object[]>(json, Options);
return new ContinuationToken(result);
}
catch (JsonException)
{
return null;
}
}
private class ContinuationTokenConverter : System.Text.Json.Serialization.JsonConverter<object>
{
public override object Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) => reader.TokenType switch
{
JsonTokenType.String => reader.GetString(),
JsonTokenType.Number => reader.GetInt64(),
_ => throw new NotSupportedException(),
};
public override void Write(Utf8JsonWriter writer, object value, JsonSerializerOptions options) => throw new NotImplementedException();
}
}
}
| 7,260
|
https://github.com/canonn-science/CanonnApi/blob/master/CanonnApi.Backend/CanonnApi.Web/Services/RemoteApis/IEdsmService.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,017
|
CanonnApi
|
canonn-science
|
C#
|
Code
| 33
| 136
|
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using CanonnApi.Web.DatabaseModels;
namespace CanonnApi.Web.Services.RemoteApis
{
public interface IEdsmService
{
Task<IEnumerable<(DatabaseModels.System System, bool Updated, string ErrorMessage)>> FetchSystemIds(IEnumerable<DatabaseModels.System> systems);
Task<IEnumerable<(Body Body, Boolean Updated, string ErrorMessage)>> FetchBodyIds(IEnumerable<Body> bodies);
}
}
| 50,106
|
https://github.com/monome/aleph/blob/master/modules/analyser/params.c
|
Github Open Source
|
Open Source
|
Unlicense
| 2,018
|
aleph
|
monome
|
C
|
Code
| 152
| 881
|
#include <string.h>
#include "module.h"
#include "params.h"
extern void fill_param_desc(ParamDesc* desc) {
strcpy(desc[eParam_linAttack].label, "linAttack");
desc[eParam_linAttack].type = eParamTypeFix;
desc[eParam_linAttack].min = FR32_MAX / 48 / 1000;
desc[eParam_linAttack].max = FR32_MAX / 48;
desc[eParam_linAttack].radix = 16;
strcpy(desc[eParam_linDecay].label, "linDecay");
desc[eParam_linDecay].type = eParamTypeFix;
desc[eParam_linDecay].min = FR32_MAX / 48 / 1000;
desc[eParam_linDecay].max = FR32_MAX / 48;
desc[eParam_linDecay].radix = 16;
strcpy(desc[eParam_logAttack].label, "logAttack");
desc[eParam_logAttack].type = eParamTypeFix;
desc[eParam_logAttack].min = 268434;
desc[eParam_logAttack].max = 268434000;
desc[eParam_logAttack].radix = 16;
strcpy(desc[eParam_logDecay].label, "logDecay");
desc[eParam_logDecay].type = eParamTypeFix;
desc[eParam_logDecay].min = 268434;
desc[eParam_logDecay].max = 268434000;
desc[eParam_logDecay].radix = 16;
strcpy(desc[eParam_linEnv].label, "linEnv");
desc[eParam_linEnv].type = eParamTypeFix;
desc[eParam_linEnv].min = 0x00000000;
desc[eParam_linEnv].max = FR32_MAX;
desc[eParam_linEnv].radix = 16;
strcpy(desc[eParam_logEnv].label, "logEnv");
desc[eParam_logEnv].type = eParamTypeFix;
desc[eParam_logEnv].min = 0x00000000;
desc[eParam_logEnv].max = FR32_MAX;
desc[eParam_logEnv].radix = 16;
strcpy(desc[eParam_pitch].label, "pitch");
desc[eParam_pitch].type = eParamTypeFix;
desc[eParam_pitch].min = 0x00000000;
desc[eParam_pitch].max = FR32_MAX;
desc[eParam_pitch].radix = 16;
strcpy(desc[eParam_cvVal3].label, "cv3");
desc[eParam_cvVal3].type = eParamTypeFix;
desc[eParam_cvVal3].min = 0x00000000;
desc[eParam_cvVal3].max = PARAM_DAC_MAX;
desc[eParam_cvVal3].radix = PARAM_DAC_RADIX;
strcpy(desc[eParam_cvSlew3].label, "cvSlew3");
desc[eParam_cvSlew3].type = eParamTypeIntegrator;
desc[eParam_cvSlew3].min = 0x00000000;
desc[eParam_cvSlew3].max = 0x7fffffff;
desc[eParam_cvSlew3].radix = 32;
}
// EOF
| 40,585
|
https://github.com/whigg/matlab-image-class/blob/master/src/@Image/write.m
|
Github Open Source
|
Open Source
|
BSD-2-Clause
| 2,019
|
matlab-image-class
|
whigg
|
MATLAB
|
Code
| 90
| 210
|
function write(this, filename, varargin)
%WRITE Write image into specified file
%
% output = write(input)
%
% Example
% % read a color image and write a new image
% img = Image.read('peppers.png');
% img2 = flip(img, 1);
% write(img2, 'colorImage.tif');
%
% See also
% Image/read
%
% ------
% Author: David Legland
% e-mail: david.legland@inra.fr
% Created: 2011-06-14, using Matlab 7.9.0.529 (R2009b)
% Copyright 2011 INRA - Cepia Software Platform.
% assumes format can be managed by Matlab Image Processing
imwrite(permute(this.data, [2 1 4 3 5]), filename, varargin{:});
| 37,578
|
https://github.com/teresalazar13/FAWOS/blob/master/code/randomresampling/random_undersamplor.py
|
Github Open Source
|
Open Source
|
CC-BY-4.0
| null |
FAWOS
|
teresalazar13
|
Python
|
Code
| 323
| 1,529
|
import itertools
import numpy as np
import pandas as pd
from typing import List
import random
from code.models.dataset import Dataset
from code.models.SensitiveClass import SensitiveClass
class DatapointsToUndersampleRU:
def __init__(self, n_times_to_undersample: int, df: pd.DataFrame) -> None:
self.n_times_to_undersample = n_times_to_undersample
self.df = df
def undersample(dataset: Dataset,
datapoints_to_undersample: DatapointsToUndersampleRU):
df = dataset.get_train_dataset()
random.seed(dataset.seed)
np.random.seed(dataset.seed)
for i in range(datapoints_to_undersample.n_times_to_undersample):
random_datapoint_to_remove = random.choice(datapoints_to_undersample.df.index) # choose random
# removes from dataframe
df = df[df.index != random_datapoint_to_remove]
# updates
datapoints_to_undersample.df = datapoints_to_undersample.df[datapoints_to_undersample.df.index != random_datapoint_to_remove]
# save new dataset
filename = dataset.get_random_undersampled_dataset_filename()
save_dataset(df, filename)
def save_dataset(dataset: pd.DataFrame, filename: str):
f = open(filename, "w+")
f.write(dataset.to_csv(index=False))
f.close()
def get_datapoints_from_class_to_undersample_list(dataset: Dataset) -> DatapointsToUndersampleRU:
mappings = dataset.get_dataset_mappings()
inversed_mappings = dataset.get_dataset_mappings_inverted()
target_class = dataset.target_class.name
positive_class = mappings[target_class][dataset.target_class.positive_class]
negative_class = mappings[target_class][dataset.target_class.negative_class]
df = dataset.get_train_dataset()
unprivileged_classes_combs = get_combinations_sensitive_attributes(dataset.sensitive_classes, mappings)
df_positive_priv, df_negative_priv, count_positive_privileged, count_negative_privileged = get_privileged_classes_counts(df, dataset.sensitive_classes,
target_class, positive_class,
negative_class, mappings)
min_n_times_to_undersample = 10000
for comb in unprivileged_classes_combs:
df_positive = df.copy(deep=True)
df_negative = df.copy(deep=True)
classes = {target_class: [dataset.target_class.positive_class]}
for class_name, class_values in comb:
df_positive = df_positive[(df_positive[class_name].isin(class_values)) & (df_positive[target_class] == positive_class)]
df_negative = df_negative[(df_negative[class_name].isin(class_values)) & (df_negative[target_class] == negative_class)]
classes[class_name] = [inversed_mappings[class_name][v] for v in class_values]
count_positive_unprivileged = len(df_positive)
count_negative_unprivileged = len(df_negative)
desired_count_positive_privileged = count_positive_unprivileged * count_negative_privileged / count_negative_unprivileged
n_times_to_undersample = int(count_positive_privileged - desired_count_positive_privileged)
print("Difference in class " + str(classes) + " is " + str(n_times_to_undersample))
effect = count_negative_unprivileged/count_positive_unprivileged - count_negative_privileged/count_positive_privileged
print("Effect of class " + str(classes) + " is " + str(effect))
if n_times_to_undersample < min_n_times_to_undersample and n_times_to_undersample != 0:
min_n_times_to_undersample = n_times_to_undersample
return DatapointsToUndersampleRU(min_n_times_to_undersample, df_positive_priv)
def get_privileged_classes_counts(df, sensitive_classes: List[SensitiveClass], target_class, positive_class,
negative_class, mappings):
df_positive = df.copy(deep=True)
df_negative = df.copy(deep=True)
for sensitive_class in sensitive_classes:
class_name = sensitive_class.name
class_values = [mappings[class_name][v] for v in sensitive_class.privileged_classes]
df_positive = df_positive[(df_positive[class_name].isin(class_values)) & (df_positive[target_class] == positive_class)]
df_negative = df_negative[(df_negative[class_name].isin(class_values)) & (df_negative[target_class] == negative_class)]
return df_positive, df_negative, len(df_positive), len(df_negative)
def get_combinations_sensitive_attributes(sensitive_classes: List[SensitiveClass], mappings):
classes_list = []
for sensitive_class in sensitive_classes:
classes = []
class_name = sensitive_class.name
priv_maps = [mappings[class_name][v] for v in sensitive_class.privileged_classes]
classes.append((class_name, priv_maps))
unpriv_maps = [mappings[class_name][v] for v in sensitive_class.unprivileged_classes]
classes.append((class_name, unpriv_maps))
classes_list.append(classes)
return itertools.product(*classes_list)
| 23,735
|
https://github.com/koushikr/ranger-1/blob/master/ranger-zk-client/src/main/java/io/appform/ranger/client/zk/ShardedRangerZKHubClient.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
ranger-1
|
koushikr
|
Java
|
Code
| 168
| 646
|
/*
* Copyright 2015 Flipkart Internet Pvt. Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.appform.ranger.client.zk;
import io.appform.ranger.core.finder.nodeselector.RoundRobinServiceNodeSelector;
import io.appform.ranger.core.finder.serviceregistry.MapBasedServiceRegistry;
import io.appform.ranger.core.finder.shardselector.MatchingShardSelector;
import io.appform.ranger.core.finderhub.ServiceFinderFactory;
import io.appform.ranger.core.model.ServiceNodeSelector;
import io.appform.ranger.core.model.ShardSelector;
import io.appform.ranger.zookeeper.serde.ZkNodeDataDeserializer;
import io.appform.ranger.zookeeper.servicefinderhub.ZkShardedServiceFinderFactory;
import lombok.Builder;
import lombok.experimental.SuperBuilder;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@SuperBuilder
public class ShardedRangerZKHubClient<T>
extends AbstractRangerZKHubClient<T, MapBasedServiceRegistry<T>, ZkNodeDataDeserializer<T>> {
@Builder.Default
private final ShardSelector<T, MapBasedServiceRegistry<T>> shardSelector = new MatchingShardSelector<>();
@Builder.Default
private final ServiceNodeSelector<T> nodeSelector = new RoundRobinServiceNodeSelector<>();
@Override
protected ServiceFinderFactory<T, MapBasedServiceRegistry<T>> getFinderFactory() {
return ZkShardedServiceFinderFactory.<T>builder()
.curatorFramework(getCuratorFramework())
.connectionString(getConnectionString())
.nodeRefreshIntervalMs(getNodeRefreshTimeMs())
.disablePushUpdaters(isDisablePushUpdaters())
.deserializer(getDeserializer())
.shardSelector(shardSelector)
.nodeSelector(nodeSelector)
.build();
}
}
| 1,306
|
https://github.com/georgiangelov2000/React-Js-Development/blob/master/Fundamentals Project HOOKS,ROUTES,API/9.restfull-api-users/src/Components/Users.js
|
Github Open Source
|
Open Source
|
MIT
| null |
React-Js-Development
|
georgiangelov2000
|
JavaScript
|
Code
| 46
| 186
|
import React from "react";
const Users = ({ users }) => {
return (
<div>
<div>
<center>
<h1>Contact List</h1>
</center>
{users.map((user, index) => (
<div key={index}>
<div className="card-body">
<h5 className="card-title">{user.name}</h5>
<h6 className="card-subtitle mb-2 text-muted">{user.email}</h6>
<p className="card-text">{user.company.catchPhrase}</p>
</div>
</div>
))}
</div>
</div>
);
};
export default Users;
| 1,320
|
https://github.com/CyberCookie/siegel/blob/master/client_core/ui/children.tsx
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
siegel
|
CyberCookie
|
TypeScript
|
Code
| 41
| 101
|
import React from 'react'
import type { ComponentAttributes } from './ui_utils'
type ThemeWithChildren = {
children: string
}
function addChildren(componentRootProps: ComponentAttributes, theme: ThemeWithChildren) {
if (componentRootProps.children) {
return <div className={ theme.children } children={ componentRootProps.children } />
}
}
export default addChildren
| 237
|
https://github.com/gobeam/truthy-react-frontend/blob/master/app/containers/EmailTemplate/index.js
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
truthy-react-frontend
|
gobeam
|
JavaScript
|
Code
| 349
| 1,299
|
/**
*
* EmailTemplate
*
*/
import React, { useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { useInjectSaga } from 'utils/injectSaga';
import { useInjectReducer } from 'utils/injectReducer';
import reducer from 'containers/EmailTemplate/reducer';
import { createStructuredSelector } from 'reselect';
import saga from 'containers/EmailTemplate/saga';
import Helmet from 'react-helmet';
import { FormattedMessage } from 'react-intl';
import messages from 'containers/EmailTemplate/messages';
import {
makeIsLoadingSelector,
makeLimitSelector,
makePageNumberSelector,
} from 'containers/EmailTemplate/selectors';
import SearchInput from 'components/SearchInput';
import CreateEmailTemplateModal from 'containers/EmailTemplate/createEmailTemplateModal';
import EditEmailTemplateModal from 'containers/EmailTemplate/editEmailTemplateModal';
import EmailTemplateTable from 'containers/EmailTemplate/emailTemplateTable';
import {
queryTemplateAction,
deleteItemByIdAction,
setFormMethodAction,
setIdAction,
setKeywordsAction,
} from 'containers/EmailTemplate/actions';
import { POST, PUT } from 'utils/constants';
import { Breadcrumb, Button } from 'antd';
import { NavLink } from 'react-router-dom';
import { makeLoggedInUserSelector } from 'containers/App/selectors';
import { checkPermissionForComponent } from 'utils/permission';
import { PlusOutlined } from '@ant-design/icons';
const key = 'emailTemplate';
const stateSelector = createStructuredSelector({
pageNumber: makePageNumberSelector(),
limit: makeLimitSelector(),
isLoading: makeIsLoadingSelector(),
user: makeLoggedInUserSelector(),
});
const CreateRoutePermission = {
resource: 'emailTemplates',
method: POST,
path: '/email-templates',
};
const EmailTemplate = () => {
const dispatch = useDispatch();
useInjectReducer({ key, reducer });
useInjectSaga({ key, saga });
const [createEmailTemplate, setCreateEmailTemplate] = useState(false);
const [editEmailTemplate, setEditEmailTemplate] = useState(false);
const { pageNumber, limit, isLoading, user } = useSelector(stateSelector);
const loadTemplates = () => dispatch(queryTemplateAction());
const onchangeFormMethod = (formMethod) =>
dispatch(setFormMethodAction(formMethod));
const onKeywordChange = (keywords) =>
dispatch(setKeywordsAction(keywords)) && loadTemplates();
const onCreate = () => {
onchangeFormMethod(POST);
setCreateEmailTemplate(true);
};
const onEdit = (updateId) => {
dispatch(setIdAction(updateId));
onchangeFormMethod(PUT);
setEditEmailTemplate(true);
};
const onDelete = (deleteId) => dispatch(deleteItemByIdAction(deleteId));
useEffect(() => {
loadTemplates();
}, [pageNumber, limit]);
return (
<>
<FormattedMessage {...messages.helmetTitle}>
{(title) => (
<Helmet>
<title>{title}</title>
</Helmet>
)}
</FormattedMessage>
<div className="truthy-breadcrumb">
<h2>
<FormattedMessage {...messages.listTitle} />
</h2>
<Breadcrumb>
<Breadcrumb.Item>
<NavLink to="/" className="links">
<FormattedMessage {...messages.dashboardTitle} />
</NavLink>
</Breadcrumb.Item>
<Breadcrumb.Item className="current active">
<FormattedMessage {...messages.listTitle} />
</Breadcrumb.Item>
</Breadcrumb>
</div>
<div className="truthy-content-header">
<div className="d-flex">
<div>
{checkPermissionForComponent(user.role, CreateRoutePermission) ? (
<Button type="primary" onClick={onCreate}>
<PlusOutlined /> <FormattedMessage {...messages.addLabel} />
</Button>
) : null}
</div>
<div className="d-flex ml-auto search-wrap">
<SearchInput isLoading={isLoading} onSearch={onKeywordChange} />
</div>
</div>
</div>
<div className="truthy-table ">
<EmailTemplateTable
onCreate={onCreate}
onEdit={onEdit}
onDelete={onDelete}
/>
</div>
<CreateEmailTemplateModal
visible={createEmailTemplate}
onCancel={() => setCreateEmailTemplate(false)}
/>
<EditEmailTemplateModal
visible={editEmailTemplate}
onCancel={() => setEditEmailTemplate(false)}
/>
</>
);
};
export default EmailTemplate;
| 46,033
|
https://github.com/dKatechev/vividus/blob/master/vividus-plugin-mobile-app/src/main/java/org/vividus/bdd/mobileapp/steps/DeviceSteps.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
vividus
|
dKatechev
|
Java
|
Code
| 197
| 506
|
/*
* Copyright 2019-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.vividus.bdd.mobileapp.steps;
import java.nio.file.Paths;
import org.apache.commons.io.FilenameUtils;
import org.jbehave.core.annotations.When;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.vividus.mobileapp.action.DeviceActions;
public class DeviceSteps
{
private static final Logger LOGGER = LoggerFactory.getLogger(DeviceSteps.class);
private final DeviceActions deviceActions;
private final String folderForFileUpload;
public DeviceSteps(String folderForFileUpload, DeviceActions deviceActions)
{
this.folderForFileUpload = folderForFileUpload;
this.deviceActions = deviceActions;
}
/**
* Uploads a file by <b>filePath</b> to a device
* @param filePath path of a file to upload
*/
@When("I upload file `$filePath` to device")
public void uploadFileToDevice(String filePath)
{
LOGGER.atInfo().addArgument(filePath)
.addArgument(folderForFileUpload)
.log("Uploading file '{}' to a device at '{}' folder");
String fileName = FilenameUtils.getName(filePath);
deviceActions.pushFile(Paths.get(folderForFileUpload, fileName).toString(), filePath);
}
}
| 20,290
|
https://github.com/igorski/zMVC/blob/master/example/Gruntfile.js
|
Github Open Source
|
Open Source
|
MIT
| null |
zMVC
|
igorski
|
JavaScript
|
Code
| 179
| 503
|
module.exports = function( grunt )
{
grunt.initConfig(
{
// copies resource files to temporary dist folder
copy : {
dev : {
files : [
{
expand : true,
cwd : "resources/",
src : [ "**/*" ],
dest : "dist/"
}
]
}
},
// resolves the commonJS dependencies for usage in the browser
browserify : {
dev : {
options: {
browserifyOptions: {
debug: true
}
},
files: {
'dist/app.js' : [ 'src/**/*.js' ]
}
}
},
// synchronized the browser to refresh when changing source files
browserSync :
{
bsFiles: {
src: [
'dist/**/*'
]
},
options: {
watchTask: true,
server: {
baseDir: 'dist/',
index: 'index.html'
}
}
},
// watches changes to the source code for running the browserify task automatically
watch : {
scripts : {
files: "src/**/*.js",
tasks: [ "browserify" ]
},
resources : {
files: "resources/**/*",
tasks: [ "copy" ]
}
}
});
grunt.loadNpmTasks( "grunt-browserify" );
grunt.loadNpmTasks( "grunt-contrib-copy" );
grunt.loadNpmTasks( "grunt-browser-sync" );
grunt.loadNpmTasks( "grunt-contrib-watch" );
grunt.registerTask( "start", function()
{
grunt.task.run( "copy" );
grunt.task.run( "browserify" );
grunt.task.run( "browserSync" );
grunt.task.run( "watch" );
});
};
| 33,969
|
https://github.com/martindilling/spires/blob/master/src/Irc/Client.php
|
Github Open Source
|
Open Source
|
MIT
| 2,016
|
spires
|
martindilling
|
PHP
|
Code
| 331
| 1,225
|
<?php
declare(strict_types=1);
namespace Spires\Irc;
use Spires\Contracts\Core\Core;
use Spires\Core\Dispatcher;
use Spires\Irc\Message\Inbound\RawMessage;
class Client
{
/**
* @var Core
*/
private $core;
/**
* @var Connection
*/
private $connection;
/**
* @var User
*/
private $user;
/**
* @var resource
*/
private $socket;
/**
* @var Dispatcher
*/
private $dispatcher;
public function __construct(Core $core, Connection $connection, User $user, Dispatcher $dispatcher)
{
$this->core = $core;
$this->connection = $connection;
$this->user = $user;
$this->dispatcher = $dispatcher;
}
public function connection() : Connection
{
return $this->connection;
}
public function channel() : string
{
return $this->connection()->channel();
}
public function user() : User
{
return $this->user;
}
public function socket() : resource
{
return $this->socket;
}
public function connect()
{
$this->logHeading('Spires connecting');
$this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_connect(
$this->socket,
$this->connection()->server(),
$this->connection()->port()
);
$this->write("NICK {$this->user()->nickname()}");
$this->write("USER {$this->user()->username()} {$this->user()->usermode()} * :{$this->user()->realname()}");
$this->write("JOIN {$this->connection()->channel()}");
}
public function read()
{
return socket_read($this->socket, 2048, PHP_NORMAL_READ);
}
public function write(string $response)
{
$response = trim($response);
$this->logWrite($response);
return socket_write($this->socket, $response . "\r\n");
}
public function logCore(Core $core)
{
$this->logHeading('Spires booted');
$this->logDebug("Providers:");
foreach ($core->getLoadedProviders() as $provider => $active) {
$this->logDebug(" - " . $provider);
}
$this->logDebug("Plugins:");
foreach ($core->getPlugins() as $name => $plugin) {
$this->logDebug(" - " . $name);
}
}
public function log(string $title, string $string)
{
$time = date('H:i:s');
$title = str_pad($title, 8, ' ', STR_PAD_RIGHT);
fwrite(STDOUT, "[{$time}|{$title}]: " . $string . "\n");
}
public function logNewLine()
{
fwrite(STDOUT, "\n");
}
public function logLine()
{
fwrite(STDOUT, str_repeat('_', 80) . "\n");
}
public function logHeading(string $title)
{
$title = str_repeat('=', 5) . ' ' . $title . ' ';
$title = str_pad($title, 60, '=', STR_PAD_RIGHT);
$line = str_repeat('=', 60);
$this->logNewLine();
$this->log('debug', $line);
$this->log('debug', $title);
$this->log('debug', $line);
$this->logNewLine();
}
public function logDebug(string $string)
{
$this->log('debug', $string);
}
public function logRead(string $string)
{
$this->log('read', $string);
}
public function logWrite(string $string)
{
$this->log('write', $string);
}
public function run()
{
$this->logHeading('Spires listening');
$parser = new Parser();
while ($raw = $this->read()) {
if (!$raw = trim($raw)) {
continue;
}
$this->logLine();
$this->logRead($raw);
$message = RawMessage::fromArray(
$parser->parse($raw . "\r\n")
);
$this->dispatcher->dispatch($message);
}
}
}
| 25,100
|
https://github.com/fi1a/collection/blob/master/tests/DataType/MapArrayObjectTest.php
|
Github Open Source
|
Open Source
|
MIT
| 2,023
|
collection
|
fi1a
|
PHP
|
Code
| 2,105
| 7,501
|
<?php
declare(strict_types=1);
namespace Fi1a\Unit\Collection\DataType;
use Fi1a\Collection\DataType\Exception\OutOfBoundsException;
use Fi1a\Collection\DataType\MapArrayObject;
use Fi1a\Collection\DataType\MapArrayObjectInterface;
use Fi1a\Collection\Exception\InvalidArgumentException;
use PHPUnit\Framework\TestCase;
/**
* Объект как массив
*/
class MapArrayObjectTest extends TestCase
{
/**
* Провайдер данных для теста testConstruct
*
* @return mixed[]
*/
public function dataProviderConstruct(): array
{
return [
[null, []],
[[], []],
[[1, 2, 3], [1, 2, 3]],
];
}
/**
* Тестирование инициализации
*
* @param mixed $data
* @param mixed $equal
*
* @dataProvider dataProviderConstruct
*/
public function testConstruct($data, $equal): void
{
$this->assertEquals($equal, (new MapArrayObject($data))->getArrayCopy());
}
/**
* Доступ к объекту как к массиву
*/
public function testOffset(): void
{
$array = new MapArrayObject();
$array[1] = 1;
$this->assertEquals(1, $array[1]);
$this->assertEquals([1 => 1], $array->getArrayCopy());
unset($array[1]);
$array->exchangeArray([0 => 0]);
$this->assertEquals([0 => 0], $array->getArrayCopy());
$this->assertCount(1, $array);
$this->assertTrue(isset($array[0]));
foreach ($array as $ind => $value) {
$this->assertEquals($array[$ind], $value);
}
$array[] = 1;
$this->assertEquals([0 => 0, 1 => 1,], $array->getArrayCopy());
$array['fields'] = [];
$this->assertIsArray($array['fields']);
$array['fields'][] = 1;
$array['fields'][] = 2;
$array['fields'][] = 3;
$this->assertEquals([1, 2, 3], $array['fields']);
$this->assertNull($array[null]);
$array->set(null, 4);
$this->assertEquals(4, $array[null]);
unset($array[null]);
$this->assertNull($array[null]);
}
/**
* Тестирование клонирования объекта
*/
public function testClone(): void
{
$array = new MapArrayObject();
$array[0] = 1;
$array[2] = 2;
$array[3] = 3;
$this->assertCount(3, $array);
$clone = clone $array;
$this->assertCount(3, $clone);
$clone[0] = 4;
$this->assertEquals(4, $clone[0]);
$this->assertEquals(1, $array[0]);
}
/**
* Тестирование метода isEmpty
*/
public function testIsEmpty(): void
{
$array = new MapArrayObject();
$this->assertTrue($array->isEmpty());
$array[] = 1;
$this->assertFalse($array->isEmpty());
}
/**
* Тестирование метода first
*/
public function testFirst(): void
{
$array = new MapArrayObject([1, 2, 3]);
$this->assertEquals(1, $array->first());
}
/**
* Тестирование метода first (исключение при пустых данных)
*/
public function testFirstException(): void
{
$array = new MapArrayObject();
$this->expectException(OutOfBoundsException::class);
$array->first();
}
/**
* Тестирование метода last
*/
public function testLast(): void
{
$array = new MapArrayObject([1, 2, 3]);
$this->assertEquals(3, $array->last());
}
/**
* Тестирование метода first (исключение при пустых данных)
*/
public function testLastException(): void
{
$array = new MapArrayObject();
$this->expectException(OutOfBoundsException::class);
$array->last();
}
/**
* Очистить массив значений
*/
public function testClear(): void
{
$array = new MapArrayObject([1, 2, 3]);
$this->assertEquals(3, $array->count());
$array->clear();
$this->assertEquals(0, $array->count());
$this->assertEquals([], $array->getArrayCopy());
}
/**
* Проверяет, присутствует ли в массиве указанное значение
*/
public function testHasValue(): void
{
$array = new MapArrayObject(['key1' => 1, 'key2' => 2, 'key3' => 3]);
$this->assertTrue($array->hasValue(2));
$this->assertFalse($array->hasValue(4));
$this->assertFalse($array->hasValue(null));
}
/**
* Проверяет, присутствует ли в массиве указанный ключ или индекс
*/
public function testHas(): void
{
$array = new MapArrayObject(['key1' => 1, 'key2' => 2, 'key3' => 3]);
$this->assertTrue($array->has('key1'));
$this->assertFalse($array->has('key4'));
$this->assertFalse($array->has(null));
}
/**
* Возвращает ключи массива
*/
public function testKeys(): void
{
$array = new MapArrayObject(['key1' => 1, 'key2' => 2, 'key3' => 3]);
$this->assertEquals(['key1', 'key2', 'key3'], $array->keys());
}
/**
* Вовзвращает значение по ключу, если значения в массиве нет, то возвращает значение $default
*/
public function testGet(): void
{
$array = new MapArrayObject(['key1' => 1, 'key2' => 2, 'key3' => 3]);
$this->assertEquals(1, $array->get('key1'));
$this->assertNull($array->get('key4'));
$this->assertEquals(4, $array->get('key4', 4));
$this->assertNull($array->get(null));
}
/**
* Устанавливает значение по ключу, если значение уже есть в массиве, возвращает его
*/
public function testPut(): void
{
$array = new MapArrayObject(['key1' => 1, 'key2' => 2, 'key3' => 3]);
$this->assertNull($array->put('key4', 4));
$this->assertEquals(4, $array->put('key4', 5));
$this->assertEquals(5, $array->get('key4'));
$this->assertNull($array->put(null, 6));
$this->assertEquals(6, $array->put(null, 7));
$this->assertEquals(7, $array->get(null));
}
/**
* Устанавливает значение по ключу, если его нет. Возвращает предыдущее значение
*/
public function testPutIfAbsent(): void
{
$array = new MapArrayObject(['key1' => 1, 'key2' => 2, 'key3' => 3]);
$this->assertNull($array->putIfAbsent('key4', 4));
$this->assertEquals(4, $array->putIfAbsent('key4', 5));
$this->assertEquals(4, $array->get('key4'));
$this->assertNull($array->putIfAbsent(null, 5));
$this->assertEquals(5, $array->putIfAbsent(null, 5));
}
/**
* Удаляет элемент по ключу, возвращает удаленное значение
*/
public function testDelete(): void
{
$array = new MapArrayObject(['key1' => 1, 'key2' => 2, 'key3' => 3, null => 5,]);
$this->assertNull($array->delete('key4'));
$this->assertEquals(1, $array->delete('key1'));
$this->assertNull($array->delete('key1'));
$this->assertEquals(5, $array->delete(null));
$this->assertNull($array->delete(null));
}
/**
* Удаляет элемент по ключу, если значение равно переданному. Если элемент удален, возвращает true.
*/
public function testDeleteIf(): void
{
$array = new MapArrayObject(['key1' => 1, 'key2' => 2, 'key3' => 3, null => 5,]);
$this->assertTrue($array->deleteIf('key1', 1));
$this->assertFalse($array->deleteIf('key1', 1));
$this->assertFalse($array->deleteIf('key2', 1));
$this->assertTrue($array->deleteIf(null, 5));
$this->assertFalse($array->deleteIf(null, 5));
}
/**
* Заменяет значение элемента по ключу, только если есть значение. Возвращает предыдущее значение
*/
public function testReplace(): void
{
$array = new MapArrayObject(['key1' => 1, 'key2' => 2, 'key3' => 3, null => 5,]);
$this->assertEquals(1, $array->replace('key1', 4));
$this->assertEquals(4, $array->get('key1'));
$this->assertNull($array->replace('key4', 4));
$this->assertNull($array->get('key4'));
$this->assertEquals(5, $array->replace(null, 6));
}
/**
* Заменяет значение элемента по ключу, только если текущее значение равно $oldValue.
* Если элемент заменен, возвращает true.
*/
public function testReplaceIf(): void
{
$array = new MapArrayObject(['key1' => 1, 'key2' => 2, 'key3' => 3, null => 5]);
$this->assertTrue($array->replaceIf('key1', 1, 4));
$this->assertFalse($array->replaceIf('key1', 1, 4));
$this->assertTrue($array->replaceIf(null, 5, 6));
$this->assertFalse($array->replaceIf(null, 5, 6));
}
/**
* Тестирование метода add массива
*/
public function testAdd(): void
{
$array = new MapArrayObject();
$array->add(1);
$array->add(2);
$array->add(3);
$this->assertEquals([0 => 1, 1 => 2, 2 => 3,], $array->getArrayCopy());
}
/**
* Тестирование метода count массива
*/
public function testCount(): void
{
$array = new MapArrayObject();
$this->assertEquals(0, $array->count());
$array->add(1);
$array->add(2);
$array->add(3);
$this->assertEquals(3, $array->count());
}
/**
* Тестирование метода column массива
*/
public function testColumn(): void
{
$array = new MapArrayObject();
$array->add(['foo' => 1,]);
$array->add(['foo' => 2,]);
$array->add(['foo' => 3,]);
$this->assertEquals([1, 2, 3,], $array->column('foo'));
}
/**
* Тестирование метода sort массива
*/
public function testSort(): void
{
$array = new MapArrayObject();
$array->add(['foo' => 3,]);
$array->add(['foo' => 2,]);
$array->add(['foo' => 1,]);
$sorted = $array->sort('foo', MapArrayObjectInterface::SORT_ASC);
$this->assertEquals([1, 2, 3,], $sorted->column('foo'));
$this->assertEquals([3, 2, 1,], $array->column('foo'));
$sorted = $array->sort('foo', MapArrayObjectInterface::SORT_DESC);
$this->assertEquals([3, 2, 1,], $sorted->column('foo'));
$this->assertEquals([3, 2, 1,], $array->column('foo'));
}
/**
* Исключение при не известном напрмарвлении сортировки
*/
public function testSortOrderException(): void
{
$this->expectException(InvalidArgumentException::class);
$array = new MapArrayObject();
$array->add(['foo' => 3,]);
$array->add(['foo' => 2,]);
$array->add(['foo' => 1,]);
$array->sort('foo', 'unknown');
}
/**
* Фильтрация значений массива
*/
public function testFilter(): void
{
$array = new MapArrayObject();
$array->add(['foo' => 3,]);
$array->add(['foo' => 2,]);
$array->add(['foo' => 1,]);
$filtered = $array->filter(function ($item) {
return $item['foo'] >= 2;
});
$this->assertEquals([['foo' => 3,], ['foo' => 2,]], $filtered->getArrayCopy());
$this->assertEquals([['foo' => 3,], ['foo' => 2,], ['foo' => 1,]], $array->getArrayCopy());
}
/**
* Возвращает массив с элементами у которых значение ключа, свойства или метода равно переданному значению
*/
public function testWhere(): void
{
$array = new MapArrayObject();
$array->add(['foo' => 3,]);
$array->add(['foo' => 2,]);
$array->add(['foo' => 1,]);
$filtered = $array->where('foo', 2);
$this->assertEquals([1 => ['foo' => 2,]], $filtered->getArrayCopy());
}
/**
* Вычисление расхождения
*/
public function testDiff(): void
{
$array1 = new MapArrayObject();
$array1->add(['foo' => 3,]);
$array1->add(['foo' => 2,]);
$array1->add(['foo' => 1,]);
$array2 = new MapArrayObject();
$array2->add(['foo' => 4,]);
$array2->add(['foo' => 2,]);
$array2->add(['foo' => 1,]);
$this->assertEquals([['foo' => 3,], ['foo' => 4,]], $array1->diff($array2)->getArrayCopy());
$this->assertEquals([['foo' => 3,], ['foo' => 2,], ['foo' => 1,]], $array1->getArrayCopy());
$this->assertEquals([['foo' => 4,], ['foo' => 2,], ['foo' => 1,]], $array2->getArrayCopy());
}
/**
* Вычисляет пересечение
*/
public function testIntersect(): void
{
$array1 = new MapArrayObject();
$array1->add(['foo' => 3,]);
$array1->add(['foo' => 2,]);
$array1->add(['foo' => 1,]);
$array2 = new MapArrayObject();
$array2->add(['foo' => 4,]);
$array2->add(['foo' => 2,]);
$array2->add(['foo' => 1,]);
$this->assertEquals(
[1 => ['foo' => 2,], 2 => ['foo' => 1,]],
$array1->intersect($array2)->getArrayCopy()
);
$this->assertEquals(
[['foo' => 3,], ['foo' => 2,], ['foo' => 1,]],
$array1->getArrayCopy()
);
$this->assertEquals(
[['foo' => 4,], ['foo' => 2,], ['foo' => 1,]],
$array2->getArrayCopy()
);
}
/**
* Объединяет элементы с элементами переданной и возвращает новый массив
*/
public function testMerge(): void
{
$array1 = new MapArrayObject();
$array1->add(['foo' => 1,]);
$array2 = new MapArrayObject();
$array2->add(['foo' => 2,]);
$this->assertEquals(
[['foo' => 1,], ['foo' => 2,]],
$array1->merge($array2)->getArrayCopy()
);
$this->assertEquals(
[['foo' => 1,]],
$array1->getArrayCopy()
);
$this->assertEquals(
[['foo' => 2,]],
$array2->getArrayCopy()
);
}
/**
* Сбросить ключи
*/
public function testResetKeys(): void
{
$array = new MapArrayObject();
$array->set(1, ['foo' => 1,]);
$array->set(2, ['foo' => 2,]);
$this->assertEquals([0 => ['foo' => 1,], 1 => ['foo' => 2,]], $array->resetKeys()->getArrayCopy());
}
/**
* Итеративно уменьшает к единственному значению, используя callback-функцию
*/
public function testReduce(): void
{
$array = new MapArrayObject([1, 2, 3]);
$this->assertEquals(6, $array->reduce(function (?int $sum, int $value) {
$sum += $value;
return $sum;
}));
}
/**
* Итеративно уменьшает коллекцию к единственному значению в обратном порядке, используя callback-функцию
*/
public function testReduceRight(): void
{
$array = new MapArrayObject([1, 2, 3]);
$this->assertEquals('321', $array->reduceRight(function (?string $sum, int $value) {
$sum .= $value;
return $sum;
}));
}
/**
* Оборачивает значения и возвращает новую коллекцию
*/
public function testWraps(): void
{
$array = new MapArrayObject([1, 2, 3]);
$this->assertEquals(['"1"', '"2"', '"3"'], $array->wraps('"')->getArrayCopy());
$this->assertEquals(['"1~', '"2~', '"3~'], $array->wraps('"', '~')->getArrayCopy());
}
/**
* Объединяет элементы в строку
*/
public function testJoin(): void
{
$array = new MapArrayObject([1, 2, 3]);
$this->assertEquals('1, 2, 3', $array->join(', '));
}
/**
* Вставить значения
*/
public function testInsert(): void
{
$array = new MapArrayObject([1, 2, 3]);
$array->insert(1, [4, 5]);
$this->assertEquals([1, 4, 5, 2, 3], $array->getArrayCopy());
$array = new MapArrayObject([1, 2, 3]);
$array->insert(4, [4, 5]);
$this->assertEquals([1, 2, 3, 4, 5,], $array->getArrayCopy());
$array = new MapArrayObject([1, 2, 3]);
$array->insert(0, [4, 5]);
$this->assertEquals([4, 5, 1, 2, 3,], $array->getArrayCopy());
}
/**
* Возвращает ключ первого элемента
*/
public function testFirstKey(): void
{
$array = new MapArrayObject([1, 2, 3]);
$this->assertEquals(0, $array->firstKey());
$array = new MapArrayObject(['foo' => 'foo', 'bar' => 'bar']);
$this->assertEquals('foo', $array->firstKey());
$array = new MapArrayObject([]);
$this->assertFalse($array->firstKey());
}
/**
* Возвращает ключ последнего элемента
*/
public function testLastKey(): void
{
$array = new MapArrayObject([1, 2, 3]);
$this->assertEquals(2, $array->lastKey());
$array = new MapArrayObject(['foo' => 'foo', 'bar' => 'bar']);
$this->assertEquals('bar', $array->lastKey());
$array = new MapArrayObject([]);
$this->assertFalse($array->lastKey());
}
/**
* Переключает значения
*/
public function testToggleValue(): void
{
$array = new MapArrayObject(['foo' => 'foo']);
$array->toggleValue('foo', 'foo', 'bar');
$this->assertEquals(['foo' => 'bar'], $array->getArrayCopy());
$array->toggleValue('foo', 'foo', 'bar');
$this->assertEquals(['foo' => 'foo'], $array->getArrayCopy());
$array = new MapArrayObject(['' => 'foo']);
$array->toggleValue(null, 'foo', 'bar');
$this->assertEquals(['' => 'bar'], $array->getArrayCopy());
$array->toggleValue(null, 'foo', 'bar');
$this->assertEquals(['' => 'foo'], $array->getArrayCopy());
}
/**
* Возвращает true, если все элементы удовлетворяют условию
*/
public function testEvery(): void
{
$array = new MapArrayObject([1, 2, 3]);
$this->assertFalse($array->every(function (int $value, $index) {
return $value > 2;
}));
$array = new MapArrayObject([3, 4, 5]);
$this->assertTrue($array->every(function (int $value, $index) {
return $value > 2;
}));
}
/**
* Возвращает коллекцию без элементов удовлетворяющих условию
*/
public function testWithout(): void
{
$array = new MapArrayObject([1, 2, 3]);
$without = $array->without(function (int $value, $index) {
return $value > 2;
});
$this->assertEquals([1], $without->getArrayCopy());
}
/**
* Возвращает коллекцию без элементов удовлетворяющих условию
*/
public function testWith(): void
{
$array = new MapArrayObject([1, 2, 3]);
$with = $array->with(function (int $value, $index) {
return $value > 2;
});
$with->resetKeys();
$this->assertEquals([3], $with->getArrayCopy());
}
/**
* Возвращает коллекцию, опуская заданное количество элементов с начала
*/
public function testDrop(): void
{
$array = new MapArrayObject([1, 2, 3]);
$this->assertEquals([2, 3], $array->drop(1)->resetKeys()->getArrayCopy());
}
/**
* Возвращает коллекцию, опуская заданное количество элементов с начала (исключение)
*/
public function testDropException(): void
{
$this->expectException(InvalidArgumentException::class);
$array = new MapArrayObject([1, 2, 3]);
$array->drop(0);
}
/**
* Возвращает коллекцию, опуская заданное количество элементов с конца
*/
public function testDropRight(): void
{
$array = new MapArrayObject([1, 2, 3]);
$this->assertEquals([1, 2], $array->dropRight(1)->resetKeys()->getArrayCopy());
}
/**
* Возвращает коллекцию, опуская заданное количество элементов с конца (исключение)
*/
public function testDropRightException(): void
{
$this->expectException(InvalidArgumentException::class);
$array = new MapArrayObject([1, 2, 3]);
$array->dropRight(0);
}
/**
* Возвращает первый элемент, который удовлетворяет условию $condition,
* возвращает false, если такого элемента не существует
*/
public function testFindValue(): void
{
$array = new MapArrayObject([1, 2, 3]);
$this->assertEquals(2, $array->findValue(function ($value, $index) {
return $value > 1;
}));
$this->assertFalse($array->findValue(function ($value, $index) {
return $value > 3;
}));
}
/**
* Возвращает последний элемент, который удовлетворяет условию $condition,
* возвращает false, если такого элемента не существует
*/
public function testFindLastValue(): void
{
$array = new MapArrayObject([3, 2, 1]);
$this->assertEquals(1, $array->findLastValue(function ($value, $index) {
return $value < 3;
}));
$this->assertFalse($array->findLastValue(function ($value, $index) {
return $value > 3;
}));
}
/**
* Возвращает первый ключ элемента, который удовлетворяет условию $condition,
* возвращает false, если такого элемента не существует
*/
public function testFindKey(): void
{
$array = new MapArrayObject(['foo' => 1, 'bar' => 2, 'baz' => 3]);
$this->assertEquals('bar', $array->findKey(function ($value, $index) {
return $value > 1;
}));
$this->assertFalse($array->findKey(function ($value, $index) {
return $value > 3;
}));
$array = new MapArrayObject([1, 2, 3]);
$this->assertEquals(1, $array->findKey(function ($value, $index) {
return $value > 1;
}));
}
/**
* Возвращает последний ключ элемента, который удовлетворяет условию $condition,
* возвращает false, если такого элемента не существует
*/
public function testFindLastKey(): void
{
$array = new MapArrayObject(['foo' => 1, 'bar' => 2, 'baz' => 3]);
$this->assertEquals('baz', $array->findLastKey(function ($value, $index) {
return $value > 1;
}));
$this->assertFalse($array->findLastKey(function ($value, $index) {
return $value > 3;
}));
$array = new MapArrayObject([1, 2, 3]);
$this->assertEquals(2, $array->findLastKey(function ($value, $index) {
return $value > 1;
}));
}
/**
* Возвращает новый массив с переданным ключем и колонкой
*/
public function testMapAndColumn(): void
{
$array = new MapArrayObject([
[
'key' => 'foo',
'value' => 'value1',
],
[
'key' => 'bar',
'value' => 'value2',
],
[
'key' => 'baz',
'value' => 'value3',
],
'qux',
]);
$this->assertEquals(
[
'foo' => 'value1',
'bar' => 'value2',
'baz' => 'value3',
],
$array->mapAndColumn('key', 'value')->getArrayCopy()
);
$this->assertEquals(
[
'foo' => [
'key' => 'foo',
'value' => 'value1',
],
'bar' => [
'key' => 'bar',
'value' => 'value2',
],
'baz' => [
'key' => 'baz',
'value' => 'value3',
],
],
$array->mapAndColumn('key')->getArrayCopy()
);
}
}
| 13,645
|
https://github.com/vitorthomaz/store-prototype/blob/master/src/store/reducers/shopping.js
|
Github Open Source
|
Open Source
|
MIT
| null |
store-prototype
|
vitorthomaz
|
JavaScript
|
Code
| 72
| 199
|
import { ADD_TO_CART, REMOVE_FROM_CART } from '../actions/shopping';
export const initialState = [];
const remove = (cart, id) => {
const index = cart.findIndex(elem => elem.id === id);
if (index === -1) return cart;
const newState = [...cart];
newState.splice(index, 1);
return newState;
};
const reducer = (state = initialState, action) => {
switch (action.type) {
case ADD_TO_CART:
return [...state, action.payload];
case REMOVE_FROM_CART:
return remove(state, action.payload.id);
default:
return state;
}
};
export default reducer;
| 21,156
|
https://github.com/harfol/harthb/blob/master/dao/src/main/java/org/thingsboard/server/dao/sql/attributes/PsqlAttributesInsertRepository.java
|
Github Open Source
|
Open Source
|
ECL-2.0, Apache-2.0
| 2,020
|
harthb
|
harfol
|
Java
|
Code
| 18
| 93
|
package org.thingsboard.server.dao.sql.attributes;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.thingsboard.server.dao.util.PsqlDao;
@PsqlDao
@Repository
@Transactional
public class PsqlAttributesInsertRepository extends AttributeKvInsertRepository {
}
| 22,346
|
https://github.com/RobertBonagura/blog/blob/master/src/components/welcome.js
|
Github Open Source
|
Open Source
|
MIT
| null |
blog
|
RobertBonagura
|
JavaScript
|
Code
| 36
| 124
|
import React from "react"
import welcomeStyles from "./styles/welcome.module.css"
export default ( props ) => (
<div className={ welcomeStyles.container }>
<div className={ welcomeStyles.photoContainer }>
<div className={ welcomeStyles.text }>
<h3>Hello, welcome to</h3>
<h1>{props.title}</h1>
<p>{props.subtitle}</p>
</div>
</div>
</div>
)
| 38,390
|
https://github.com/jmartindelasierra/meteostatR/blob/master/man/climate_normals.Rd
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
meteostatR
|
jmartindelasierra
|
R
|
Code
| 43
| 131
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/climate_normals.R
\name{climate_normals}
\alias{climate_normals}
\title{Climate normals}
\usage{
climate_normals(station)
}
\arguments{
\item{station}{String. The weather station ID.}
}
\value{
Average monthly weather.
}
\description{
Climate normals
}
\examples{
climate_normals(station = "10637")
}
| 34,527
|
https://github.com/DariaKarpovich/basic-js/blob/master/src/hanoi-tower.js
|
Github Open Source
|
Open Source
|
MIT
| null |
basic-js
|
DariaKarpovich
|
JavaScript
|
Code
| 30
| 86
|
import { NotImplementedError } from '../extensions/index.js';
export default function calculateHanoi(disksNumber, turnsSpeed) {
let turns = Math.pow(2,disksNumber) - 1;
let seconds = Math.trunc(turns/turnsSpeed * 60 * 60);
return {turns, seconds};
}
| 50,077
|
https://github.com/cozy/editor-core/blob/master/examples/5-full-page-minimal.tsx
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
editor-core
|
cozy
|
TSX
|
Code
| 102
| 309
|
import styled from 'styled-components';
import React from 'react';
import { borderRadius } from '@atlaskit/theme/constants';
import {
akEditorCodeBackground,
akEditorCodeBlockPadding,
akEditorCodeFontFamily,
} from '@atlaskit/editor-shared-styles';
import Editor from './../src/editor';
export const Wrapper: any = styled.div`
height: 500px;
`;
Wrapper.displayName = 'Wrapper';
export const Content: any = styled.div`
padding: 0 20px;
height: 100%;
background: #fff;
box-sizing: border-box;
& .ProseMirror {
& pre {
font-family: ${akEditorCodeFontFamily};
background: ${akEditorCodeBackground};
padding: ${akEditorCodeBlockPadding};
border-radius: ${borderRadius()}px;
}
}
`;
Content.displayName = 'Content';
export type Props = {};
export type State = { disabled: boolean };
export default function Example() {
return (
<Wrapper>
<Content>
<Editor appearance="full-page" />
</Content>
</Wrapper>
);
}
| 23,213
|
https://github.com/zLulus/NotePractice/blob/master/MAUI/Maui.Demo/Maui.Demo/Pages/Layouts/FlexLayoutPage.xaml.cs
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,023
|
NotePractice
|
zLulus
|
C#
|
Code
| 15
| 48
|
namespace Maui.Demo.Pages.Layouts;
public partial class FlexLayoutPage : ContentPage
{
public FlexLayoutPage()
{
InitializeComponent();
}
}
| 39,292
|
https://github.com/codingbooo/FishDaily/blob/master/fishdaily/app/src/main/java/codingbo/fishdaily/data/source/local/DailyLocalDataSource.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,017
|
FishDaily
|
codingbooo
|
Java
|
Code
| 329
| 1,356
|
package codingbo.fishdaily.data.source.local;
import android.content.Context;
import android.support.annotation.NonNull;
import java.util.List;
import codingbo.fishdaily.App;
import codingbo.fishdaily.data.dao.DailyDao;
import codingbo.fishdaily.data.dao.TagDao;
import codingbo.fishdaily.data.dao.TaskDao;
import codingbo.fishdaily.data.entity.Daily;
import codingbo.fishdaily.data.entity.Tag;
import codingbo.fishdaily.data.entity.Task;
import codingbo.fishdaily.data.source.DailyDataSource;
/**
* 日常数据库实现类
*/
public class DailyLocalDataSource implements DailyDataSource {
private static DailyLocalDataSource INSTANCE;
private final TagDao mTagDao;
private final TaskDao mTaskDao;
private final DailyDao mDailyDao;
private DailyLocalDataSource(Context context) {
mDailyDao = ((App) context.getApplicationContext()).getDaoSession().getDailyDao();
mTagDao = ((App) context.getApplicationContext()).getDaoSession().getTagDao();
mTaskDao = ((App) context.getApplicationContext()).getDaoSession().getTaskDao();
}
public static DailyLocalDataSource getInstance(Context context) {
if (INSTANCE == null) {
INSTANCE = new DailyLocalDataSource(context);
}
return INSTANCE;
}
@Override
public void getDailies(LoadDailiesCallback callback) {
checkCallback(callback);
List<Daily> dailies = mDailyDao.loadAll();
for (Daily daily : dailies) {
daily.setTaskList(findTasks(String.valueOf(daily.getId())));
}
if (/*dailies != null &&*/ dailies.size() > 0) {
callback.onDailiesLoaded(dailies);
} else {
callback.onDataNotAvailable();
}
}
@Override
public void getDailies(int startIndex, int length, LoadDailiesCallback callback) {
checkCallback(callback);
List<Daily> dailies = mDailyDao.queryBuilder()
.limit(length)
.offset(startIndex)
.list();
for (Daily daily : dailies) {
daily.setTaskList(findTasks(String.valueOf(daily.getId())));
}
if (/*dailies != null &&*/ dailies.size() > 0) {
callback.onDailiesLoaded(dailies);
} else {
callback.onDataNotAvailable();
}
}
@Override
public void getDaily(String dailyId, GetDailyCallback callback) {
checkCallback(callback);
Daily daily = mDailyDao.load(Long.parseLong(dailyId));
List<Task> taskList = findTasks(dailyId);
daily.setTaskList(taskList);
if (callback != null) {
callback.onDailyLoaded(daily);
} else {
callback.onDataNotAvailable();
}
}
@NonNull
private List<Task> findTasks(String dailyId) {
List<Task> taskList = mTaskDao.queryBuilder()
.where(TaskDao.Properties.DailyId.eq(dailyId))
.orderAsc(TaskDao.Properties.TagId)
.list();
for (Task task : taskList) {
findTag(task);
}
return taskList;
}
private void findTag(Task task) {
Tag tag = mTagDao.load(task.getTagId());
task.setTag(tag);
}
private void checkCallback(Object callback) {
if (callback == null) {
throw new RuntimeException("callback can not be null!");
}
}
@Override
public String saveDaily(Daily daily) {
long dailyId = mDailyDao.insert(daily);
List<Task> list = daily.getTaskList();
for (Task task : list) {
task.setDailyId(dailyId);
mTaskDao.insert(task);
}
return String.valueOf(dailyId);
}
@Override
public void deleteDaily(String dailyId) {
List<Task> tasks = findTasks(dailyId);
mTaskDao.deleteInTx(tasks);
mDailyDao.deleteByKey(Long.parseLong(dailyId));
}
@Override
public void updateDaily(Daily daily) {
//删除数据库老数据
List<Task> tasks = findTasks(String.valueOf(daily.getId()));
mTaskDao.deleteInTx(tasks);
//重新插入数据
List<Task> list = daily.getTaskList();
for (Task task : list) {
task.setDailyId(daily.getId());
mTaskDao.insert(task);
}
mDailyDao.update(daily);
}
@Override
public void refreshDailies() {
}
@Override
public void deleteAllDailies() {
mDailyDao.deleteAll();
mTaskDao.deleteAll();
}
}
| 32,347
|
https://github.com/mcgowanb/client-side-scripting-202-2/blob/master/js/script-p3.js
|
Github Open Source
|
Open Source
|
MIT
| 2,017
|
client-side-scripting-202-2
|
mcgowanb
|
JavaScript
|
Code
| 800
| 2,461
|
var startDate, endDate;
var formatString = "MMMM Do YYYY HH:mm";
var currentWeatherURL = "http://api.openweathermap.org/data/2.5/weather?id=2961423&APPID=8c6860362c19a97e94d507247ba0e59a&units=metric";
var historicWeatherURL = "http://api.openweathermap.org/data/2.5/forecast?id=2961423&APPID=8c6860362c19a97e94d507247ba0e59a&units=metric";
var locationName;
var temperatureIcon = " °C";
var averageTemp = 0, highTemp = 0, lowestTemp = 9999;
var weatherIcons;
$(document).ready(function () {
var page = location.href.split("/").slice(-1).toString().split("?")[0];
setMenuPressed(page);
//load json file for cloud icons
$.getJSON("json/icons.json", function (data) {
weatherIcons = data;
});
//historic weather data loaded via api call to highcharts
$.getJSON(historicWeatherURL, function (data) {
var tempData = new Array;
var windIntervals = new Array;
var timeValues = new Array;
var count = 0, avgWindSpeed = 0;
locationName = data.city.name;
//iterate through the results set
$.each(data.list, function (key, val) {
//multiplying by 1000 to match js milliseconds for date time
var time = val.dt * 1000;
var temp = val.main.temp;
avgWindSpeed += val.wind.speed;
averageTemp += temp;
//getting the lowest temp from the result set
if (temp < lowestTemp) {
lowestTemp = temp;
}
//getting the highest temp from the result set
if (temp > highTemp) {
highTemp = temp;
}
tempData.push([time, temp]);
windIntervals.push([time, val.wind.speed]);
timeValues.push(time);
count++;
});
averageTemp /= count;
avgWindSpeed /= count;
//getting start and end dates for display from the dataset
startDate = moment(tempData[0][0]).format(formatString);
endDate = moment(tempData[tempData.length - 1][0]).format(formatString);
//calling function for graph
displayMainGraph(windIntervals, tempData, avgWindSpeed, averageTemp);
//update dom with high and low temp including the icons
$("#temp-low").text(lowestTemp + temperatureIcon);
$("#temp-high").text(highTemp + temperatureIcon);
});
//get current weather infromation via api call
$.getJSON(currentWeatherURL, function (data) {
$("#temp-current").text(data.main.temp + temperatureIcon);
setWeatherInformation(data.weather[0], data.clouds);
setOtherWeatherData(data.main);
});
});
//main highcharts function
function displayMainGraph(windIntervals, tempData, avgSpeed, averageTemp) {
$('#main-graph').highcharts({
chart: {
zoomType: 'x'
},
title: {
text: 'Weather Data for ' + locationName
},
subtitle: {
text: 'for the period ' + startDate + ' to ' + endDate
},
xAxis: {
type: 'datetime',
labels: {
overflow: 'justify'
}
},
credits: {
enabled: false
},
yAxis: [
{
title: {
text: 'Wind speed (m/s)'
},
labels: {
format: '{value}(m/s)',
style: {
color: Highcharts.getOptions().colors[1]
}
},
minorGridLineWidth: 0,
gridLineWidth: 0,
alternateGridColor: null,
//average windspeed and temperature lines
plotLines: [
{
value: avgSpeed,
color: 'blue',
dashStyle: 'longdash',
width: 1,
label: {
text: 'avg speed ' + avgSpeed.toFixed(2) + ' m/s',
align: 'right'
}
},
{
value: averageTemp,
color: 'green',
dashStyle: 'shortdash',
width: 1,
label: {
text: 'avg temp ' + averageTemp.toFixed(2) + ' °C',
align: 'right'
}
}
],
//plot lines across graph for varying weather types
plotBands: [{ // Light air
from: 0.3,
to: 1.5,
color: 'rgba(68, 170, 213, 0.1)',
label: {
text: 'Light air',
style: {
color: '#606060'
}
}
}, { // Light breeze
from: 1.5,
to: 3.3,
color: 'rgba(0, 0, 0, 0)',
label: {
text: 'Light breeze',
style: {
color: '#606060'
}
}
}, { // Gentle breeze
from: 3.3,
to: 5.5,
color: 'rgba(68, 170, 213, 0.1)',
label: {
text: 'Gentle breeze',
style: {
color: '#606060'
}
}
}, { // Moderate breeze
from: 5.5,
to: 8,
color: 'rgba(0, 0, 0, 0)',
label: {
text: 'Moderate breeze',
style: {
color: '#606060'
}
}
}, { // Fresh breeze
from: 8,
to: 11,
color: 'rgba(68, 170, 213, 0.1)',
label: {
text: 'Fresh breeze',
style: {
color: '#606060'
}
}
}, { // Strong breeze
from: 11,
to: 14,
color: 'rgba(0, 0, 0, 0)',
label: {
text: 'Strong breeze',
style: {
color: '#606060'
}
}
}, { // High wind
from: 14,
to: 15,
color: 'rgba(68, 170, 213, 0.1)',
label: {
text: 'High wind',
style: {
color: '#606060'
}
}
}],
opposite: true
},
{
title: {
text: 'Temp °C'
},
labels: {
format: '{value} °C',
style: {
color: Highcharts.getOptions().colors[3]
}
}
}
],
tooltip: {
shared: true
},
//dataSeries
series: [
{
name: 'Wind Speed',
type: 'spline',
data: windIntervals,
color: '#5CB85C',
tooltip: {
valueSuffix: ' (m/s)'
}
},
{
name: "Temperature",
type: 'spline',
data: tempData,
tooltip: {
valueSuffix: ' ( °C)'
}
}
],
navigation: {
menuItemStyle: {
fontSize: '10px'
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle',
borderWidth: 0,
backgroundColor: (Highcharts.theme && Highcharts.theme.legendBackgroundColor) || '#FFFFFF'
}
});
}
//controlling the pressed button effect on the menu bar
function setMenuPressed(page) {
switch (page) {
case "index.html":
$("#p-1").addClass("active");
break;
case "page-2.html":
$("#p-2").addClass("active");
break;
case "page-3.html":
$("#p-3").addClass("active");
break;
}
}
//set the real time weather information at the top of the page
function setWeatherInformation(data, clouds) {
var prefix = 'wi wi-';
var code = data.id;
var icon = weatherIcons[code].icon;
if (!(code > 699 && code < 800) && !(code > 899 && code < 1000)) {
icon = 'day-' + icon;
}
icon = prefix + icon;
$("#weather-icon").addClass(icon);
var $weatherString = $("<div><span class='medium'>" + data.main + "</span></div>");
var $cloudString = $("<div><small>Cloud cover: " + clouds.all + "%</small></div>");
$("#weather-data").append($weatherString).append($cloudString);
}
//setting other weather information on the page
function setOtherWeatherData(data) {
var $data = [
$("<div><span class='medium'>Atmospheric Pressure: </span><span class='small other'>" + data.pressure + " hPa</span></div>"),
$("<div><span class='medium'>Humidity: </span><span class='small other'>" + data.humidity + "%</span></div>")
];
$("#other-weather").append($data);
}
| 34,963
|
https://github.com/Killeroo/RainbowWorm/blob/master/Program.cs
|
Github Open Source
|
Open Source
|
Unlicense
| null |
RainbowWorm
|
Killeroo
|
C#
|
Code
| 151
| 443
|
using System;
using System.Threading;
namespace RainbowWorm
{
class MainClass
{
public const String DEFAULT_TEXT = "-++###########++-";
public static ConsoleColor defaultColor = Console.ForegroundColor;
public static void Main(string[] args)
{
string wormTxt = DEFAULT_TEXT;
// Setup console
Console.CursorVisible = false;
Console.CancelKeyPress += new ConsoleCancelEventHandler(ExitHandler);
// Setup string
if (args.Length > 0) {
// Use first arg as worm text if its set
wormTxt = string.IsNullOrEmpty(args[0]) ? DEFAULT_TEXT : args[0];
}
// Colours to use
ConsoleColor[] colors = new ConsoleColor[] {
ConsoleColor.Blue,
ConsoleColor.Cyan,
ConsoleColor.Gray,
ConsoleColor.Green,
ConsoleColor.Magenta,
ConsoleColor.Red,
ConsoleColor.White,
ConsoleColor.Yellow
};
// Draw worm
//Source: https://codegolf.stackexchange.com/a/18733
int index = 0;
for (var i = 0d; ;) {
if (index == colors.Length) { index = 0; }
Console.ForegroundColor = colors[index];
Console.Write("{0," + (int)(40 + 20 * Math.Sin(i += .1)) + "}\n", wormTxt);
index++;
Thread.Sleep(25);
}
}
protected static void ExitHandler(object sender, ConsoleCancelEventArgs args)
{
// Restore console
Console.CursorVisible = true;
Console.ForegroundColor = defaultColor;
}
}
}
| 49,209
|
https://github.com/planlodge/ChowNow-Theme-Wordpress/blob/master/tests/data/wpcom-themes/chaostheory/functions.php
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,018
|
ChowNow-Theme-Wordpress
|
planlodge
|
PHP
|
Code
| 1,907
| 6,240
|
<?php
$themecolors = array(
'bg' => '1B1B1B',
'border' => '0A0A0A',
'text' => 'DDDDDD',
'link' => '6DCFF6'
);
$content_width = 510; // pixels
// And thus begins the Sandbox guts! Registers our default
// options, specifically loads the 2c-1.css file as default skin
function sandbox_get_option($name) {
$defaults = array(
'skin' => '2c-l',
);
$options = array_merge($defaults, (array) get_option('sandbox_options'));
if ( isset($options[$name]) )
return $options[$name];
return false;
}
// Andy really goes nuts with arrays, which has been a good thing. Very good.
function sandbox_set_options($new_options) {
$options = (array) get_option('sandbox_options');
$options = array_merge($options, (array) $new_options);
return update_option('sandbox_options', $options);
}
// Template tag: echoes a stylesheet link if one is selected
function sandbox_stylesheets() {
$skin = sandbox_get_option('skin');
if ( $skin != 'none' ) {
?>
<link rel="stylesheet" type="text/css" media="all" href="<?php echo get_template_directory_uri() . "/skins/$skin.css" ?>" title="Sandbox" />
<?php
}
}
// Template tag: echoes a link to skip navigation if the
// global_navigation option is set to "Y" in the skin file
function sandbox_skipnav() {
if ( !sandbox_get_option('globalnav') )
return;
echo '<p class="access"><a href="#content" title="'.__('Skip navigation to the content', 'sandbox').'">'.__('Skip navigation', 'sandbox').'</a></p>';
}
// Template tag: echoes a page list for navigation if the
// global_navigation option is set to "Y" in the skin file
function sandbox_globalnav() {
echo "<div id='globalnav'><ul id='menu'>";
$menu = wp_list_pages('title_li=&sort_column=menu_order&echo=0&depth=1');
echo str_replace(array("\r", "\n", "\t"), '', $menu); // Strip intratag whitespace
echo "</ul></div>";
}
// Template tag: echoes semantic classes in the <body>
function sandbox_body_class( $print = true ) {
global $wp_query, $current_user;
$c = array('wordpress');
sandbox_date_classes(time(), $c);
is_home() ? $c[] = 'home' : null;
is_archive() ? $c[] = 'archive' : null;
is_date() ? $c[] = 'date' : null;
is_search() ? $c[] = 'search' : null;
is_paged() ? $c[] = 'paged' : null;
is_attachment() ? $c[] = 'attachment' : null;
is_404() ? $c[] = 'four04' : null; // CSS does not allow a digit as first character
if ( is_single() ) {
the_post();
$c[] = 'single';
if ( isset($wp_query->post->post_date) )
sandbox_date_classes(mysql2date('U', $wp_query->post->post_date), $c, 's-');
foreach ( (array) get_the_category() as $cat )
$c[] = 's-category-' . $cat->category_nicename;
$c[] = 's-author-' . get_the_author_login();
rewind_posts();
}
else if ( is_author() ) {
$author = $wp_query->get_queried_object();
$c[] = 'author';
$c[] = 'author-' . $author->user_nicename;
}
else if ( is_category() ) {
$cat = $wp_query->get_queried_object();
$c[] = 'category';
$c[] = 'category-' . $cat->category_nicename;
}
else if ( is_page() ) {
the_post();
$c[] = 'page';
$c[] = 'page-author-' . get_the_author_login();
rewind_posts();
}
if ( $current_user->ID )
$c[] = 'loggedin';
$c = join(' ', apply_filters('body_class', $c));
return $print ? print($c) : $c;
}
// Generates semantic classes for each post DIV element
function sandbox_post_class( $print = true ) {
global $post, $sandbox_post_alt;
//gets 'alt' for every other post DIV, describes the post status
$c = array("p$sandbox_post_alt", $post->post_status);
// Author for the post queried
$c[] = 'author-' . sanitize_title_with_dashes(strtolower(get_the_author('login')));
// For password-protected posts
if ( $post->post_password )
$c[] = 'protected';
// Applies the time- and date-based classes (below) to post DIV
sandbox_date_classes(mysql2date('U', $post->post_date), $c);
// If it's the other to the every, then add 'alt' class
if ( ++$sandbox_post_alt % 2 )
$c[] = 'alt';
// Separates classes with a single space, collates classes for post DIV
$c = join(' ', get_post_class( $c, $post->ID ) );
// And tada!
return $print ? print($c) : $c;
}
$sandbox_post_alt = 1;
// Template tag: echoes semantic classes for a comment <li>
function sandbox_comment_class( $print = true ) {
global $comment, $post, $sandbox_comment_alt;
$c = array($comment->comment_type, "c$sandbox_comment_alt");
if ( $comment->user_id > 0 ) {
$user = get_userdata($comment->user_id);
$c[] = "byuser commentauthor-$user->user_login";
if ( $comment->user_id === $post->post_author )
$c[] = 'bypostauthor';
}
sandbox_date_classes(mysql2date('U', $comment->comment_date), $c, 'c-');
if ( ++$sandbox_comment_alt % 2 )
$c[] = 'alt';
if ( is_trackback() ) {
$c[] = 'trackback';
}
$c = join(' ', apply_filters('comment_class', $c));
return $print ? print($c) : $c;
}
// Adds four time- and date-based classes to an array
// with all times relative to GMT (sometimes called UTC)
function sandbox_date_classes($t, &$c, $p = '') {
$t = $t + (get_settings('gmt_offset') * 3600);
$c[] = $p . 'y' . gmdate('Y', $t); // Year
$c[] = $p . 'm' . gmdate('m', $t); // Month
$c[] = $p . 'd' . gmdate('d', $t); // Day
$c[] = $p . 'h' . gmdate('h', $t); // Hour
}
// Returns a list of the post's categories, minus the queried one
function sandbox_cats_meow($glue) {
$current_cat = single_cat_title('', false);
$separator = "\n";
$cats = explode($separator, get_the_category_list($separator));
foreach ( $cats as $i => $str ) {
if ( strstr($str, ">$current_cat<") ) {
unset($cats[$i]);
break;
}
}
if ( empty($cats) )
return false;
return trim(join($glue, $cats));
}
// Sandbox widgets: Replaces the default search widget with one
// that matches what is in the Sandbox sidebar by default
function widget_sandbox_search($args) {
extract($args);
if ( empty($title) )
$title = __('Search', 'sandbox');
?>
<?php echo $before_widget ?>
<?php echo $before_title ?><label for="s"><?php echo $title ?></label><?php echo $after_title ?>
<form id="searchform" method="get" action="<?php bloginfo('home') ?>">
<div>
<input id="s" name="s" type="text" value="<?php echo wp_specialchars(stripslashes($_GET['s']), true) ?>" size="10" />
<input id="searchsubmit" name="searchsubmit" type="submit" value="<?php _e('Find »', 'sandbox') ?>" />
</div>
</form>
<?php echo $after_widget ?>
<?php
}
// Sandbox widgets: Replaces the default meta widget with one
// that matches what is in the Sandbox sidebar by default
function widget_sandbox_meta($args) {
extract($args);
if ( empty($title) )
$title = __('Meta', 'sandbox');
?>
<?php echo $before_widget; ?>
<?php echo $before_title . $title . $after_title; ?>
<ul>
<?php wp_register() ?>
<li><?php wp_loginout() ?></li>
<?php wp_meta() ?>
</ul>
<?php echo $after_widget; ?>
<?php
}
// Sandbox widgets: Adds the Sandbox's home link as a widget, which
// appears when NOT on the home page OR on a page of the home page
function widget_sandbox_homelink($args) {
extract($args);
$options = get_option('widget_sandbox_homelink');
$title = empty($options['title']) ? __('« Home') : $options['title'];
?>
<?php if ( !is_home() || is_paged() ) { ?>
<?php echo $before_widget; ?>
<?php echo $before_title ?><a href="<?php bloginfo('home') ?>" title="<?php echo wp_specialchars(get_bloginfo('name'), 1) ?>"><?php echo $title ?></a><?php echo $after_title ?>
<?php echo $after_widget; ?>
<?php } ?>
<?php
}
// Sandbox widgets: Adds the option to set the text for the home link widget
function widget_sandbox_homelink_control() {
$options = $newoptions = get_option('widget_sandbox_homelink');
if ( $_POST["homelink-submit"] ) {
$newoptions['title'] = strip_tags(stripslashes($_POST["homelink-title"]));
}
if ( $options != $newoptions ) {
$options = $newoptions;
update_option('widget_sandbox_homelink', $options);
}
$title = htmlspecialchars($options['title'], ENT_QUOTES);
?>
<p style="text-align:left;"><?php _e('Adds a link to the home page on every page <em>except</em> the home.', 'sandbox'); ?></p>
<p>
<label for="homelink-title">
<?php _e('Link Text:'); ?>
<input class="widefat" id="homelink-title" name="homelink-title" type="text" value="<?php echo $title; ?>" />
</label>
</p>
<input type="hidden" id="homelink-submit" name="homelink-submit" value="1" />
<?php
}
// Sandbox widgets: Adds a widget with the Sandbox RSS links
// as they appear in the default Sandbox sidebar, which are good
function widget_sandbox_rsslinks($args) {
extract($args);
$options = get_option('widget_sandbox_rsslinks');
$title = empty($options['title']) ? __('RSS Links') : $options['title'];
?>
<?php echo $before_widget; ?>
<?php echo $before_title . $title . $after_title; ?>
<ul>
<li><a href="<?php bloginfo('rss2_url') ?>" title="<?php echo wp_specialchars(get_bloginfo('name'), 1) ?> RSS 2.0 Feed" rel="alternate" type="application/rss+xml"><?php _e('All posts', 'sandbox') ?></a></li>
<li><a href="<?php bloginfo('comments_rss2_url') ?>" title="<?php echo wp_specialchars(bloginfo('name'), 1) ?> Comments RSS 2.0 Feed" rel="alternate" type="application/rss+xml"><?php _e('All comments', 'sandbox') ?></a></li>
</ul>
<?php echo $after_widget; ?>
<?php
}
// Sandbox widgets: Adds the option to set the text for the RSS link widget
function widget_sandbox_rsslinks_control() {
$options = $newoptions = get_option('widget_sandbox_rsslinks');
if ( $_POST["rsslinks-submit"] ) {
$newoptions['title'] = strip_tags(stripslashes($_POST["rsslinks-title"]));
}
if ( $options != $newoptions ) {
$options = $newoptions;
update_option('widget_sandbox_rsslinks', $options);
}
$title = htmlspecialchars($options['title'], ENT_QUOTES);
?>
<p>
<label for="rsslinks-title">
<?php _e('Title:'); ?>
<input class="widefat" id="rsslinks-title" name="rsslinks-title" type="text" value="<?php echo $title; ?>" />
</label>
</p>
<input type="hidden" id="rsslinks-submit" name="rsslinks-submit" value="1" />
<?php
}
// Template tag & Sandbox widget: Creates a string to produce
// links in either WP 2.1 or then WP 2.0 style, relative to install
function widget_sandbox_links() {
wp_list_bookmarks(array('title_before'=>'<h3>', 'title_after'=>'</h3>', 'show_images'=>true));
}
// Sandbox skins menu: creates the array to collect
// information from the skins currently installed
function sandbox_skin_info($skin) {
$info = array(
'skin_name' => $skin,
'skin_uri' => '',
'description' => '',
'version' => '1.0',
'author' => __('Anonymous', 'sandbox'),
'author_uri' => '',
'global_navigation' => 'Y',
);
if ( !file_exists(ABSPATH."wp-content/themes/sandbox/skins/$skin.css") )
return array();
$css = (array) file(ABSPATH."wp-content/themes/sandbox/skins/$skin.css");
foreach ( $css as $line ) {
if ( strstr($line, '*/') )
return $info;
if ( !strstr($line, ':') )
continue;
list ( $k, $v ) = explode(':', $line, 2);
$k = str_replace(' ', '_', strtolower(trim($k)));
if ( array_key_exists($k, $info) )
$info[$k] = stripslashes(wp_filter_kses(trim($v)));
}
}
// Sandbox skins menu: Registers the workings of the skins menu
function sandbox_admin_skins() {
$skins = array();
if ( isset ( $_GET['message'] ) ) {
switch ( $_GET['message'] ) {
case 'updated' :
echo "\n<div id='message' class='updated fade'><p>".__('Sandbox skin saved successfully.', 'sandbox')."</p></div>\n";
break;
}
}
$current_skin = sandbox_get_option('skin');
$_skins = glob(ABSPATH.'wp-content/themes/sandbox/skins/*.css');
foreach ( $_skins as $k => $v ) {
$info = array();
preg_match('/\/([^\/]+).css$/i', $v, $matches);
if ( !empty($matches[1]) ) {
$skins[$matches[1]] = sandbox_skin_info($matches[1]);
}
}
?>
<script type="text/javascript">
<!-- function showme(o) { document.getElementById('show').src = o.src; } //-->
</script>
<div class="wrap">
<h2><?php _e('Current Skin', 'sandbox') ?></h2>
<div id="currenttheme">
<?php if ( file_exists(get_template_directory() . "/skins/$current_skin.png") ) : ?>
<img src="<?php echo get_template_directory_uri() . "/skins/$current_skin.png"; ?>" alt="<?php _e('Current skin preview', 'sandbox'); ?>" />
<?php endif; ?>
<?php
if ( is_array($skins[$current_skin]) )
extract($skins[$current_skin]);
if ( !empty($skin_uri) )
$skin_name = "<a href=\"$skin_uri\" title=\"$skin_name by $author\">$skin_name</a>";
if ( !empty($author_uri) )
$author = "<a href=\"$author_uri\" title=\"$author\">$author</a>";
?>
<h3><?php printf(__('%1$s %2$s by %3$s'), $skin_name, $version, $author) ; ?></h3>
<p><?php echo $description; ?></p>
</div>
<div class="clearer" style="clear:both;"></div>
<h2><?php _e('Available Skins', 'sandbox') ?></h2>
<?php
foreach ( $skins as $skin => $info ) :
if ( $skin == $current_skin || !is_array($info) )
continue;
extract($info);
$activate_link = "themes.php?page=skins&action=activate&skin=$skin";
// wp_nonce_url first introduced in WP 2.0.3
if ( function_exists('wp_nonce_url') )
$activate_link = wp_nonce_url($activate_link, 'switch-skin_' . $skin);
?>
<div class="available-theme">
<h3><a href="<?php echo $activate_link; ?>" title="Activate the <?php echo "$skin_name"; ?> skin"><?php echo "$skin_name $version"; ?></a></h3>
<a href="<?php echo $activate_link; ?>" class="screenshot" title="Activate the <?php echo "$skin_name"; ?> skin">
<?php if ( file_exists(get_template_directory() . "/skins/$skin.png" ) ) : ?>
<img src="<?php echo get_template_directory_uri() . "/skins/$skin.png"; ?>" alt="<?php echo "$skin_name"; ?>" />
<?php endif; ?>
</a>
<p><?php echo $description; ?></p>
</div>
<?php endforeach; ?>
<h2><?php _e('Sandbox Info', 'sandbox'); ?></h2>
<p><?php printf(__('Check the <a href="%1$s" title="Read the Sandbox readme.html">documentation</a> for help installing new skins and information on the rich semantic markup that makes the Sandbox unique.', 'sandbox'), get_template_directory_uri() . '/readme.html'); ?></p>
</div>
<?php
}
// Sandbox skins menu: initializes the settings for the skins menu
function sandbox_init() {
load_theme_textdomain('sandbox');
if ( $GLOBALS['pagenow'] == 'themes.php'
&& isset($_GET['page']) && $_GET['page'] == 'skins'
&& isset($_GET['action']) && $_GET['action'] == 'activate'
&& current_user_can('switch_themes') ) {
check_admin_referer('switch-skin_' . $_GET['skin']);
$info = sandbox_skin_info($_GET['skin']);
sandbox_set_options(array(
'skin' => wp_filter_kses($_GET['skin']),
'globalnav' => bool_from_yn($info['global_navigation'])
));
wp_redirect('themes.php?page=skins&message=updated');
}
}
// Sandbox skins menu: tells WordPress (nicely) to load the skins menu
function sandbox_admin_menu() {
add_theme_page(__('Sandbox Skins', 'sandbox'), __('Sandbox Skins', 'sandbox'), 'switch_themes', 'skins', 'sandbox_admin_skins');
}
// Sandbox widgets: initializes Widgets for the Sandbox
function sandbox_widgets_init() {
// Overrides the Widgets default and uses <h3>'s for sidebar headings
$p = array(
'before_title' => "<h3 class='widgettitle'>",
'after_title' => "</h3>\n",
);
// How many? Two?! That's it?
register_sidebars(2, $p);
// Registers the widgets specific to the Sandbox, as set earlier
unregister_widget('WP_Widget_Search');
wp_register_sidebar_widget('search', __('Search', 'sandbox'), 'widget_sandbox_search');
unregister_widget('WP_Widget_Meta');
wp_register_sidebar_widget('meta', __('Meta', 'sandbox'), 'widget_sandbox_meta');
unregister_widget('WP_Widget_Links');
wp_register_sidebar_widget('links', __('Links', 'sandbox'), 'widget_sandbox_links');
register_sidebar_widget(array('Home Link', 'widgets'), 'widget_sandbox_homelink');
register_widget_control(array('Home Link', 'widgets'), 'widget_sandbox_homelink_control', null, 125);
register_sidebar_widget(array('RSS Links', 'widgets'), 'widget_sandbox_rsslinks');
register_widget_control(array('RSS Links', 'widgets'), 'widget_sandbox_rsslinks_control', null, 90);
}
// Runs our code at the end to check that everything needed has loaded
add_action('init', 'sandbox_init', 1);
add_action('widgets_init', 'sandbox_widgets_init');
#add_action('admin_menu', 'sandbox_admin_menu');
// Adds filters for greater compliance
add_filter('archive_meta', 'wptexturize');
add_filter('archive_meta', 'convert_smilies');
add_filter('archive_meta', 'convert_chars');
add_filter('archive_meta', 'wpautop');
?>
| 19,337
|
https://github.com/OKhomiakova/thesis/blob/master/pages/admin/admin_add_user.php
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
thesis
|
OKhomiakova
|
PHP
|
Code
| 187
| 1,078
|
<?php
include ("../../logic/check_admin.php");
include ("../../logic/add_data_user.php");
?>
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Новый пользователь</title>
<link rel="stylesheet" href="../style.css">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
</head>
<body>
<?php include '../header.php';?>
<nav>
<ul>
<li class="dropdown">
<a class="active dropbtn" href="javascript:void(0)">Пользователи</a>
<div class="dropdown-content">
<a href="admin_add_user.php"><i class="fas fa-user-plus"></i> Добавить</a>
<a href="admin_delete_user.php"><i class="fas fa-user-times"></i> Удалить</a>
</div>
</li>
<li class="dropdown">
<a class="dropbtn" href="javascript:void(0)">Препараты</a>
<div class="dropdown-content">
<a href="admin_add_drug.php"><i class="fas fa-plus"></i> Добавить</a>
<a href="admin_delete_drug.php"><i class="fas fa-minus"></i> Удалить</a>
</div>
</li>
<li class="dropdown" style="float: right;">
<a class="dropbtn" href="javascript:void(0)"><?php echo $_SESSION['user_name']?></a>
<div class="dropdown-content">
<a href="../change_password.php"><i class="fas fa-key"></i> Сменить пароль</a>
<a href="../../logic/logout.php"><i class="fas fa-sign-out-alt"></i> Выйти</a>
</div>
</li>
</ul>
</nav>
<form name="add_user" method="POST">
<div style='display: flex; justify-content:center;'>
<fieldset style='width: 80%;' >
<legend><h2 style="margin: 0;">Новый пользователь</h2></legend>
<div class="passport">
<label for="userName">ФИО Пользователя</label>
<input type="text" id="userName" name="userName" maxlength="100" required>
<div style="display:flex;">
<div style="display:grid; flex: 40%; margin-right: 10px;" >
<label for="login" style="position: relative;">Логин</label>
<input type="text" id="login" name="login" required>
</div>
<div style="display:grid; flex: 40%; margin-left: 10px;">
<label for="password">Пароль</label>
<input type="text" id="password" name="password" required>
</div>
</div>
<label for="isAdmin">Права администратора</label>
<div class="align">
<p><input type="radio" id="isAdmin" name="isAdmin" value="yes" checked>Да</p>
<p><input type="radio" id="isAdmin" name="isAdmin" value="no">Нет</p>
</div>
<input type="submit" name="submit" value="Добавить пользователя">
</div>
</fieldset>
</div>
</form>
<?php include '../footer.php';?>
</body>
</html>
| 19,435
|
https://github.com/VIchenlei/client-V1/blob/master/src/main/sass/page-main.sass
|
Github Open Source
|
Open Source
|
MIT
| null |
client-V1
|
VIchenlei
|
Sass
|
Code
| 71
| 236
|
@import '../../sass/defs'
.page-main
position: absolute
width: 100%
height: 100%
display: flex
flex-flow: column nowrap
// flex: auto
background: url("/img/ratebg.png") no-repeat cover
@media screen and (max-width: $width-medium) and (orientation: landscape)
overflow: hidden
.back-homepage
cursor: pointer
display: flex
align-items: center
&:hover
color: $btn-bg
.page-body
position: relative
display: flex
flex: auto
perspective: 2000px
transform-style: preserve-3d
.sub-page
position: absolute
width: 100%
height: 100%
display: flex
flex-flow: row nowrap
align-items: stretch
color: $main-color
#cesiumContainer
width: 100%
| 23,488
|
https://github.com/derbirch/hexo-theme-inside/blob/master/lib/renderer/markdown/plugins/tree.js
|
Github Open Source
|
Open Source
|
MIT
| null |
hexo-theme-inside
|
derbirch
|
JavaScript
|
Code
| 132
| 365
|
const container = require('markdown-it-container');
const Token = require('markdown-it/lib/token');
const { parsePipe } = require('../../../utils');
module.exports = [container, 'tree', {
render(tokens, idx, options, env, slf) {
const meta = parsePipe('|' + tokens[idx].info.trim().slice(4));
const { styles } = env;
const treeIcon = styles['tree--' + meta.options.icon] || styles['tree--square'];
if (tokens[idx].nesting === 1) {
for (let i = idx;; i++) {
if (
tokens[i].type === 'inline' &&
tokens[i + 2].type === 'bullet_list_open'
) {
const checkbox = new Token('input', 'input', 0);
checkbox.attrPush(['type', 'checkbox']);
tokens[i + 1].hidden = tokens[i - 1].hidden = false;
tokens[i + 1].tag = tokens[i - 1].tag = 'header';
tokens.splice(i - 1, 0, checkbox);
// step foward since a new token has just been inserted
i++;
} else if (tokens[i].type === 'container_tree_close') {
return `<div class="${styles.tree} ${treeIcon}">`;
}
}
}
return '</div>';
}
}];
| 2,787
|
https://github.com/chillerlan/php-qrcode/blob/master/tests/Data/ECITest.php
|
Github Open Source
|
Open Source
|
Apache-2.0, MIT, LicenseRef-scancode-warranty-disclaimer, CC-BY-4.0
| 2,023
|
php-qrcode
|
chillerlan
|
PHP
|
Code
| 432
| 1,634
|
<?php
/**
* ECITest.php
*
* @created 12.03.2023
* @author smiley <smiley@chillerlan.net>
* @copyright 2023 smiley
* @license MIT
*/
namespace chillerlan\QRCodeTest\Data;
use chillerlan\QRCode\QROptions;
use chillerlan\QRCode\Common\{BitBuffer, ECICharset, Mode};
use chillerlan\QRCode\Data\{Byte, ECI, Number, QRCodeDataException, QRData, QRDataModeInterface};
use PHPUnit\Framework\TestCase;
/**
* Tests the ECI class
*/
final class ECITest extends TestCase{
protected QRData $QRData;
protected string $testdata = '无可奈何燃花作香';
private int $testCharset = ECICharset::GB18030;
protected function setUp():void{
$this->QRData = new QRData(new QROptions);
}
private function getDataSegments():array{
return [
new ECI($this->testCharset),
new Byte(mb_convert_encoding($this->testdata, ECICharset::MB_ENCODINGS[$this->testCharset], mb_internal_encoding())),
];
}
/** @inheritDoc */
public function testDataModeInstance():void{
$datamode = new ECI($this->testCharset);
$this::assertInstanceOf(QRDataModeInterface::class, $datamode);
}
/**
* returns versions within the version breakpoints 1-9, 10-26 and 27-40
*/
public static function versionBreakpointProvider():array{
return ['1-9' => [7], '10-26' => [15], '27-40' => [30]];
}
/**
* @inheritDoc
* @dataProvider versionBreakpointProvider
*/
public function testDecodeSegment(int $version):void{
$options = new QROptions;
$options->version = $version;
/** @var \chillerlan\QRCode\Data\QRDataModeInterface[] $segments */
$segments = $this->getDataSegments();
// invoke a QRData instance and write data
$this->QRData = new QRData($options, $segments);
// get the filled bitbuffer
$bitBuffer = $this->QRData->getBitBuffer();
// read the first 4 bits
$this::assertSame($segments[0]::DATAMODE, $bitBuffer->read(4));
// decode the data
$this::assertSame($this->testdata, ECI::decodeSegment($bitBuffer, $options->version));
}
/** @inheritDoc */
public function testInvalidDataException():void{
$this->expectException(QRCodeDataException::class);
$this->expectExceptionMessage('invalid encoding id:');
/** @phan-suppress-next-line PhanNoopNew */
new ECI(-1);
}
/**
* since the ECI class only accepts integer values,
* we'll use this test to check for the upper end of the accepted input range
*
* @inheritDoc
*/
public function testInvalidDataOnEmptyException():void{
$this->expectException(QRCodeDataException::class);
$this->expectExceptionMessage('invalid encoding id:');
/** @phan-suppress-next-line PhanNoopNew */
new ECI(1000000);
}
public static function eciCharsetIdProvider():array{
return [
[ 0, 8],
[ 127, 8],
[ 128, 16],
[ 16383, 16],
[ 16384, 24],
[999999, 24],
];
}
/**
* @dataProvider eciCharsetIdProvider
*/
public function testReadWrite(int $id, int $lengthInBits):void{
$bitBuffer = new BitBuffer;
$eci = (new ECI($id))->write($bitBuffer, 1);
$this::assertSame($lengthInBits, $eci->getLengthInBits());
$this::assertSame(Mode::ECI, $bitBuffer->read(4));
$this::assertSame($id, ECI::parseValue($bitBuffer)->getID());
}
/**
* Tests if and exception is thrown when the ECI segment is followed by a mode that is not 8-bit byte
*/
public function testDecodeECISegmentFollowedByInvalidModeException():void{
$this->expectException(QRCodeDataException::class);
$this->expectExceptionMessage('ECI designator followed by invalid mode:');
$options = new QROptions;
$options->version = 5;
/** @var \chillerlan\QRCode\Data\QRDataModeInterface[] $segments */
$segments = $this->getDataSegments();
// follow the ECI segment by a non-8bit-byte segment
$segments[1] = new Number('1');
$bitBuffer = (new QRData($options, $segments))->getBitBuffer();
$this::assertSame(Mode::ECI, $bitBuffer->read(4));
ECI::decodeSegment($bitBuffer, $options->version);
}
public function unknownEncodingDataProvider():array{
return [
'CP437' => [0, "\x41\x42\x43"],
'ISO_IEC_8859_1_GLI' => [1, "\x41\x42\x43"],
];
}
/**
* Tests detection of an unknown character set
*
* @dataProvider unknownEncodingDataProvider
*/
public function testConvertUnknownEncoding(int $id, string $data):void{
$options = new QROptions;
$options->version = 5;
$segments = [new ECI($id), new Byte($data)];
$bitBuffer = (new QRData($options, $segments))->getBitBuffer();
$this::assertSame(Mode::ECI, $bitBuffer->read(4));
$this::assertSame($data, ECI::decodeSegment($bitBuffer, $options->version));
}
}
| 22,326
|
https://github.com/CCDirectLink/crosscode-map-editor-tool/blob/master/webapp/src/app/components/map-fs-tree-view/map-fs-tree-view.component.ts
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
crosscode-map-editor-tool
|
CCDirectLink
|
TypeScript
|
Code
| 191
| 684
|
import { Component, OnInit, OnDestroy, Input } from '@angular/core';
import { MapFileSystemService } from '../../shared/map-filesystem/map-filesystem.service';
import { MatSidenav, MatTreeNestedDataSource } from '@angular/material';
import { Subscription } from 'rxjs';
import { FileTreeNode } from './treeNode.model';
import { NestedTreeControl } from '@angular/cdk/tree';
import { MapFolder, MapFile } from '../../shared/map-filesystem/map-filesystem.model';
import { MapLoaderService } from '../../shared/map-loader.service';
import { CrossCodeMap } from '../../models/cross-code-map';
@Component({
selector: 'app-map-fs-tree-view',
templateUrl: './map-fs-tree-view.component.html',
styleUrls: ['./map-fs-tree-view.component.scss']
})
export class MapFsTreeViewComponent implements OnInit, OnDestroy {
@Input() sidenav!: MatSidenav;
private fsSubcription!: Subscription;
treeControl = new NestedTreeControl<FileTreeNode>(node => node.children);
dataSource = new MatTreeNestedDataSource<FileTreeNode>();
constructor(private mapFsService: MapFileSystemService,
private mapLoaderService: MapLoaderService) { }
ngOnInit() {
this.dataSource.data = [];
this.fsSubcription = this.mapFsService.fs.subscribe(
(rootFolder) => {
if (rootFolder) {
this.initFolders(rootFolder);
} else {
this.dataSource.data = [];
}
}
);
}
onClick(file: FileTreeNode) {
this.mapFsService.loadMap(file.original).subscribe(
(map: CrossCodeMap) => {
map.file = file.original;
this.mapLoaderService.loadRawMap(map);
},
(error: any) => {
console.log(error);
}
)
}
private initFolders(rootFolder: MapFolder) {
const children = [];
for (const file of rootFolder.children) {
children.push(new FileTreeNode(file));
}
this.dataSource.data = children;
}
hasChild = (_: number, node: FileTreeNode) => !!node.children;
ngOnDestroy() {
if (this.fsSubcription) {
this.fsSubcription.unsubscribe();
}
}
refresh() {
this.mapFsService.refresh();
}
close() {
return this.sidenav.close();
}
}
| 26,935
|
https://github.com/yandgong307/SNP_calling_pipeline/blob/master/mutationCountsTable/makeGeneCounts_parallel.py
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
SNP_calling_pipeline
|
yandgong307
|
Python
|
Code
| 566
| 1,739
|
#////////////////////////////////////////////////////////////////////
#////////////////////////////////////////////////////////////////////
<<<<<<< HEAD
# script: makeGeneCounts_parallel.py
# author: Lincoln
=======
# script: makeGeneCounts.py
# author: Lincoln
>>>>>>> b6191860c404154094b8aa86beae91fa7578464d
# date: 12.18.18
#
# Creates a gene/cell table for the mutations found in a given
# population of cells. Trying to implement parallelization here
# Run this on a big-ass machine
#
# usage:
# python3 makeGeneCounts_parallel.py
#////////////////////////////////////////////////////////////////////
#////////////////////////////////////////////////////////////////////
import argparse
import numpy as np
import VCF # comes from Kamil Slowikowski
import os
import os.path
import pickle
import csv
import pandas as pd
import re
import sys
import multiprocessing as mp
import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)
def getFileNames(input_dir):
# Get file names based on the specified path
files = []
for file in os.listdir(input_dir):
if file.endswith(".vcf"):
fullPath = (os.path.join(input_dir, file))
files.append(fullPath)
return files
def getGenomePos(sample):
# Returns a genome position sting that will match against the ones w/in COSMIC db
chr = str(sample[0])
chr = chr.replace("chr", "")
pos = int(sample[1])
ref = str(sample[3])
alt = str(sample[4])
if (len(ref) == 1) and (len(alt) == 1): # most basic case
secondPos = pos
elif (len(ref) > 1) and (len(alt) == 1):
secondPos = pos + len(ref)
elif (len(alt) > 1) and (len(ref) == 1):
secondPos = pos + len(alt)
else: # multibase-for-multibase substitution
alts = alt.split(",")
assert len(alts) > 1
len_alts = [len(alt) for alt in alts]
secondPos = pos + max(len_alts)
genomePos = chr + ':' + str(pos) + '-' + str(secondPos)
return genomePos
def getGeneName(posString):
# want to return the gene name from a given genome position string
# (ie. '1:21890111-21890111'), by querying the hg38-plus.gtf
global m19_lookup
# work on posString
chrom = posString.split(':')[0]
posString_remove = posString.split(':')[1]
lPosition = int(posString_remove.split('-')[0])
rPosition = int(posString_remove.split('-')[1])
# work on m19_gtf
chromStr = 'chr' + str(chrom)
gene_names = m19_lookup[chromStr].overlap(rPosition, lPosition+1)
gene_names = list({gname.data for gname in gene_names})
if len(gene_names) > 0:
return gene_names
else:
return ""
def getGeneCellMutCounts(f):
# Creates dictionry obj where every key is a cell and every value is
# a list of the genes we found mutations in for that cell.
tup = [] # not really a tuple, just a list, i guess
cell = os.path.basename(f)
cell = cell.replace(".vcf", "")
print(cell) # to see where we are
df = VCF.dataframe(f)
genomePos_query = df.apply(getGenomePos, axis=1) # apply function for every row in df
shared = list(set(genomePos_query)) # genomePos_query (potentially) has dups
sharedGeneNames = [f for e in shared for f in getGeneName(e)]
tup = [cell, sharedGeneNames]
return(tup)
def formatDataFrame(raw_df):
# logic for creating the cell/mutation counts table from the raw
# output that getGeneCellMutCounts provides
cellNames = list(raw_df.index)
genesList = []
for i in range(0, raw_df.shape[0]):
currList = list(raw_df.iloc[i].unique()) # unique genes for curr_cell
for elm in currList:
if elm not in genesList:
genesList.append(elm)
genesList1 = pd.Series(genesList)
df = pd.DataFrame(columns=genesList1, index=cellNames) # initialize blank dataframe
for col in df.columns: # set everybody to zero
df[col] = 0
for i in range(0,raw_df.shape[0]):
currCell = raw_df.index[i]
currRow = raw_df.iloc[i]
for currGene in currRow:
df[currGene][currCell] += 1
return(df)
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("--ref-gtf",
type=argparse.FileType('r'),
required=True)
parser.add_argument("--input-dir",
required=True)
parser.add_argument("--output",
type=argparse.FileType('w'),
default="geneCellMutationCounts_test_toggle.csv")
parser.add_argument("--nprocs", type=int, default=16)
parser.add_argument("--interval-tree",
type=argparse.FileType("r"),
required=True)
return parser.parse_args()
def main():
global m19_lookup
args = parse_args()
m19_lookup = pickle.load(open(args.interval_tree.name, 'rb'))
fNames = getFileNames(args.input_dir)
print('creating pool')
p = mp.Pool(processes=args.nprocs)
try:
cells_list = p.map(getGeneCellMutCounts, fNames, chunksize=1) # default chunksize=1
finally:
p.close()
p.join()
cells_dict = {}
for item in cells_list:
cells_dict.update({item[0]:item[1]})
print('writing file')
filterDict_pd = pd.DataFrame.from_dict(cells_dict, orient="index") # orient refers to row/col orientation
filterDict_format = formatDataFrame(filterDict_pd)
filterDict_format.to_csv(args.output.name)
if __name__ == "__main__":
main()
| 32,128
|
https://github.com/rstacruz/flowloop/blob/master/web/js/store/settings_reducer.js
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
flowloop
|
rstacruz
|
JavaScript
|
Code
| 261
| 573
|
import buildReducer from 'build-reducer'
import put from '101/put'
import del from '101/del'
import Settings from '../selectors/settings'
/**
* Settings reducer
*/
export default buildReducer({
'init': (state) => {
return put(state, {
'settings': {}
})
},
'settings:update': updateSettings,
'settings:reset': resetSettings,
'timer:setLabelId': setLabelId,
'label:delete': deleteLabel,
'settings:cycleTimerMode': (state, action) => {
const mode = Settings.full(state)['timer:mode']
const idx = Settings.TIMER_MODES.indexOf(mode)
const newIdx = (idx + 1) % Settings.TIMER_MODES.length
const newMode = Settings.TIMER_MODES[newIdx]
return put(state, {
'settings.timer:mode': newMode
})
}
})
/*
* Setting the label for a timer;
* persist it as the default label
*/
function setLabelId (state /*: State */, { id } /*: { id: string } */) /*: State */ {
let settings /*: Settings */ = state.settings || {}
settings = { ...settings, 'labels:default': id }
return { ...state, settings }
}
/**
* When deleting al abel that's the current labels:default,
* reset it to the old default.
*/
function deleteLabel (state /*: State */, { id } /*: { id: string } */) /*: State */ {
let settings /*: Settings */ = state.settings || {}
if (settings['labels:default'] === id) {
settings = del(settings, 'labels:default')
}
return { ...state, settings }
}
/**
* Update settings
*/
function updateSettings (state /*: State */, { payload } /*: { payload: Settings } */) /*: State */ {
let settings /*: Settings */ = state.settings
settings = { ...settings, ...(payload || {}) }
return { ...state, settings }
}
/**
* Resets settings to default.
*/
function resetSettings (state /*: State */) {
return { ...state, settings: {} }
}
| 2,254
|
https://github.com/bosley/vtitan/blob/master/src/titan.hpp
|
Github Open Source
|
Open Source
|
MIT
| null |
vtitan
|
bosley
|
C++
|
Code
| 138
| 479
|
#ifndef TITAN_HPP
#define TITAN_HPP
#include "exec/env.hpp"
#include "exec/exec.hpp"
#include "lang/tokens.hpp"
#include "lang/parser.hpp"
#include <string>
#include <vector>
namespace titan {
class titan : public exec_cb_if {
public:
titan();
~titan();
void set_analyze(bool analyze) { _analyze = analyze; }
void set_execute(bool execute) { _execute = execute; }
int do_repl();
int do_run(std::string file);
void set_include_dirs(std::vector<std::string> dir_list);
// Install an external function to the environment
bool install_xfunc(const std::string& name, env::xfunc *tei)
{
if(!tei){ return false; }
return _environment.add_xfunc(name, tei);
}
instructions::variable* get_env_var(const std::string& name)
{
return _environment.get_variable(name);
}
bool new_env_var(instructions::variable* var, bool as_global)
{
return _environment.new_variable(var, as_global);
}
virtual void signal(exec_sig sig, const std::string& msg) override;
private:
bool _run;
bool _analyze;
bool _execute;
bool _is_repl;
struct fp_info {
std::string_view name;
size_t line;
size_t col;
};
fp_info _current_file;
env _environment;
parser _parser;
exec * _executor;
bool run_tokens(std::vector<TD_Pair> tokens);
};
} // namespace titan
#endif
| 48,969
|
https://github.com/chenUT/spookystuff/blob/master/test-install.sh
|
Github Open Source
|
Open Source
|
LicenseRef-scancode-unknown-license-reference, Apache-2.0
| 2,015
|
spookystuff
|
chenUT
|
Shell
|
Code
| 9
| 48
|
#!/usr/bin/env bash
MAVEN_OPTS="-Xmx3g -XX:MaxPermSize=512M -XX:ReservedCodeCacheSize=512m" mvn clean install -q
| 6,874
|
https://github.com/fisfat/newurban/blob/master/resources/views/articles/search.blade.php
|
Github Open Source
|
Open Source
|
MIT
| null |
newurban
|
fisfat
|
PHP
|
Code
| 45
| 241
|
@extends('layouts.app')
@section('content')
@if(isset($results))
<div class="card">
<div class="card-header">
<h3 class="text-center">SEARCH RESULTS</h3>
</div>
<div class="card-body">
<ul class="list-group list-unstyled text-center">
@foreach($results as $result)
<a href="/articles/{{$result->id}}" style="text-decoration:none;"><li class="list-group-item">{{$result->title}} <em class="" style="font-size:12px;">Created at: {{$result->created_at}}</em></li></a>
@endforeach
</ul>
</div>
</div>
<div class=" row justify-content-center m-4 ">
{{ $results->onEachSide(4)->links() }}
</div>
@endif
@endsection
| 23,317
|
https://github.com/LIbanezDev/fakebook/blob/master/chat/src/app.module.ts
|
Github Open Source
|
Open Source
|
MIT
| null |
fakebook
|
LIbanezDev
|
TypeScript
|
Code
| 43
| 116
|
import { Module } from '@nestjs/common';
import { EmailModule } from './modules/email/email.module';
import { ConfigModule } from '@nestjs/config';
import { globalConfig } from './config/global.config';
@Module({
imports: [
EmailModule,
ConfigModule.forRoot({
cache: true,
isGlobal: true,
load: [globalConfig],
}),
],
})
export class AppModule {
}
| 38,024
|
https://github.com/uvsmtid/turbo-banyan/blob/master/turbo-banyan-student-service/src/test/java/com/spectsys/banyan/utils/JsonUtilsTest.java
|
Github Open Source
|
Open Source
|
MIT
| null |
turbo-banyan
|
uvsmtid
|
Java
|
Code
| 75
| 340
|
package com.spectsys.banyan.utils;
import com.spectsys.banyan.entity.StudentEntity;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import static com.spectsys.banyan.utils.TestData.STUDENT_1;
import static org.junit.jupiter.api.Assertions.assertEquals;
@Slf4j
public class JsonUtilsTest {
@Test
public void round_trip_conversion() {
// GIVEN
final StudentEntity inputObject = STUDENT_1;
// WHEN
final String lineJson = JsonUtils.toLineJson(inputObject);
final String prettyJson = JsonUtils.toPrettyJson(inputObject);
final StudentEntity lineOutputObject = JsonUtils.fromJson(lineJson, StudentEntity.class);
final StudentEntity prettyOutputObject = JsonUtils.fromJson(prettyJson, StudentEntity.class);
// THEN
log.info("lineJson: {}", lineJson);
log.info("prettyJson: {}", prettyJson);
log.info("lineOutputObject: {}", lineOutputObject);
log.info("prettyOutputObject: {}", prettyOutputObject);
assertEquals(inputObject, lineOutputObject);
assertEquals(inputObject, prettyOutputObject);
}
}
| 1,127
|
https://github.com/Kyrie-Zhao/BNN-PYNQ/blob/master/bnn/src/training/augmentors.py
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,020
|
BNN-PYNQ
|
Kyrie-Zhao
|
Python
|
Code
| 459
| 1,205
|
#BSD 3-Clause License
#=======
#
#Copyright (c) 2018, Xilinx Inc.
#All rights reserved.
#
#Redistribution and use in source and binary forms, with or without
#modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
#EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
#WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
#DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY
#DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
#(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
#LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
#ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
#(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
#SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import numpy as np
import scipy.ndimage as ndimg
def linear_rotations(X, Y, angles, original=True):
Xo = np.copy(X)
Yo = np.copy(Y)
i = 0
for angle in angles:
Xtmp = ndimg.rotate(Xo, angle, prefilter=False, mode='nearest', axes=(2,3), reshape=False)
Ytmp = np.copy(Yo)
if not original and i == 0:
X = Xtmp
Y = Ytmp
else:
X = np.append(X, Xtmp, axis=0)
Y = np.append(Y, Ytmp, axis=0)
i += 1
return (X, Y)
def random_rotations(X, Y, rnd_range, factor, extend=True):
if extend:
angles = np.random.uniform(rnd_range[0], rnd_range[1], size=factor)
return linear_rotations(X, Y, angles)
else:
X = np.copy(X)
Y = np.copy(Y)
N = len(Y)
angles = np.random.uniform(rnd_range[0], rnd_range[1], size=(N))
X = np.array(map(lambda v: ndimg.rotate(v[0], v[1], prefilter=False, mode='nearest', axes=(1,2), reshape=False), zip(X,angles)))
return (X, Y)
def adjusted_crop(X, Y, offsets, size):
Xo = np.copy(X)
Yo = np.copy(Y)
w = size[0]
h = size[1]
i = 0
for offset in offsets:
wo=offset[0]
ho=offset[1]
Xtmp = np.copy(Xo[:,:,wo:wo+w,ho:ho+h])
Ytmp = np.copy(Yo)
if i == 0:
X = Xtmp
Y = Ytmp
else:
X = np.append(X, Xtmp, axis=0)
Y = np.append(Y, Ytmp, axis=0)
i += 1
return (X, Y)
def random_crop(X, Y, rnd_range, factor, size, extend=True):
if extend:
offsets = np.random.randint(rnd_range[0], size=(factor,1))
offsets = np.append(offsets, np.random.randint(rnd_range[1], size=(factor,1)), axis=1)
return adjusted_crop(X, Y, offsets, size)
else:
N = len(Y)
w = size[0]
h = size[1]
wos = np.random.randint(rnd_range[0], size=(N))
hos = np.random.randint(rnd_range[1], size=(N))
X = np.array(map(lambda v: v[0][:,v[1]:v[1]+w,v[2]:v[2]+h], zip(X,wos,hos)))
return (X, Y)
| 36,708
|
https://github.com/luyouli/ZHSan/blob/master/WorldOfTheThreeKingdoms/GameObjects/ArchitectureDetail/EventEffect/EventEffectKindPack/EventEffect1230.cs
|
Github Open Source
|
Open Source
|
MS-PL
| 2,021
|
ZHSan
|
luyouli
|
C#
|
Code
| 34
| 121
|
using GameObjects;
using System;
using System.Runtime.Serialization;namespace GameObjects.ArchitectureDetail.EventEffect
{
[DataContract]public class EventEffect1230 : EventEffectKind
{
public override void ApplyEffectKind(Architecture a, Event e)
{
while (a.Facilities.Count > 0)
{
a.DemolishFacility(a.Facilities[0] as Facility);
}
}
}
}
| 10,420
|
https://github.com/open-mpi/ompi-www/blob/master/community/lists/devel/2010/03/7561.php
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,023
|
ompi-www
|
open-mpi
|
PHP
|
Code
| 639
| 2,386
|
<?
$subject_val = "Re: [OMPI devel] Adding error/verbose messages to the TCP BTL";
include("../../include/msg-header.inc");
?>
<!-- received="Sun Mar 7 14:13:28 2010" -->
<!-- isoreceived="20100307191328" -->
<!-- sent="Sun, 7 Mar 2010 14:13:19 -0500" -->
<!-- isosent="20100307191319" -->
<!-- name="George Bosilca" -->
<!-- email="bosilca_at_[hidden]" -->
<!-- subject="Re: [OMPI devel] Adding error/verbose messages to the TCP BTL" -->
<!-- id="B5F8F3C0-00C2-456D-A024-B91604F19D31_at_eecs.utk.edu" -->
<!-- charset="us-ascii" -->
<!-- inreplyto="B1023930-85F4-4C38-B4A3-2103F0D7C17A_at_open-mpi.org" -->
<!-- expires="-1" -->
<div class="center">
<table border="2" width="100%" class="links">
<tr>
<th><a href="date.php">Date view</a></th>
<th><a href="index.php">Thread view</a></th>
<th><a href="subject.php">Subject view</a></th>
<th><a href="author.php">Author view</a></th>
</tr>
</table>
</div>
<p class="headers">
<strong>Subject:</strong> Re: [OMPI devel] Adding error/verbose messages to the TCP BTL<br>
<strong>From:</strong> George Bosilca (<em>bosilca_at_[hidden]</em>)<br>
<strong>Date:</strong> 2010-03-07 14:13:19
</p>
<ul class="links">
<!-- next="start" -->
<li><strong>Next message:</strong> <a href="7562.php">George Bosilca: "Re: [OMPI devel] RFC: Rename --enable-*-threads and ENABLE*THREAD* (take 2)"</a>
<li><strong>Previous message:</strong> <a href="7560.php">Leonardo Fialho: "Re: [OMPI devel] Missing Symbol"</a>
<li><strong>In reply to:</strong> <a href="7559.php">Ralph Castain: "Re: [OMPI devel] Adding error/verbose messages to the TCP BTL"</a>
<!-- nextthread="start" -->
<li><strong>Next in thread:</strong> <a href="7564.php">Jeff Squyres: "Re: [OMPI devel] Adding error/verbose messages to the TCP BTL"</a>
<li><strong>Reply:</strong> <a href="7564.php">Jeff Squyres: "Re: [OMPI devel] Adding error/verbose messages to the TCP BTL"</a>
<!-- reply="end" -->
</ul>
<hr>
<!-- body="start" -->
<p>
Then let's just be patient until OPAL_SOS make it in the trunk, and save us the burden of a large effort made twice.
<br>
<p> george.
<br>
<p>On Mar 5, 2010, at 22:35 , Ralph Castain wrote:
<br>
<p><span class="quotelev1">>
</span><br>
<span class="quotelev1">> On Mar 5, 2010, at 7:22 PM, Jeff Squyres wrote:
</span><br>
<span class="quotelev1">>
</span><br>
<span class="quotelev2">>> On Mar 5, 2010, at 6:10 PM, Ralph Castain wrote:
</span><br>
<span class="quotelev2">>>
</span><br>
<span class="quotelev4">>>>> I agree with Jeff's comments about the BTL_ERROR. How about a middle ground here? We let the BTLs use BTL_ERROR, eventually with some modifications, and we redirect the BTL_ERROR to a more advanced macro including support for orte_show_help? This will require going over all the BTLs, but on the bright side it will give us a 100% consistency on retorting errors.
</span><br>
<span class="quotelev3">>>>
</span><br>
<span class="quotelev3">>>> Sounds reasonable to me - I'm happy to help do it, assuming Jeff also concurs. I assume we would then replace all the show_help calls as well? Otherwise, I'm not sure what we gain as the direct orte_show_help dependency will remain. Or are those calls too specialized to be replaced with BTL_ERROR?
</span><br>
<span class="quotelev2">>>
</span><br>
<span class="quotelev2">>> Should this kind of thing wait for OPAL_SOS?
</span><br>
<span class="quotelev2">>>
</span><br>
<span class="quotelev2">>> (I mention this because the OPAL_SOS RFC will be sent to devel Real Soon Now...)
</span><br>
<span class="quotelev1">>
</span><br>
<span class="quotelev1">> Sure - OPAL_SOS will supersede all this anyway.
</span><br>
<span class="quotelev1">>
</span><br>
<span class="quotelev2">>>
</span><br>
<span class="quotelev2">>> --
</span><br>
<span class="quotelev2">>> Jeff Squyres
</span><br>
<span class="quotelev2">>> jsquyres_at_[hidden]
</span><br>
<span class="quotelev2">>> For corporate legal information go to:
</span><br>
<span class="quotelev2">>> <a href="http://www.cisco.com/web/about/doing_business/legal/cri/">http://www.cisco.com/web/about/doing_business/legal/cri/</a>
</span><br>
<span class="quotelev2">>>
</span><br>
<span class="quotelev2">>>
</span><br>
<span class="quotelev2">>> _______________________________________________
</span><br>
<span class="quotelev2">>> devel mailing list
</span><br>
<span class="quotelev2">>> devel_at_[hidden]
</span><br>
<span class="quotelev2">>> <a href="http://www.open-mpi.org/mailman/listinfo.cgi/devel">http://www.open-mpi.org/mailman/listinfo.cgi/devel</a>
</span><br>
<span class="quotelev1">>
</span><br>
<span class="quotelev1">>
</span><br>
<span class="quotelev1">> _______________________________________________
</span><br>
<span class="quotelev1">> devel mailing list
</span><br>
<span class="quotelev1">> devel_at_[hidden]
</span><br>
<span class="quotelev1">> <a href="http://www.open-mpi.org/mailman/listinfo.cgi/devel">http://www.open-mpi.org/mailman/listinfo.cgi/devel</a>
</span><br>
<!-- body="end" -->
<hr>
<ul class="links">
<!-- next="start" -->
<li><strong>Next message:</strong> <a href="7562.php">George Bosilca: "Re: [OMPI devel] RFC: Rename --enable-*-threads and ENABLE*THREAD* (take 2)"</a>
<li><strong>Previous message:</strong> <a href="7560.php">Leonardo Fialho: "Re: [OMPI devel] Missing Symbol"</a>
<li><strong>In reply to:</strong> <a href="7559.php">Ralph Castain: "Re: [OMPI devel] Adding error/verbose messages to the TCP BTL"</a>
<!-- nextthread="start" -->
<li><strong>Next in thread:</strong> <a href="7564.php">Jeff Squyres: "Re: [OMPI devel] Adding error/verbose messages to the TCP BTL"</a>
<li><strong>Reply:</strong> <a href="7564.php">Jeff Squyres: "Re: [OMPI devel] Adding error/verbose messages to the TCP BTL"</a>
<!-- reply="end" -->
</ul>
<div class="center">
<table border="2" width="100%" class="links">
<tr>
<th><a href="date.php">Date view</a></th>
<th><a href="index.php">Thread view</a></th>
<th><a href="subject.php">Subject view</a></th>
<th><a href="author.php">Author view</a></th>
</tr>
</table>
</div>
<!-- trailer="footer" -->
<? include("../../include/msg-footer.inc") ?>
| 42,766
|
https://github.com/athiththan11/RepoDeWS/blob/master/src/main/java/com/athiththan/soap/devservice/model/Repo.java
|
Github Open Source
|
Open Source
|
MIT
| null |
RepoDeWS
|
athiththan11
|
Java
|
Code
| 204
| 669
|
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.7
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2019.08.02 at 10:50:33 PM IST
//
package com.athiththan.soap.devservice.model;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>
* Java class for repo complex type.
*
* <p>
* The following schema fragment specifies the expected content contained within
* this class.
*
* <pre>
* <complexType name="repo">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="name" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="username" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="forks" type="{http://www.w3.org/2001/XMLSchema}int"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "repo", propOrder = { "name", "username", "forks" })
@Entity
public class Repo {
@Id
@XmlElement(required = true)
protected String name;
@XmlElement(required = true)
protected String username;
protected int forks;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getForks() {
return forks;
}
public void setForks(int forks) {
this.forks = forks;
}
}
| 19,763
|
https://github.com/StriveMath/codemedium-editor/blob/master/src/css/quasar.variables.sass
|
Github Open Source
|
Open Source
|
Unlicense
| 2,021
|
codemedium-editor
|
StriveMath
|
Sass
|
Code
| 154
| 725
|
// Quasar Sass (& SCSS) Variables
// @see https://coolors.co/1e1e3f-fad000-ff628c-3ad900-9effff-8ef9f3-ffffff-cbf3f0-2ec4b6-756d54
// Blocks
$block-red: #ff628c
$block-orange: #FF9D00
$block-yellow: #fad000
$block-green: #2ca300
$block-teal: #2EC4B6
$block-blue: #5D37F0
// Theme
$tertiary: #6a63a1
$bg-main: #2d2b55
$icon-active: #fff
$icon-inactive: #A599E9
$item-active-bg: #222244
$item-inactive-bg: #28284e
$scrollbar-draggable: #6a63a1
$scrollbar-draggable-hover: #4d21fc
// Terminal
$ansi-black: #000000
$ansi-red: #EC3A37F5
$ansi-green: #3AD900
$ansi-yellow: $block-orange
$ansi-blue: #6943FF
$ansi-magenta: #FF2C70
$ansi-cyan: #80FCFF
$ansi-white: #FFFFFF
$ansi-bright-black: #5C5C61
$ansi-bright-red: #EC3A37F5
$ansi-bright-green: #3AD900
$ansi-bright-yellow: $block-orange
$ansi-bright-blue: #6943FF
$ansi-bright-magenta: #FB94FF
$ansi-bright-cyan: #80FCFF
$ansi-bright-white: #FFFFFF
// Quasar overrides
$panel-padding: 20px
$primary : #1e1e3f
$secondary : $block-yellow
$accent : $block-yellow
$dark : #222244
$positive : $block-green
$negative : $block-red
$info : #9effff
$warning : $block-orange
$h1: (size: 3rem, line-height: 3rem, letter-spacing: -.01562em, weight: 600)
$h2: (size: 2rem, line-height: 2rem, letter-spacing: -.01562em, weight: 600)
$h3: (size: 1.5rem, line-height: 1.5rem, letter-spacing: -.01562em, weight: 600)
$separator-color-dark: darken($dark, 5%) !important
$separator-color: darken($dark, 5%) !important
// Functinos
@function anti-bg-color($color)
@if (lightness( $color ) > 40)
@return $dark
@else
@return #ffffff
| 21,603
|
https://github.com/remore/gemstat/blob/master/lib/gemstat/cache/gemfiles/r/rtrace:0.0.2/Gemfile
|
Github Open Source
|
Open Source
|
MIT
| 2,015
|
gemstat
|
remore
|
Ruby
|
Code
| 2
| 8
|
gem 'geocoder'
| 12,751
|
https://github.com/mellinoe/corefx/blob/master/src/System.Linq.Expressions/tests/Catalog/ReflectionExtensions.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,017
|
corefx
|
mellinoe
|
C#
|
Code
| 51
| 135
|
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Reflection;
namespace System.Linq.Expressions.Tests
{
static class ReflectionExtensions
{
public static ConstructorInfo GetDeclaredConstructor(this TypeInfo type, Type[] parameterTypes)
{
return type.DeclaredConstructors.SingleOrDefault(c => c.GetParameters().Select(p => p.ParameterType).SequenceEqual(parameterTypes));
}
}
}
| 48,105
|
https://github.com/cityjoy/NetCoreFrame.Admin/blob/master/CoreFrame.Web/Areas/Base_SysManage/Controllers/Base_MenuController.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
NetCoreFrame.Admin
|
cityjoy
|
C#
|
Code
| 218
| 916
|
using CoreFrame.Business.Base_SysManage;
using CoreFrame.Entity.MenuManage;
using CoreFrame.Util;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Linq;
namespace CoreFrame.Web
{
[Area("Base_SysManage")]
public class Base_MenuController : BaseMvcController
{
private IBase_MenuBusiness _base_MenuBusiness ;
public Base_MenuController(IBase_MenuBusiness dev_Base_MenuBusiness)
{
_base_MenuBusiness = dev_Base_MenuBusiness;
}
#region 视图功能
public ActionResult Index()
{
return View();
}
public ActionResult Form(int id)
{
var theData = id.IsNullOrEmpty() ? new Menu() : _base_MenuBusiness.GetEntity(id);
return View(theData);
}
#endregion
#region 获取数据
/// <summary>
/// 获取数据列表
/// </summary>
/// <param name="condition">查询类型</param>
/// <param name="keyword">关键字</param>
/// <returns></returns>
public ActionResult GetDataList(string condition, string keyword, Pagination pagination)
{
var dataList = _base_MenuBusiness.GetDataList(condition, keyword, pagination);
return Content(pagination.BuildTableResult_DataGrid(dataList).ToJson());
}
/// <summary>
/// 获取数据列表
/// </summary>
/// <param name="menuLevel">查询类型</param>
/// <returns></returns>
public ActionResult GetMenuLevel(string menuLevel)
{
var dataList = _base_MenuBusiness.GetIQueryableList(m=>m.MenuLevel== menuLevel).ToList();
return Content(dataList.ToJson());
}
#endregion
#region 提交数据
/// <summary>
/// 保存
/// </summary>
/// <param name="theData">保存的数据</param>
public ActionResult SaveData(Menu theData)
{
if (theData.MenuLevel == "3")
{
theData.Permission = theData.ModuleValue + "." + "search";
}
if (theData.Id==0)
{
if (theData.MenuLevel == "1")
{
if (_base_MenuBusiness.GetIQueryableList(m => m.ModuleValue == theData.ModuleValue).Any())
{
return Error("保存失败,模块值已存在");
}
}
_base_MenuBusiness.Insert(theData);
}
else
{
if (theData.MenuLevel == "1")
{
if (_base_MenuBusiness.GetIQueryableList(m => m.ModuleValue == theData.ModuleValue && m.MenuLevel == "1"&&m.Id!=theData.Id).Any())
{
return Error("保存失败,模块值已存在");
}
}
_base_MenuBusiness.Update(theData);
}
return Success();
}
/// <summary>
/// 删除数据
/// </summary>
/// <param name="theData">删除的数据</param>
public ActionResult DeleteData(string ids)
{
_base_MenuBusiness.Delete(ids.ToList<string>());
return Success("删除成功!");
}
#endregion
}
}
| 24,449
|
https://github.com/jaysonsantos/python-binary-memcached/blob/master/bmemcached/client/mixin.py
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
python-binary-memcached
|
jaysonsantos
|
Python
|
Code
| 484
| 1,472
|
import six
from bmemcached.client.constants import PICKLE_PROTOCOL, SOCKET_TIMEOUT
from bmemcached.compat import pickle
from bmemcached.protocol import Protocol
class ClientMixin(object):
""" Client mixin with basic commands.
:param servers: A list of servers with ip[:port] or unix socket.
:type servers: list
:param username: If your server requires SASL authentication, provide the username.
:type username: six.string_types
:param password: If your server requires SASL authentication, provide the password.
:type password: six.string_types
:param compression: This memcached client uses zlib compression by default,
but you can change it to any Python module that provides
`compress` and `decompress` functions, such as `bz2`.
:type compression: Python module
:param socket_timeout: The timeout applied to memcached connections.
:type socket_timeout: float
:param pickle_protocol: The pickling protocol to use, 0-5. See
https://docs.python.org/3/library/pickle.html#data-stream-format
default is 0 (human-readable, original format).
:type pickle_protocol: int
:param pickler: Use this to replace the object serialization mechanism.
:type pickler: function
:param unpickler: Use this to replace the object deserialization mechanism.
:type unpickler: function
:param tls_context: A TLS context in order to connect to TLS enabled
memcached servers.
:type tls_context: ssl.SSLContext
"""
def __init__(self, servers=('127.0.0.1:11211',),
username=None,
password=None,
compression=None,
socket_timeout=SOCKET_TIMEOUT,
pickle_protocol=PICKLE_PROTOCOL,
pickler=pickle.Pickler,
unpickler=pickle.Unpickler,
tls_context=None):
self.username = username
self.password = password
self.compression = compression
self.socket_timeout = socket_timeout
self.pickle_protocol = pickle_protocol
self.pickler = pickler
self.unpickler = unpickler
self.tls_context = tls_context
self.set_servers(servers)
@property
def servers(self):
for server in self._servers:
yield server
def set_servers(self, servers):
"""
Iter to a list of servers and instantiate Protocol class.
:param servers: A list of servers
:type servers: list
:return: Returns nothing
:rtype: None
"""
if isinstance(servers, six.string_types):
servers = [servers]
assert servers, "No memcached servers supplied"
self._servers = [Protocol(
server=server,
username=self.username,
password=self.password,
compression=self.compression,
socket_timeout=self.socket_timeout,
pickle_protocol=self.pickle_protocol,
pickler=self.pickler,
unpickler=self.unpickler,
tls_context=self.tls_context,
) for server in servers]
def flush_all(self, time=0):
"""
Send a command to server flush|delete all keys.
:param time: Time to wait until flush in seconds.
:type time: int
:return: True in case of success, False in case of failure
:rtype: bool
"""
returns = []
for server in self.servers:
returns.append(server.flush_all(time))
return any(returns)
def stats(self, key=None):
"""
Return server stats.
:param key: Optional if you want status from a key.
:type key: six.string_types
:return: A dict with server stats
:rtype: dict
"""
# TODO: Stats with key is not working.
returns = {}
for server in self.servers:
returns[server.server] = server.stats(key)
return returns
def disconnect_all(self):
"""
Disconnect all servers.
:return: Nothing
:rtype: None
"""
for server in self.servers:
server.disconnect()
def get(self, key, default=None, get_cas=False):
raise NotImplementedError()
def gets(self, key):
raise NotImplementedError()
def get_multi(self, keys, get_cas=False):
raise NotImplementedError()
def set(self, key, value, time=0, compress_level=-1):
raise NotImplementedError()
def cas(self, key, value, cas, time=0, compress_level=-1):
raise NotImplementedError()
def set_multi(self, mappings, time=0, compress_level=-1):
raise NotImplementedError()
def add(self, key, value, time=0, compress_level=-1):
raise NotImplementedError()
def replace(self, key, value, time=0, compress_level=-1):
raise NotImplementedError()
def delete(self, key, cas=0): # type: (six.string_types, int) -> bool
raise NotImplementedError()
def delete_multi(self, keys):
raise NotImplementedError()
def incr(self, key, value):
# TODO: Implement missing parameters
raise NotImplementedError()
def decr(self, key, value):
# TODO: Implement missing parameters
raise NotImplementedError()
| 25,411
|
https://github.com/mehdisellami/dropShippingdeploy/blob/master/wp-content/plugins/facebook-for-woocommerce/includes/Products.php
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
dropShippingdeploy
|
mehdisellami
|
PHP
|
Code
| 1,677
| 4,289
|
<?php
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
*
* This source code is licensed under the license found in the
* LICENSE file in the root directory of this source tree.
*
* @package FacebookCommerce
*/
namespace SkyVerge\WooCommerce\Facebook;
use WC_Facebook_Product;
defined( 'ABSPATH' ) or exit;
/**
* Products handler.
*
* @since 1.10.0
*/
class Products {
/** @var string the meta key used to flag whether a product should be synced in Facebook */
const SYNC_ENABLED_META_KEY = '_wc_facebook_sync_enabled';
// TODO probably we'll want to run some upgrade routine or somehow move meta keys to follow the same patter e.g. _wc_facebook_visibility {FN 2020-01-17}
/** @var string the meta key used to flag whether a product should be visible in Facebook */
const VISIBILITY_META_KEY = 'fb_visibility';
/** @var string the meta key used to the source of the product in Facebook */
const PRODUCT_IMAGE_SOURCE_META_KEY = '_wc_facebook_product_image_source';
/** @var string product image source option to use the product image of simple products or the variation image of variations in Facebook */
const PRODUCT_IMAGE_SOURCE_PRODUCT = 'product';
/** @var string product image source option to use the parent product image in Facebook */
const PRODUCT_IMAGE_SOURCE_PARENT_PRODUCT = 'parent_product';
/** @var string product image source option to use the parent product image in Facebook */
const PRODUCT_IMAGE_SOURCE_CUSTOM = 'custom';
/** @var array memoized array of sync enabled status for products */
private static $products_sync_enabled = [];
/** @var array memoized array of visibility status for products */
private static $products_visibility = [];
/**
* Sets the sync handling for products to enabled or disabled.
*
* @since 1.10.0
*
* @param \WC_Product[] $products array of product objects
* @param bool $enabled whether sync should be enabled for $products
*/
private static function set_sync_for_products( array $products, $enabled ) {
self::$products_sync_enabled = [];
$enabled = wc_bool_to_string( $enabled );
foreach ( $products as $product ) {
if ( $product instanceof \WC_Product ) {
if ( $product->is_type( 'variable' ) ) {
foreach ( $product->get_children() as $variation ) {
$product_variation = wc_get_product( $variation );
if ( $product_variation instanceof \WC_Product ) {
$product_variation->update_meta_data( self::SYNC_ENABLED_META_KEY, $enabled );
$product_variation->save_meta_data();
}
}
} else {
$product->update_meta_data( self::SYNC_ENABLED_META_KEY, $enabled );
$product->save_meta_data();
}
}
}
}
/**
* Enables sync for given products.
*
* @since 1.10.0
*
* @param \WC_Product[] $products an array of product objects
*/
public static function enable_sync_for_products( array $products ) {
self::set_sync_for_products( $products, true );
}
/**
* Disables sync for given products.
*
* @since 1.10.0
*
* @param \WC_Product[] $products an array of product objects
*/
public static function disable_sync_for_products( array $products ) {
self::set_sync_for_products( $products, false );
}
/**
* Disables sync for products that belong to the given category or tag.
*
* @since 2.0.0
*
* @param array $args {
* @type string|array $taxonomy product_cat or product_tag
* @type string|array $include array or comma/space-separated string of term IDs to include
* }
*/
public static function disable_sync_for_products_with_terms( array $args ) {
$args = wp_parse_args( $args, [
'taxonomy' => 'product_cat',
'include' => [],
] );
$products = [];
// get all products belonging to the given terms
if ( is_array( $args['include'] ) && ! empty( $args['include'] ) ) {
$terms = get_terms( [
'taxonomy' => $args['taxonomy'],
'fields' => 'slugs',
'include' => array_map( 'intval', $args['include'] ),
] );
if ( ! is_wp_error( $terms ) && ! empty( $terms ) ) {
$taxonomy = $args['taxonomy'] === 'product_tag' ? 'tag' : 'category';
$products = wc_get_products( [
$taxonomy => $terms,
'limit' => -1,
] );
}
}
if ( ! empty( $products ) ) {
Products::disable_sync_for_products( $products );
}
}
/**
* Determines whether the given product should be synced.
*
* @see Products::published_product_should_be_synced()
*
* @since 1.10.0
*
* @param \WC_Product $product
* @return bool
*/
public static function product_should_be_synced( \WC_Product $product ) {
return 'publish' === $product->get_status() && self::published_product_should_be_synced( $product );
}
/**
* Determines whether the given product should be synced assuming the product is published.
*
* If a product is enabled for sync, but belongs to an excluded term, it will return as excluded from sync:
* @see Products::is_sync_enabled_for_product()
* @see Products::is_sync_excluded_for_product_terms()
*
* @since 2.0.0-dev.1
*
* @param \WC_Product $product
* @return bool
*/
public static function published_product_should_be_synced( \WC_Product $product ) {
$should_sync = self::is_sync_enabled_for_product( $product );
// define the product to check terms on
if ( $should_sync ) {
$terms_product = $product->is_type( 'variation' ) ? wc_get_product( $product->get_parent_id() ) : $product;
} else {
$terms_product = null;
}
// allow simple or variable products (and their variations) with zero or empty price - exclude other product types with zero or empty price
if ( $should_sync && ( ! $terms_product || ( ! self::get_product_price( $product ) && ! in_array( $terms_product->get_type(), [ 'simple', 'variable' ] ) ) ) ) {
$should_sync = false;
}
// exclude products that are excluded from the store catalog or from search results
if ( $should_sync && ( ! $terms_product || has_term( [ 'exclude-from-catalog', 'exclude-from-search' ], 'product_visibility', $terms_product->get_id() ) ) ) {
$should_sync = false;
}
// exclude products that belong to one of the excluded terms
if ( $should_sync && ( ! $terms_product || self::is_sync_excluded_for_product_terms( $terms_product ) ) ) {
$should_sync = false;
}
return $should_sync;
}
/**
* Determines whether the given product should be removed from the catalog.
*
* A product should be removed if it is no longer in stock and the user has opted-in to hide products that are out of stock.
*
* @since 2.0.0
*
* @param \WC_Product $product
* @return bool
*/
public static function product_should_be_deleted( \WC_Product $product ) {
return 'yes' === get_option( 'woocommerce_hide_out_of_stock_items' ) && ! $product->is_in_stock();
}
/**
* Determines whether a product is enabled to be synced in Facebook.
*
* If the product is not explicitly set to disable sync, it'll be considered enabled.
* This applies to products that may not have the meta value set.
*
* @since 1.10.0
*
* @param \WC_Product $product product object
* @return bool
*/
public static function is_sync_enabled_for_product( \WC_Product $product ) {
if ( ! isset( self::$products_sync_enabled[ $product->get_id() ] ) ) {
if ( $product->is_type( 'variable' ) ) {
// assume variable products are not synced until a synced child is found
$enabled = false;
foreach ( $product->get_children() as $child_id ) {
$child_product = wc_get_product( $child_id );
if ( $child_product && self::is_sync_enabled_for_product( $child_product ) ) {
$enabled = true;
break;
}
}
} else {
$enabled = 'no' !== $product->get_meta( self::SYNC_ENABLED_META_KEY );
}
self::$products_sync_enabled[ $product->get_id() ] = $enabled;
}
return self::$products_sync_enabled[ $product->get_id() ];
}
/**
* Determines whether the product's terms would make it excluded to be synced from Facebook.
*
* @since 1.10.0
*
* @param \WC_Product $product product object
* @return bool if true, product should be excluded from sync, if false, product can be included in sync (unless manually excluded by individual product meta)
*/
public static function is_sync_excluded_for_product_terms( \WC_Product $product ) {
if ( $integration = facebook_for_woocommerce()->get_integration() ) {
$excluded_categories = $integration->get_excluded_product_category_ids();
$excluded_tags = $integration->get_excluded_product_tag_ids();
} else {
$excluded_categories = $excluded_tags = [];
}
$categories = $product->get_category_ids();
$tags = $product->get_tag_ids();
// returns true if no terms on the product, or no terms excluded, or if the product does not contain any of the excluded terms
$matches = ( ! $categories || ! $excluded_categories || ! array_intersect( $categories, $excluded_categories ) )
&& ( ! $tags || ! $excluded_tags || ! array_intersect( $tags, $excluded_tags ) );
return ! $matches;
}
/**
* Sets a product's visibility in the Facebook shop.
*
* @since 1.10.0
*
* @param \WC_Product $product product object
* @param bool $visibility true for 'published' or false for 'staging'
* @return bool success
*/
public static function set_product_visibility( \WC_Product $product, $visibility ) {
unset( self::$products_visibility[ $product->get_id() ] );
if ( ! is_bool( $visibility ) ) {
return false;
}
$product->update_meta_data( self::VISIBILITY_META_KEY, wc_bool_to_string( $visibility ) );
$product->save_meta_data();
self::$products_visibility[ $product->get_id() ] = $visibility;
return true;
}
/**
* Checks whether a product should be visible on Facebook.
*
* @since 1.10.0
*
* @param \WC_Product $product
* @return bool
*/
public static function is_product_visible( \WC_Product $product ) {
// accounts for a legacy bool value, current should be (string) 'yes' or (string) 'no'
if ( ! isset( self::$products_visibility[ $product->get_id() ] ) ) {
if ( $product->is_type( 'variable' ) ) {
// assume variable products are not visible until a visible child is found
$is_visible = false;
foreach ( $product->get_children() as $child_id ) {
$child_product = wc_get_product( $child_id );
if ( $child_product && self::is_product_visible( $child_product ) ) {
$is_visible = true;
break;
}
}
} elseif ( $meta = $product->get_meta( self::VISIBILITY_META_KEY ) ) {
$is_visible = wc_string_to_bool( $product->get_meta( self::VISIBILITY_META_KEY ) );
} else {
$is_visible = true;
}
self::$products_visibility[ $product->get_id() ] = $is_visible;
}
return self::$products_visibility[ $product->get_id() ];
}
/**
* Gets the product price used for Facebook sync.
*
* TODO: Consider adding memoization, but ensure we can protect the implementation against price changes during the same request {WV-2020-08-20}
* See https://github.com/facebookincubator/facebook-for-woocommerce/pull/1468
*
* @since 2.0.0-dev.1
*
* @param int $price product price in cents
* @param \WC_Product $product product object
* @return int
*/
public static function get_product_price( \WC_Product $product ) {
$facebook_price = $product->get_meta( WC_Facebook_Product::FB_PRODUCT_PRICE );
// use the user defined Facebook price if set
if ( is_numeric( $facebook_price ) ) {
$price = $facebook_price;
} elseif ( class_exists( 'WC_Product_Composite' ) && $product instanceof \WC_Product_Composite ) {
$price = get_option( 'woocommerce_tax_display_shop' ) === 'incl' ? $product->get_composite_price_including_tax() : $product->get_composite_price();
} elseif ( class_exists( 'WC_Product_Bundle' )
&& empty( $product->get_regular_price() )
&& 'bundle' === $product->get_type() ) {
// if product is a product bundle with individually priced items, we rely on their pricing
$price = wc_get_price_to_display( $product, [ 'price' => $product->get_bundle_price() ] );
} else {
$price = wc_get_price_to_display( $product, [ 'price' => $product->get_regular_price() ] );
}
$price = (int) ( $price ? round( $price * 100 ) : 0 );
/**
* Filters the product price used for Facebook sync.
*
* @since 2.0.0-dev.1
*
* @param int $price product price in cents
* @param float $facebook_price user defined facebook price
* @param \WC_Product $product product object
*/
return (int) apply_filters( 'wc_facebook_product_price', $price, (float) $facebook_price, $product );
}
}
| 7,099
|
https://github.com/dityafaizal/niagahoster/blob/master/resources/js/components/module/ModuleList.vue
|
Github Open Source
|
Open Source
|
MIT
| null |
niagahoster
|
dityafaizal
|
Vue
|
Code
| 54
| 220
|
<template>
<div class="module__list">
<div class="module__list--title">
<h1>Modul Lengkap untuk Menjalankan Aplikasi Anda.</h1>
</div>
<div class="module__list--list">
<ul>
<li v-for="(data, i) in listModules.modules" :key="i">{{data.module}}</li>
</ul>
</div>
<div class="module__list--cta btn md transblue">
Selengkapnya
</div>
</div>
</template>
<script>
import ModuleList from '../../json/ModuleList.json';
export default {
data() {
return {
listModules: ModuleList,
}
}
}
</script>
<style lang="css" scoped>
</style>
| 21,794
|
https://github.com/BT-OpenSource/bt-openlink-java/blob/master/openlink-core/src/main/java/com/bt/openlink/type/CallFeatureDeviceKey.java
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
bt-openlink-java
|
BT-OpenSource
|
Java
|
Code
| 160
| 512
|
package com.bt.openlink.type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.annotation.Nonnull;
public final class CallFeatureDeviceKey extends CallFeature {
private static final long serialVersionUID = -1837276539059039203L;
@Nonnull private final List<DeviceKey> deviceKeys;
private CallFeatureDeviceKey(@Nonnull final Builder builder) {
super(builder);
this.deviceKeys = Collections.unmodifiableList(builder.deviceKeys);
}
@Nonnull
public List<DeviceKey> getDeviceKeys() {
return deviceKeys;
}
public static final class Builder extends AbstractCallFeatureBuilder<Builder> {
@Nonnull private final List<DeviceKey> deviceKeys = new ArrayList<>();
private Builder() {
}
@Nonnull
public static Builder start() {
return new Builder();
}
@Nonnull
public CallFeatureDeviceKey build() {
setType(FeatureType.DEVICE_KEYS);
validate();
return new CallFeatureDeviceKey(this);
}
@Nonnull
public CallFeatureDeviceKey build(final List<String> errors) {
setType(FeatureType.DEVICE_KEYS);
validate(errors);
return new CallFeatureDeviceKey(this);
}
@Override
protected void validate() {
super.validate();
if (deviceKeys.isEmpty()) {
throw new IllegalStateException("At least one device key must be set");
}
}
@Override
public void validate(final List<String> errors) {
super.validate(errors);
if (deviceKeys.isEmpty()) {
errors.add("Invalid feature; at least one device key must be set");
}
}
@Nonnull
public Builder addDeviceKey(@Nonnull final DeviceKey deviceKey) {
this.deviceKeys.add(deviceKey);
return this;
}
}
}
| 28,297
|
https://github.com/acaria/ajras/blob/master/Resources/config.plist
|
Github Open Source
|
Open Source
|
MIT
| 2,016
|
ajras
|
acaria
|
XML Property List
|
Code
| 63
| 510
|
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Gameplay</key>
<dict>
<key>Rules</key>
<dict>
<key>SpecialInterval</key>
<string>15</string>
<key>MovesInterval</key>
<integer>1</integer>
</dict>
<key>Touch</key>
<dict>
<key>SwipeSpeed</key>
<real>0.2</real>
<key>SwipeLength</key>
<integer>30</integer>
</dict>
</dict>
<key>GridDim</key>
<dict>
<key>width</key>
<integer>11</integer>
<key>height</key>
<integer>9</integer>
</dict>
<key>GridLayout</key>
<dict>
<key>PanelPosition</key>
<dict>
<key>x</key>
<integer>210</integer>
<key>y</key>
<integer>20</integer>
</dict>
<key>BlockSize</key>
<dict>
<key>height</key>
<integer>60</integer>
<key>width</key>
<integer>60</integer>
</dict>
<key>GridPosition</key>
<dict>
<key>x</key>
<integer>13</integer>
<key>y</key>
<integer>13</integer>
</dict>
</dict>
</dict>
</plist>
| 9,723
|
https://github.com/hardykay/lara-for-tp/blob/master/tests/Features/ArtisanTest.php
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
lara-for-tp
|
hardykay
|
PHP
|
Code
| 68
| 360
|
<?php
namespace Larafortp\Tests\Features;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Support\Str;
use Larafortp\Tests\TestCase;
class ArtisanTest extends TestCase
{
public function testMakeModel()
{
$this->artisan('make:model Test');
$this->assertFileExists(base_path('app/Test.php'));
}
public function testMakeFactory()
{
$this->artisan('make:factory Test');
$this->assertFileExists(database_path('factories/Test.php'));
}
public function testMakeSeed()
{
$this->artisan('make:seeder TestSeeder');
$this->assertFileExists(database_path('seeds/TestSeeder.php'));
}
public function testMakeMigration()
{
$this->artisan('make:migration create_test_table');
$files = new Filesystem();
$exists_flag = false;
collect($files->files(database_path('migrations')))->each(function ($item) use (&$exists_flag) {
if (Str::is(date('Y_m_d_Hi').'*'.'_create_test_table.php', $item->getRelativePathname())) {
$exists_flag = true;
}
});
$this->assertTrue($exists_flag);
}
}
| 43,973
|
https://github.com/weisenzcharles/weinode/blob/master/Java/learning-notes/base-example/src/main/java/org/charles/learning/base/thread/concurrent/CounterThread.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
weinode
|
weisenzcharles
|
Java
|
Code
| 102
| 257
|
package org.charles.learning.thread.concurrent;
import java.util.concurrent.locks.ReentrantLock;
public class CounterThread extends Thread {
private String name;
public CounterThread(String name) {
this.name = name;
}
public void run() {
Counter.add();
System.out.println(this.name + " Count is " + Counter.getCount());
}
public static void main(String[] args) {
for (int i = 0; i < 5000; i++) {
CounterThread mt1 = new CounterThread("Thread-" + i);
mt1.start();
}
}
static class Counter {
private final static ReentrantLock LOCK = new ReentrantLock(true);
private static int counter = 0;
public static int getCount() {
return counter;
}
public static void add() {
LOCK.lock();
counter = counter + 1;
LOCK.unlock();
}
}
}
| 6,580
|
https://github.com/xxxmpsxxx/IqOptionApiDotNet/blob/master/src/IqOptionApiDotNet/Wss/IqOptionWebSocketClient.GetInitializationData.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
IqOptionApiDotNet
|
xxxmpsxxx
|
C#
|
Code
| 30
| 130
|
using System.Threading.Tasks;
using IqOptionApiDotNet.Models;
using IqOptionApiDotNet.Ws.Request;
namespace IqOptionApiDotNet.Ws
{
public partial class IqOptionWebSocketClient
{
#region [GetInitializationData]
public Task<InitializationData> GetInitializationDataAsync(string requestId)
{
return SendMessageAsync(requestId, new GetInitializationDataRequestMessage(), InitializationDataObservable);
}
#endregion
}
}
| 1,412
|
https://github.com/Greator/playground_internal/blob/master/web/app/plugins/buddyboss-platform/bp-templates/bp-nouveau/buddypress/video/add-video-thumbnail.php
|
Github Open Source
|
Open Source
|
MIT
| null |
playground_internal
|
Greator
|
PHP
|
Code
| 300
| 1,936
|
<?php
/**
* BuddyBoss - Add/Edit Video Thumbnail
*
* @package BuddyBoss\Core
*
* @since BuddyBoss 1.7.0
*/
?>
<div class="bp-video-thumbnail-uploader <?php echo bb_video_is_ffmpeg_installed() ? 'generating_thumb ' : 'no_ffmpeg'; ?>" style="display: none;">
<transition name="modal">
<div class="modal-mask bb-white bbm-model-wrap bbm-uploader-model-wrap">
<div class="modal-wrapper">
<div class="modal-container">
<header class="bb-model-header">
<a href="#" class="bp-video-thumbnail-upload-tab bp-thumbnail-upload-tab selected bp-video-thumbnail-uploader-modal-title" data-content="bp-video-thumbnail-dropzone-content" id="">
<?php esc_html_e( 'Change Thumbnail', 'buddyboss' ); ?>
</a>
<span id="bp-video-thumbnail-uploader-modal-status-text" style="display: none;"></span>
<a class="bb-model-close-button bp-video-thumbnail-uploader-close" id="" href="#">
<span class="bb-icon bb-icon-close"></span>
</a>
</header>
<div class="video-thumbnail-content">
<div class="bp-video-thumbnail-auto-generated">
<ul class="video-thumb-list loading">
<li class="lg-grid-1-5 md-grid-1-3 sm-grid-1-3 thumb_loader">
<div class="video-thumb-block">
<i class="bb-icon-loader animate-spin"></i>
<span>Generating thumbnail…</span>
</div>
</li>
<li class="lg-grid-1-5 md-grid-1-3 sm-grid-1-3 thumb_loader">
<div class="video-thumb-block">
<i class="bb-icon-loader animate-spin"></i>
<span>Generating thumbnail…</span>
</div>
</li>
</ul>
</div>
<div class="bb-dropzone-wrap bp-video-thumbnail-upload-tab-content bp-upload-tab-content bp-video-thumbnail-dropzone-content" id="custom_image_ele">
<input id="bb-video-5711" class="bb-custom-check" type="radio" value="5766" name="bb-video-thumbnail-select">
<label class="bp-tooltip" data-bp-tooltip-pos="up" data-bp-tooltip="Select" for="bb-video-5711">
<span class="bb-icon bb-icon-check"></span>
</label>
<div class="bb-field-wrap">
<div class="video-thumbnail-uploader-wrapper">
<div class="dropzone video-thumbnail-uploader-dropzone-select" id=""></div>
<div class="uploader-post-video-thumbnail-template" style="display:none;">
<div class="dz-preview dz-file-preview">
<div class="dz-image">
<img data-dz-thumbnail />
</div>
<div class="dz-progress-ring-wrap">
<i class="bb-icon bb-icon-camera-fill"></i>
<svg class="dz-progress-ring" width="62" height="62">
<circle class="progress-ring__circle" stroke="white" stroke-width="3" fill="transparent" r="29.5" cx="31" cy="31" stroke-dasharray="185.354, 185.354" stroke-dashoffset="185" />
</svg>
</div>
<div class="dz-error-message"><span data-dz-errormessage></span></div>
<div class="dz-error-mark">
<svg width="54px" height="54px" viewBox="0 0 54 54" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><title>Error</title>
<g stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
<g stroke="#747474" stroke-opacity="0.198794158" fill="#FFFFFF" fill-opacity="0.816519475">
<path d="M32.6568542,29 L38.3106978,23.3461564 C39.8771021,21.7797521 39.8758057,19.2483887 38.3137085,17.6862915 C36.7547899,16.1273729 34.2176035,16.1255422 32.6538436,17.6893022 L27,23.3431458 L21.3461564,17.6893022 C19.7823965,16.1255422 17.2452101,16.1273729 15.6862915,17.6862915 C14.1241943,19.2483887 14.1228979,21.7797521 15.6893022,23.3461564 L21.3431458,29 L15.6893022,34.6538436 C14.1228979,36.2202479 14.1241943,38.7516113 15.6862915,40.3137085 C17.2452101,41.8726271 19.7823965,41.8744578 21.3461564,40.3106978 L27,34.6568542 L32.6538436,40.3106978 C34.2176035,41.8744578 36.7547899,41.8726271 38.3137085,40.3137085 C39.8758057,38.7516113 39.8771021,36.2202479 38.3106978,34.6538436 L32.6568542,29 Z M27,53 C41.3594035,53 53,41.3594035 53,27 C53,12.6405965 41.3594035,1 27,1 C12.6405965,1 1,12.6405965 1,27 C1,41.3594035 12.6405965,53 27,53 Z"></path>
</g>
</g>
</svg>
</div>
</div>
</div>
</div>
</div>
<div class="video-thumbnail-custom" style="display:none;">
<span class="close-thumbnail-custom"></span>
<img src="" alt="" />
</div>
</div>
</div>
<input type="hidden" value="" class="video-edit-thumbnail-hidden-video-id">
<input type="hidden" value="" class="video-edit-thumbnail-hidden-attachment-id">
<footer class="bb-model-footer flex align-items-center">
<a class="button push-right bp-video-thumbnail-submit is-disabled" id="" href="#"><?php esc_html_e( 'Change', 'buddyboss' ); ?></a>
</footer>
</div>
</div>
</div>
</transition>
</div>
| 15,369
|
https://github.com/superfinserv/insurace/blob/master/resources/views/pos/webview/other/maintainance.blade.php
|
Github Open Source
|
Open Source
|
MIT
| null |
insurace
|
superfinserv
|
PHP
|
Code
| 537
| 2,306
|
@extends('webview.layouts.app')
@section('content')
<div class="container">
<div class="row">
<div class="col-12 px-0">
<div class="list-group list-group-flush ">
<a class="list-group-item border-top active text-dark" href="notification-details.html">
<div class="row">
<div class="col-auto align-self-center">
<i class="material-icons text-template-primary">local_mall</i>
</div>
<div class="col pl-0">
<div class="row mb-1">
<div class="col">
<p class="mb-0">New Order received</p>
</div>
<div class="col-auto pl-0">
<p class="small text-mute text-trucated mt-1">2/12/2019</p>
</div>
</div>
<p class="small text-mute">Order from Anand Mhatva recieved for Electronics with 6 quanity.</p>
</div>
</div>
</a>
<a class="list-group-item border-top active text-dark" href="notification-details.html">
<div class="row">
<div class="col-auto align-self-center">
<i class="material-icons text-template-primary">account_balance_wallet</i>
</div>
<div class="col pl-0">
<div class="row mb-1">
<div class="col">
<p class="mb-0">Balance has benn added</p>
</div>
<div class="col-auto pl-0">
<p class="small text-mute text-trucated mt-1">2/12/2019</p>
</div>
</div>
<p class="small text-mute">Order from Anand Mhatva recieved for Electronics with 6 quanity.</p>
</div>
</div>
</a>
<a class="list-group-item border-top text-dark" href="notification-details.html">
<div class="row">
<div class="col-auto align-self-center">
<i class="material-icons text-template-primary">account_circle</i>
</div>
<div class="col pl-0">
<div class="row mb-1">
<div class="col">
<p class="mb-0">Friend request received</p>
</div>
<div class="col-auto pl-0">
<p class="small text-mute text-trucated mt-1">2/12/2019</p>
</div>
</div>
<p class="small text-mute">New friend request received from Mickey John from Australia</p>
</div>
</div>
</a>
<a class="list-group-item border-top text-dark" href="notification-details.html">
<div class="row">
<div class="col-auto align-self-center">
<i class="material-icons text-template-primary">check_circle</i>
</div>
<div class="col pl-0">
<div class="row mb-1">
<div class="col">
<p class="mb-0">Email Updated</p>
</div>
<div class="col-auto pl-0">
<p class="small text-mute text-trucated mt-1">2/12/2019</p>
</div>
</div>
<p class="small text-mute">Your email change request has been successfully updated</p>
</div>
</div>
</a>
<a class="list-group-item border-top text-dark" href="notification-details.html">
<div class="row">
<div class="col-auto align-self-center">
<i class="material-icons text-template-primary">account_balance_wallet</i>
</div>
<div class="col pl-0">
<div class="row mb-1">
<div class="col">
<p class="mb-0">Balance has benn added</p>
</div>
<div class="col-auto pl-0">
<p class="small text-mute text-trucated mt-1">2/12/2019</p>
</div>
</div>
<p class="small text-mute">Order from Anand Mhatva recieved for Electronics with 6 quanity.</p>
</div>
</div>
</a>
<a class="list-group-item border-top new text-dark" href="notification-details.html">
<div class="row">
<div class="col-auto align-self-center">
<i class="material-icons text-template-primary">local_mall</i>
</div>
<div class="col pl-0">
<div class="row mb-1">
<div class="col">
<p class="mb-0">New Order received</p>
</div>
<div class="col-auto pl-0">
<p class="small text-mute text-trucated mt-1">2/12/2019</p>
</div>
</div>
<p class="small text-mute">Order from Anand Mhatva recieved for Electronics with 6 quanity.</p>
</div>
</div>
</a>
<a class="list-group-item border-top text-dark" href="notification-details.html">
<div class="row">
<div class="col-auto align-self-center">
<i class="material-icons text-template-primary">account_balance_wallet</i>
</div>
<div class="col pl-0">
<div class="row mb-1">
<div class="col">
<p class="mb-0">Balance has benn added</p>
</div>
<div class="col-auto pl-0">
<p class="small text-mute text-trucated mt-1">2/12/2019</p>
</div>
</div>
<p class="small text-mute">Order from Anand Mhatva recieved for Electronics with 6 quanity.</p>
</div>
</div>
</a>
<a class="list-group-item border-top text-dark" href="#">
<div class="row">
<div class="col-auto align-self-center">
<i class="material-icons text-template-primary">account_circle</i>
</div>
<div class="col pl-0">
<div class="row mb-1">
<div class="col">
<p class="mb-0">Friend request received</p>
</div>
<div class="col-auto pl-0">
<p class="small text-mute text-trucated mt-1">2/12/2019</p>
</div>
</div>
<p class="small text-mute">New friend request received from Mickey John from Australia</p>
</div>
</div>
</a>
<a class="list-group-item border-top text-dark" href="#">
<div class="row">
<div class="col-auto align-self-center">
<i class="material-icons text-template-primary">check_circle</i>
</div>
<div class="col pl-0">
<div class="row mb-1">
<div class="col">
<p class="mb-0">Email Updated</p>
</div>
<div class="col-auto pl-0">
<p class="small text-mute text-trucated mt-1">2/12/2019</p>
</div>
</div>
<p class="small text-mute">Your email change request has been successfully updated</p>
</div>
</div>
</a>
<a class="list-group-item border-top text-dark" href="#">
<div class="row">
<div class="col-auto align-self-center">
<i class="material-icons text-template-primary">account_balance_wallet</i>
</div>
<div class="col pl-0">
<div class="row mb-1">
<div class="col">
<p class="mb-0">Balance has benn added</p>
</div>
<div class="col-auto pl-0">
<p class="small text-mute text-trucated mt-1">2/12/2019</p>
</div>
</div>
<p class="small text-mute">Order from Anand Mhatva recieved for Electronics with 6 quanity.</p>
</div>
</div>
</a>
</div>
</div>
</div>
</div>
@endsection
| 19,789
|
https://github.com/luoyuan800/NeverEnd/blob/master/src/cn/luo/yuan/maze/client/display/dialog/GoodsDialog.java
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,017
|
NeverEnd
|
luoyuan800
|
Java
|
Code
| 67
| 327
|
package cn.luo.yuan.maze.client.display.dialog;
import android.widget.ListView;
import cn.luo.yuan.maze.R;
import cn.luo.yuan.maze.client.display.adapter.GoodsAdapter;
import cn.luo.yuan.maze.client.service.NeverEnd;
import cn.luo.yuan.maze.client.utils.Resource;
import cn.luo.yuan.maze.model.goods.Goods;
import java.util.ArrayList;
import java.util.List;
/**
* Created by luoyuan on 2017/7/6.
*/
public class GoodsDialog {
public void show(NeverEnd context){
ListView list = new ListView(context.getContext());
List<Goods> goods = context.getDataManager().loadAllGoods(false);
List<Goods> rGoodes = new ArrayList<>(goods.size());
for(Goods g : goods){
if(g.getCount() > 0){
rGoodes.add(g);
}
}
list.setAdapter(new GoodsAdapter(context, rGoodes));
SimplerDialogBuilder.build(list, Resource.getString(R.string.close), null,context.getContext(), true);
}
}
| 17,044
|
https://github.com/bahrus/be-vigilant/blob/master/be-vigilant.ts
|
Github Open Source
|
Open Source
|
MIT
| null |
be-vigilant
|
bahrus
|
TypeScript
|
Code
| 286
| 1,230
|
import {define, BeDecoratedProps } from 'be-decorated/be-decorated.js';
import {BeVigilantActions, BeVigilantProps, BeVigilantVirtualProps} from './types';
import {register} from 'be-hive/register.js';
export class BeVigilantController implements BeVigilantActions{
#target: Element | undefined;
#mutationObserver: MutationObserver | undefined;
async attachBehiviors(){
const beHive = (this.#target!.getRootNode() as DocumentFragment).querySelector('be-hive');
if(beHive === null) return;
const beDecoratedProps = Array.from(beHive.children) as any as BeDecoratedProps[];
for(const beDecor of beDecoratedProps){
const el = beDecor as any as Element;
await customElements.whenDefined(el.localName);
const matches = Array.from(this.#target!.querySelectorAll(`${beDecor.upgrade}[be-${beDecor.ifWantsToBe}],${beDecor.upgrade}[data-be-${beDecor.ifWantsToBe}]`));
for(const match of matches){
const data = match.hasAttribute(`data-be-${beDecor.ifWantsToBe}`) ? 'data-' : '';
const attrVal = match.getAttribute(`${data}be-${beDecor.ifWantsToBe}`);
match.setAttribute(`${data}is-${beDecor.ifWantsToBe}`, attrVal!);
match.removeAttribute(`${data}be-${beDecor.ifWantsToBe}`);
beDecor.newTarget = match;
}
}
}
intro(proxy: Element & BeVigilantVirtualProps, target: Element, beDecor: BeDecoratedProps){
this.#target = target;
this.attachBehiviors();
}
addObserver({}: this){
this.removeObserver(this);
this.#mutationObserver = new MutationObserver(this.callback);
this.#mutationObserver.observe(this.#target!, this as MutationObserverInit);
this.callback([], this.#mutationObserver);//notify subscribers that the observer is ready
}
callback = (mutationList: MutationRecord[], observer: MutationObserver) => {
for(const mut of mutationList){
const addedNodes = Array.from(mut.addedNodes);
let foundBeHiveElement = false;
for(const addedNode of addedNodes){
if(addedNode.nodeType === Node.ELEMENT_NODE){
const attrs = (addedNode as Element).attributes;
for(let i = 0, ii = attrs.length; i < ii; i++){
const attr = attrs[i];
if(attr.name.startsWith('be-') || attr.name.startsWith('data-be-')){
foundBeHiveElement = true;
break;
}
}
}
}
if(foundBeHiveElement){
this.attachBehiviors();
}
}
this.#target!.dispatchEvent(new CustomEvent(this.asType, {
detail: {
mutationList,
}
}));
}
removeObserver({}: this){
if(!this.#mutationObserver){
return;
}
this.#mutationObserver.disconnect();
this.#mutationObserver = undefined;
}
finale(proxy: Element & BeVigilantVirtualProps, target: Element, beDecor: BeDecoratedProps){
this.removeObserver(this);
this.#target = undefined;
}
}
export interface BeVigilantController extends BeVigilantProps{}
const tagName = 'be-vigilant';
const ifWantsToBe = 'vigilant';
const upgrade = '*';
define<BeVigilantProps & BeDecoratedProps<BeVigilantProps, BeVigilantActions>, BeVigilantActions>({
config:{
tagName,
propDefaults:{
ifWantsToBe,
upgrade,
intro: 'intro',
virtualProps: ['subtree', 'attributes', 'characterData', 'childList', 'asType'],
primaryProp: 'asType',
proxyPropDefaults:{
childList: true,
asType: 'be-vigilant-changed',
}
},
actions:{
addObserver: {
ifAllOf: ['asType'],
ifKeyIn: ['subtree', 'attributes', 'characterData', 'childList'],
}
}
},
complexPropDefaults:{
controller: BeVigilantController,
}
});
register(ifWantsToBe, upgrade, tagName);
| 14,945
|
https://github.com/fasttakerbg/Final_Project_Second/blob/master/public/scripts/controller.js
|
Github Open Source
|
Open Source
|
MIT
| 2,017
|
Final_Project_Second
|
fasttakerbg
|
JavaScript
|
Code
| 149
| 489
|
import { dataService } from 'dataService'
import { handlebarsHandler } from 'handlebarsHandler'
class Controller {
getHome() {
const promises = [
dataService.carouselContent(),
dataService.countryInfo(),
dataService.recentPosts(),
dataService.displayMedia(),
];
Promise.all(promises).then((values) => {
const carouselContent = values[0];
const countryInfo = values[1];
const recentPosts = values[2];
const media = values[3];
// let peruInfo = values[0];
// let egyptInfo = values[1];
// let cambodiaInfo = values[2];
// let bulgariaInfo = values[3];
handlebarsHandler.createTemplate('home', '#template-content', {
carouselContent: carouselContent,
countryInfo: countryInfo,
recentPosts: recentPosts,
media: media,
});
});
}
getPost() {
const promises = [
dataService.loadPost(),
dataService.recentPosts(),
dataService.getComments(),
];
Promise.all(promises).then((values) => {
const post = values[0];
const recentPosts = values[1];
const comments = values[2];
handlebarsHandler.createTemplate('post', '#template-content', {
recentPosts: recentPosts,
post: post,
comments: comments,
});
});
}
getBlog() {
const promises = [
dataService.getBlog(),
];
Promise.all(promises).then((values) => {
const blogArticles = values[0];
handlebarsHandler.createTemplate('blog', '#template-content', {
blogArticles: blogArticles,
});
});
}
}
const controller = new Controller();
export { controller };
| 1,064
|
https://github.com/revsys/django-test-plus/blob/master/test_project/test_app/tests/test_pytest.py
|
Github Open Source
|
Open Source
|
BSD-2-Clause
| 2,023
|
django-test-plus
|
revsys
|
Python
|
Code
| 46
| 198
|
import pytest
from test_plus.compat import DRF
def test_something(tp):
response = tp.get("view-200")
assert response.status_code == 200
@pytest.mark.skipif(DRF is False, reason="DRF is not installed.")
def test_api(tp_api):
response = tp_api.post("view-json", extra={"format": "json"})
assert response.status_code == 200
def test_assert_login_required(tp):
tp.assertLoginRequired("view-needs-login")
def test_assert_in_context(tp):
response = tp.get('view-context-with')
assert 'testvalue' in response.context
tp.assertInContext('testvalue')
| 39,209
|
https://github.com/Acidburn0zzz/ui/blob/master/app/components/pipeline-event-row/component.js
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,018
|
ui
|
Acidburn0zzz
|
JavaScript
|
Code
| 57
| 174
|
import Component from '@ember/component';
import { computed, get } from '@ember/object';
export default Component.extend({
tagName: 'tr',
classNameBindings: ['highlighted'],
highlighted: computed('selectedEvent', 'event.id', {
get() {
return get(this, 'selectedEvent') === get(this, 'event.id');
}
}),
actions: {
clickRow() {
const fn = get(this, 'eventClick');
if (typeof fn === 'function') {
fn(get(this, 'event.id'));
}
}
},
click() {
this.send('clickRow');
}
});
| 16,360
|
https://github.com/SamCao1991/hicma/blob/master/scripts/test.sh
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,022
|
hicma
|
SamCao1991
|
Shell
|
Code
| 179
| 661
|
#!/bin/bash -le
module purge
if [ "$HOSTNAME" == "thana" ]; then
. ./scripts/power8.modules
else
. ./scripts/modules-ecrc.sh
. ./scripts/modules-ecrc-mpi.sh
fi
module list
set -x
# TEST
PRE=""
factor=1
debug=0
mpi=0
if [ $# -ne 5 ]; then
echo "Usage: factor[1,2,4...] debug[d,-] mpi[m,-] nthreads problem"
ii=0
for i in $*; do
echo "$ii: |$i|"
ii=$((ii+1))
done
exit -1
fi
factor=$1
debug=$2
mpi=$3
nthreads=$4
problem=$5
nmpi=8
if [ "$mpi" != "-" ]; then
nmpi=$mpi
if [ $debug == "d" ]; then
CMD="mpirun -n $nmpi xterm -hold -e gdb -ex run --args "
else
CMD="mpirun -n $nmpi "
fi
else
if [ $debug == "d" ]; then
CMD="gdb -ex run --args"
fi
fi
echo $CMD
export STARPU_SILENT=1
irange="3 3"; nta=$nthreads;_b=400; acc=1e-8; check="--check"
for nt in $nta;do
n=$((m/factor))
maxrank=$((nb/factor))
#echo BASH-MAXRANK: $maxrank
#echo BASH-DEBUG: $debug
#_b=1600
#_b=324
nb=$_b;
for _i in `seq $irange`;do
_is=$((_i*_i))
m=$((_is*_b));
n=$((_is*_b/factor));
maxrank=$((_b/factor))
run="./build/timing/time_zpotrf_tile \
--m=$m \
--n_range=$n:$n \
--k=$m \
--mb=$nb \
--nb=$maxrank \
--nowarmup \
--threads=$nt \
--rk=0 \
--acc=$acc \
$check \
$problem \
--starshwavek=40 \
--starshdecay=2 \
--starshmaxrank=$maxrank"
echo "Executing: $CMD $run"
$CMD $run
done
done
| 25,140
|
https://github.com/lmc-eu/matej-client-php5/blob/master/tests/unit/RequestBuilder/CampaignRequestBuilderTest.php
|
Github Open Source
|
Open Source
|
MIT
| 2,018
|
matej-client-php5
|
lmc-eu
|
PHP
|
Code
| 228
| 1,301
|
<?php
namespace Lmc\Matej\RequestBuilder;
use Fig\Http\Message\RequestMethodInterface;
use Lmc\Matej\Exception\DomainException;
use Lmc\Matej\Exception\LogicException;
use Lmc\Matej\Http\RequestManager;
use Lmc\Matej\Model\Command\Sorting;
use Lmc\Matej\Model\Command\UserRecommendation;
use Lmc\Matej\Model\Request;
use Lmc\Matej\Model\Response;
use PHPUnit\Framework\TestCase;
/**
* @covers \Lmc\Matej\RequestBuilder\AbstractRequestBuilder
* @covers \Lmc\Matej\RequestBuilder\CampaignRequestBuilder
*/
class CampaignRequestBuilderTest extends TestCase
{
/** @test */
public function shouldBuildRequestWithCommands()
{
$builder = new CampaignRequestBuilder();
$recommendationCommand1 = UserRecommendation::create('userId1', 'scenario1')->setCount(1)->setRotationRate(1.0)->setRotationTime(600);
$recommendationCommand2 = UserRecommendation::create('userId2', 'scenario2')->setCount(2)->setRotationRate(0.5)->setRotationTime(700);
$recommendationCommand3 = UserRecommendation::create('userId3', 'scenario3')->setCount(3)->setRotationRate(0.0)->setRotationTime(800);
$builder->addRecommendation($recommendationCommand1);
$builder->addRecommendations([$recommendationCommand2, $recommendationCommand3]);
$sortingCommand1 = Sorting::create('userId1', ['itemId1', 'itemId2']);
$sortingCommand2 = Sorting::create('userId2', ['itemId2', 'itemId3']);
$sortingCommand3 = Sorting::create('userId3', ['itemId3', 'itemId4']);
$builder->addSorting($sortingCommand1);
$builder->addSortings([$sortingCommand2, $sortingCommand3]);
$builder->setRequestId('custom-request-id-foo');
$request = $builder->build();
$this->assertInstanceOf(Request::class, $request);
$this->assertSame(RequestMethodInterface::METHOD_POST, $request->getMethod());
$this->assertSame('/campaign', $request->getPath());
$requestData = $request->getData();
$this->assertCount(6, $requestData);
$this->assertContains($recommendationCommand1, $requestData);
$this->assertContains($recommendationCommand2, $requestData);
$this->assertContains($recommendationCommand3, $requestData);
$this->assertContains($sortingCommand1, $requestData);
$this->assertContains($sortingCommand2, $requestData);
$this->assertContains($sortingCommand3, $requestData);
$this->assertSame('custom-request-id-foo', $request->getRequestId());
}
/** @test */
public function shouldThrowExceptionWhenBuildingEmptyCommands()
{
$builder = new CampaignRequestBuilder();
$this->expectException(LogicException::class);
$this->expectExceptionMessage('At least one command must be added to the builder');
$builder->build();
}
/** @test */
public function shouldThrowExceptionWhenBatchSizeIsTooBig()
{
$builder = new CampaignRequestBuilder();
for ($i = 0; $i < 501; $i++) {
$builder->addRecommendation(UserRecommendation::create('userId1', 'scenario1')->setCount(1)->setRotationRate(1.0)->setRotationTime(600));
$builder->addSorting(Sorting::create('userId1', ['itemId1', 'itemId2']));
}
$this->expectException(DomainException::class);
$this->expectExceptionMessage('Request contains 1002 commands, but at most 1000 is allowed in one request.');
$builder->build();
}
/** @test */
public function shouldThrowExceptionWhenSendingCommandsWithoutRequestManager()
{
$builder = new CampaignRequestBuilder();
$builder->addSorting(Sorting::create('userId1', ['itemId1', 'itemId2']));
$this->expectException(LogicException::class);
$this->expectExceptionMessage('Instance of RequestManager must be set to request builder');
$builder->send();
}
/** @test */
public function shouldSendRequestViaRequestManager()
{
$requestManagerMock = $this->createMock(RequestManager::class);
$requestManagerMock->expects($this->once())->method('sendRequest')->with($this->isInstanceOf(Request::class))->willReturn(new Response(0, 0, 0, 0));
$builder = new CampaignRequestBuilder();
$builder->setRequestManager($requestManagerMock);
$builder->addRecommendation(UserRecommendation::create('userId1', 'scenario1')->setCount(1)->setRotationRate(1.0)->setRotationTime(600));
$builder->addSorting(Sorting::create('userId1', ['itemId1', 'itemId2']));
$builder->send();
}
}
| 820
|
https://github.com/pedrograngeiro/Webcrasping-E-sports-Wiki/blob/master/extrairdados/cblol_week5.py
|
Github Open Source
|
Open Source
|
MIT
| null |
Webcrasping-E-sports-Wiki
|
pedrograngeiro
|
Python
|
Code
| 148
| 585
|
import requests
from bs4 import BeautifulSoup
import csv
cont = 0
i = 0
j = 0
mediabaron = 0
mediabaronfinal = 0
source = requests.get('https://lol.gamepedia.com/CBLOL/2021_Season/Split_1/Scoreboards/Week_5').text
soup = BeautifulSoup(source, 'html.parser')
barons = soup.find_all('div', "sb-footer-item sb-footer-item-barons")
dias = soup.find_all('span', "mw-headline")
times = soup.find_all('span', "teamname")
listatime = []
partidas = [[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0]]
itembaron = []
for baron in barons:
itembaron.append(int(baron.text))
for time in times:
listatime.append(time.text)
for l in range(0,len(partidas)):
for c in range(0,2):
partidas[l][c] = listatime[i]
i = i + 1
"""
##################### VISUALIZAÇÃO BONITA #######################
print("-=" * 30)
for l in range(0,len(partidas)):
print("==Partida==", (l+1))
for c in range(0,2):
print( partidas[l][c])
print("Barons: ", end='') #Contagem de barons por time
print(itembaron[cont])
cont = cont + 1
print()
#################### FIM VISULIZAÇÃO BONITA #####################
"""
###Contagem de Barons###
for i in range(0,len(itembaron)):
mediabaron = mediabaron + itembaron[i]
###Fim de contagem Barons###
"""with open('baronweek5.csv', 'w', encoding='utf-8', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(itembaron)
writer.writerow(listatime)
writer.writerow(partidas)"""
| 31,959
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.