repo_name stringlengths 6 101 | path stringlengths 4 300 | text stringlengths 7 1.31M |
|---|---|---|
JartC0ding/libc | sys/send.c | <gh_stars>0
#include <sys/net.h>
#include <sys/get_syscall_id.h>
#include <string.h>
int sys_socket_send_id = -1;
int send(int socket, const void* data, size_t size) {
if (sys_socket_send_id == -1) {
sys_socket_send_id = get_syscall_id("sys_socket_send");
}
int success = 0;
__asm__ __volatile__ ("int $0x30" : "=d" (success) : "a" (sys_socket_send_id), "b" (socket), "c" (data), "d" (size));
return success;
} |
roy-zz/algorithm | src/test/java/com/roy/algorithm/inflearn/retry1/array/FlipPrimeNumber.java | <gh_stars>0
package com.roy.algorithm.inflearn.retry1.array;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
// ๋ค์ง์ ์์
//
// N๊ฐ์ ์์ฐ์๊ฐ ์
๋ ฅ๋๋ฉด ๊ฐ ์์ฐ์๋ฅผ ๋ค์ง์ ํ ๊ทธ ๋ค์ง์ ์๊ฐ ์์์ด๋ฉด ๊ทธ ์์๋ฅผ ์ถ๋ ฅํ๋ ํ๋ก๊ทธ๋จ์ ์์ฑํ์ธ์.
// ์๋ฅผ ๋ค์ด 32๋ฅผ ๋ค์ง์ผ๋ฉด 23์ด๊ณ , 23์ ์์์ด๋ค. ๊ทธ๋ฌ๋ฉด 23์ ์ถ ๋ ฅํ๋ค. ๋จ 910๋ฅผ ๋ค์ง์ผ๋ฉด 19๋ก ์ซ์ํ ํด์ผ ํ๋ค.
// ์ฒซ ์๋ฆฌ๋ถํฐ์ ์ฐ์๋ 0์ ๋ฌด์ํ๋ค.
// - ์
๋ ฅ์ค๋ช
// ์ฒซ ์ค์ ์์ฐ์์ ๊ฐ์ N(3<=N<=100)์ด ์ฃผ์ด์ง๊ณ , ๊ทธ ๋ค์ ์ค์ N๊ฐ์ ์์ฐ์๊ฐ ์ฃผ์ด์ง๋ค. ๊ฐ ์์ฐ์์ ํฌ๊ธฐ๋ 100,000๋ฅผ ๋์ง ์๋๋ค.
// - ์ถ๋ ฅ์ค๋ช
// ์ฒซ ์ค์ ๋ค์ง์ ์์๋ฅผ ์ถ๋ ฅํฉ๋๋ค. ์ถ๋ ฅ์์๋ ์
๋ ฅ๋ ์์๋๋ก ์ถ๋ ฅํฉ๋๋ค.
// - ์
๋ ฅ์์ 1
// 9
// 32 55 62 20 250 370 200 30 100
// - ์ถ๋ ฅ์์ 1
// 23 2 73 2 3
@SuppressWarnings("NewClassNamingConvention")
public class FlipPrimeNumber {
public boolean isPrime(int number) {
if (number <= 1) {
return false;
}
for (int i = 2; i < number; i++) {
if (number % i == 0) {
return false;
}
}
return true;
}
public Integer[] solution1(int... inputs) {
List<Integer> flipPrimeNumbers = new ArrayList<>();
for (int i = 0; i < inputs.length; i++) {
int tmp = inputs[i];
int result = 0;
while (tmp > 0) {
// ์
๋ ฅ๋ฐ์ ๊ฐ์ 10์ผ๋ก ๋๋ ๊ฐ์ ์์์ ์ ๊ตฌํ๋ค.
int decimalPoint = tmp % 10;
// ๊ฒฐ๊ณผ ๊ฐ์ 10์ ๊ณฑํด์ฃผ๊ณ ์์์ ์ ๋ํ๋ค.
result = result * 10 + decimalPoint;
// ํ์ฌ ๊ฐ์ 10์ผ๋ก ๋๋์ด 1์ ์๋ฆฌ๋ฅผ ๋ฒ๋ฆฌ๋๋ก ํ๋ค.
tmp = tmp / 10;
}
if (isPrime(result)) {
flipPrimeNumbers.add(result);
}
}
return flipPrimeNumbers.toArray(new Integer[0]);
}
// StringBuilder์ reverse๋ฅผ ํ์ฉํ ๋ฐฉ๋ฒ์ด๋ค.
// ์
๋ ฅ๋ฐ์ ๋ฌธ์์ด์ String์ผ๋ก ๋ณํํ์ฌ reverseํจ์๋ฅผ ์ฌ์ฉํ์ฌ ๋ค์ง๋๋ค.
// ๋ค์ง์ ๋ฌธ์์ด์ Integer์ parseInt ํจ์๋ฅผ ์ฌ์ฉํ์ฌ ํ๋ณํ์ ์ํจ๋ค.
// ์ด ๋ ๊ฐ์ฅ ์์๋ฆฌ๊ฐ 0์ธ ๊ฒฝ์ฐ 0์ ์ ๊ฑฐ๋๊ณ ์ซ์๋ก ํ๋ณํ์ด ๋๋ค.
public Integer[] solution2(int... inputs) {
List<Integer> flipPrimeNumbers = new ArrayList<>();
for (int input : inputs) {
input = Integer.parseInt(new StringBuilder(String.valueOf(input)).reverse().toString());
if (isPrime(input)) {
flipPrimeNumbers.add(input);
}
}
return flipPrimeNumbers.toArray(new Integer[0]);
}
@Test
@DisplayName("๋ค์ง์ ์์")
public void main() {
Integer[] expectedAnswer = {23, 2, 73, 2, 3};
Integer[] answer1 = solution1(32, 55, 62, 20, 250, 370, 200, 30, 100);
assertArrayEquals(expectedAnswer, answer1);
Integer[] answer2 = solution2(32, 55, 62, 20, 250, 370, 200, 30, 100);
assertArrayEquals(expectedAnswer, answer2);
}
}
|
ForeverZer0/fmod | lib/fmod/channel_control.rb | <reponame>ForeverZer0/fmod
module FMOD
##
# @abstract
# The base class for both {Channel} and {ChannelGroup} objects.
class ChannelControl < Handle
##
# Describes a volume point to fade from or towards, using a clock offset and
# 0.0 to 1.0 volume level.
#
# @attr clock [Integer] DSP clock of the parent channel group to set the
# fade point volume.
# @attr volume [Float] lume level where 0.0 is silent and 1.0 is normal
# volume. Amplification is supported.
FadePoint = Struct.new(:clock, :volume)
##
# Emulates an Array-type container of a {ChannelControl}'s DSP chain.
class DspChain
include Enumerable
##
# Creates a new instance of a {DspChain} for the specified
# {ChannelControl}.
#
# @param channel [ChannelControl] The channel or channel group to create
# the collection wrapper for.
def initialize(channel)
FMOD.type?(channel, ChannelControl)
@channel = channel
end
##
# Retrieves the number of DSPs within the chain. This includes the
# built-in {FMOD::Effects::Fader} DSP.
# @return [Integer]
def count
buffer = "\0" * Fiddle::SIZEOF_INT
FMOD.invoke(:ChannelGroup_GetNumDSPs, @channel, buffer)
buffer.unpack1('l')
end
##
# @overload each(&block)
# If called with a block, passes each DSP in turn before returning self.
# @yield [dsp] Yields a DSP instance to the block.
# @yieldparam dsp [Dsp] The DSP instance.
# @return [self]
# @overload each
# Returns an enumerator for the {DspChain} if no block is given.
# @return [Enumerator]
def each
return to_enum(:each) unless block_given?
(0...count).each { |i| yield self[i] }
self
end
##
# Element reference. Returns the element at index.
# @param index [Integer] The index into the {DspChain} to retrieve.
# @return [Dsp|nil] The DSP at the specified index, or +nil+ if index is
# out of range.
def [](index)
return nil unless index.between?(-2, count)
dsp = "\0" * Fiddle::SIZEOF_INTPTR_T
FMOD.invoke(:ChannelGroup_GetDSP, @channel, index, dsp)
Dsp.from_handle(dsp)
end
##
# Element assignment. Sets the element at the specified index.
# @param index [Integer] The index into the {DspChain} to set.
# @param dsp [Dsp] A DSP instance.
# @return [Dsp] The given DSP instance.
def []=(index, dsp)
FMOD.type?(dsp, Dsp)
FMOD.invoke(:ChannelGroup_AddDSP, @channel, index, dsp)
dsp
end
##
# Appends or pushes the given object(s) on to the end of this {DspChain}. This
# expression returns +self+, so several appends may be chained together.
# @param dsp [Dsp] One or more DSP instance(s).
# @return [self]
def add(*dsp)
dsp.each { |d| self[DspIndex::TAIL] = d }
self
end
##
# Prepends objects to the front of +self+, moving other elements upwards.
# @param dsp [Dsp] A DSP instance.
# @return [self]
def unshift(dsp)
self[DspIndex::HEAD] = dsp
self
end
##
# Removes the last element from +self+ and returns it, or +nil+ if the
# {DspChain} is empty.
# @return [Dsp|nil]
def pop
dsp = self[DspIndex::TAIL]
remove(dsp)
dsp
end
##
# Returns the first element of +self+ and removes it (shifting all other
# elements down by one). Returns +nil+ if the array is empty.
# @return [Dsp|nil]
def shift
dsp = self[DspIndex::HEAD]
remove(dsp)
dsp
end
##
# Deletes the specified DSP from this DSP chain. This does not release ot
# dispose the DSP unit, only removes from this {DspChain}, as a DSP unit
# can be shared.
# @param dsp [Dsp] The DSP to remove.
# @return [self]
def remove(dsp)
return unless dsp.is_a?(Dsp)
FMOD.invoke(:ChannelGroup_RemoveDSP, @channel, dsp)
self
end
##
# Returns the index of the specified DSP.
# @param dsp [Dsp] The DSP to retrieve the index of.
# @return [Integer] The index of the DSP.
def index(dsp)
FMOD.type?(dsp, Dsp)
buffer = "\0" * Fiddle::SIZEOF_INT
FMOD.invoke(:ChannelGroup_GetDSPIndex, @channel, dsp, buffer)
buffer.unpack1('l')
end
##
# Moves a DSP unit that exists in this {DspChain} to a new index.
# @param dsp [Dsp] The DSP instance to move, must exist within this
# {DspChain}.
# @param index [Integer] The new index to place the specified DSP.
# @return [self]
def move(dsp, index)
FMOD.type?(dsp, Dsp)
FMOD.invoke(:ChannelGroup_SetDSPIndex, @channel, dsp, index)
self
end
alias_method :size, :count
alias_method :length, :count
alias_method :length, :count
alias_method :delete, :remove
alias_method :push, :add
alias_method :<<, :add
private_class_method :new
end
##
# Represents the start (and/or stop) time relative to the parent channel
# group DSP clock, with sample accuracy.
#
# @attr start [Integer] The DSP clock of the parent channel group to audibly
# start playing sound at.
# @attr end [Integer] The DSP clock of the parent channel group to audibly
# stop playing sound at.
# @attr stop [Boolean] +true+ to stop according to
# {ChannelControl.playing?}, otherwise +false+ to remain "active" and a
# new start delay could start playback again at a later time.
ChannelDelay = Struct.new(:start, :end, :stop)
##
# The settings for the 3D distance filter properties.
#
# @attr custom [Boolean] The enabled/disabled state of the FMOD distance
# rolloff calculation. Default is +false+.
# @attr level [Float] The manual user attenuation, where 1.0 is no
# attenuation and 0.0 is complete attenuation. Default is 1.0.
# @attr frequency [Float] The center frequency in Hz for the high-pass
# filter used to simulate distance attenuation, from 10.0 to 22050.0.
# Default is 1500.0.
DistanceFilter = Struct.new(:custom, :level, :frequency)
include Fiddle
include FMOD::Core
##
# @!attribute volume
# Gets or sets the linear volume level.
#
# Volume level can be below 0.0 to invert a signal and above 1.0 to
# amplify the signal. Note that increasing the signal level too far may
# cause audible distortion.
#
# @return [Float]
float_reader(:volume, :ChannelGroup_GetVolume)
float_writer(:volume=, :ChannelGroup_SetVolume)
##
# @!attribute volume_ramp
# Gets or sets flag indicating whether the channel automatically ramps
# when setting volumes.
#
# When changing volumes on a non-paused channel, FMOD normally adds a
# small ramp to avoid a pop sound. This function allows that setting to be
# overridden and volume changes to be applied immediately.
#
# @return [Boolean]
bool_reader(:volume_ramp, :ChannelGroup_GetVolumeRamp)
bool_writer(:volume_ramp=, :ChannelGroup_SetVolumeRamp)
##
# @!attribute pitch
# Sets the pitch value.
#
# This function scales existing frequency values by the pitch.
# * *0.5:* One octave lower
# * *2.0:* One octave higher
# * *1.0:* Normal pitch
# @return [Float]
float_reader(:pitch, :ChannelGroup_GetPitch)
float_writer(:pitch=, :ChannelGroup_SetPitch)
##
# @!attribute mode
# Changes some attributes for a {ChannelControl} based on the mode passed in.
#
# Supported flags:
# * {Mode::LOOP_OFF}
# * {Mode::LOOP_NORMAL}
# * {Mode::LOOP_BIDI}
# * {Mode::TWO_D}
# * {Mode::THREE_D}
# * {Mode::HEAD_RELATIVE_3D}
# * {Mode::WORLD_RELATIVE_3D}
# * {Mode::INVERSE_ROLLOFF_3D}
# * {Mode::LINEAR_ROLLOFF_3D}
# * {Mode::LINEAR_SQUARE_ROLLOFF_3D}
# * {Mode::CUSTOM_ROLLOFF_3D}
# * {Mode::IGNORE_GEOMETRY_3D}
# * {Mode::VIRTUAL_PLAY_FROM_START}
#
# When changing the loop mode, sounds created with {Mode::CREATE_STREAM}
# may have already been pre-buffered and executed their loop logic ahead
# of time before this call was even made. This is dependant on the size of
# the sound versus the size of the stream decode buffer. If this happens,
# you may need to re-flush the stream buffer by calling {Channel.seek}.
# Note this will usually only happen if you have sounds or loop points
# that are smaller than the stream decode buffer size.
#
# @return [Integer] Mode bits.
integer_reader(:mode, :ChannelGroup_GetMode)
integer_writer(:mode=, :ChannelGroup_SetMode)
##
# @!method playing?
# @return [Boolean] the playing state.
bool_reader(:playing?, :ChannelGroup_IsPlaying)
##
# @!method paused?
# @return [Boolean] the paused state.
bool_reader(:paused?, :ChannelGroup_GetPaused)
##
# @!method muted?
# @return [Boolean] the mute state.
bool_reader(:muted?, :ChannelGroup_GetMute)
##
# @!attribute [r] audibility
# The combined volume after 3D spatialization and geometry occlusion
# calculations including any volumes set via the API.
#
# This does not represent the waveform, just the calculated result of all
# volume modifiers. This value is used by the virtual channel system to
# order its channels between real and virtual.
#
# @return [Float] the combined volume after 3D spatialization and geometry
# occlusion.
float_reader(:audibility, :ChannelGroup_GetAudibility)
# @!attribute low_pass_gain
# The dry signal when low-pass filtering is applied.
# * *Minimum:* 0.0 (silent, full filtering)
# * *Maximum:* 1.0 (full volume, no filtering)
# * *Default:* 1.0
# @return [Float] the linear gain level.
float_reader(:low_pass_gain, :ChannelGroup_GetLowPassGain)
float_writer(:low_pass_gain=, :ChannelGroup_SetLowPassGain, 0.0, 1.0)
# @!group 3D Sound
##
# @!attribute level3D
# The 3D pan level.
# * *Minimum:* 0.0 (attenuation is ignored and panning as set by 2D panning
# functions)
# * *Maximum:* 1.0 (pan and attenuate according to 3D position)
# * *Default:* 0.0
# @return [Float] the 3D pan level.
float_reader(:level3D, :ChannelGroup_Get3DLevel)
float_writer(:level3D=, :ChannelGroup_Set3DLevel, 0.0, 1.0)
##
# @!attribute spread3D
# The speaker spread angle.
# * *Minimum:* 0.0
# * *Maximum:* 360.0
# * *Default:* 0.0
# @return [Float] the spread of a 3D sound in speaker space.
float_reader(:spread3D, :ChannelGroup_Get3DSpread)
float_writer(:spread3D, :ChannelGroup_Set3DSpread, 0.0, 360.0)
##
# @!attribute doppler3D
# The doppler scale.
# * *Minimum:* 0.0 (none)
# * *Maximum:* 5.0 (exaggerated)
# * *Default:* 1.0 (normal)
# @return [Float] the amount by which doppler is scaled.
float_reader(:doppler3D, :ChannelGroup_Get3DDopplerLevel)
float_writer(:doppler3D=, :ChannelGroup_Set3DDopplerLevel, 0.0, 5.0)
##
# @!attribute direct_occlusion
# @return [Float] the occlusion factor for the direct path.
def direct_occlusion
direct = "\0" * SIZEOF_FLOAT
FMOD.invoke(:ChannelGroup_Get3DOcclusion, self, direct, nil)
direct.unpack1('f')
end
def direct_occlusion=(direct)
direct = direct.clamp(0.0, 1.0)
reverb = reverb_occlusion
FMOD.invoke(:ChannelGroup_Set3DOcclusion, self, direct, reverb)
direct
end
##
# @!attribute reverb_occlusion
# @return [Float] the occlusion factor for the reverb mix.
def reverb_occlusion
reverb = "\0" * SIZEOF_FLOAT
FMOD.invoke(:ChannelGroup_Get3DOcclusion, self, nil, reverb)
reverb.unpack1('f')
end
def reverb_occlusion=(reverb)
direct = direct_occlusion
reverb = reverb.clamp(0.0, 1.0)
FMOD.invoke(:ChannelGroup_Set3DOcclusion, self, direct, reverb)
reverb
end
##
# @!attribute position3D
# @return [Vector] the position used to apply panning, attenuation and
# doppler.
def position3D
position = Vector.zero
FMOD.invoke(:ChannelGroup_Get3DAttributes, self, position, nil, nil)
position
end
def position3D=(vector)
FMOD.type?(vector, Vector)
FMOD.invoke(:ChannelGroup_Set3DAttributes, self, vector, nil, nil)
vector
end
##
# @!attribute velocity3D
# @return [Vector] the velocity used to apply panning, attenuation and
# doppler.
def velocity3D
velocity = Vector.zero
FMOD.invoke(:ChannelGroup_Get3DAttributes, self, nil, velocity, nil)
velocity
end
def velocity3D=(vector)
FMOD.type?(vector, Vector)
FMOD.invoke(:ChannelGroup_Set3DAttributes, self, nil, vector, nil)
vector
end
##
# @!attribute distance_filter
# @return [DistanceFilter] the behaviour of a 3D distance filter, whether to
# enable or disable it, and frequency characteristics.
def distance_filter
args = ["\0" * SIZEOF_INT, "\0" * SIZEOF_FLOAT, "\0" * SIZEOF_FLOAT]
FMOD.invoke(:ChannelGroup_Get3DDistanceFilter, self, *args)
args = args.join.unpack('lff')
args[0] = args[0] != 0
DistanceFilter.new(*args)
end
def distance_filter=(filter)
FMOD.type?(filter, DistanceFilter)
args = filter.values
args[0] = args[0].to_i
FMOD.invoke(:ChannelGroup_Set3DDistanceFilter, self, *args)
end
##
# @!attribute custom_rolloff
# A custom rolloff curve to define how audio will attenuate over distance.
#
# Must be used in conjunction with {Mode::CUSTOM_ROLLOFF_3D} flag to be
# activated.
#
# <b>Points must be sorted by distance! Passing an unsorted list to FMOD
# will result in an error.</b>
# @return [Array<Vector>] the rolloff curve.
def custom_rolloff
count = "\0" * SIZEOF_INT
FMOD.invoke(:ChannelGroup_Get3DCustomRolloff, self, nil, count)
count = count.unpack1('l')
return [] if count.zero?
size = SIZEOF_FLOAT * 3
FMOD.invoke(:ChannelGroup_Get3DCustomRolloff, self, ptr = int_ptr, nil)
buffer = Pointer.new(ptr.unpack1('J'), count * size).to_str
(0...count).map { |i| Vector.new(*buffer[i * size, size].unpack('fff')) }
end
def custom_rolloff=(rolloff)
FMOD.type?(rolloff, Array)
vectors = rolloff.map { |vector| vector.to_str }.join
FMOD.invoke(:ChannelGroup_Set3DCustomRolloff, self, vectors, rolloff.size)
rolloff
end
##
# @!attribute min_distance
# @return [Float] Minimum volume distance in "units". (Default: 1.0)
# @see max_distance
# @see min_max_distance
def min_distance
min = "\0" * SIZEOF_FLOAT
FMOD.invoke(:ChannelGroup_Get3DMinMaxDistance, self, min, nil)
min.unpack1('f')
end
def min_distance=(distance)
min_max_distance(distance, max_distance)
end
##
# @!attribute max_distance
# @return [Float] Maximum volume distance in "units". (Default: 10000.0)
# @see min_distance
# @see in_max_distance
def max_distance
max = "\0" * SIZEOF_FLOAT
FMOD.invoke(:ChannelGroup_Get3DMinMaxDistance, self, nil, max)
max.unpack1('f')
end
def max_distance=(distance)
min_max_distance(min_distance, distance)
end
##
# Sets the minimum and maximum audible distance.
#
# When the listener is in-between the minimum distance and the sound source
# the volume will be at its maximum. As the listener moves from the minimum
# distance to the maximum distance the sound will attenuate following the
# rolloff curve set. When outside the maximum distance the sound will no
# longer attenuate.
#
# Minimum distance is useful to give the impression that the sound is loud
# or soft in 3D space. An example of this is a small quiet object, such as a
# bumblebee, which you could set a small minimum distance such as 0.1. This
# would cause it to attenuate quickly and disappear when only a few meters
# away from the listener. Another example is a jumbo jet, which you could
# set to a minimum distance of 100.0 causing the volume to stay at its
# loudest until the listener was 100 meters away, then it would be hundreds
# of meters more before it would fade out.
#
# Maximum distance is effectively obsolete unless you need the sound to stop
# fading out at a certain point. Do not adjust this from the default if you
# dont need to. Some people have the confusion that maximum distance is the
# point the sound will fade out to zero, this is not the case.
#
# @param min [Float] Minimum volume distance in "units".
# * *Default:* 1.0
# @param max [Float] Maximum volume distance in "units".
# * *Default:* 10000.0
#
# @see min_distance
# @see max_distance
# @return [void]
def min_max_distance(min, max)
FMOD.invoke(:ChannelGroup_Set3DMinMaxDistance, self, min, max)
end
##
# @!attribute cone_orientation
# @return [Vector] the orientation of the sound projection cone.
def cone_orientation
vector = FMOD::Core::Vector.new
FMOD.invoke(:ChannelGroup_Get3DConeOrientation, self, vector)
vector
end
def cone_orientation=(vector)
FMOD.type?(vector, Vector)
FMOD.invoke(:ChannelGroup_Set3DConeOrientation, self, vector)
vector
end
##
# @!attribute cone_settings
# The angles that define the sound projection cone including the volume when
# outside the cone.
# @since 0.9.2
# @return [ConeSettings] the sound projection cone.
def cone_settings
args = ["\0" * SIZEOF_FLOAT, "\0" * SIZEOF_FLOAT, "\0" * SIZEOF_FLOAT]
FMOD.invoke(:ChannelGroup_Get3DConeSettings, self, *args)
ConeSettings.new(*args.map { |arg| arg.unpack1('f') } )
end
def cone_settings=(settings)
FMOD.type?(settings, ConeSettings)
set_cone(*settings.values)
settings
end
##
# Sets the angles that define the sound projection cone including the volume
# when outside the cone.
# @param inside_angle [Float] Inside cone angle, in degrees. This is the
# angle within which the sound is at its normal volume.
# @param outside_angle [Float] Outside cone angle, in degrees. This is the
# angle outside of which the sound is at its outside volume.
# @param outside_volume [Float] Cone outside volume.
# @since 0.9.2
# @return [void]
def set_cone(inside_angle, outside_angle, outside_volume)
if outside_angle < inside_angle
raise Error, 'Outside angle must be greater than inside angle.'
end
FMOD.invoke(:ChaennlGroup_Set3DConeSettings, self, inside_angle,
outside_angle, outside_volume)
self
end
# @!endgroup
##
# Add a volume point to fade from or towards, using a clock offset and 0.0
# to 1.0 volume level.
# @overload add_fade(fade_point)
# @param fade_point [FadePoint] Fade point structure defining the values.
# @overload add_fade(clock, volume)
# @param clock [Integer] DSP clock of the parent channel group to set the
# fade point volume.
# @param volume [Float] Volume level where 0.0 is silent and 1.0 is normal
# volume. Amplification is supported.
# @return [self]
def add_fade(*args)
args = args[0].values if args.size == 1 && args[0].is_a?(FadePoint)
FMOD.invoke(:ChannelGroup_AddFadePoint, self, *args)
self
end
##
# Retrieves the number of fade points set within the {ChannelControl}.
# @return [Integer] The number of fade points.
def fade_point_count
count = "\0" * SIZEOF_INT
FMOD.invoke(:ChannelGroup_GetFadePoints, self, count, nil, nil)
count.unpack1('l')
end
##
# Retrieve information about fade points stored within a {ChannelControl}.
# @return [Array<FadePoint>] An array of {FadePoint} objects, or an empty
# array if no fade points are present.
def fade_points
count = fade_point_count
return [] if count.zero?
clocks = "\0" * (count * SIZEOF_LONG_LONG)
volumes = "\0" * (count * SIZEOF_FLOAT)
FMOD.invoke(:ChannelGroup_GetFadePoints, self, int_ptr, clocks, volumes)
args = clocks.unpack('Q*').zip(volumes.unpack('f*'))
args.map { |values| FadePoint.new(*values) }
end
##
# Remove volume fade points on the time-line. This function will remove
# multiple fade points with a single call if the points lay between the 2
# specified clock values (inclusive).
# @param clock_start [Integer] DSP clock of the parent channel group to
# start removing fade points from.
# @param clock_end [Integer] DSP clock of the parent channel group to start
# removing fade points to.
# @return [self]
def remove_fade_points(clock_start, clock_end)
FMOD.invoke(:ChannelGroup_RemoveFadePoints, self, clock_start, clock_end)
self
end
##
# Sets the speaker volume levels for each speaker individually, this is a
# helper to avoid having to set the mix matrix.
#
# Levels can be below 0 to invert a signal and above 1 to amplify the
# signal. Note that increasing the signal level too far may cause audible
# distortion. Speakers specified that don't exist will simply be ignored.
# For more advanced speaker control, including sending the different
# channels of a stereo sound to arbitrary speakers, see {#matrix}.
#
# @note This function overwrites any pan/mix-level by overwriting the
# {ChannelControl}'s matrix.
#
# @param fl [Float] Volume level for the front left speaker of a
# multichannel speaker setup, 0.0 (silent), 1.0 (normal volume).
# @param fr [Float] Volume level for the front right speaker of a
# multichannel speaker setup, 0.0 (silent), 1.0 (normal volume).
# @param center [Float] Volume level for the center speaker of a
# multichannel speaker setup, 0.0 (silent), 1.0 (normal volume).
# @param lfe [Float] Volume level for the sub-woofer speaker of a
# multichannel speaker setup, 0.0 (silent), 1.0 (normal volume).
# @param sl [Float] Volume level for the surround left speaker of a
# multichannel speaker setup, 0.0 (silent), 1.0 (normal volume).
# @param sr [Float] Volume level for the surround right speaker of a
# multichannel speaker setup, 0.0 (silent), 1.0 (normal volume).
# @param bl [Float] Volume level for the back left speaker of a multichannel
# speaker setup, 0.0 (silent), 1.0 (normal volume).
# @param br [Float] Volume level for the back right speaker of a
# multichannel speaker setup, 0.0 (silent), 1.0 (normal volume).
# @return [self]
def output_mix(fl, fr, center, lfe, sl, sr, bl, br)
FMOD.invoke(:ChannelGroup_SetMixLevelsOutput, self, fl,
fr, center, lfe, sl, sr, bl, br)
self
end
##
# Sets the incoming volume level for each channel of a multi-channel sound.
# This is a helper to avoid calling {#matrix}.
#
# A multi-channel sound is a single sound that contains from 1 to 32
# channels of sound data, in an interleaved fashion. If in the extreme case,
# a 32 channel wave file was used, an array of 32 floating point numbers
# denoting their volume levels would be passed in to the levels parameter.
#
# @param levels [Array<Float>] Array of volume levels for each incoming
# channel.
# @return [self]
def input_mix(*levels)
count = levels.size
binary = levels.pack('f*')
FMOD.invoke(:ChannelGroup_SetMixLevelsInput, self, binary, count)
self
end
##
# @!attribute matrix
# A 2D pan matrix that maps input channels (columns) to output speakers
# (rows).
#
# Levels can be below 0 to invert a signal and above 1 to amplify the
# signal. Note that increasing the signal level too far may cause audible
# distortion.
#
# The matrix size will generally be the size of the number of channels in
# the current speaker mode. Use {System.software_format }to determine this.
#
# If a matrix already exists then the matrix passed in will applied over the
# top of it. The input matrix can be smaller than the existing matrix.
#
# A "unit" matrix allows a signal to pass through unchanged. For example for
# a 5.1 matrix a unit matrix would look like this:
# [[ 1, 0, 0, 0, 0, 0 ]
# [ 0, 1, 0, 0, 0, 0 ]
# [ 0, 0, 1, 0, 0, 0 ]
# [ 0, 0, 0, 1, 0, 0 ]
# [ 0, 0, 0, 0, 1, 0 ]
# [ 0, 0, 0, 0, 0, 1 ]]
#
# @return [Array<Array<Float>>] a 2-dimensional array of volume levels in
# row-major order. Each row represents an output speaker, each column
# represents an input channel.
def matrix
o, i = "\0" * SIZEOF_INT, "\0" * SIZEOF_INT
FMOD.invoke(:ChannelGroup_GetMixMatrix, self, nil, o, i, 0)
o, i = o.unpack1('l'), i.unpack1('l')
return [] if o.zero? || i.zero?
buffer = "\0" * (SIZEOF_FLOAT * o * i)
FMOD.invoke(:ChannelGroup_GetMixMatrix, self, buffer, int_ptr, int_ptr, 0)
buffer.unpack('f*').each_slice(i).to_a
end
def matrix=(matrix)
out_count, in_count = matrix.size, matrix.first.size
unless matrix.all? { |ary| ary.size == in_count }
raise Error, "Matrix contains unequal length input channels."
end
data = matrix.flatten.pack('f*')
FMOD.invoke(:ChannelGroup_SetMixMatrix, self, data,
out_count, in_count, 0)
end
##
# Sets the pan level, this is a helper to avoid setting the {#matrix}.
#
# Mono sounds are panned from left to right using constant power panning
# (non-linear fade). This means when pan = 0.0, the balance for the sound in
# each speaker is 71% left and 71% right, not 50% left and 50% right. This
# gives (audibly) smoother pans.
#
# Stereo sounds heave each left/right value faded up and down according to
# the specified pan position. This means when pan is 0.0, the balance for
# the sound in each speaker is 100% left and 100% right. When pan is -1.0,
# only the left channel of the stereo sound is audible, when pan is 1.0,
# only the right channel of the stereo sound is audible.
#
# @param pan [Float] The desired pan level.
# * *Minimum:* -1.0 (left)
# * *Maximum:* 1.0 (right)
# * *Default:* 0.0 (center)
#
# @return [self]
def pan(pan)
FMOD.invoke(:ChannelGroup_SetPan, self, pan.clamp(-1.0, 1.0))
self
end
##
# Stops the channel (or all channels in the channel group) from playing.
#
# Makes it available for re-use by the priority system.
#
# @return [void]
def stop
FMOD.invoke(:ChannelGroup_Stop, self)
end
##
# Sets the paused state.
#
# @return [self]
# @see resume
# @see paused?
def pause
FMOD.invoke(:ChannelGroup_SetPaused, self, 1)
self
end
##
# Resumes playback from a paused state.
#
# @return [self]
# @see pause
# @see paused?
def resume
FMOD.invoke(:ChannelGroup_SetPaused, self, 0)
self
end
##
# Sets the mute state effectively silencing it or returning it to its normal
# volume.
#
# @return [self]
# @see unmute
# @see muted?
def mute
FMOD.invoke(:ChannelGroup_SetMute, self, 1)
self
end
##
# Resumes the volume from a muted state.
#
# @return [self]
# @see mute
# @see muted?
def unmute
FMOD.invoke(:ChannelGroup_SetMute, self, 0)
self
end
##
# @!attribute dsps
# @return [DspChain] the DSP chain of the {ChannelControl}, containing the
# effects currently applied.
def dsps
DspChain.send(:new, self)
end
##
# @!attribute [r] parent
# @return [System] the parent {System} object that was used to create this
# object.
def parent
FMOD.invoke(:ChannelGroup_GetSystemObject, self, system = int_ptr)
System.new(system)
end
##
# Add a short 64 sample volume ramp to the specified time in the future
# using fade points.
#
# @param clock [Integer] DSP clock of the parent channel group when the
# volume will be ramped to.
# @param volume [Float] Volume level where 0 is silent and 1.0 is normal
# volume. Amplification is supported.
#
# @return [void]
def fade_ramp(clock, volume)
FMOD.invoke(:ChannelGroup_SetFadePointRamp, self, clock, volume)
end
##
# Retrieves the DSP clock value which count up by the number of samples per
# second in the software mixer, i.e. if the default sample rate is 48KHz,
# the DSP clock increments by 48000 per second.
#
# @return [Integer] the current clock value.
def dsp_clock
buffer = "\0" * SIZEOF_LONG_LONG
FMOD.invoke(:ChannelGroup_GetDSPClock, self, buffer, nil)
buffer.unpack1('Q')
end
##
# Retrieves the DSP clock value which count up by the number of samples per
# second in the software mixer, i.e. if the default sample rate is 48KHz,
# the DSP clock increments by 48000 per second.
#
# @return [Integer] the current parent clock value.
def parent_clock
buffer = "\0" * SIZEOF_LONG_LONG
FMOD.invoke(:ChannelGroup_GetDSPClock, self, nil, buffer)
buffer.unpack1('Q')
end
##
# Retrieves the wet level (or send level) for a particular reverb instance.
#
# @param index [Integer] Index of the particular reverb instance to target.
#
# @return [Float] the send level for the signal to the reverb, from 0 (none)
# to 1.0 (full).
# @see set_reverb_level
def get_reverb_level(index)
wet = "\0" * SIZEOF_FLOAT
FMOD.invoke(:ChannelGroup_GetReverbProperties, self, index, wet)
wet.unpack1('f')
end
##
# Sets the wet level (or send level) of a particular reverb instance.
#
# A Channel is automatically connected to all existing reverb instances due
# to the default wet level of 1.0. A ChannelGroup however will not send to
# any reverb by default requiring an explicit call to this function.
#
# A ChannelGroup reverb is optimal for the case where you want to send 1
# mixed signal to the reverb, rather than a lot of individual channel reverb
# sends. It is advisable to do this to reduce CPU if you have many Channels
# inside a ChannelGroup.
#
# Keep in mind when setting a wet level for a ChannelGroup, any Channels
# under that ChannelGroup will still have their existing sends to the
# reverb. To avoid this doubling up you should explicitly set the Channel
# wet levels to 0.0.
#
# @param index [Integer] Index of the particular reverb instance to target.
#
# @return [void]
# @see get_reverb_level
def set_reverb_level(index, wet_level)
wet = wet_level.clamp(0.0, 1.0)
FMOD.invoke(:ChannelGroup_SetReverbProperties, self, index, wet)
end
##
# @!attribute delay
# The start (and/or stop) time relative to the parent channel group DSP
# clock, with sample accuracy.
#
# Every channel and channel group has its own DSP Clock. A channel or
# channel group can be delayed relatively against its parent, with sample
# accurate positioning. To delay a sound, use the 'parent' channel group DSP
# clock to reference against when passing values into this function.
#
# If a parent channel group changes its pitch, the start and stop times will
# still be correct as the parent clock is rate adjusted by that pitch.
#
# @return [ChannelDelay] the delay.
# @see set_delay
def delay
clock_start = "\0" * SIZEOF_LONG_LONG
clock_end = "\0" * SIZEOF_LONG_LONG
stop = "\0" * SIZEOF_INT
FMOD.invoke(:ChannelGroup_GetDelay, self, clock_start, clock_end, stop)
stop = stop.unpack1('l') != 0
ChannelDelay.new(clock_start.unpack1('Q'), clock_end.unpack1('Q'), stop)
end
def delay=(delay)
FMOD.type?(delay, ChannelDelay)
set_delay(delay.start, delay.end, delay.stop)
delay
end
##
# The start (and/or stop) time relative to the parent channel group DSP
# clock, with sample accuracy.
#
# Every channel and channel group has its own DSP Clock. A channel or
# channel group can be delayed relatively against its parent, with sample
# accurate positioning. To delay a sound, use the 'parent' channel group DSP
# clock to reference against when passing values into this function.
#
# If a parent channel group changes its pitch, the start and stop times will
# still be correct as the parent clock is rate adjusted by that pitch.
#
# @param clock_start [Integer] DSP clock of the parent channel group to
# audibly start playing sound at, a value of 0 indicates no delay.
# @param clock_end [Integer] DSP clock of the parent channel group to
# audibly stop playing sound at, a value of 0 indicates no delay.
# @param stop [Boolean] +true+ to stop according to {#playing?}, otherwise
# +false+ to remain "active" and a new start delay could start playback
# again at a later time.
#
# @return [self]
# @see delay
def set_delay(clock_start, clock_end, stop)
stop = stop.to_i
FMOD.invoke(:ChannelGroup_SetDelay, self, clock_start, clock_end, stop)
self
end
# @!group Callbacks
##
# Binds the given block so that it will be invoked when the channel is
# stopped, either by {#stop} or when playback reaches an end.
# @example
# >> channel.on_stop do
# >> puts "Channel stop"
# >> end
# >> channel.stop
#
# "Channel stop"
# @param proc [Proc] Proc to call. Optional, must give block if nil.
# @yield The block to call when the {ChannelControl} is stopped.
# @yieldreturn [Channel] The {ChannelControl} receiving this callback.
# @return [self]
def on_stop(proc = nil, &block)
set_callback(0, &(block_given? ? block : proc))
end
##
# Binds the given block so that it will be invoked when the a voice is
# swapped to or from emulated/real.
# @param proc [Proc] Proc to call. Optional, must give block if nil.
# @yield [emulated] The block to call when a voice is swapped, with flag
# indicating if voice is emulated passed to it.
# @yieldparam emulated [Boolean]
# * *true:* Swapped from real to emulated
# * *false:* Swapped from emulated to real
# @yieldreturn [Channel] The {ChannelControl} receiving this callback.
# @return [self]
def on_voice_swap(proc = nil, &block)
set_callback(1, &(block_given? ? block : proc))
end
##
# Binds the given block so that it will be invoked when a sync-point is
# encountered.
# @param proc [Proc] Proc to call. Optional, must give block if nil.
# @yield [index] The block to call when a sync-point is encountered, with
# the index of the sync-point passed to it.
# @yieldparam index [Integer] The sync-point index.
# @yieldreturn [Channel] The {ChannelControl} receiving this callback.
# @return [self]
def on_sync_point(proc = nil, &block)
set_callback(2, &(block_given? ? block : proc))
end
##
# Binds the given block so that it will be invoked when the occlusion is
# calculated.
# @param proc [Proc] Proc to call. Optional, must give block if nil.
# @yield [direct, reverb] The block to call when occlusion is calculated,
# with pointers to the direct and reverb occlusion values passed to it.
# @yieldparam direct [Pointer] A pointer to a floating point direct value
# that can be read (de-referenced) and modified after the geometry engine
# has calculated it for this channel.
# @yieldparam reverb [Pointer] A pointer to a floating point reverb value
# that can be read (de-referenced) and modified after the geometry engine
# has calculated it for this channel.
# @yieldreturn [Channel] The {ChannelControl} receiving this callback.
# @return [self]
def on_occlusion(proc = nil, &block)
set_callback(3, &(block_given? ? block : proc))
end
# @!endgroup
##
# @api private
def initialize(address = nil)
super
@callbacks = {}
ret = TYPE_INT
sig = [TYPE_VOIDP, TYPE_INT, TYPE_INT, TYPE_VOIDP, TYPE_VOIDP]
abi = FMOD::ABI
bc = Closure::BlockCaller.new(ret, sig, abi) do |_c, _t, cb_type, d1, d2|
if @callbacks[cb_type]
case cb_type
when 0 then @callbacks[0].each(&:call)
when 1
virtual = d1.to_s(SIZEOF_INT).unpack1('l') != 0
@callbacks[1].each { |cb| cb.call(virtual) }
when 2
index = d1.to_s(SIZEOF_INT).unpack1('l')
@callbacks[2].each { |cb| cb.call(index) }
when 3 then @callbacks[3].each { |cb| cb.call(d1, d2) }
else raise FMOD::Error, "Invalid channel callback type."
end
end
Result::OK
end
FMOD.invoke(:ChannelGroup_SetCallback, self, bc)
end
private
def set_callback(index, &block)
raise LocalJumpError, "No block given." unless block_given?
@callbacks[index] ||= []
@callbacks[index] << block
self
end
end
end
|
1980s-housewife/TFM-4.3-Reloaded | src/main/java/me/StevenLawson/TotalFreedomMod/commands/Command_permban.java | package me.StevenLawson.TotalFreedomMod.commands;
import me.StevenLawson.TotalFreedomMod.ban.PermbanList;
import org.apache.commons.lang3.StringUtils;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
@CommandPermissions(level = AdminLevel.SUPER, source = SourceType.BOTH, blockHostConsole = true)
@CommandParameters(description = "Manage permanently banned players and IPs.", usage = "/<command> <list | reload>")
public class Command_permban extends FreedomCommand {
@Override
public boolean run(CommandSender sender, org.bukkit.entity.Player sender_p, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) {
if (args.length != 1) {
return false;
}
if (args[0].equalsIgnoreCase("list")) {
dumplist(sender);
}
else if (args[0].equalsIgnoreCase("reload"))
{
if (!senderIsConsole)
{
sender.sendMessage(FreedomCommand.MSG_NO_PERMS);
return true;
}
playerMsg("Reloading permban list...", ChatColor.RED);
PermbanList.load();
dumplist(sender);
}
else
{
return false;
}
return true;
}
private void dumplist(CommandSender sender)
{
if (PermbanList.getPermbannedPlayers().isEmpty())
{
playerMsg("No permanently banned player names.");
}
else
{
playerMsg(PermbanList.getPermbannedPlayers().size() + " permanently banned players:");
playerMsg(StringUtils.join(PermbanList.getPermbannedPlayers(), ", "));
}
if (PermbanList.getPermbannedIps().isEmpty())
{
playerMsg("No permanently banned IPs.");
}
else
{
playerMsg(PermbanList.getPermbannedIps().size() + " permanently banned IPs:");
playerMsg(StringUtils.join(PermbanList.getPermbannedIps(), ", "));
}
}
}
|
isabella232/openui5-fhir | test/sap-fhir-test-app/webapp/controller/structureDefinition/StructureDefinition.controller.js | sap.ui.define([
"sap/ui/core/mvc/Controller",
"../../utils/Utils",
"sap/m/MessageBox",
"../../utils/Formatter",
"sap/base/Log"
], function(Controller, Utils, MessageBox, Formatter, Log) {
"use strict";
return Controller.extend("sap-fhir-test-app.controller.structureDefinition.StructureDefinition", {
formatter : Formatter,
onInit : function() {
this.initializeRouter();
},
initializeRouter : function() {
this.oRouter = sap.ui.core.UIComponent.getRouterFor(this);
this.oRouter.getRoute("structureDefinition").attachPatternMatched(this._onStructureDefinitionScreenMatched, this);
},
onNavBack : function() {
this.oRouter.navTo("structureDefinitionsListAndTables", {
tab : this.sTabKey
});
},
onPressEdit : function() {
this.toggleEditMode();
},
toggleEditMode : function() {
var clientModel = this.getView().getModel("client");
var bIsEditMode = clientModel.getProperty("/isEditMode");
clientModel.setProperty("/isEditMode", !bIsEditMode);
},
getStructureDefinitionBusyDialog : function() {
return this.getView().byId("structureDefinitionBusyDialog");
},
onStructureDefinitionBusyDialogClosed : function(oEvent) {
if (oEvent.getParameter("cancelPressed") === true) {
this._mRequests.structureDefinition.abort();
}
},
openStructureDefinitionBusyDialog : function() {
var oBusyDialog = this.getStructureDefinitionBusyDialog();
oBusyDialog.open();
},
closeStructureDefinitionBusyDialog : function() {
var oBusyDialog = this.getStructureDefinitionBusyDialog();
oBusyDialog.close();
},
_onStructureDefinitionScreenMatched : function(oEvent) {
this.sTabKey = oEvent.getParameter("arguments").tab;
this.sStructDefinitionId = oEvent.getParameter("arguments").structId;
this.byId("structureDefinitionPage").bindElement({
path : "/StructureDefinition/" + this.sStructDefinitionId,
parameters : {
groupId : "structureDefinition"
}
});
},
onPressRefresh : function() {
this.getView().getModel().refresh();
},
onPressSave : function() {
this.openStructureDefinitionBusyDialog();
this._mRequests = this.getView().getModel().submitChanges("structureDefinition", this.onSuccessfulSave.bind(this), this.onFailureSave.bind(this));
if (!this._mRequests) {
sap.m.MessageToast.show(Utils.getI18nText(this.getView(), "structureDefinitionMsgSaveNoChanges"));
this.toggleEditMode();
this.closeStructureDefinitionBusyDialog();
}
},
onPressCancel : function() {
this.getView().getModel().resetChanges();
this.toggleEditMode();
},
onSuccessfulSave : function(oResponse) {
this.toggleEditMode();
this.closeStructureDefinitionBusyDialog();
sap.m.MessageToast.show(Utils.getI18nText(this.getView(), "structureDefinitionMsgSaveSuccess"));
Log.info("Successful save operation with response: " + JSON.stringify(oResponse));
},
onFailureSave : function(oError, aResource, aOperationOutcome) {
this.closeStructureDefinitionBusyDialog();
MessageBox.error(Utils.getI18nText(this.getView(), "structureDefinitionMsgSaveFailed", [oError.message]), {
styleClass: this.getOwnerComponent().getContentDensityClass()
});
},
createStructDef : function() {
// state of the art way of fhir model
var sResId = this.getView().getModel().create("StructureDefinition", {});
this.byId("structDefCreateScrollContainer").bindElement({
path : "/StructureDefinition/" + sResId,
parameters : {
groupId : "stdChange"
}
});
// not implemented yet - state of the art odata model like
// this.getView().getModel().create("StructureDefinition", {
// resource : {
// name : this.byId("newName").getValue(),
// description : this.byId("newDescription").getValue()
// },
// groupId : "stdChange"
// });
// this.getView().getModel().submitChanges("stdChange");
}
});
});
|
ceekay1991/AliPayForDebug | AliPayForDebug/AliPayForDebug/AlipayWallet_Headers/CDPObserver.h | //
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Sep 17 2017 16:24:48).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by <NAME>.
//
#import <objc/NSObject.h>
@protocol PromotionCenterDelegate;
@interface CDPObserver : NSObject
{
int _type;
id <PromotionCenterDelegate> _observer;
}
+ (id)observerWithType:(int)arg1 observer:(id)arg2;
@property(nonatomic) __weak id <PromotionCenterDelegate> observer; // @synthesize observer=_observer;
@property(nonatomic) int type; // @synthesize type=_type;
- (void).cxx_destruct;
@end
|
iridium-browser/iridium-browser | chrome/browser/vr/elements/text_button.h | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_VR_ELEMENTS_TEXT_BUTTON_H_
#define CHROME_BROWSER_VR_ELEMENTS_TEXT_BUTTON_H_
#include <memory>
#include "base/macros.h"
#include "chrome/browser/vr/elements/button.h"
#include "chrome/browser/vr/elements/text.h"
namespace vr {
// TextButton is a Button that sizes itself to a supplied text string.
class TextButton : public Button {
public:
TextButton(float text_height, AudioDelegate* audio_delegate);
~TextButton() override;
void SetText(const std::u16string& text);
private:
void OnSetColors(const ButtonColors& colors) override;
Text* text_ = nullptr;
DISALLOW_COPY_AND_ASSIGN(TextButton);
};
} // namespace vr
#endif // CHROME_BROWSER_VR_ELEMENTS_TEXT_BUTTON_H_
|
Mu-L/arangodb | 3rdParty/rocksdb/6.27/db_stress_tool/db_stress_common.cc | // Copyright (c) 2011-present, Facebook, Inc. All rights reserved.
// This source code is licensed under both the GPLv2 (found in the
// COPYING file in the root directory) and Apache 2.0 License
// (found in the LICENSE.Apache file in the root directory).
//
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
//
#ifdef GFLAGS
#include "db_stress_tool/db_stress_common.h"
#include <cmath>
#include "util/file_checksum_helper.h"
#include "util/xxhash.h"
ROCKSDB_NAMESPACE::Env* db_stress_env = nullptr;
#ifndef NDEBUG
// If non-null, injects read error at a rate specified by the
// read_fault_one_in or write_fault_one_in flag
std::shared_ptr<ROCKSDB_NAMESPACE::FaultInjectionTestFS> fault_fs_guard;
#endif // NDEBUG
enum ROCKSDB_NAMESPACE::CompressionType compression_type_e =
ROCKSDB_NAMESPACE::kSnappyCompression;
enum ROCKSDB_NAMESPACE::CompressionType bottommost_compression_type_e =
ROCKSDB_NAMESPACE::kSnappyCompression;
enum ROCKSDB_NAMESPACE::ChecksumType checksum_type_e =
ROCKSDB_NAMESPACE::kCRC32c;
enum RepFactory FLAGS_rep_factory = kSkipList;
std::vector<double> sum_probs(100001);
constexpr int64_t zipf_sum_size = 100000;
namespace ROCKSDB_NAMESPACE {
// Zipfian distribution is generated based on a pre-calculated array.
// It should be used before start the stress test.
// First, the probability distribution function (PDF) of this Zipfian follows
// power low. P(x) = 1/(x^alpha).
// So we calculate the PDF when x is from 0 to zipf_sum_size in first for loop
// and add the PDF value togetger as c. So we get the total probability in c.
// Next, we calculate inverse CDF of Zipfian and store the value of each in
// an array (sum_probs). The rank is from 0 to zipf_sum_size. For example, for
// integer k, its Zipfian CDF value is sum_probs[k].
// Third, when we need to get an integer whose probability follows Zipfian
// distribution, we use a rand_seed [0,1] which follows uniform distribution
// as a seed and search it in the sum_probs via binary search. When we find
// the closest sum_probs[i] of rand_seed, i is the integer that in
// [0, zipf_sum_size] following Zipfian distribution with parameter alpha.
// Finally, we can scale i to [0, max_key] scale.
// In order to avoid that hot keys are close to each other and skew towards 0,
// we use Rando64 to shuffle it.
void InitializeHotKeyGenerator(double alpha) {
double c = 0;
for (int64_t i = 1; i <= zipf_sum_size; i++) {
c = c + (1.0 / std::pow(static_cast<double>(i), alpha));
}
c = 1.0 / c;
sum_probs[0] = 0;
for (int64_t i = 1; i <= zipf_sum_size; i++) {
sum_probs[i] =
sum_probs[i - 1] + c / std::pow(static_cast<double>(i), alpha);
}
}
// Generate one key that follows the Zipfian distribution. The skewness
// is decided by the parameter alpha. Input is the rand_seed [0,1] and
// the max of the key to be generated. If we directly return tmp_zipf_seed,
// the closer to 0, the higher probability will be. To randomly distribute
// the hot keys in [0, max_key], we use Random64 to shuffle it.
int64_t GetOneHotKeyID(double rand_seed, int64_t max_key) {
int64_t low = 1, mid, high = zipf_sum_size, zipf = 0;
while (low <= high) {
mid = (low + high) / 2;
if (sum_probs[mid] >= rand_seed && sum_probs[mid - 1] < rand_seed) {
zipf = mid;
break;
} else if (sum_probs[mid] >= rand_seed) {
high = mid - 1;
} else {
low = mid + 1;
}
}
int64_t tmp_zipf_seed = zipf * max_key / zipf_sum_size;
Random64 rand_local(tmp_zipf_seed);
return rand_local.Next() % max_key;
}
void PoolSizeChangeThread(void* v) {
assert(FLAGS_compaction_thread_pool_adjust_interval > 0);
ThreadState* thread = reinterpret_cast<ThreadState*>(v);
SharedState* shared = thread->shared;
while (true) {
{
MutexLock l(shared->GetMutex());
if (shared->ShouldStopBgThread()) {
shared->IncBgThreadsFinished();
if (shared->BgThreadsFinished()) {
shared->GetCondVar()->SignalAll();
}
return;
}
}
auto thread_pool_size_base = FLAGS_max_background_compactions;
auto thread_pool_size_var = FLAGS_compaction_thread_pool_variations;
int new_thread_pool_size =
thread_pool_size_base - thread_pool_size_var +
thread->rand.Next() % (thread_pool_size_var * 2 + 1);
if (new_thread_pool_size < 1) {
new_thread_pool_size = 1;
}
db_stress_env->SetBackgroundThreads(new_thread_pool_size,
ROCKSDB_NAMESPACE::Env::Priority::LOW);
// Sleep up to 3 seconds
db_stress_env->SleepForMicroseconds(
thread->rand.Next() % FLAGS_compaction_thread_pool_adjust_interval *
1000 +
1);
}
}
void DbVerificationThread(void* v) {
assert(FLAGS_continuous_verification_interval > 0);
auto* thread = reinterpret_cast<ThreadState*>(v);
SharedState* shared = thread->shared;
StressTest* stress_test = shared->GetStressTest();
assert(stress_test != nullptr);
while (true) {
{
MutexLock l(shared->GetMutex());
if (shared->ShouldStopBgThread()) {
shared->IncBgThreadsFinished();
if (shared->BgThreadsFinished()) {
shared->GetCondVar()->SignalAll();
}
return;
}
}
if (!shared->HasVerificationFailedYet()) {
stress_test->ContinuouslyVerifyDb(thread);
}
db_stress_env->SleepForMicroseconds(
thread->rand.Next() % FLAGS_continuous_verification_interval * 1000 +
1);
}
}
void PrintKeyValue(int cf, uint64_t key, const char* value, size_t sz) {
if (!FLAGS_verbose) {
return;
}
std::string tmp;
tmp.reserve(sz * 2 + 16);
char buf[4];
for (size_t i = 0; i < sz; i++) {
snprintf(buf, 4, "%X", value[i]);
tmp.append(buf);
}
auto key_str = Key(key);
Slice key_slice = key_str;
fprintf(stdout, "[CF %d] %s (%" PRIi64 ") == > (%" ROCKSDB_PRIszt ") %s\n",
cf, key_slice.ToString(true).c_str(), key, sz, tmp.c_str());
}
// Note that if hot_key_alpha != 0, it generates the key based on Zipfian
// distribution. Keys are randomly scattered to [0, FLAGS_max_key]. It does
// not ensure the order of the keys being generated and the keys does not have
// the active range which is related to FLAGS_active_width.
int64_t GenerateOneKey(ThreadState* thread, uint64_t iteration) {
const double completed_ratio =
static_cast<double>(iteration) / FLAGS_ops_per_thread;
const int64_t base_key = static_cast<int64_t>(
completed_ratio * (FLAGS_max_key - FLAGS_active_width));
int64_t rand_seed = base_key + thread->rand.Next() % FLAGS_active_width;
int64_t cur_key = rand_seed;
if (FLAGS_hot_key_alpha != 0) {
// If set the Zipfian distribution Alpha to non 0, use Zipfian
double float_rand =
(static_cast<double>(thread->rand.Next() % FLAGS_max_key)) /
FLAGS_max_key;
cur_key = GetOneHotKeyID(float_rand, FLAGS_max_key);
}
return cur_key;
}
// Note that if hot_key_alpha != 0, it generates the key based on Zipfian
// distribution. Keys being generated are in random order.
// If user want to generate keys based on uniform distribution, user needs to
// set hot_key_alpha == 0. It will generate the random keys in increasing
// order in the key array (ensure key[i] >= key[i+1]) and constrained in a
// range related to FLAGS_active_width.
std::vector<int64_t> GenerateNKeys(ThreadState* thread, int num_keys,
uint64_t iteration) {
const double completed_ratio =
static_cast<double>(iteration) / FLAGS_ops_per_thread;
const int64_t base_key = static_cast<int64_t>(
completed_ratio * (FLAGS_max_key - FLAGS_active_width));
std::vector<int64_t> keys;
keys.reserve(num_keys);
int64_t next_key = base_key + thread->rand.Next() % FLAGS_active_width;
keys.push_back(next_key);
for (int i = 1; i < num_keys; ++i) {
// Generate the key follows zipfian distribution
if (FLAGS_hot_key_alpha != 0) {
double float_rand =
(static_cast<double>(thread->rand.Next() % FLAGS_max_key)) /
FLAGS_max_key;
next_key = GetOneHotKeyID(float_rand, FLAGS_max_key);
} else {
// This may result in some duplicate keys
next_key = next_key + thread->rand.Next() %
(FLAGS_active_width - (next_key - base_key));
}
keys.push_back(next_key);
}
return keys;
}
size_t GenerateValue(uint32_t rand, char* v, size_t max_sz) {
size_t value_sz =
((rand % kRandomValueMaxFactor) + 1) * FLAGS_value_size_mult;
assert(value_sz <= max_sz && value_sz >= sizeof(uint32_t));
(void)max_sz;
*((uint32_t*)v) = rand;
for (size_t i = sizeof(uint32_t); i < value_sz; i++) {
v[i] = (char)(rand ^ i);
}
v[value_sz] = '\0';
return value_sz; // the size of the value set.
}
std::string NowNanosStr() {
uint64_t t = db_stress_env->NowNanos();
std::string ret;
PutFixed64(&ret, t);
return ret;
}
std::string GenerateTimestampForRead() { return NowNanosStr(); }
namespace {
class MyXXH64Checksum : public FileChecksumGenerator {
public:
explicit MyXXH64Checksum(bool big) : big_(big) {
state_ = XXH64_createState();
XXH64_reset(state_, 0);
}
virtual ~MyXXH64Checksum() override { XXH64_freeState(state_); }
void Update(const char* data, size_t n) override {
XXH64_update(state_, data, n);
}
void Finalize() override {
assert(str_.empty());
uint64_t digest = XXH64_digest(state_);
// Store as little endian raw bytes
PutFixed64(&str_, digest);
if (big_) {
// Throw in some more data for stress testing (448 bits total)
PutFixed64(&str_, GetSliceHash64(str_));
PutFixed64(&str_, GetSliceHash64(str_));
PutFixed64(&str_, GetSliceHash64(str_));
PutFixed64(&str_, GetSliceHash64(str_));
PutFixed64(&str_, GetSliceHash64(str_));
PutFixed64(&str_, GetSliceHash64(str_));
}
}
std::string GetChecksum() const override {
assert(!str_.empty());
return str_;
}
const char* Name() const override {
return big_ ? "MyBigChecksum" : "MyXXH64Checksum";
}
private:
bool big_;
XXH64_state_t* state_;
std::string str_;
};
class DbStressChecksumGenFactory : public FileChecksumGenFactory {
std::string default_func_name_;
std::unique_ptr<FileChecksumGenerator> CreateFromFuncName(
const std::string& func_name) {
std::unique_ptr<FileChecksumGenerator> rv;
if (func_name == "FileChecksumCrc32c") {
rv.reset(new FileChecksumGenCrc32c(FileChecksumGenContext()));
} else if (func_name == "MyXXH64Checksum") {
rv.reset(new MyXXH64Checksum(false /* big */));
} else if (func_name == "MyBigChecksum") {
rv.reset(new MyXXH64Checksum(true /* big */));
} else {
// Should be a recognized function when we get here
assert(false);
}
return rv;
}
public:
explicit DbStressChecksumGenFactory(const std::string& default_func_name)
: default_func_name_(default_func_name) {}
std::unique_ptr<FileChecksumGenerator> CreateFileChecksumGenerator(
const FileChecksumGenContext& context) override {
if (context.requested_checksum_func_name.empty()) {
return CreateFromFuncName(default_func_name_);
} else {
return CreateFromFuncName(context.requested_checksum_func_name);
}
}
const char* Name() const override { return "FileChecksumGenCrc32cFactory"; }
};
} // namespace
std::shared_ptr<FileChecksumGenFactory> GetFileChecksumImpl(
const std::string& name) {
// Translate from friendly names to internal names
std::string internal_name;
if (name == "crc32c") {
internal_name = "FileChecksumCrc32c";
} else if (name == "xxh64") {
internal_name = "MyXXH64Checksum";
} else if (name == "big") {
internal_name = "MyBigChecksum";
} else {
assert(name.empty() || name == "none");
return nullptr;
}
return std::make_shared<DbStressChecksumGenFactory>(internal_name);
}
} // namespace ROCKSDB_NAMESPACE
#endif // GFLAGS
|
bugsbunnyshah/braineous_dataplatform | src/main/java/com/appgallabs/dataplatform/query/ObjectGraphQueryService.java | package com.appgallabs.dataplatform.query;
import com.appgallabs.dataplatform.ingestion.service.MapperService;
import com.appgallabs.dataplatform.util.JsonUtil;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
import org.apache.tinkerpop.gremlin.sparql.process.traversal.dsl.sparql.SparqlTraversalSource;
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import java.util.*;
@ApplicationScoped
public class ObjectGraphQueryService {
private static Logger logger = LoggerFactory.getLogger(ObjectGraphQueryService.class);
@Inject
private MapperService mapperService;
@Inject
private GraphQueryGenerator graphQueryGenerator;
@Inject
private GraphQueryProcessor graphQueryProcessor;
private TinkerGraph g;
private GraphData graphData;
private SparqlTraversalSource server;
@PostConstruct
public void onStart()
{
//TODO: instantiate with a RemoteGraphData
/*BaseConfiguration configuration = new BaseConfiguration();
configuration.addProperty("port", 8182);
configuration.addProperty("hosts", Arrays.asList("gremlin-server"));
configuration.addProperty("gremlin.remote.remoteConnectionClass","org.apache.tinkerpop.gremlin.driver.remote.DriverRemoteConnection");
configuration.addProperty("connectionPool.maxContentLength", 131072);
configuration.addProperty("connectionPool.enableSsl", false);
configuration.addProperty("connectionPool.maxSize", 80);
configuration.addProperty("connectionPool.minSize", 10);
configuration.addProperty("connectionPool.maxInProcessPerConnection", 16);
configuration.addProperty("connectionPool.minInProcessPerConnection", 8);
configuration.addProperty("connectionPool.maxWaitForConnection", 10000);
configuration.addProperty("connectionPool.minSimultaneousUsagePerConnection", 10);
configuration.addProperty("connectionPool.maxSimultaneousUsagePerConnection", 10);
//configuration.addProperty("serializer.className", "org.apache.tinkerpop.gremlin.driver.ser.AbstractGryoMessageSerializerV3d0");
//configuration.addProperty("serializer.config.serializeResultToString", "true");
configuration.addProperty("serializer.className",
"org.apache.tinkerpop.gremlin.driver.ser.GraphSONMessageSerializerV3d0");
RemoteConnection remoteConnection = RemoteConnection.from(configuration);
SparqlTraversalSource server = new SparqlTraversalSource(remoteConnection);*/
this.g = TinkerGraph.open();
this.server = new SparqlTraversalSource(g);
this.graphData = new LocalGraphData(server);
}
@PreDestroy
public void onStop(){
this.g = null;
this.server = null;
this.graphData = null;
}
public void setGraphData(GraphData graphData)
{
this.graphData = graphData;
}
public GraphData getGraphData()
{
return this.graphData;
}
public JsonArray queryByCriteria(String entity, JsonObject criteria)
{
JsonArray response = new JsonArray();
String query = this.graphQueryGenerator.generateQueryByCriteria(entity,criteria);
GraphTraversal result = this.graphQueryProcessor.query(this.graphData, query);
Iterator<Vertex> itr = result.toSet().iterator();
while(itr.hasNext())
{
Vertex vertex = itr.next();
JsonObject vertexJson = JsonParser.parseString(vertex.property("source").value().toString()).getAsJsonObject();
response.add(vertexJson);
}
return response;
}
public JsonArray navigateByCriteria(String entity, String relationship, JsonObject criteria) throws Exception
{
JsonArray response = new JsonArray();
String navQuery = this.graphQueryGenerator.generateNavigationQuery(entity,
relationship,criteria);
GraphTraversal result = this.graphQueryProcessor.navigate(this.graphData,navQuery);
//result = result.flatMap(result);
//System.out.println(result);
Iterator<Map> itr = result.toSet().iterator();
while(itr.hasNext())
{
Map map = itr.next();
Vertex edge = (Vertex) map.get(entity);
if(edge != null) {
System.out.println(edge.label());
if (edge.label().equals(entity)) {
JsonObject edgeJson = JsonParser.parseString(edge.property("source").value().toString()).getAsJsonObject();
response.add(edgeJson);
}
}
else
{
System.out.println("NOT_fOUND");
}
}
return response;
}
public Vertex saveObjectGraph(String entity,
JsonObject parent,JsonObject child,boolean isProperty)
{
Vertex vertex;
if(!isProperty)
{
vertex = this.g.addVertex(T.label,entity);
}
else
{
vertex = this.g.addVertex(T.label, entity);
}
JsonObject json = parent;
if(child != null)
{
json = child;
}
Set<String> properties = json.keySet();
List<Vertex> children = new ArrayList<>();
for(String property:properties)
{
if(json.get(property).isJsonObject())
{
JsonObject propertyObject = json.getAsJsonObject(property);
Vertex propertyVertex = this.saveObjectGraph(property,parent,propertyObject,true);
children.add(propertyVertex);
}
else if(json.get(property).isJsonPrimitive())
{
String value = json.get(property).getAsString();
vertex.property(property,value);
}
}
vertex.property("source",json.toString());
vertex.property("vertexId",UUID.randomUUID().toString());
for(Vertex local:children)
{
vertex.addEdge("edge_"+local.label(), local, T.id, UUID.randomUUID().toString(), "weight", 0.5d);
}
return vertex;
}
}
|
cmsxbc/oneDAL | cpp/daal/src/algorithms/dbscan/oneapi/dbscan_kernel_ucapi.h | /* file: dbscan_kernel_ucapi.h */
/*******************************************************************************
* Copyright 2020-2021 Intel Corporation
*
* 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.
*******************************************************************************/
/*
//++
// Declaration of template function that computes DBSCAN for GPU.
//--
*/
#ifndef __DBSCAN_KERNEL_UCAPI_H
#define __DBSCAN_KERNEL_UCAPI_H
#include "src/algorithms/kernel.h"
#include "data_management/data/numeric_table.h"
#include "services/internal/sycl/execution_context.h"
namespace daal
{
namespace algorithms
{
namespace dbscan
{
namespace internal
{
template <typename algorithmFPType>
class DBSCANBatchKernelUCAPI : public Kernel
{
public:
services::Status compute(const daal::data_management::NumericTable * ntData, const daal::data_management::NumericTable * ntWeights,
daal::data_management::NumericTable * ntAssignments, daal::data_management::NumericTable * ntNClusters,
daal::data_management::NumericTable * ntCoreIndices, daal::data_management::NumericTable * ntCoreObservations,
const Parameter * par);
private:
services::Status getCores(const services::internal::sycl::UniversalBuffer & data, uint32_t nRows, uint32_t nFeatures, int nNbrs,
algorithmFPType eps);
services::Status getCoresWithWeights(const services::internal::sycl::UniversalBuffer & data, uint32_t nRows, uint32_t nFeatures,
algorithmFPType nNbrs, algorithmFPType eps);
services::Status updateQueue(uint32_t clusterId, uint32_t nRows, uint32_t nFeatures, algorithmFPType eps, uint32_t queueBegin, uint32_t queueEnd,
const services::internal::sycl::UniversalBuffer & data, services::internal::sycl::UniversalBuffer & clusters);
services::Status startNextCluster(uint32_t clusterId, uint32_t nRows, uint32_t queueEnd, services::internal::sycl::UniversalBuffer & clusters,
bool & found);
services::Status processResultsToCompute(DAAL_UINT64 resultsToCompute, daal::data_management::NumericTable * ntData,
daal::data_management::NumericTable * ntCoreIndices,
daal::data_management::NumericTable * ntCoreObservations);
services::Status initializeBuffers(uint32_t nRows, daal::data_management::NumericTable * weights);
services::Status buildProgram(services::internal::sycl::ClKernelFactoryIface & kernel_factory);
services::Status setQueueFront(uint32_t queueEnd);
services::Status getQueueFront(uint32_t & queueEnd);
static constexpr uint32_t _maxSubgroupSize = 32;
bool _useWeights;
services::internal::sycl::UniversalBuffer _weights;
services::internal::sycl::UniversalBuffer _queue;
services::internal::sycl::UniversalBuffer _isCore;
services::internal::sycl::UniversalBuffer _lastPoint;
services::internal::sycl::UniversalBuffer _queueFront;
};
} // namespace internal
} // namespace dbscan
} // namespace algorithms
} // namespace daal
#endif
|
spacether/keyboardplotter | setup.py | <filename>setup.py
from setuptools import setup, find_packages
import pathlib
this_directory = pathlib.Path(__file__).parent
with open(this_directory / 'README.md', encoding='utf-8') as f:
long_description = f.read()
version = {}
with open(this_directory.joinpath('keyboardlayout', 'version.py')) as f:
exec(f.read(), version)
setup(
name = 'keyboardlayout',
install_requires = ['PyYAML >= 5.3.1'],
python_requires='>=3.7',
version = version['__version__'],
description = 'A python library to display different keyboards',
author = '<NAME>',
packages = find_packages(),
package_data={'keyboardlayout': ['layouts/*.yaml']},
url = "https://github.com/spacether/keyboardlayout",
keywords = [
"keyboard",
"qwerty",
"layout",
"azerty",
"pygame",
"tkinter",
"accessibility"
],
setup_requires=['pytest-runner'],
tests_require=['pytest', 'pygame'],
extras_require={
'dev': [
'sphinx',
'setuptools',
'wheel',
'twine',
]
},
classifiers = [
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Intended Audience :: End Users/Desktop',
'Operating System :: Microsoft :: Windows',
'Operating System :: POSIX',
'Operating System :: MacOS',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Multimedia :: Graphics',
'Topic :: Games/Entertainment :: Simulation',
'Development Status :: 5 - Production/Stable',
],
long_description=long_description,
long_description_content_type='text/markdown',
)
|
WorkPlusFE/js-sdk | dist/contact/getContacts.js | "use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var core = require("../core");
var constants_1 = require("../constants");
/**
* ๆๅผๅฝๅ็ป็ป็่็ณปไบบๅ่กจ๏ผ้ๆฉๅคไธช่็ณปไบบ
*
* @export
* @param {ContactsOptions} [options]
* @returns {Promise<ContactsRes>}
*/
function getContacts(options) {
var args = {
selectedContacts: (options === null || options === void 0 ? void 0 : options.selectedContacts) || [],
hideMe: (options === null || options === void 0 ? void 0 : options.hideMe) || false,
filterSenior: (options === null || options === void 0 ? void 0 : options.filterSenior) || 1,
};
return core.exec(constants_1.WORKPLUS_CONTACT, 'getContacts', [args], options === null || options === void 0 ? void 0 : options.success, options === null || options === void 0 ? void 0 : options.fail, false);
}
exports.default = getContacts;
|
Bloodknight/NeuTorsion | code/wxWidgets/src/mgl/dirmgl.cpp | /////////////////////////////////////////////////////////////////////////////
// Name: mgl/dir.cpp
// Purpose: wxDir implementation for MGL
// Author: <NAME>, <NAME>
// Modified by:
// Created: 2001/12/09
// RCS-ID: $Id: dirmgl.cpp,v 1.8 2005/04/05 16:10:15 ABX Exp $
// Copyright: (c) 1999 <NAME> <<EMAIL>>
// (c) 2001-2002 SciTech Software, Inc. (www.scitechsoft.com)
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
// ============================================================================
// declarations
// ============================================================================
// ----------------------------------------------------------------------------
// headers
// ----------------------------------------------------------------------------
#if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
#pragma implementation "dir.h"
#endif
// For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#include "wx/defs.h"
#ifndef __UNIX__
#ifndef WX_PRECOMP
#include "wx/intl.h"
#include "wx/log.h"
#endif // PCH
#include "wx/dir.h"
#include "wx/filefn.h" // for wxMatchWild
#include "wx/mgl/private.h"
// ----------------------------------------------------------------------------
// macros
// ----------------------------------------------------------------------------
#define M_DIR ((wxDirData *)m_data)
// ----------------------------------------------------------------------------
// private classes
// ----------------------------------------------------------------------------
// this class stores everything we need to enumerate the files
class wxDirData
{
public:
wxDirData(const wxString& dirname);
~wxDirData();
bool IsOk() const { return m_dir != NULL; }
void SetFileSpec(const wxString& filespec);
void SetFlags(int flags) { m_flags = flags; }
void Rewind();
bool Read(wxString *filename);
const wxString& GetName() const { return m_dirname; }
private:
void *m_dir;
wxString m_dirname;
wxString m_filespec;
int m_flags;
};
// ============================================================================
// implementation
// ============================================================================
// ----------------------------------------------------------------------------
// wxDirData
// ----------------------------------------------------------------------------
wxDirData::wxDirData(const wxString& dirname)
: m_dirname(dirname)
{
m_dir = NULL;
// throw away the trailing slashes
size_t n = m_dirname.length();
wxCHECK_RET( n, _T("empty dir name in wxDir") );
while ( n > 0 && m_dirname[--n] == wxFILE_SEP_PATH ) {}
m_dirname.Truncate(n + 1);
}
wxDirData::~wxDirData()
{
if ( m_dir )
PM_findClose(m_dir);
}
void wxDirData::SetFileSpec(const wxString& filespec)
{
#ifdef __DOS__
if ( filespec.empty() )
m_filespec = _T("*.*");
else
#endif
m_filespec = filespec;
}
void wxDirData::Rewind()
{
if ( m_dir )
{
PM_findClose(m_dir);
m_dir = NULL;
}
}
bool wxDirData::Read(wxString *filename)
{
PM_findData data;
bool matches = false;
data.dwSize = sizeof(data);
wxString path = m_dirname;
path += wxFILE_SEP_PATH;
path.reserve(path.length() + 255); // speed up string concatenation
while ( !matches )
{
if ( m_dir )
{
if ( !PM_findNextFile(m_dir, &data) )
return false;
}
else
{
m_dir = PM_findFirstFile(path + m_filespec , &data);
if ( m_dir == PM_FILE_INVALID )
{
m_dir = NULL;
return false;
}
}
// don't return "." and ".." unless asked for
if ( data.name[0] == '.' &&
((data.name[1] == '.' && data.name[2] == '\0') ||
(data.name[1] == '\0')) )
{
if ( !(m_flags & wxDIR_DOTDOT) )
continue;
// we found a valid match
break;
}
// check the type now
if ( !(m_flags & wxDIR_FILES) && !(data.attrib & PM_FILE_DIRECTORY) )
{
// it's a file, but we don't want them
continue;
}
else if ( !(m_flags & wxDIR_DIRS) && (data.attrib & PM_FILE_DIRECTORY) )
{
// it's a dir, and we don't want it
continue;
}
matches = m_flags & wxDIR_HIDDEN ? true : !(data.attrib & PM_FILE_HIDDEN);
}
*filename = data.name;
return true;
}
// ----------------------------------------------------------------------------
// wxDir helpers
// ----------------------------------------------------------------------------
/* static */
bool wxDir::Exists(const wxString& dir)
{
return wxDirExists(dir);
}
// ----------------------------------------------------------------------------
// wxDir construction/destruction
// ----------------------------------------------------------------------------
wxDir::wxDir(const wxString& dirname)
{
m_data = NULL;
(void)Open(dirname);
}
bool wxDir::Open(const wxString& dirname)
{
delete M_DIR;
m_data = NULL;
if ( !wxDir::Exists(dirname) )
{
wxLogError(_("Directory '%s' doesn't exist!"), dirname.c_str());
return false;
}
m_data = new wxDirData(dirname);
return true;
}
bool wxDir::IsOpened() const
{
return m_data != NULL;
}
wxString wxDir::GetName() const
{
wxString name;
if ( m_data )
{
name = M_DIR->GetName();
if ( !name.empty() && (name.Last() == wxFILE_SEP_PATH) )
{
// chop off the last (back)slash
name.Truncate(name.length() - 1);
}
}
return name;
}
wxDir::~wxDir()
{
delete M_DIR;
}
// ----------------------------------------------------------------------------
// wxDir enumerating
// ----------------------------------------------------------------------------
bool wxDir::GetFirst(wxString *filename,
const wxString& filespec,
int flags) const
{
wxCHECK_MSG( IsOpened(), false, _T("must wxDir::Open() first") );
M_DIR->Rewind();
M_DIR->SetFileSpec(filespec);
M_DIR->SetFlags(flags);
return GetNext(filename);
}
bool wxDir::GetNext(wxString *filename) const
{
wxCHECK_MSG( IsOpened(), false, _T("must wxDir::Open() first") );
wxCHECK_MSG( filename, false, _T("bad pointer in wxDir::GetNext()") );
return M_DIR->Read(filename);
}
#endif // !__UNIX__
|
vanrez-nez/glory-box-game | src/game/enemy/enemy-rays.js | <filename>src/game/enemy/enemy-rays.js
import { EVENTS } from '@/game/const';
import JobScheduler from '@/game/job-scheduler';
import GameEnemyRaySfx from '@/game/sfx/enemy-ray-sfx';
const DEFAULT = {
parent: null,
maxRays: 3,
};
export default class GameEnemyRays {
constructor(opts) {
this.opts = { ...DEFAULT, ...opts };
this.lastRayTime = 0;
this.rays = [];
this.bodies = [];
this.clock = new THREE.Clock();
this.events = new EventEmitter3();
this.scheduler = new JobScheduler();
this.initRays();
this.attachEvents();
}
attachEvents() {
const { rays } = this;
rays.forEach(r => r.body.events.on(EVENTS.CollisionBegan,
this.onEnemyRayCollision.bind(this, r)));
}
initRays() {
const { bodies, rays, opts } = this;
for (let i = 0; i < opts.maxRays; i++) {
const sfx = new GameEnemyRaySfx({});
sfx.mesh.scale.y = 100;
rays.push(sfx);
bodies.push(sfx.body);
opts.parent.add(sfx.mesh);
}
}
onEnemyRayCollision(ray) {
ray.body.enabled = false;
this.events.emit(EVENTS.EnemyRayHit);
}
updateRays(delta, camera, playerPosition) {
const { rays } = this;
for (let i = 0; i < rays.length; i++) {
const ray = rays[i];
if (ray.running) {
ray.mesh.lookAt(camera.position);
}
ray.update(delta, playerPosition.y);
}
}
fireRays(playerPosition) {
const { clock, rays, scheduler } = this;
const dt = clock.getElapsedTime() - this.lastRayTime;
if (dt > 5) {
const count = THREE.Math.randInt(1, rays.length);
const offsets = [0, -15, 15];
for (let i = 0; i < count; i++) {
const r = rays[i];
if (r.running === false && !scheduler.jobExists(i)) {
this.lastRayTime = clock.getElapsedTime();
const posX = playerPosition.x + offsets[i];
scheduler.addJob(i, () => {
r.fire(posX);
}, i * 0.4);
}
}
}
}
restart() {
this.lastRayTime = 0;
this.clock.start();
this.scheduler.empty();
this.rays.forEach(r => r.hide());
}
update(delta, camera, playerPosition) {
this.updateRays(delta, camera, playerPosition);
this.fireRays(playerPosition);
this.scheduler.update(delta);
}
}
|
AlexChartrand440/advanced-java | 04.040 Creating Tables/src/main/java/application/App.java | <reponame>AlexChartrand440/advanced-java
package application;
import java.sql.DriverManager;
import java.sql.SQLException;
public class App {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Class.forName("org.sqlite.JDBC");
String dbUrl = "jdbc:sqlite:people.db";
var conn = DriverManager.getConnection(dbUrl);
var stmt = conn.createStatement();
var sql = "create table if not exists user (id integer primary key, name text not null)";
stmt.execute(sql);
sql = "drop table user";
stmt.execute(sql);
stmt.close();
conn.close();
}
}
|
BeYkeRYkt/CyanWool | src/main/java/net/CyanWool/block/entity/CyanTileEntity.java | <reponame>BeYkeRYkt/CyanWool
package net.CyanWool.block.entity;
import net.CyanWool.api.block.Block;
import net.CyanWool.api.block.BlockState;
import net.CyanWool.api.block.entity.TileEntity;
import org.spacehq.opennbt.tag.builtin.CompoundTag;
public abstract class CyanTileEntity implements TileEntity {
private Block block;
public CyanTileEntity(Block block) {
this.block = block;
}
@Override
public Block getBlock() {
return block;
}
@Override
public CompoundTag getCompoundTag() {
return block;
}
@Override
public BlockState getBlockState() {
return block.getBlockState();
}
} |
punkieL/proCon | leetcode/1-100/13-roman-to-integer/13.cc | #include "iostream"
#include "unordered_map"
#include "string"
#include "vector"
#include "climits"
using namespace std;
class Solution {
//I, V, X, L, C, D, M
//1, 5, 10, 50, 100, 500, 1000
/*const vector<int> nums = {
1,5,10,50,100,500,1000
};
const vector<char> alphabet = {
'I', 'V', 'X', 'L', 'C', 'D', 'M'
};*/
const unordered_map<char, int> table = {
{'I', 1},
{'V', 5},
{'X', 10},
{'L', 50},
{'C', 100},
{'D', 500},
{'M', 1000}
};
public:
int romanToInt(string s) {
int res = 0;
int tmp = 0;
int strend = static_cast<int>(s.size()) - 1;
int next = strend < 0 ? 0 : table.find(s[0])->second;
for(int i = 0; i < strend; i++){
tmp = next;
next = table.find(s[i+1])->second;
res += next > tmp ? -tmp : tmp;
//cout << res << " " << next << endl;
}
res += table.find(s[strend])->second;
return res;
}
};
int main(int argc, char const *argv[]) {
Solution a;
a.romanToInt("DCXXI");
a.romanToInt("MCMXCVI");
return 0;
}
|
Arodev76/L2Advanced | src/main/java/l2f/gameserver/network/serverpackets/ExMoveToLocationAirShip.java | <reponame>Arodev76/L2Advanced
package l2f.gameserver.network.serverpackets;
import l2f.gameserver.model.entity.boat.Boat;
import l2f.gameserver.utils.Location;
public class ExMoveToLocationAirShip extends L2GameServerPacket
{
private int _objectId;
private Location _origin, _destination;
public ExMoveToLocationAirShip(Boat boat)
{
_objectId = boat.getObjectId();
_origin = boat.getLoc();
_destination = boat.getDestination();
}
@Override
protected final void writeImpl()
{
writeEx(0x65);
writeD(_objectId);
writeD(_destination.x);
writeD(_destination.y);
writeD(_destination.z);
writeD(_origin.x);
writeD(_origin.y);
writeD(_origin.z);
}
} |
swthomas55/QuickTheories | src/main/java/org/quicktheories/quicktheories/generators/ArbitraryDSL.java | package org.quicktheories.quicktheories.generators;
import java.util.List;
import org.quicktheories.quicktheories.core.Source;
/**
* Class for creating Sources of constant values, enum values, sequences and
* specified items of the same type
*/
public class ArbitraryDSL {
/**
* Generates the same constant value
*
* @param <T>
* type of value to generate
* @param constant
* the constant value to generate
* @return a Source of type T of the constant value
*/
public <T> Source<T> constant(T constant) {
return Arbitrary.constant(constant);
}
/**
* Generates enum values of type T by randomly picking one from the defined
* constants. When shrinking, enum constants defined first will be considered
* "smaller".
*
* @param <T>
* type of value to generate
* @param e
* the enum class to produce constants from
* @return a Source of type T of randomly selected enum values
*/
public <T extends Enum<T>> Source<T> enumValues(Class<T> e) {
return pick(e.getEnumConstants());
}
/**
* Generates a value by randomly picking one from the supplied. When
* shrinking, values supplied earlier will be considered "smaller".
*
* @param <T>
* type of value to generate
* @param ts
* the values of T to pick from
* @return a Source of type T of values selected randomly from ts
*/
@SuppressWarnings("unchecked")
public <T> Source<T> pick(T... ts) {
return pick(java.util.Arrays.asList(ts));
}
/**
* Generates a value by randomly picking one from the supplied. When
* shrinking, values earlier in the list will be considered "smaller".
*
* @param <T>
* type of value to generate
* @param ts
* the values of T to pick from
* @return a Source of type T of values selected randomly from ts
*/
public <T> Source<T> pick(List<T> ts) {
return Arbitrary.pick(ts);
}
/**
* Generates a value in order deterministically from the supplied values.
*
* If more examples are requested than are supplied then the sequence will be
* repeated.
*
* @param <T>
* type of value to generate
* @param ts
* values to create sequence from
* @return a Source of type T of values selected from ts
*/
@SuppressWarnings("unchecked")
public <T> Source<T> sequence(T... ts) {
return sequence(java.util.Arrays.asList(ts));
}
/**
* Generates a value in order deterministically from the supplied list.
*
* If more examples are requested than are present in the list then the
* sequence will be repeated.
*
* @param <T>
* type of value to generate
* @param ts
* values to create sequence from
* @return a Source of type T of values selected from ts
*/
public <T> Source<T> sequence(List<T> ts) {
return Arbitrary.sequence(ts);
}
/**
* Generates a value in order deterministically from the supplied values,
* starting from the last supplied value.
*
* If more examples are requested than are supplied then the last value will
* be repeated.
*
* @param <T> type to generate
*
* @param ts
* values to create sequence from
* @return a Source of type T of of values selected from ts
*/
@SuppressWarnings("unchecked")
public <T> Source<T> reverse(T... ts) {
return Arbitrary.reverse(ts);
}
}
|
Arquisoft/Voting_2b | VotingSystem_2b/src/main/java/es/uniovi/asw/electionday/parser/RCandidatureExcel.java | <filename>VotingSystem_2b/src/main/java/es/uniovi/asw/electionday/parser/RCandidatureExcel.java
package es.uniovi.asw.electionday.parser;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import es.uniovi.asw.model.Candidature;
public class RCandidatureExcel extends RCandidature implements ReadCandidature{
public List<Candidature> readFile(String path) {
XSSFWorkbook wb;
XSSFSheet sheet;
Iterator<Row> rows;
Row row = null;
Candidature candidatura;
List<Candidature> candidaturas = new ArrayList<Candidature>();
try {
wb = new XSSFWorkbook(new File(path));
System.out.println("Leyendo fichero " + path);
sheet = wb.getSheetAt(0);
rows = sheet.iterator();
//First line (headers in excel file)
rows.next();
while (rows.hasNext()) {
row = rows.next();
candidatura = new Candidature();
candidatura.setName(row.getCell(0)!=null ? row.getCell(0).toString():null);
candidatura.setInitial(row.getCell(1)!=null ? row.getCell(1).toString():null);
candidatura.setDescription(row.getCell(2)!=null ? row.getCell(2).toString():null);
//Row empty, without cells
if (!candidatura.isEmpty())
candidaturas.add(candidatura);
}
} catch (InvalidFormatException e) {
System.out.println("El fichero no es un .xlsx");
} catch (Exception e) {
String[] fileName = path.split("/");
System.out.println("El fichero " + fileName[fileName.length - 1] + " no existe");
}
return candidaturas;
}
}
|
reTHINK-project/dev-slack-interworking | server/ephemeral-auth/api/controllers/CredentialController.js | /**
* CredentialController
*
* @description :: Server-side logic for managing credentials
* @help :: See http://sailsjs.org/#!/documentation/concepts/Controllers
*/
var fetch = require('node-fetch');
var crypto = require('crypto');
var secret = sails.config.ephemeral.secret_key;
var uri = sails.config.ephemeral.ims_uri;
var getCredential = function(uname, domain) {
var hmac = crypto.createHmac('sha1', secret);
var ttl = 86400;
var timestamp = Math.floor(Date.now() / 1000) + ttl;
var username = new Buffer(timestamp + ':' + uname);
var uris = [ uri ];
hmac.update(username);
return {
username: username.toString('utf-8') + '@' + domain,
password: <PASSWORD>().toString('base64'),
ttl: ttl,
uris: uris
};
}
module.exports = {
find: function(req, res) {
var credential;
if(!req.get('authorization')) {
res.status(401);
res.send();
} else {
var token = req.get('authorization').split(' ')[1]
fetch('https://www.googleapis.com/oauth2/v3/tokeninfo?access_token=' + token, { method: 'GET' })
.then(response => {
if (response.status >= 200 && response.status < 300) {
fetch('https://www.googleapis.com/oauth2/v1/userinfo?access_token=' + token)
.then(res_user => res_user.json())
.then(body => {
var email_parts = body.email.split('@')
var username = email_parts[0]
var domain = email_parts[1]
res.send(getCredential(username, domain))
}).catch(err => {
console.log(err)
res.status(500)
res.send(err)
})
} else {
res.status(response.status)
response.text().then(text => res.send(text))
}
});
}
}
};
|
zhangkn/iOS14Header | System/Library/PrivateFrameworks/BookLibrary.framework/BookLibrary.h | <filename>System/Library/PrivateFrameworks/BookLibrary.framework/BookLibrary.h<gh_stars>1-10
#import <BookLibrary/BLSSDownloadManifestRequestAdapter.h>
#import <BookLibrary/BLStoreItemMetadataRequest.h>
#import <BookLibrary/BLSecureOfflineKeyDeliveryRequest.h>
#import <BookLibrary/BLStreamingKeyRequest.h>
#import <BookLibrary/BLDAAPItemsRequest.h>
#import <BookLibrary/BLRestoreRequestItem.h>
#import <BookLibrary/BLOfflineKeyRequest.h>
#import <BookLibrary/BLHLSKeyFetcher.h>
#import <BookLibrary/BLDAAPHideItemsRequest.h>
#import <BookLibrary/BLLibrary.h>
#import <BookLibrary/BLDownloadMetadata.h>
#import <BookLibrary/BLRestoreResponseItem.h>
#import <BookLibrary/BLItemContentRating.h>
#import <BookLibrary/BLEduCloudContainer.h>
#import <BookLibrary/BLMediaItemUtils.h>
#import <BookLibrary/BLHLSPlaylist.h>
#import <BookLibrary/BLHLSMedia.h>
#import <BookLibrary/BLHLSGroup.h>
#import <BookLibrary/BLHLSStreamInf.h>
#import <BookLibrary/BLHLSMap.h>
#import <BookLibrary/BLHLSSegment.h>
#import <BookLibrary/BLHLSPlaylistState.h>
#import <BookLibrary/BLHLSKey.h>
#import <BookLibrary/BLDownloadManifestRequest.h>
#import <BookLibrary/BLDAAPLoginRequest.h>
#import <BookLibrary/IMLibraryPlist.h>
#import <BookLibrary/BLBundleClass.h>
#import <BookLibrary/BLUtilities.h>
#import <BookLibrary/BLServiceProxy.h>
#import <BookLibrary/BLPurchaseDAAPParser.h>
#import <BookLibrary/BLHLSAudiobookFetcher.h>
#import <BookLibrary/BLJaliscoServerDatabase.h>
#import <BookLibrary/BLItemArtworkImage.h>
#import <BookLibrary/BLDownload.h>
#import <BookLibrary/BLDAAPArtRequest.h>
#import <BookLibrary/BLPurchaseResponseItem.h>
#import <BookLibrary/BLPurchaseResponse.h>
#import <BookLibrary/IMLockFile.h>
#import <BookLibrary/BLLibraryUtility.h>
#import <BookLibrary/BLPurchaseRequest.h>
#import <BookLibrary/BLItemImageCollection.h>
#import <BookLibrary/BLJaliscoServerSource.h>
#import <BookLibrary/BLDownloadStatus.h>
#import <BookLibrary/BLPurchaseDAAPItem.h>
#import <BookLibrary/BLJaliscoServerInfo.h>
#import <BookLibrary/BLURLRequestEncoder.h>
#import <BookLibrary/BLDAAPServerInfoRequest.h>
#import <BookLibrary/BLDAAPBuffer.h>
#import <BookLibrary/BLJaliscoDAAPClient.h>
#import <BookLibrary/BLDAAPURLRequest.h>
#import <BookLibrary/BLServiceInterface.h>
#import <BookLibrary/BLMetrics.h>
#import <BookLibrary/BLBookItem.h>
#import <BookLibrary/BLPurchaseDAAPServer.h>
#import <BookLibrary/BKPurchaseDAAPBackoff.h>
#import <BookLibrary/BLM3U8Parser.h>
#import <BookLibrary/BLJaliscoVersion.h>
#import <BookLibrary/BLDAAPDatabasesRequest.h>
#import <BookLibrary/BLJaliscoItem.h>
#import <BookLibrary/BLJaliscoReadOnlyDAAPClient.h>
#import <BookLibrary/BLFamilyCircleController.h>
#import <BookLibrary/BLJaliscoServerItem.h>
#import <BookLibrary/BLDAAPUpdateRequest.h>
#import <BookLibrary/BLRequest.h>
#import <BookLibrary/BLUIHostServiceProxy.h>
#import <BookLibrary/BLDownloadQueue.h>
#import <BookLibrary/BLDownloadManifestResponse.h>
|
qtlmovie/qtlmovie | src/TestUnit/QtlVariableTest.cpp | <reponame>qtlmovie/qtlmovie
//----------------------------------------------------------------------------
//
// Copyright (c) 2013-2017, <NAME>
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// 2. 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.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 OWNER OR CONTRIBUTORS 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.
//
//----------------------------------------------------------------------------
//
// Unit test for class QtlVariable
//
//----------------------------------------------------------------------------
#include "QtlTest.h"
#include "QtlVariable.h"
class QtlVariableTest : public QObject
{
Q_OBJECT
private slots:
void testElementaryType();
void testClass();
};
#include "QtlVariableTest.moc"
QTL_TEST_CLASS(QtlVariableTest);
//----------------------------------------------------------------------------
// Test case: usage on elementary types.
void QtlVariableTest::testElementaryType()
{
typedef QtlVariable<int> IntVariable;
IntVariable v1;
QVERIFY(!v1.set());
QTLVERIFY_THROW(v1.value(), QtlUninitializedException);
IntVariable v2(v1);
QVERIFY(!v2.set());
QTLVERIFY_THROW(v2.value(), QtlUninitializedException);
v2 = 1;
QVERIFY(v2.set());
QCOMPARE(v2.value(), 1);
IntVariable v3(v2);
QVERIFY(v3.set());
QCOMPARE(v3.value(), 1);
IntVariable v4(2);
QVERIFY(v4.set());
QCOMPARE(v4.value(), 2);
v4 = v1;
QVERIFY(!v4.set());
v4 = v2;
QVERIFY(v4.set());
QCOMPARE(v4.value(), 1);
v4.reset();
QVERIFY(!v4.set());
v4.reset();
QVERIFY(!v4.set());
v1 = 1;
v2.reset();
QVERIFY(v1.set());
QVERIFY(!v2.set());
QCOMPARE(v1.value(), 1);
QCOMPARE(v1.value(2), 1);
QCOMPARE(v2.value(2), 2);
v1 = 1;
v2 = 1;
v3 = 3;
v4.reset();
IntVariable v5;
QVERIFY(v1.set());
QVERIFY(v2.set());
QVERIFY(v3.set());
QVERIFY(!v4.set());
QVERIFY(!v5.set());
QVERIFY(v1 == v2);
QVERIFY(v1 != v3);
QVERIFY(v1 != v4);
QVERIFY(v4 != v5);
QVERIFY(v1 == 1);
QVERIFY(v1 != 2);
QVERIFY(v4 != 1);
}
// A class which identifies each instance by an explicit value.
// Also count the number of instances in the class.
namespace {
class TestData
{
private:
TestData(); // inaccessible
int _value;
static int _instanceCount;
public:
// Constructors
TestData(int value) : _value(value) {_instanceCount++;}
TestData(const TestData& other) : _value(other._value) {_instanceCount++;}
TestData& operator=(const TestData& other) {_value = other._value; return *this;}
bool operator==(const TestData& other) {return _value == other._value;}
// Destructor
~TestData() {_instanceCount--;}
// Get the object's value
int v() const {return _value;}
// Get the number of instances
static int instanceCount() {return _instanceCount;}
};
int TestData::_instanceCount = 0;
}
// Test case: usage on class types.
void QtlVariableTest::testClass()
{
typedef QtlVariable<TestData> TestVariable;
QVERIFY(TestData::instanceCount() == 0);
{
TestVariable v1;
QVERIFY(!v1.set());
QTLVERIFY_THROW(v1.value().v(), QtlUninitializedException);
QCOMPARE(TestData::instanceCount(), 0);
TestVariable v2(v1);
QVERIFY(!v2.set());
QCOMPARE(TestData::instanceCount(), 0);
v2 = TestData(1);
QVERIFY(v2.set());
QCOMPARE(v2.value().v(), 1);
QCOMPARE(TestData::instanceCount(), 1);
TestVariable v3(v2);
QVERIFY(v3.set());
QCOMPARE(TestData::instanceCount(), 2);
TestVariable v4(TestData(2));
QVERIFY(v4.set());
QCOMPARE(TestData::instanceCount(), 3);
v4 = v1;
QVERIFY(!v4.set());
QCOMPARE(TestData::instanceCount(), 2);
v4 = v2;
QVERIFY(v4.set());
QCOMPARE(TestData::instanceCount(), 3);
v4.reset();
QVERIFY(!v4.set());
QCOMPARE(TestData::instanceCount(), 2);
v4.reset();
QVERIFY(!v4.set());
QCOMPARE(TestData::instanceCount(), 2);
v1 = TestData(1);
QCOMPARE(TestData::instanceCount(), 3);
v2.reset();
QCOMPARE(TestData::instanceCount(), 2);
QVERIFY(v1.set());
QVERIFY(!v2.set());
QCOMPARE(v1.value().v(), 1);
QCOMPARE(v1.value(TestData(2)).v(), 1);
QCOMPARE(v2.value(TestData(2)).v(), 2);
QCOMPARE(TestData::instanceCount(), 2);
v1 = TestData(1);
QCOMPARE(TestData::instanceCount(), 2);
v2 = TestData(1);
QCOMPARE(TestData::instanceCount(), 3);
v3 = TestData(3);
QCOMPARE(TestData::instanceCount(), 3);
v4.reset();
QCOMPARE(TestData::instanceCount(), 3);
TestVariable v5;
QCOMPARE(TestData::instanceCount(), 3);
QVERIFY(v1.set());
QVERIFY(v2.set());
QVERIFY(v3.set());
QVERIFY(!v4.set());
QVERIFY(!v5.set());
QVERIFY(v1 == v2);
QVERIFY(v1 != v3);
QVERIFY(v1 != v4);
QVERIFY(v4 != v5);
QCOMPARE(v1.value().v(), 1);
QVERIFY(v1 == TestData(1));
QVERIFY(v1 != TestData(2));
QVERIFY(v4 != TestData(1));
QCOMPARE(TestData::instanceCount(), 3);
}
// Check that the destructor of variable properly destroys the contained object
QCOMPARE(TestData::instanceCount(), 0);
}
|
henrikfroehling/polyglot | lib/src/Delphi/Syntax/Expressions/DelphiSetConstructorSyntax.hpp | #ifndef INTERLINCK_DELPHI_SYNTAX_DELPHISETCONSTRUCTORSYNTAX_H
#define INTERLINCK_DELPHI_SYNTAX_DELPHISETCONSTRUCTORSYNTAX_H
#include "interlinck/Core/Syntax/SyntaxKinds.hpp"
#include "interlinck/Core/Syntax/SyntaxVariant.hpp"
#include "interlinck/Core/Types.hpp"
#include "Core/Basic/Macros.hpp"
#include "Delphi/Syntax/Expressions/DelphiExpressionSyntax.hpp"
namespace interlinck::Core::Syntax
{
class ISyntaxToken;
} // end namespace interlinck::Core::Syntax
namespace interlinck::Delphi::Syntax
{
class DelphiSetConstructorSyntax : public DelphiExpressionSyntax
{
public:
explicit DelphiSetConstructorSyntax(Core::Syntax::SyntaxKind syntaxKind,
const Core::Syntax::ISyntaxToken* openBracketToken,
const Core::Syntax::ISyntaxToken* closeBracketToken) noexcept;
~DelphiSetConstructorSyntax() noexcept override = default;
inline const Core::Syntax::ISyntaxToken* openBracketToken() const noexcept { return _openBracketToken; }
inline const Core::Syntax::ISyntaxToken* closeBracketToken() const noexcept { return _closeBracketToken; }
inline Core::Syntax::SyntaxVariant first() const noexcept final { return Core::Syntax::SyntaxVariant::asToken(_openBracketToken); }
inline Core::Syntax::SyntaxVariant last() const noexcept final { return Core::Syntax::SyntaxVariant::asToken(_closeBracketToken); }
inline il_string typeName() const noexcept override { CREATE_TYPENAME(DelphiSetConstructorSyntax) }
protected:
const Core::Syntax::ISyntaxToken* _openBracketToken;
const Core::Syntax::ISyntaxToken* _closeBracketToken;
};
} // end namespace interlinck::Delphi::Syntax
#endif // INTERLINCK_DELPHI_SYNTAX_DELPHISETCONSTRUCTORSYNTAX_H
|
aohanhongzhi/SpringCloud-multiple-gradle | common/src/main/java/hxy/dream/common/filter/TokenFilter.java | <filename>common/src/main/java/hxy/dream/common/filter/TokenFilter.java
package hxy.dream.common.filter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import java.io.IOException;
/**
* @author iris
*/
@Order(1)
@WebFilter(filterName = "TokenFilter", urlPatterns = "/*", initParams = {
@WebInitParam(name = "URL", value = "http://localhost:8080")}, asyncSupported = true)
public class TokenFilter implements Filter {
Logger logger = LoggerFactory.getLogger(TokenFilter.class);
@Override
public void init(FilterConfig filterConfig) throws ServletException {
logger.info("\n====>TokenFilterๅๅงๅ้
็ฝฎไฟกๆฏ[{}]", filterConfig);
}
/**
* ่ฟ้ๅฐฑๆฏ่ทๅtoken๏ผๆๅ็จๆทไฟกๆฏๅฐSpringSecurityๅฎๅ
จไธไธๆไธญ
*
* @param request
* @param response
* @param chain
* @throws IOException
* @throws ServletException
*/
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
// logger.info("\n====>TokenFilter่ฟๆปคๅจไฝฟ็จ[{}]", chain);
chain.doFilter(request, response);
}
@Override
public void destroy() {
logger.info("\n====>TokenFilter้ๆฏ");
}
}
|
cys3c/viper-shell | application/scripts/vulnserver/vs-badchar-eip3.py | #!/usr/bin/python
import time, struct, sys
import socket as so
try:
server = sys.argv[1]
port = 5555
except IndexError:
print "[+] Usage %s host" % sys.argv[0]
sys.exit()
badchars = (
"\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10"
"\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f\x20"
"\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2a\x2b\x2c\x2d\x2e\x2f\x30"
"\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3a\x3b\x3c\x3d\x3e\x3f\x40"
"\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4a\x4b\x4c\x4d\x4e\x4f\x50"
"\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5a\x5b\x5c\x5d\x5e\x5f\x60"
"\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6a\x6b\x6c\x6d\x6e\x6f\x70"
"\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7a\x7b\x7c\x7d\x7e\x7f\x80"
"\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90"
"\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0"
"\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0"
"\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0"
"\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0"
"\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0"
"\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0"
"\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff" )
req1 = "AUTH " + "\x41"*1040 + "\x42\x42\x42\x42" + badchars + "C" * (1072 - 1040 - 4 - len(badchars) )
s = so.socket(so.AF_INET, so.SOCK_STREAM)
try:
s.connect((server, port))
print repr(s.recv(1024))
s.send(req1)
print repr(s.recv(1024))
except:
print "[!] connection refused, check debugger"
s.close()
|
instagram4j/instagram4j-realtime | src/main/java/com/github/instagram4j/realtime/utils/ZipUtil.java | package com.github.instagram4j.realtime.utils;
import java.io.ByteArrayOutputStream;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;
public class ZipUtil {
public static byte[] zip(byte[] in) {
ByteArrayOutputStream baos = new ByteArrayOutputStream(in.length);
Deflater compressor = new Deflater(9);
compressor.setInput(in);
compressor.finish();
byte[] buffer = new byte[1024];
while (!compressor.finished()) {
int len = compressor.deflate(buffer);
baos.write(buffer, 0, len);
}
return baos.toByteArray();
}
public static byte[] unzip(byte[] in) throws DataFormatException {
ByteArrayOutputStream baos = new ByteArrayOutputStream(in.length);
Inflater decompressor = new Inflater();
decompressor.setInput(in);
byte[] buffer = new byte[1024];
while (!decompressor.finished()) {
final int len = decompressor.inflate(buffer);
baos.write(buffer, 0, len);
}
return baos.toByteArray();
}
}
|
KEVINYZY/plume | tests/test_perceptron.py | from plume.perceptron import PerceptronClassifier
import numpy as np
x_train = np.array([[3, 3], [4, 3], [1, 1]])
y_train = np.array([1, 1, -1])
clf = PerceptronClassifier(dual=False)
clf.fit(x_train, y_train)
print(clf.get_model())
print(clf.predict(x_train))
clf1 = PerceptronClassifier()
clf1.fit(x_train, y_train)
print(clf1.get_model())
print(clf1.predict(x_train))
|
bigmadkev/poinz | client/test/unit/clientActionReducerTest.js | <filename>client/test/unit/clientActionReducerTest.js<gh_stars>0
import {v4 as uuid} from 'uuid';
import {
CANCEL_EDIT_STORY,
COMMAND_SENT,
EDIT_STORY,
EVENT_RECEIVED,
HIDE_NEW_USER_HINTS,
LOCATION_CHANGED,
SET_LANGUAGE,
STATUS_FETCHED,
TOGGLE_BACKLOG,
TOGGLE_LOG,
TOGGLE_USER_MENU,
SHOW_TRASH,
HIDE_TRASH
} from '../../app/actions/types';
import initialState from '../../app/store/initialState';
import clientActionReducer from '../../app/services/clientActionReducer';
import {
cancelEditStory,
editStory,
hideNewUserHints,
hideTrash,
setLanguage,
showTrash,
toggleBacklog,
toggleLog,
toggleUserMenu
} from '../../app/actions';
test(COMMAND_SENT, () => {
const startingState = initialState();
const cmdId1 = uuid();
const cmdId2 = uuid();
let modifiedState = clientActionReducer(startingState, {
type: COMMAND_SENT,
command: {
id: cmdId1,
name: 'superCommand',
payload: {
some: 'more data'
}
}
});
modifiedState = clientActionReducer(modifiedState, {
type: COMMAND_SENT,
command: {
id: cmdId2,
name: 'secondSuperCommand'
}
});
expect(modifiedState.pendingCommands).toEqual({
[cmdId1]: {
id: cmdId1,
name: 'superCommand',
payload: {
some: 'more data'
}
},
[cmdId2]: {
id: cmdId2,
name: 'secondSuperCommand'
}
});
});
test(EVENT_RECEIVED, () => {
const cmdId1 = uuid();
const cmdId2 = uuid();
const startingState = {
...initialState(),
pendingCommands: {
[cmdId1]: {
id: cmdId1,
name: 'superCommand',
payload: {
some: 'more data'
}
},
[cmdId2]: {
id: cmdId2,
name: 'secondSuperCommand'
}
}
};
let modifiedState = clientActionReducer(startingState, {
type: EVENT_RECEIVED,
correlationId: 'does-not-match',
eventName: 'usernameSet'
});
expect(Object.values(modifiedState.pendingCommands).length).toBe(2); // still both commands
modifiedState = clientActionReducer(modifiedState, {
type: EVENT_RECEIVED,
correlationId: cmdId1,
eventName: 'usernameSet'
});
expect(modifiedState.pendingCommands[cmdId1]).toBeUndefined();
expect(modifiedState.pendingCommands[cmdId2]).toBeDefined();
modifiedState = clientActionReducer(modifiedState, {
type: EVENT_RECEIVED,
correlationId: cmdId2,
eventName: 'usernameSet'
});
expect(modifiedState.pendingCommands[cmdId2]).toBeUndefined();
});
test(TOGGLE_BACKLOG, () => {
const startingState = initialState();
let modifiedState = clientActionReducer(startingState, toggleBacklog());
expect(modifiedState.backlogShown).toBe(true);
modifiedState = clientActionReducer(modifiedState, toggleBacklog());
expect(modifiedState.backlogShown).toBe(false);
});
test(TOGGLE_USER_MENU + ' and ' + TOGGLE_LOG, () => {
const startingState = initialState();
let modifiedState = clientActionReducer(startingState, toggleUserMenu());
expect(modifiedState.userMenuShown).toBe(true);
expect(modifiedState.logShown).toBe(false);
modifiedState = clientActionReducer(modifiedState, toggleLog());
expect(modifiedState.userMenuShown).toBe(false);
expect(modifiedState.logShown).toBe(true);
modifiedState = clientActionReducer(modifiedState, toggleUserMenu());
expect(modifiedState.userMenuShown).toBe(true);
expect(modifiedState.logShown).toBe(false);
modifiedState = clientActionReducer(modifiedState, toggleUserMenu());
expect(modifiedState.userMenuShown).toBe(false);
expect(modifiedState.logShown).toBe(false);
modifiedState = clientActionReducer(modifiedState, toggleLog());
modifiedState = clientActionReducer(modifiedState, toggleLog());
expect(modifiedState.userMenuShown).toBe(false);
expect(modifiedState.logShown).toBe(false);
});
test(EDIT_STORY + ' and ' + CANCEL_EDIT_STORY, () => {
const storyId1 = uuid();
const storyId2 = uuid();
const startingState = {
...initialState(),
stories: {
[storyId1]: {},
[storyId2]: {}
}
};
let modifiedState = clientActionReducer(startingState, editStory(storyId1));
expect(modifiedState.stories[storyId1].editMode).toBe(true);
// multiple stories can be in edit mode simultaneously
modifiedState = clientActionReducer(modifiedState, editStory(storyId2));
expect(modifiedState.stories[storyId1].editMode).toBe(true);
expect(modifiedState.stories[storyId2].editMode).toBe(true);
// cancel edit mode for story 1
modifiedState = clientActionReducer(modifiedState, cancelEditStory(storyId1));
expect(modifiedState.stories[storyId1].editMode).toBe(false);
expect(modifiedState.stories[storyId2].editMode).toBe(true);
});
test(SET_LANGUAGE, () => {
const startingState = initialState();
let modifiedState = clientActionReducer(startingState, setLanguage('someLangCode'));
expect(modifiedState.language).toEqual('someLangCode');
});
test(HIDE_NEW_USER_HINTS, () => {
const startingState = initialState();
let modifiedState = clientActionReducer(startingState, hideNewUserHints());
expect(modifiedState.hideNewUserHints).toBe(true);
});
test(STATUS_FETCHED, () => {
const startingState = initialState();
let modifiedState = clientActionReducer(startingState, {
type: STATUS_FETCHED,
status: {some: 'data'}
});
expect(modifiedState.appStatus).toEqual({
some: 'data'
});
});
test(LOCATION_CHANGED, () => {
const startingState = initialState();
let modifiedState = clientActionReducer(startingState, {
type: LOCATION_CHANGED,
pathname: 'somePathName'
});
expect(modifiedState.pathname).toEqual('somePathName');
});
test(SHOW_TRASH + ' and ' + HIDE_TRASH, () => {
const startingState = initialState();
let modifiedState = clientActionReducer(startingState, showTrash());
expect(modifiedState.trashShown).toBe(true);
modifiedState = clientActionReducer(modifiedState, hideTrash());
expect(modifiedState.trashShown).toBe(false);
});
|
harper-carroll/kibana | src/ui/public/utils/diff_time_picker_vals.js | <reponame>harper-carroll/kibana
import _ from 'lodash';
import angular from 'angular';
export default function DiffTimePickerValuesFn() {
var valueOf = function (o) {
if (o) return o.valueOf();
};
return function (rangeA, rangeB) {
if (_.isObject(rangeA) && _.isObject(rangeB)) {
if (
valueOf(rangeA.to) !== valueOf(rangeB.to)
|| valueOf(rangeA.from) !== valueOf(rangeB.from)
|| valueOf(rangeA.value) !== valueOf(rangeB.value)
|| valueOf(rangeA.pause) !== valueOf(rangeB.pause)
) {
return true;
}
} else {
return !angular.equals(rangeA, rangeB);
}
return false;
};
};
|
nixsolutions/icalendar-bot | app/commands/unknown.rb | # frozen_string_literal: true
module Commands
class Unknown < Base
private
def handle_call(message, _user)
send_message(
chat_id: message.chat.id,
text: message_text
)
end
def handle_callback(callback, _user, _args)
answer_callback_query(
callback_query_id: callback.id,
text: callback_text
)
end
def callback_text
I18n.t('unknown.callback_text')
end
def message_text
I18n.t('unknown.text')
end
end
end
|
davidlamyc/ui-testing-infra-copy | src/step_definitions/support/interaction/fillInput.js | export default (elementLocator, text) => {
$(currentPage[elementLocator]).waitForDisplayed();
$(currentPage[elementLocator]).setValue(text);
} |
bsulkowski/game-theory | src/gui/SpatialPayoffChoice.java | <gh_stars>0
package gametheory.gui;
import gametheory.SymmetricDualGame;
import gametheory.spatial.AveragePayoff;
import gametheory.spatial.SpatialPayoff;
import gametheory.spatial.SumPayoff;
public class SpatialPayoffChoice extends ParametrizedChoice {
public SpatialPayoffChoice() {
choiceList = new String[] {
"sum",
"average"
};
choiceDefault = 0;
parameterList = new String[][] {
{"payin", "self"},
{"self"}
};
parameterDefault = new Object[][] {
{0.0, false},
{false}
};
parameterType = new int[][] {
{DOUBLE, BOOLEAN},
{BOOLEAN}
};
setDefaultValues();
}
public SpatialPayoff getSpatialPayoff(SymmetricDualGame game) {
if (choiceList[choice].equals("sum")) {
return new SumPayoff(
game,
(Double) getParameter("payin"),
(Boolean) getParameter("self")
);
}
if (choiceList[choice].equals("average")) {
return new AveragePayoff(
game,
(Boolean) getParameter("self")
);
}
return null;
}
}
|
ekmixon/mbed-tools | src/mbed_tools/targets/get_board.py | <reponame>ekmixon/mbed-tools
#
# Copyright (c) 2020-2021 Arm Limited and Contributors. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
"""Interface for accessing Mbed-Enabled Development Board data.
An instance of `mbed_tools.targets.board.Board` can be retrieved by calling one of the public functions.
"""
import logging
from enum import Enum
from typing import Callable
from mbed_tools.targets.env import env
from mbed_tools.targets.exceptions import UnknownBoard, UnsupportedMode, BoardDatabaseError
from mbed_tools.targets.board import Board
from mbed_tools.targets.boards import Boards
logger = logging.getLogger(__name__)
def get_board_by_product_code(product_code: str) -> Board:
"""Returns first `mbed_tools.targets.board.Board` matching given product code.
Args:
product_code: the product code to look up in the database.
Raises:
UnknownBoard: a board with a matching product code was not found.
"""
return get_board(lambda board: board.product_code == product_code)
def get_board_by_online_id(slug: str, target_type: str) -> Board:
"""Returns first `mbed_tools.targets.board.Board` matching given online id.
Args:
slug: The slug to look up in the database.
target_type: The target type to look up in the database, normally one of `platform` or `module`.
Raises:
UnknownBoard: a board with a matching slug and target type could not be found.
"""
matched_slug = slug.casefold()
return get_board(lambda board: board.slug.casefold() == matched_slug and board.target_type == target_type)
def get_board_by_jlink_slug(slug: str) -> Board:
"""Returns first `mbed-tools.targets.board.Board` matching given slug.
With J-Link, the slug is extracted from a board manufacturer URL, and may not match
the Mbed slug. The J-Link slug is compared against the slug, board_name and
board_type of entries in the board database until a match is found.
Args:
slug: the J-Link slug to look up in the database.
Raises:
UnknownBoard: a board matching the slug was not found.
"""
matched_slug = slug.casefold()
return get_board(
lambda board: any(matched_slug == c.casefold() for c in [board.slug, board.board_name, board.board_type])
)
def get_board(matching: Callable) -> Board:
"""Returns first `mbed_tools.targets.board.Board` for which `matching` is True.
Uses database mode configured in the environment.
Args:
matching: A function which will be called to test matching conditions for each board in database.
Raises:
UnknownBoard: a board matching the criteria could not be found in the board database.
"""
database_mode = _get_database_mode()
if database_mode == _DatabaseMode.OFFLINE:
logger.info("Using the offline database (only) to identify boards.")
return Boards.from_offline_database().get_board(matching)
if database_mode == _DatabaseMode.ONLINE:
logger.info("Using the online database (only) to identify boards.")
return Boards.from_online_database().get_board(matching)
try:
logger.info("Using the offline database to identify boards.")
return Boards.from_offline_database().get_board(matching)
except UnknownBoard:
logger.info("Unable to identify a board using the offline database, trying the online database.")
try:
return Boards.from_online_database().get_board(matching)
except BoardDatabaseError:
logger.error("Unable to access the online database to identify a board.")
raise UnknownBoard()
class _DatabaseMode(Enum):
"""Selected database mode."""
OFFLINE = 0
ONLINE = 1
AUTO = 2
def _get_database_mode() -> _DatabaseMode:
database_mode = env.MBED_DATABASE_MODE
try:
return _DatabaseMode[database_mode]
except KeyError:
raise UnsupportedMode(f"{database_mode} is not a supported database mode.")
|
yvenshane/CiLuNetwork | CiLuNetwork/CiLuNetwork/Classes/FaceRecognition/WindVaneBridge.framework/Headers/WVWebViewBasicProtocol.h | /*
* WVWebViewBasicProtocol.h
*
* Created by WindVane.
* Copyright (c) 2017ๅนด ้ฟ้ๅทดๅทด-ๆทๅฎๆๆฏ้จ. All rights reserved.
*/
#import "WVBridgeProtocol.h"
#import "WVJavaScriptExecutor.h"
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
/**
* ๅ
ๅซไบ WebView ๅบๆฌๅ่ฝ็ๅ่ฎฎใ
*/
@protocol WVWebViewBasicProtocol <WVJavaScriptExecutor>
/**
* ไธ WebView ๅ
ณ่็ UIScrollViewใ
*/
@property (nonatomic, readonly, strong, nonnull) UIScrollView * scrollView;
#pragma mark - Loading
/**
* ๅ ่ฝฝๆๅฎ็่ฏทๆฑใ
*/
- (void)loadRequest:(NSURLRequest * _Nonnull)request;
/**
* ๅ ่ฝฝๆๅฎ็ HTML ๅญ็ฌฆไธฒๅ URL๏ผๅฟ
้กปๆๅฎๅฏ็จ็ URLใ
*/
- (void)loadHTMLString:(NSString * _Nonnull)string baseURL:(NSURL * _Nullable)baseURL;
/**
* ๅ ่ฝฝๆๅฎ็่ฏทๆฑ๏ผๅนถ้ๆฉๆฏๅฆๆทปๅ ้ป่ฎคๅๆฐ๏ผ็ฑ [WVUserConfig setDefaultParamForFirstLoad:] ่ฎพ็ฝฎ๏ผใ
*/
- (void)loadRequest:(NSURLRequest * _Nonnull)request withDefaultParam:(BOOL)useDefaultParam;
/**
* ๅ ่ฝฝๆๅฎ็ URLใ
*/
- (void)loadURL:(NSString * _Nonnull)url;
/**
* ๅ ่ฝฝๆๅฎ็ URL๏ผๅนถ้ๆฉๆฏๅฆๆทปๅ ้ป่ฎคๅๆฐ๏ผ็ฑ [WVUserConfig setDefaultParamForFirstLoad:] ่ฎพ็ฝฎ๏ผใ
*/
- (void)loadURL:(NSString * _Nonnull)url withDefaultParam:(BOOL)useDefaultParam;
/**
* ๅๆญขๅ ่ฝฝใ
*/
- (void)stopLoading;
/**
* ้ๆฐๅ ่ฝฝใ
*/
- (void)reload;
/**
* WebView ๅฝๅๅ ่ฝฝ็ URL๏ผๆฏไธป้กต้ข็ URL๏ผ่้ iframeใ
*/
@property (nonatomic, copy, readonly, nullable) NSURL * URL;
/**
* WebView ๆฏๅฆๆญฃๅจๅ ่ฝฝๅ
ๅฎนใ
*/
@property (nonatomic, assign, readonly, getter=isLoading) BOOL loading;
#pragma mark - Navigating
/**
* ๅ้ๅๅฒ่ฎฐๅฝใ
*/
- (void)goBack;
/**
* ๅ่ฟๅๅฒ่ฎฐๅฝใ
*/
- (void)goForward;
/**
* ๆฏๅฆๅฏไปฅๅ้ๅๅฒ่ฎฐๅฝใ
*/
@property (nonatomic, readonly, getter=canGoBack) BOOL canGoBack;
/**
* ๆฏๅฆๅฏไปฅๅ่ฟๅๅฒ่ฎฐๅฝใ
*/
@property (nonatomic, readonly, getter=canGoForward) BOOL canGoForward;
/**
* ๅๅฝๅ WebView ๅ้ไบไปถ๏ผๅนถ่ฟๅไบไปถๆฏๅฆ่ขซ JS ๅๆถ้ป่ฎค่กไธบใ
* ๅ
่ฎธๅจไปปๆ็บฟ็จ่ฐ็จ๏ผๅนถๆปๆฏๅจไธป็บฟ็จๅ่ฐใ
*/
- (void)dispatchEvent:(NSString * _Nonnull)eventName withParam:(NSDictionary * _Nullable)param withCallback:(WVEventCallback _Nullable)callback;
// ใไธๅปบ่ฎฎไฝฟ็จใๆง่ก JavaScript ๅญ็ฌฆไธฒ๏ผๅๆญฅๆง่กใ
- (NSString * _Nullable)stringByEvaluatingJavaScriptFromString:(NSString * _Nonnull)script DEPRECATED_MSG_ATTRIBUTE("่ฏทไฝฟ็จ evaluateJavaScript:completionHandler: ๆนๆณ");
#pragma mark - Identifier
/**
* ่ทๅ WebView ๅฝๅ้กต้ข็ๅฏไธๆ ่ฏใ
*/
- (NSString * _Nonnull)pageIdentifier;
/**
* ่ฎพ็ฝฎ WebView ๅฝๅ้กต้ข็ๅฏไธๆ ่ฏใ
*/
- (void)setPageIdentifier:(NSString * _Nonnull)pageIdentifier;
@end
|
black-vision-engine/bv-engine | BlackVision/LibBlackVision/Source/Engine/Models/Plugins/HelperUVGenerator.h | <reponame>black-vision-engine/bv-engine
#pragma once
#include "Mathematics/glm_inc.h"
#include "Engine/Models/Plugins/Channels/Geometry/Simple/DefaultGeometryVertexAttributeChannel.h"
namespace bv{
namespace model{
namespace Helper
{
class UVGenerator
{
private:
static void ScaleVec2 ( float* min, float* max, std::vector<glm::vec2>& uvs );
static void ScaleVec3 ( float* min, float* max, std::vector<glm::vec3>& uvws );
public:
//static void generateU( Float3AttributeChannelPtr verts, Float1AttributeChannelPtr uvs );
static void GenerateUV ( Float3AttributeChannelPtr verts, Float2AttributeChannelPtr uvs, glm::vec3 versorU, glm::vec3 versorV, bool scale );
static void GenerateUVW ( Float3AttributeChannelPtr verts, Float3AttributeChannelPtr uvs, glm::vec3 versorU, glm::vec3 versorV, glm::vec3 versorW, bool scale );
static void GenerateUV ( const std::vector< glm::vec3 > & verts, std::vector< glm::vec2 > & uvs, glm::vec3 versorU, glm::vec3 versorV, bool scale );
static void GenerateUVW ( const std::vector< glm::vec3 > & verts, std::vector< glm::vec3 > & uvs, glm::vec3 versorU, glm::vec3 versorV, glm::vec3 versorW, bool scale );
static void GenerateUV ( const std::vector< glm::vec3 > & verts, SizeType startRange, SizeType endRange, std::vector< glm::vec2 > & uvs, glm::vec3 versorU, glm::vec3 versorV, bool scale );
};
}}} |
andrewyang96/AdventOfCode2017 | day13/solution.py | <gh_stars>0
from typing import Dict
def get_packet_scan_severity(firewall: Dict[int, int]) -> int:
severity = 0
curr_pos = {idx: 0 for idx in firewall}
dirs = {idx: 1 for idx in firewall}
for idx in range(max(firewall.keys())+1):
if curr_pos.get(idx) == 0:
severity += idx * firewall[idx]
for i, pos in curr_pos.items():
if firewall[i] > 1:
if pos == firewall[i] - 1:
dirs[i] = -1
elif pos == 0:
dirs[i] = 1
curr_pos[i] += dirs[i]
return severity
def get_packet_scan_delay(firewall: Dict[int, int], debug_interval=1000) -> int:
curr_pos = {idx: 0 for idx in firewall}
dirs = {idx: 1 for idx in firewall}
delays = [None for _ in range(max(firewall.keys())+1)]
count = 0
while True:
delays = [count] + delays[:-1]
for i, pos in curr_pos.items():
if pos == 0:
delays[i] = None
if delays[-1] is not None:
return delays[-1]
for i, pos in curr_pos.items():
if firewall[i] > 1:
if pos == firewall[i] - 1:
dirs[i] = -1
elif pos == 0:
dirs[i] = 1
curr_pos[i] += dirs[i]
if count % debug_interval == 0:
print(count)
count += 1
|
PRIDE-Utilities/ms-data-core-api | src/test/java/uk/ac/ebi/pride/utilities/data/exporters/MzTabMzIdentMLConverterTest.java | package uk.ac.ebi.pride.utilities.data.exporters;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import uk.ac.ebi.pride.jmztab.model.MZTabFile;
import uk.ac.ebi.pride.jmztab.utils.MZTabFileConverter;
import uk.ac.ebi.pride.utilities.data.controller.impl.ControllerImpl.MzIdentMLControllerImpl;
import java.io.*;
import java.net.URL;
import static org.junit.Assert.assertTrue;
/**
* MzTab Converter of mzIdentML files. The class allow to convert mzIdentML
* files to mzTab including the protein groups and PSMs.
*
* @author <NAME>
* @author <NAME>
*/
@Ignore
public class MzTabMzIdentMLConverterTest {
private MzIdentMLControllerImpl mzIdentMLController = null;
private MzIdentMLControllerImpl mzIdentMLMassiveController = null;
private MzIdentMLControllerImpl mzIdentMLPTMsController = null;
@Before
@Ignore
public void setUp() throws Exception {
URL url = MzTabPRIDEConverterTest.class.getClassLoader().getResource("55merge_mascot_full.mzid");
if (url == null) {
throw new IllegalStateException("no file for input found!");
}
File inputFile = new File(url.toURI());
mzIdentMLController = new MzIdentMLControllerImpl(inputFile);
url = MzTabPRIDEConverterTest.class.getClassLoader().getResource("20140326_C04A.mzid");
if (url == null) {
throw new IllegalStateException("no file for input found!");
}
inputFile = new File(url.toURI());
mzIdentMLMassiveController = new MzIdentMLControllerImpl(inputFile);
url = MzTabPRIDEConverterTest.class.getClassLoader().getResource("MzID_PTMS.scored.mzid");
if (url == null) {
throw new IllegalStateException("no file for input found!");
}
inputFile = new File(url.toURI());
mzIdentMLPTMsController = new MzIdentMLControllerImpl(inputFile);
}
@Test
@Ignore
public void convertToMzTab() throws IOException {
AbstractMzTabConverter mzTabconverter = new MzIdentMLMzTabConverter(mzIdentMLController);
MZTabFile mzTabFile = mzTabconverter.getMZTabFile();
MZTabFileConverter checker = new MZTabFileConverter();
checker.check(mzTabFile);
assertTrue("No errors reported during the conversion from MzIdentML to MzTab", checker.getErrorList().size() == 0);
}
@Test
@Ignore
public void convertMassiveToMzTab() throws IOException {
AbstractMzTabConverter mzTabconverter = new MzIdentMLMzTabConverter(mzIdentMLMassiveController);
MZTabFile mzTabFile = mzTabconverter.getMZTabFile();
MZTabFileConverter checker = new MZTabFileConverter();
checker.check(mzTabFile);
assertTrue("No errors reported during the conversion from MzIdentML to MzTab", checker.getErrorList().size() == 0);
}
@Test
@Ignore
public void convertPTMsToMzTab() throws IOException {
AbstractMzTabConverter mzTabconverter = new MzIdentMLMzTabConverter(mzIdentMLPTMsController);
MZTabFile mzTabFile = mzTabconverter.getMZTabFile();
MZTabFileConverter checker = new MZTabFileConverter();
checker.check(mzTabFile);
assertTrue("No errors reported during the conversion from MzIdentML to MzTab", checker.getErrorList().size() == 0);
File tmpFile = File.createTempFile("temp", "mztab");
mzTabFile.printMZTab(new BufferedOutputStream(new FileOutputStream(tmpFile)) );
tmpFile.deleteOnExit();
}
@After
public void tearDown() throws Exception {
}
}
|
christhekeele/ex_venture | assets/js/redux/loginReducer.js | import { createReducer } from "../kalevala";
import { Types } from "./actions";
const INITIAL_STATE = {
active: false,
loggedIn: false,
};
const loginActive = (state) => {
return { ...state, active: true };
};
const loggedIn = (state) => {
return { ...state, loggedIn: true };
};
const HANDLERS = {
[Types.LOGIN_ACTIVE]: loginActive,
[Types.LOGGED_IN]: loggedIn,
};
export const loginReducer = createReducer(INITIAL_STATE, HANDLERS);
|
PkayJava/overlap2d-dev | src/main/java/com/o2d/pkayjava/editor/controller/commands/CutItemsCommand.java | /*
* ******************************************************************************
* * Copyright 2015 See AUTHORS file.
* *
* * 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.o2d.pkayjava.editor.controller.commands;
import java.util.Collection;
import java.util.HashMap;
import java.util.Set;
import com.badlogic.ashley.core.Component;
import com.badlogic.ashley.core.Entity;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.utils.Json;
import com.o2d.pkayjava.editor.controller.commands.*;
import com.o2d.pkayjava.editor.controller.commands.CopyItemsCommand;
import com.o2d.pkayjava.runtime.data.CompositeVO;
import com.o2d.pkayjava.editor.view.stage.Sandbox;
import com.o2d.pkayjava.editor.Overlap2DFacade;
import com.o2d.pkayjava.editor.factory.ItemFactory;
import com.o2d.pkayjava.runtime.components.NodeComponent;
import com.o2d.pkayjava.runtime.components.ParentNodeComponent;
import com.o2d.pkayjava.editor.utils.runtime.EntityUtils;
/**
* Created by azakhary on 4/28/2015.
*/
public class CutItemsCommand extends EntityModifyRevertableCommand {
private String backup;
@Override
public void doAction() {
backup = CopyItemsCommand.getJsonStringFromEntities(sandbox.getSelector().getSelectedItems());
String data = CopyItemsCommand.getJsonStringFromEntities(sandbox.getSelector().getSelectedItems());
Object[] payload = new Object[2];
payload[0] = new Vector2(Sandbox.getInstance().getCamera().position.x,Sandbox.getInstance().getCamera().position.y);
payload[1] = data;
Sandbox.getInstance().copyToClipboard(payload);
sandbox.getSelector().removeCurrentSelectedItems();
facade.sendNotification(DeleteItemsCommand.DONE);
}
@Override
public void undoAction() {
Json json = new Json();
CompositeVO compositeVO = json.fromJson(CompositeVO.class, backup);
Set<Entity> newEntitiesList = PasteItemsCommand.createEntitiesFromVO(compositeVO);
for (Entity entity : newEntitiesList) {
Overlap2DFacade.getInstance().sendNotification(ItemFactory.NEW_ITEM_ADDED, entity);
}
sandbox.getSelector().setSelections(newEntitiesList, true);
}
}
|
qingshui5555/azrwebi | src/main/java/com/movit/rwe/modules/bi/base/entity/hive/Patient.java | package com.movit.rwe.modules.bi.base.entity.hive;
import java.util.Date;
/**
*
* @Project : az-rwe-bi-web
* @Title : Patient.java
* @Package com.movit.rwe.common.entity
* @Description : ๆฃ่
* @author Yuri.Zheng
* @email <EMAIL>
* @date 2016ๅนด3ๆ1ๆฅ ไธๅ10:57:20
*
*/
public class Patient {
/**
* ไธป้ฎ
*/
private String guid;
/**
* ็
ไบบ็ผ็
*/
private String eCode;
/**
* ็ ็ฉถ
*/
private String studyId;
/**
* ๆฃ่
็ปไธป้ฎ
*/
private String groupGuid;
private String center;
private String gender;
private String race;
/**
* ็ๆฅ
*/
private Date birthday;
/**
* ่บซ้ซ
*/
private Double height;
/**
* ไฝ้
*/
private Double weight;
public String getGuid() {
return guid;
}
public void setGuid(String guid) {
this.guid = guid;
}
public String geteCode() {
return eCode;
}
public void seteCode(String eCode) {
this.eCode = eCode;
}
public String getStudyId() {
return studyId;
}
public void setStudyId(String studyId) {
this.studyId = studyId;
}
public String getGroupGuid() {
return groupGuid;
}
public void setGroupGuid(String groupGuid) {
this.groupGuid = groupGuid;
}
public String getCenter() {
return center;
}
public void setCenter(String center) {
this.center = center;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getRace() {
return race;
}
public void setRace(String race) {
this.race = race;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public Double getHeight() {
return height;
}
public void setHeight(Double height) {
this.height = height;
}
public Double getWeight() {
return weight;
}
public void setWeight(Double weight) {
this.weight = weight;
}
}
|
open-repos/apache-ant | src/main/org/apache/tools/ant/types/resources/Resources.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* 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.apache.tools.ant.types.resources;
import java.io.File;
import java.util.AbstractCollection;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.Stack;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.types.DataType;
import org.apache.tools.ant.types.Resource;
import org.apache.tools.ant.types.ResourceCollection;
/**
* Generic {@link ResourceCollection}: Either stores nested {@link ResourceCollection}s,
* making no attempt to remove duplicates, or references another {@link ResourceCollection}.
* @since Ant 1.7
*/
public class Resources extends DataType implements AppendableResourceCollection {
/** {@code static} empty {@link ResourceCollection} */
public static final ResourceCollection NONE = new ResourceCollection() {
@Override
public boolean isFilesystemOnly() {
return true;
}
@Override
public Iterator<Resource> iterator() {
return EMPTY_ITERATOR;
}
@Override
public int size() {
return 0;
}
};
/** {@code static} empty {@link Iterator} */
public static final Iterator<Resource> EMPTY_ITERATOR = Collections.emptyIterator();
private class MyCollection extends AbstractCollection<Resource> {
private volatile Collection<Resource> cached;
@Override
public int size() {
return getCache().size();
}
@Override
public Iterator<Resource> iterator() {
return getCache().iterator();
}
private synchronized Collection<Resource> getCache() {
if (cached == null) {
cached = internalResources().collect(Collectors.toList());
}
return cached;
}
}
private class MyIterator implements Iterator<Resource> {
private Iterator<ResourceCollection> rci = getNested().iterator();
private Iterator<Resource> ri;
@Override
public boolean hasNext() {
boolean result = ri != null && ri.hasNext();
while (!result && rci.hasNext()) {
ri = rci.next().iterator();
result = ri.hasNext();
}
return result;
}
@Override
public Resource next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
return ri.next();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
private List<ResourceCollection> rc;
private Optional<Collection<Resource>> cacheColl = Optional.empty();
private volatile boolean cache = false;
/**
* Create a new {@link Resources}.
*/
public Resources() {
}
/**
* Create a new {@link Resources}.
* @param project {@link Project}
* @since Ant 1.8
*/
public Resources(Project project) {
setProject(project);
}
/**
* Set whether to cache collections.
* @param b {@code boolean} cache flag.
* @since Ant 1.8.0
*/
public void setCache(boolean b) {
cache = b;
}
/**
* Add a {@link ResourceCollection}.
* @param c the {@link ResourceCollection} to add.
*/
@Override
public synchronized void add(ResourceCollection c) {
if (isReference()) {
throw noChildrenAllowed();
}
if (c == null) {
return;
}
if (rc == null) {
rc = Collections.synchronizedList(new ArrayList<>());
}
rc.add(c);
invalidateExistingIterators();
cacheColl = Optional.empty();
setChecked(false);
}
/**
* Fulfill the {@link ResourceCollection} contract.
* @return an {@link Iterator} of {@link Resources}.
*/
@Override
public synchronized Iterator<Resource> iterator() {
if (isReference()) {
return getRef().iterator();
}
validate();
return new FailFast(this, cacheColl.map(Iterable::iterator).orElseGet(MyIterator::new));
}
/**
* Fulfill the {@link ResourceCollection} contract.
* @return number of elements as {@code int}.
*/
@Override
public synchronized int size() {
if (isReference()) {
return getRef().size();
}
validate();
return cacheColl.isPresent() ? cacheColl.get().size() : (int) internalResources().count();
}
/**
* Fulfill the {@link ResourceCollection} contract.
* @return {@code true} if all {@link Resource}s represent files.
*/
@Override
public boolean isFilesystemOnly() {
if (isReference()) {
return getRef().isFilesystemOnly();
}
validate();
return getNested().stream().allMatch(ResourceCollection::isFilesystemOnly);
}
/**
* Format this <code>Resources</code> as a {@link String}.
* @return a descriptive <code>String</code>.
*/
@Override
public synchronized String toString() {
if (isReference()) {
return getRef().toString();
}
validate();
final Stream<?> stream = cache ? cacheColl.get().stream() : getNested().stream();
return stream.map(String::valueOf).collect(Collectors.joining(File.pathSeparator));
}
/**
* Overrides the base implementation to recurse on all {@link DataType}
* child elements that may have been added.
* @param stk the stack of data types to use (recursively).
* @param p the {@link Project} to use to dereference the references.
* @throws BuildException on error.
*/
@Override
protected void dieOnCircularReference(Stack<Object> stk, Project p)
throws BuildException {
if (isReference()) {
super.dieOnCircularReference(stk, p);
return;
}
if (!isChecked()) {
getNested().stream().filter(DataType.class::isInstance).map(DataType.class::cast)
.forEach(dt -> pushAndInvokeCircularReferenceCheck(dt, stk, p));
setChecked(true);
}
}
/**
* Allow subclasses to notify existing Iterators they have experienced concurrent modification.
*/
protected void invalidateExistingIterators() {
FailFast.invalidate(this);
}
/**
* Resolves references, allowing any {@link ResourceCollection}.
* @return the referenced {@link ResourceCollection}.
*/
private ResourceCollection getRef() {
return getCheckedRef(ResourceCollection.class);
}
private synchronized void validate() {
dieOnCircularReference();
if (cache && !cacheColl.isPresent()) {
cacheColl = Optional.of(new MyCollection());
}
}
private synchronized List<ResourceCollection> getNested() {
return rc == null ? Collections.emptyList() : rc;
}
private synchronized Stream<Resource> internalResources() {
return StreamSupport.stream(
Spliterators.spliteratorUnknownSize(new MyIterator(), Spliterator.NONNULL), false);
}
}
|
luxe/unilang | source/bazel/deps/xorg_libXt/get.bzl | <gh_stars>10-100
# Do not edit this file directly.
# It was auto-generated by: code/programs/reflexivity/reflexive_refresh
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
def xorgLibXt():
http_archive(
name="xorg_libXt" ,
build_file="//bazel/deps/xorg_libXt:build.BUILD" ,
sha256="d154ab7b84da70d5df5cd7be6b2a6cd16f13524937c20c4ecfc28fcdcb253bfe" ,
strip_prefix="xorg-libXt-51cbf52b7668ad46a428dabe8e79e6819e825b20" ,
urls = [
"https://github.com/Unilang/xorg-libXt/archive/51cbf52b7668ad46a428dabe8e79e6819e825b20.tar.gz",
], patches = [
"//bazel/deps/xorg_libXt/patches:p1.patch",
],
patch_args = [
"-p1",
],
patch_cmds = [
"mv include/X11 X11",
],
)
|
mariogeiger/jax | jax/scipy/special.py | <reponame>mariogeiger/jax<gh_stars>1-10
# Copyright 2020 Google LLC
#
# 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.
from jax._src.scipy.special import (
betainc as betainc,
betaln as betaln,
digamma as digamma,
entr as entr,
erf as erf,
erfc as erfc,
erfinv as erfinv,
exp1 as exp1,
expi as expi,
expit as expit,
expn as expn,
gammainc as gammainc,
gammaincc as gammaincc,
gammaln as gammaln,
i0 as i0,
i0e as i0e,
i1 as i1,
i1e as i1e,
logit as logit,
logsumexp as logsumexp,
lpmn as lpmn,
lpmn_values as lpmn_values,
multigammaln as multigammaln,
log_ndtr as log_ndtr,
ndtr as ndtr,
ndtri as ndtri,
polygamma as polygamma,
sph_harm as sph_harm,
xlogy as xlogy,
xlog1py as xlog1py,
zeta as zeta,
)
|
tcd/eddy | lib/definitions/elements/manual/i/I07.interchange_receiver_id.rb | module Eddy
module Elements
# ### Element Summary:
#
# - Id: I07
# - Name: Interchange Receiver ID
# - Type: AN
# - Min/Max: 15/15
# - Description: Identification code published by the receiver of the data; When sending, it is used by the sender as their sending ID, thus other parties sending to them will use this as a receiving ID to route data to them
class I07 < Eddy::Models::Element::AN
# @param val [String] (nil)
# @param req [String] (nil)
# @param ref [String] (nil)
# @return [void]
def initialize(val: nil, req: nil, ref: nil)
@id = "I07"
@name = "Interchange Receiver ID"
@description = "Identification code published by the receiver of the data; When sending, it is used by the sender as their sending ID, thus other parties sending to them will use this as a receiving ID to route data to them"
super(
min: 15,
max: 15,
req: req,
ref: ref,
val: val,
)
end
end
end
end
|
uk-gov-mirror/hmrc.professional-subscriptions-frontend | test/views/CannotClaimEmployerContributionViewSpec.scala | <filename>test/views/CannotClaimEmployerContributionViewSpec.scala
/*
* Copyright 2021 HM Revenue & Customs
*
* 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 views
import models.NormalMode
import views.behaviours.ViewBehaviours
import views.html.CannotClaimEmployerContributionView
class CannotClaimEmployerContributionViewSpec extends ViewBehaviours {
"CannotClaimEmployerContribution view" must {
val application = applicationBuilder(userAnswers = Some(emptyUserAnswers)).build()
val view = application.injector.instanceOf[CannotClaimEmployerContributionView]
val applyView = view.apply(NormalMode, taxYear, index)(fakeRequest, messages)
behave like normalPage(applyView, "cannotClaimEmployerContribution")
behave like pageWithBackLink(applyView)
"have correct content" in {
val doc = asDocument(applyView)
assertContainsMessages(doc, messages("cannotClaimEmployerContribution.para1"))
doc.getElementById("submit").text() mustBe messages("cannotClaimEmployerContribution.button")
}
}
}
|
himanshuMaheshwari2311/Design-Patterns-In-Java | src/main/java/com/stark/patterns/behavioral/template/WebOrder.java | <filename>src/main/java/com/stark/patterns/behavioral/template/WebOrder.java
package com.stark.patterns.behavioral.template;
public class WebOrder extends OrderTemplate {
@Override
public void doCheckout() {
System.out.println("Web checkout");
}
@Override
public void doPayment() {
System.out.println("Web Payment");
}
@Override
public void doReceipt() {
System.out.println("Web Receipt");
}
@Override
public void doDelivery() {
System.out.println("Web delivery");
}
}
|
jonas333/minimal-j | ext/rest/src/main/java/org/minimalj/rest/RestHTTPD.java | package org.minimalj.rest;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.minimalj.application.Application;
import org.minimalj.application.Configuration;
import org.minimalj.backend.Backend;
import org.minimalj.metamodel.model.MjEntity;
import org.minimalj.metamodel.model.MjModel;
import org.minimalj.repository.query.By;
import org.minimalj.repository.query.Query;
import org.minimalj.repository.query.Query.QueryLimitable;
import org.minimalj.rest.openapi.OpenAPIFactory;
import org.minimalj.security.Subject;
import org.minimalj.transaction.InputStreamTransaction;
import org.minimalj.transaction.OutputStreamTransaction;
import org.minimalj.transaction.Transaction;
import org.minimalj.util.IdUtils;
import org.minimalj.util.SerializationContainer;
import org.minimalj.util.StringUtils;
import org.minimalj.util.resources.Resources;
import fi.iki.elonen.NanoHTTPD;
import fi.iki.elonen.NanoHTTPD.Response.Status;
public class RestHTTPD extends NanoHTTPD {
private final Map<String, Class<?>> classByName;
public RestHTTPD( int port, boolean secure) {
super(port);
if (secure) {
try {
String keyAndTrustStoreClasspathPath = Configuration.get("MjKeystore"); // in example '/mjdevkeystore.jks'
char[] passphrase = Configuration.get("MjKeystorePassphrase").toCharArray(); // ub example 'mjdev1'
makeSecure(makeSSLSocketFactory(keyAndTrustStoreClasspathPath, passphrase), null);
} catch (IOException e) {
e.printStackTrace();
}
}
classByName = initClassMap();
}
protected Map<String, Class<?>> initClassMap() {
Map<String, Class<?>> classByName = new HashMap<>();
MjModel model = new MjModel(Application.getInstance().getEntityClasses());
for (MjEntity entity : model.entities) {
classByName.put(entity.getSimpleClassName(), entity.getClazz());
}
return classByName;
}
@Override
public Response serve(String uriString, Method method, Map<String, String> headers, Map<String, String> parameters,
Map<String, String> files) {
String[] pathElements;
try {
URI uri = new URI(uriString);
String path = uri.getPath();
if (path.startsWith("/")) {
path = path.substring(1);
}
pathElements = path.split("/");
} catch (URISyntaxException e) {
return newFixedLengthResponse(Status.BAD_REQUEST, "text/html", e.getMessage());
}
Class<?> clazz = null;
if (pathElements.length > 0 && !StringUtils.isEmpty(pathElements[0]) && !Character.isLowerCase(pathElements[0].charAt(0))) {
clazz = classByName.get(pathElements[0]);
if (clazz == null) {
return newFixedLengthResponse(Status.NOT_FOUND, "text/html", "Class not available");
}
}
if (method == Method.GET) {
if (StringUtils.equals("swagger-ui", pathElements[0])) {
if (pathElements.length == 1) {
if (!uriString.endsWith("/")) {
Response r = newFixedLengthResponse(Response.Status.REDIRECT, MIME_HTML, "");
r.addHeader("Location", uriString + "/");
return r;
}
return newChunkedResponse(Status.OK, "text/html",
getClass().getResourceAsStream(uriString + "index.html"));
} else if (StringUtils.equals("swagger.json", pathElements[1])) {
return newFixedLengthResponse(Status.OK, "text/json",
new OpenAPIFactory().create(Application.getInstance()));
} else {
int pos = uriString.lastIndexOf('.');
String mimeType = Resources.getMimeType(uriString.substring(pos + 1));
return newChunkedResponse(Status.OK, mimeType, getClass().getResourceAsStream(uriString));
}
}
if (pathElements.length == 1 && clazz != null) {
// GET entity (get all or pages of size x)
Query query = By.all();
String sizeParameter = parameters.get("size");
if (!StringUtils.isBlank(sizeParameter)) {
int offset = 0;
String offsetParameter = parameters.get("offset");
if (!StringUtils.isBlank(offsetParameter)) {
try {
offset = Integer.valueOf(offsetParameter);
} catch (NumberFormatException e) {
return newFixedLengthResponse(Status.BAD_REQUEST, "text/json",
"page parameter invalid: " + offsetParameter);
}
}
try {
int size = Integer.valueOf(sizeParameter);
query = ((QueryLimitable) query).limit(offset, size);
} catch (NumberFormatException e) {
return newFixedLengthResponse(Status.BAD_REQUEST, "text/json",
"size parameter invalid: " + sizeParameter);
}
}
List<?> object = Backend.find(clazz, query);
return newFixedLengthResponse(Status.OK, "text/json", EntityJsonWriter.write(object));
}
if (pathElements.length == 2) {
// GET entity/id (get one)
String id = pathElements[1];
Object object = Backend.read(clazz, id);
if (object != null) {
return newFixedLengthResponse(Status.OK, "text/json", EntityJsonWriter.write(object));
} else {
return newFixedLengthResponse(Status.NOT_FOUND, "text/plain",
clazz.getSimpleName() + " with id " + id + " not found");
}
}
} else if (method == Method.POST) {
if (clazz != null) {
String inputString = files.get("postData");
if (inputString == null) {
return newFixedLengthResponse(Status.BAD_REQUEST, "text/plain", "No Input");
}
Object inputObject = EntityJsonReader.read(clazz, inputString);
Object id = Backend.insert(inputObject);
return newFixedLengthResponse(Status.OK, "text/plain", id.toString());
}
} else if (method == Method.DELETE) {
if (clazz != null) {
if (pathElements.length >= 2) {
String id = pathElements[1];
Backend.delete(clazz, id);
} else {
return newFixedLengthResponse(Status.BAD_REQUEST, "text/plain", "Post expects id in url");
}
}
} else if (method == Method.PUT) {
String inputFileName = files.get("content");
if (inputFileName == null) {
return newFixedLengthResponse(Status.BAD_REQUEST, "text/plain", "No Input");
}
if (pathElements.length >= 1 && StringUtils.equals("java-transaction", pathElements[0])) {
return transaction(headers, inputFileName);
} else if (clazz != null && pathElements.length == 2) {
String id = pathElements[1];
Object object = Backend.read(clazz, id);
try (FileInputStream fis = new FileInputStream(new File(inputFileName))) {
Object inputObject = EntityJsonReader.read(object, fis);
IdUtils.setId(object, id); // don't let the id be changed
object = Backend.save(inputObject);
return newFixedLengthResponse(Status.OK, "text/json", EntityJsonWriter.write(object));
} catch (IOException x) {
return newFixedLengthResponse(Status.BAD_REQUEST, "text/plain", "Could not read input");
}
} else {
return newFixedLengthResponse(Status.BAD_REQUEST, "text/plain", "Put excepts class/id in url");
}
} else if (method == Method.OPTIONS) {
Response response = newFixedLengthResponse(Status.OK, "text/plain", null);
response.addHeader("Access-Control-Allow-Origin", "*");
response.addHeader("Access-Control-Allow-Methods", "POST, GET, DELETE, PUT, PATCH, OPTIONS");
response.addHeader("Access-Control-Allow-Headers", "API-Key,accept, Content-Type");
response.addHeader("Access-Control-Max-Age", "1728000");
return response;
} else {
return newFixedLengthResponse(Status.METHOD_NOT_ALLOWED, "text/plain", "Method not allowed: " + method);
}
return newFixedLengthResponse(Status.BAD_REQUEST, "text/plain", "Not a valid request url");
}
private Response transaction(Map<String, String> headers, String inputFileName) {
try (InputStream is = new FileInputStream(inputFileName)) {
if (Backend.getInstance().isAuthenticationActive()) {
String token = headers.get("token");
return transaction(token, is);
} else {
return transaction(is);
}
} catch (Exception e) {
return newFixedLengthResponse(Status.BAD_REQUEST, "text/plain", e.getMessage());
}
}
private Response transaction(String token, InputStream is) {
if (!StringUtils.isEmpty(token)) {
Subject subject = Backend.getInstance().getAuthentication().getUserByToken(UUID.fromString(token));
if (subject != null) {
Subject.setCurrent(subject);
} else {
return newFixedLengthResponse(Status.UNAUTHORIZED, "text/plain", "Invalid token");
}
}
try {
return transaction(is);
} finally {
Subject.setCurrent(null);
}
}
private Response transaction(InputStream inputStream) {
try (ObjectInputStream ois = new ObjectInputStream(inputStream)) {
Object input = ois.readObject();
if (!(input instanceof Transaction)) {
return newFixedLengthResponse(Status.BAD_REQUEST, "text/plain", "Input not a Transaction but a " + input.getClass().getName());
}
Transaction<?> transaction = (Transaction<?>) input;
if (transaction instanceof InputStreamTransaction) {
InputStreamTransaction<?> inputStreamTransaction = (InputStreamTransaction<?>) transaction;
inputStreamTransaction.setStream(ois);
}
if (transaction instanceof OutputStreamTransaction) {
return newFixedLengthResponse(Status.NOT_IMPLEMENTED, "text/plain", "OutputStreamTransaction not implemented");
}
Object output;
try {
output = Backend.execute((Transaction<?>) transaction);
} catch (Exception e) {
return newFixedLengthResponse(Status.INTERNAL_ERROR, "text/plain", e.getMessage());
}
try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(byteArrayOutputStream)) {
oos.writeObject(SerializationContainer.wrap(output));
oos.flush();
byte[] bytes = byteArrayOutputStream.toByteArray();
try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes)) {
return newFixedLengthResponse(Status.OK, "application/octet-stream", byteArrayInputStream, bytes.length);
}
}
} catch (Exception e) {
return newFixedLengthResponse(Status.BAD_REQUEST, "text/plain", e.getMessage());
}
}
}
|
jerrybowman/tlc.open.java | tlc-commons-project/tlc-io-x937/src/main/java/com/thelastcheck/io/x9/copy/dstu/X937ReturnAddendumDRecordCopier.java | <reponame>jerrybowman/tlc.open.java
package com.thelastcheck.io.x9.copy.dstu;
import com.thelastcheck.commons.base.exception.InvalidDataException;
import com.thelastcheck.io.base.Record;
import com.thelastcheck.io.x9.X9Record;
import com.thelastcheck.io.x9.copy.X937RecordCopier;
import com.thelastcheck.io.x9.factory.X9RecordFactory;
import com.thelastcheck.io.x937.records.X937ReturnAddendumDRecord;
/**
* @author <NAME>
*/
public class X937ReturnAddendumDRecordCopier implements X937RecordCopier {
private X9RecordFactory factory;
public X937ReturnAddendumDRecordCopier(X9RecordFactory factory) {
this.factory = factory;
}
public X9Record copy(X9Record input) throws InvalidDataException {
Record output = factory.newX9Record(input.recordType());
X937ReturnAddendumDRecord in = (X937ReturnAddendumDRecord) input;
X937ReturnAddendumDRecord out = (X937ReturnAddendumDRecord) output;
out.returnAddendumDRecordNumber(in.returnAddendumDRecordNumber());
out.endorsingBankRoutingNumber(in.endorsingBankRoutingNumber());
out.endorsingBankEndorsementDate(in.endorsingBankEndorsementDateAsString());
out.endorsingBankItemSequenceNumber(in.endorsingBankItemSequenceNumber());
out.truncationIndicator(in.truncationIndicator());
out.endorsingBankConversionIndicator(in.endorsingBankConversionIndicator());
out.endorsingBankCorrectionIndicator(in.endorsingBankCorrectionIndicator());
out.returnReason(in.returnReason());
out.userField(in.userField());
out.reserved(in.reserved());
return out;
}
}
|
carmenlau/authgear-server | pkg/portal/task/deps.go | package task
import (
"github.com/google/wire"
"github.com/authgear/authgear-server/pkg/portal/task/tasks"
)
var DependencySet = wire.NewSet(
NewInProcessExecutorLogger,
NewExecutor,
wire.Bind(new(Executor), new(*InProcessExecutor)),
wire.Struct(new(InProcessQueue), "*"),
)
func NewExecutor(
logger InProcessExecutorLogger,
sendMessageTask *tasks.SendMessagesTask,
) *InProcessExecutor {
executor := &InProcessExecutor{
Logger: logger,
}
tasks.ConfigureSendMessagesTask(executor, sendMessageTask)
return executor
}
|
lhr-solar/BPS | Tests/Test_BSP_I2C.c | /* Copyright (c) 2020 <NAME> Racing Solar */
#include "common.h"
#include "config.h"
#include "BSP_I2C.h"
#include "EEPROM.h"
#define ADDRESS 0x0005
int main() {
BSP_I2C_Init();
printf("EEPROM initialized\n");
uint8_t buffer[4] = {0xfe, 0xed, 0xbe, 0xef};
EEPROM_WriteMultipleBytes(ADDRESS, 4, buffer);
uint8_t readBuffer[4];
BSP_I2C_Read(EEPROM_ADDRESS, ADDRESS, readBuffer, 4);
printf("read EEPROM\n");
for (int i = 0; i < 4; i++){
printf("%x\n", readBuffer[i]);
}
printf("--------------------\n");
EEPROM_Reset();
EEPROM_Load();
EEPROM_Tester();
EEPROM_SerialPrintData();
while(1){}
return 0;
}
|
hmrc/safety-and-security-entry-declaration-frontend | app/pages/Waypoint.scala | <gh_stars>0
/*
* Copyright 2022 HM Revenue & Customs
*
* 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 pages
import models.{CheckMode, Mode, NormalMode}
import pages.consignees._
import pages.consignors.{AddConsignorPage, CheckConsignorPage}
import pages.goods._
import pages.predec.CheckPredecPage
import pages.routedetails.{AddCountryEnRoutePage, AddPlaceOfLoadingPage, AddPlaceOfUnloadingPage, CheckRouteDetailsPage}
import pages.transport.{AddOverallDocumentPage, AddSealPage, CheckTransportPage}
case class Waypoint (
page: WaypointPage,
mode: Mode,
urlFragment: String
)
object Waypoint {
private def staticFragments: Map[String, Waypoint] =
Map(
AddConsigneePage.normalModeUrlFragment -> AddConsigneePage.waypoint(NormalMode),
AddConsigneePage.checkModeUrlFragment -> AddConsigneePage.waypoint(CheckMode),
AddNotifiedPartyPage.checkModeUrlFragment -> AddNotifiedPartyPage.waypoint(CheckMode),
AddNotifiedPartyPage.checkModeUrlFragment -> AddNotifiedPartyPage.waypoint(CheckMode),
AddNotifiedPartyPage.normalModeUrlFragment -> AddNotifiedPartyPage.waypoint(NormalMode),
AddConsignorPage.normalModeUrlFragment -> AddConsignorPage.waypoint(NormalMode),
AddConsignorPage.checkModeUrlFragment -> AddConsignorPage.waypoint(CheckMode),
AddCountryEnRoutePage.normalModeUrlFragment -> AddCountryEnRoutePage.waypoint(NormalMode),
AddCountryEnRoutePage.checkModeUrlFragment -> AddCountryEnRoutePage.waypoint(CheckMode),
AddPlaceOfLoadingPage.normalModeUrlFragment -> AddPlaceOfLoadingPage.waypoint(NormalMode),
AddPlaceOfLoadingPage.checkModeUrlFragment -> AddPlaceOfLoadingPage.waypoint(CheckMode),
AddPlaceOfUnloadingPage.normalModeUrlFragment -> AddPlaceOfUnloadingPage.waypoint(NormalMode),
AddPlaceOfUnloadingPage.checkModeUrlFragment -> AddPlaceOfUnloadingPage.waypoint(CheckMode),
AddGoodsPage.normalModeUrlFragment -> AddGoodsPage.waypoint(NormalMode),
AddGoodsPage.checkModeUrlFragment -> AddGoodsPage.waypoint(CheckMode),
AddSealPage.normalModeUrlFragment -> AddSealPage.waypoint(NormalMode),
AddSealPage.checkModeUrlFragment -> AddSealPage.waypoint(CheckMode),
AddOverallDocumentPage.normalModeUrlFragment -> AddOverallDocumentPage.waypoint(NormalMode),
AddOverallDocumentPage.checkModeUrlFragment -> AddOverallDocumentPage.waypoint(CheckMode),
CheckPredecPage.urlFragment -> CheckPredecPage.waypoint,
CheckRouteDetailsPage.urlFragment -> CheckRouteDetailsPage.waypoint,
CheckConsigneesAndNotifiedPartiesPage.urlFragment -> CheckConsigneesAndNotifiedPartiesPage.waypoint,
CheckTransportPage.urlFragment -> CheckTransportPage.waypoint,
)
def fromString(s: String): Option[Waypoint] =
staticFragments
.get(s)
.orElse(
CheckConsigneePage.waypointFromString(s)
.orElse(CheckNotifiedPartyPage.waypointFromString(s))
.orElse(CheckConsignorPage.waypointFromString(s))
.orElse(CheckGoodsItemPage.waypointFromString(s))
.orElse(CheckPackageItemPage.waypointFromString(s))
.orElse(AddItemContainerNumberPage.waypointFromString(s))
.orElse(AddPackagePage.waypointFromString(s))
.orElse(AddDocumentPage.waypointFromString(s))
)
}
|
Aleshkev/algoritmika | preoi-2019/dzien-5/drzewa--brut.cpp | #include <bits/stdc++.h>
using namespace std;
typedef intmax_t I;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr), cout.tie(nullptr);
I w, h;
cin >> w >> h;
I best_c = -1, n_best = 0;
for (I x = 0; x < w; ++x) {
for (I y = 0; y < h; ++y) {
vector<vector<bool>> visible(w, vector<bool>(h, false));
for (I dx = -x; dx < w - x; ++dx) {
for (I dy = -y; dy < h - y; ++dy) {
if ((dx == 0 && dy == 0) || __gcd(abs(dx), abs(dy)) != 1) continue;
visible[x + dx][y + dy] = true;
}
}
I c = 0;
for (I xi = 0; xi < w; ++xi) {
for (I yi = 0; yi < h; ++yi) {
c += visible[xi][yi];
}
}
if (c > best_c) {
best_c = c;
n_best = 1;
} else if (c == best_c) {
++n_best;
}
}
}
cout << best_c << ' ' << n_best << '\n';
#ifdef UNITEST
cout.flush();
system("pause");
#endif
return 0;
}
|
codavide/swarmros | libswarmio/include/swarmio/Endpoint.h | #pragma once
#include <swarmio/Node.h>
#include <swarmio/data/Message.pb.h>
namespace swarmio
{
/**
* @brief Forward declare Mailbox
*
*/
class Mailbox;
/**
* @brief Abstract base class for Endpoint implementations.
*
* When an Endpoint is created and started, it announces itself
* to all members of the swarm and start sending and receiving
* messages. Different implementations might provide different
* services for discovery, authentication, authorization and
* encryption.
*
*/
class SWARMIO_API Endpoint
{
protected:
/**
* @brief Allow Mailboxes to register themselves
*
*/
friend Mailbox;
/**
* @brief Register a Mailbox to receive messages.
*
* Each registered Mailbox receives each message sent to
* the endpoint, and can choose to handle it or ignore it.
*
* Thread-safe. Messages will be delivered on a separate thread.
*
* @param mailbox Mailbox to register.
*/
virtual void RegisterMailbox(Mailbox* mailbox) = 0;
/**
* @brief Unregister a Mailbox from receiving messages.
*
* Thread-safe.
*
* @param mailbox Mailbox to unregister.
*/
virtual void UnregisterMailbox(Mailbox* mailbox)= 0;
/**
* @brief Relocate a mailbox to another in-memory location.
*
* Supports thread-safe move operations on Mailboxes.
*
* @param mailbox Mailbox to register.
*/
virtual void ReplaceMailbox(Mailbox* oldMailbox, Mailbox* newMailbox) = 0;
public:
/**
* @brief Start a background thread and begin processing
* messages on this endpoint.
*
*/
virtual void Start() = 0;
/**
* @brief Send a termination signal and wait until the
* endpoint finished processing messages.
*
* Thread-safe.
*
*/
virtual void Stop() = 0;
/**
* @brief Set the message identifier for a message.
*
* Thread safe.
*
* @param message Message
*/
virtual void Tag(data::Message* message) = 0;
/**
* @brief Send a message to a specific member of the swarm.
* Call with node set to nullptr to send a message
* to all members of the swarm.
*
* Thread-safe.
*
* @param message Message
* @param node Node the message will be sent to
*/
virtual void Send(data::Message* message, const Node* node) = 0;
/**
* @brief Retreive a node by its UUID
*
* @param uuid UUID
* @return const Node*
*/
virtual const Node* NodeForUUID(const std::string& uuid) = 0;
/**
* @brief Get the UUID of the local node
*
* @return const std::string&
*/
virtual const std::string& GetUUID() = 0;
/**
* @brief Destroy the Endpoint object
*
*/
virtual ~Endpoint() { }
};
} |
bigjunnn/addressbook-level3 | src/test/java/dukecooks/model/dashboard/DashboardNameTest.java | <reponame>bigjunnn/addressbook-level3
package dukecooks.model.dashboard;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
import dukecooks.model.dashboard.components.DashboardName;
import dukecooks.testutil.Assert;
public class DashboardNameTest {
@Test
public void constructor_null_throwsNullPointerException() {
Assert.assertThrows(NullPointerException.class, () -> new DashboardName(null));
}
@Test
public void constructor_invalidDashboardName_throwsIllegalArgumentException() {
String invalidName = "";
Assert.assertThrows(IllegalArgumentException.class, () -> new DashboardName(invalidName));
}
@Test
public void isValidDashboardName() {
// null name
Assert.assertThrows(NullPointerException.class, () -> DashboardName.isValidName(null));
// invalid name
assertFalse(DashboardName.isValidName("")); // empty string
assertFalse(DashboardName.isValidName(" ")); // spaces only
assertFalse(DashboardName.isValidName("^")); // only non-alphanumeric characters
assertFalse(DashboardName.isValidName("Bake a cake*")); // contains non-alphanumeric characters
// valid name
assertTrue(DashboardName.isValidName("Bake a cake")); // alphabets only
assertTrue(DashboardName.isValidName("12345")); // numbers only
assertTrue(DashboardName.isValidName("peter the 2nd")); // alphanumeric characters
assertTrue(DashboardName.isValidName("Capital Tan")); // with capital letters
assertTrue(DashboardName.isValidName("<NAME> Jr 2nd")); // long names
}
}
|
usergeek/canistergeek-ic-js | lib/es5/ui/SummaryHelpPopoverWithData.js | <gh_stars>1-10
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SummaryHelpPopoverWithData = void 0;
const React = __importStar(require("react"));
const antd_1 = require("antd");
const AbstractHelpPopover_1 = require("./AbstractHelpPopover");
const CalculationUtils_1 = require("../dataProvider/CalculationUtils");
const DateTimeUtils_1 = require("./DateTimeUtils");
function SummaryHelpPopoverWithData(props) {
return React.createElement(AbstractHelpPopover_1.AbstractHelpPopover, { title: "Prediction based on 2 data points", content: React.createElement(React.Fragment, null,
React.createElement(antd_1.Space, { direction: "vertical" },
React.createElement("div", null,
React.createElement("div", null,
"From: ",
DateTimeUtils_1.DateTimeUtils.formatDate(props.data.date.fromMillis, "dayTime")),
React.createElement("div", null,
"To: ",
DateTimeUtils_1.DateTimeUtils.formatDate(props.data.date.toMillis, "dayTime"))),
React.createElement("div", null,
"Difference: ",
CalculationUtils_1.CalculationUtils.formatNumericValue(props.data.data.difference),
props.differenceTitlePostfix),
React.createElement("div", null,
"Prediction: ",
props.predictionLabel))) });
}
exports.SummaryHelpPopoverWithData = SummaryHelpPopoverWithData;
//# sourceMappingURL=SummaryHelpPopoverWithData.js.map |
dandeezy/liftweb | lift/src/main/scala/net/liftweb/http/RequestType.scala | /*
* Copyright 2007-2008 WorldWide Conferencing, LLC
*
* 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 net.liftweb.http
import _root_.javax.servlet.http.{HttpServletRequest}
@serializable
abstract class RequestType {
def post_? : Boolean = false
def get_? : Boolean = false
def head_? : Boolean = false
def put_? : Boolean = false
def delete_? : Boolean = false
}
@serializable
case object GetRequest extends RequestType {
override def get_? = true
}
@serializable
case object PostRequest extends RequestType {
override def post_? = true
}
@serializable
case object HeadRequest extends RequestType {
override def head_? = true
}
@serializable
case object PutRequest extends RequestType {
override def put_? = true
}
@serializable
case object DeleteRequest extends RequestType {
override def delete_? = true
}
@serializable
case class UnknownRequest(method: String) extends RequestType
object RequestType {
def apply(req: HttpServletRequest): RequestType = {
req.getMethod.toUpperCase match {
case "GET" => GetRequest
case "POST" => PostRequest
case "HEAD" => HeadRequest
case "PUT" => PutRequest
case "DELETE" => DeleteRequest
case meth => UnknownRequest(meth)
}
}
}
|
vismaya-Kalaiselvan/cape-python | cape_privacy/pandas/transformations/__init__.py | <gh_stars>100-1000
from cape_privacy.pandas.transformations.column_redact import ColumnRedact
from cape_privacy.pandas.transformations.perturbation import DatePerturbation
from cape_privacy.pandas.transformations.perturbation import NumericPerturbation
from cape_privacy.pandas.transformations.rounding import DateTruncation
from cape_privacy.pandas.transformations.rounding import NumericRounding
from cape_privacy.pandas.transformations.row_redact import RowRedact
from cape_privacy.pandas.transformations.tokenizer import ReversibleTokenizer
from cape_privacy.pandas.transformations.tokenizer import Tokenizer
from cape_privacy.pandas.transformations.tokenizer import TokenReverser
__all__ = [
"DateTruncation",
"DatePerturbation",
"NumericPerturbation",
"NumericRounding",
"ReversibleTokenizer",
"Tokenizer",
"TokenReverser",
"ColumnRedact",
"RowRedact",
]
|
strickyak/c2go | types/dereference.go | package types
import (
"errors"
"regexp"
"strings"
)
func GetDereferenceType(cType string) (string, error) {
// In the form of: "char [8]" -> "char"
search := regexp.MustCompile(`([\w ]+)\s*\[\d+\]`).FindStringSubmatch(cType)
if len(search) > 0 {
return strings.TrimSpace(search[1]), nil
}
// In the form of: "char **" -> "char *"
search = regexp.MustCompile(`([\w ]+)\s*(\*+)`).FindStringSubmatch(cType)
if len(search) > 0 {
return search[1] + search[2][0:len(search[2])-1], nil
}
return "", errors.New(cType)
}
|
kireevaa85/2019-09-otus-java-Kireev | hw13-DI/src/main/java/ru/otus/api/service/DBServiceUser.java | package ru.otus.api.service;
import ru.otus.api.model.User;
import java.util.List;
import java.util.Optional;
public interface DBServiceUser {
long saveUser(User user);
Optional<User> getUser(long id);
Optional<User> getUserFullInfo(long id);
List<User> getAllUsers();
void updateUser(User user);
}
|
ruan3/OpenLive_Android_text | app/src/main/java/io/agora/model/IModelImpl.java | package io.agora.model;
import io.agora.contract.IContract;
/**
* Created by MVPHelper on 2017/07/04
*/
public class IModelImpl implements IContract.Model{
} |
Ametys/runtime | main/plugin-admin/src/org/ametys/runtime/plugins/admin/jvmstatus/monitoring/alerts/AbstractAlertSampleManager.java | /*
* Copyright 2016 Anyware Services
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ametys.runtime.plugins.admin.jvmstatus.monitoring.alerts;
import java.util.HashMap;
import java.util.Map;
import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.ConfigurationException;
import org.ametys.runtime.config.Config;
import org.ametys.runtime.i18n.I18nizableText;
import org.ametys.runtime.plugins.admin.jvmstatus.monitoring.alerts.AlertSampleManager.Threshold.Operator;
import org.ametys.runtime.plugins.admin.jvmstatus.monitoring.sample.AbstractSampleManager;
/**
* AbstractAlertSampleManager gives you the infrastructure for easily
* deploying an {@link AlertSampleManager}.
* If the configuration mailBody is i18n, it can include two parameters :
* the first one is the current value, the second one is the threshold value
*/
public abstract class AbstractAlertSampleManager extends AbstractSampleManager implements AlertSampleManager
{
/** The subject of the mail */
protected I18nizableText _subject;
/** The body of the mail */
protected I18nizableText _body;
@Override
public void configure(Configuration configuration) throws ConfigurationException
{
super.configure(configuration);
_subject = I18nizableText.parseI18nizableText(configuration.getChild("mailSubject"), "plugin." + _pluginName);
_body = I18nizableText.parseI18nizableText(configuration.getChild("mailBody"), "plugin." + _pluginName);
}
@Override
public Map<String, Threshold> getThresholdValues()
{
if (Config.getInstance() == null)
{
return null;
}
Map<String, Threshold> result = new HashMap<>();
Map<String, String> configNames = getThresholdConfigNames();
Map<String, Operator> operators = getOperators();
for (String datasourceName : configNames.keySet())
{
String configName = configNames.get(datasourceName);
Object value = _getTypedValue(configName);
result.put(datasourceName, new Threshold(operators.get(datasourceName), datasourceName, value, _subject, _body));
}
return result;
}
private Object _getTypedValue(String configName)
{
String stringValue = Config.getInstance().getValueAsString(configName);
if (stringValue == null || "".equals(stringValue))
{
return null;
}
Long longValue = Config.getInstance().getValueAsLong(configName);
if (longValue != null)
{
return longValue;
}
Double doubleValue = Config.getInstance().getValueAsDouble(configName);
return doubleValue;
}
/**
* Provides the configuration names for each datasource an alert is attached to.
* This method must return a map with the same keys as {@link #getOperators()}
* @return the configuration names for each datasource an alert is attached to.
*/
protected abstract Map<String, String> getThresholdConfigNames();
/**
* Provides the kind of operator for triggering the alert for each datasource an alert is attached to.
* This method must return a map with the same keys as {@link #getThresholdConfigNames()}
* @return the kind of operator for triggering the alert for each datasource an alert is attached to.
*/
protected abstract Map<String, Operator> getOperators();
}
|
cordelster/harvest | pkg/tree/node/node_test.go | package node
import (
"testing"
)
func Test_simpleName(t *testing.T) {
tests := []struct {
name string
s string
want string
}{
{name: "empty", s: "", want: ""},
{name: "simple", s: "abc", want: "abc"},
{name: "simple 1 space", s: "abc ", want: "abc"},
{name: "simple more space", s: "abc ", want: "abc"},
{name: "simple prefix", s: "^^abc => asdf ", want: "abc"},
{name: "space prefix", s: " abc => asdf ", want: "abc"},
{name: "dashed", s: "cpu-busy => zig", want: "cpu-busy"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := simpleName(tt.s); got != tt.want {
t.Errorf("simpleName() = %v, want %v", got, tt.want)
}
})
}
}
func TestNode_FlatList(t *testing.T) {
tests := []struct {
name string
tree *Node
want string
count int
}{
{name: "perf", tree: makeTree("counters", "instance_name"), want: "instance_name", count: 1},
{name: "conf", tree: makeTree("counters", "node-details-info", "cpu-busytime"),
want: "node-details-info cpu-busytime", count: 1},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
list := make([]string, 0)
tt.tree.FlatList(&list, "")
if len(list) != tt.count {
t.Errorf("flat list has size= %v, want %v", len(list), tt.count)
}
if list[0] != tt.want {
t.Errorf("flat list[0] got=[%v], want=[%v]", list[0], tt.want)
}
})
}
}
func makeTree(names ...string) *Node {
tree := Node{
name: []byte("root"),
Children: make([]*Node, 0),
}
cursor := &tree
for i, n := range names {
if i == len(names)-1 {
cursor.AddChild(&Node{Content: []byte(n)})
} else {
child := &Node{name: []byte(n)}
cursor.AddChild(child)
cursor = child
}
}
return tree.GetChildS(names[0])
}
|
1432junaid/cpp | container/adaptor/queue.cpp | <reponame>1432junaid/cpp
#include<queue>
#include<iostream>
using namespace std;
int main(){
queue<int>q;
/* cout<<q.empty()<<endl;
for(int i=0; i<q.size();i++){
q.push(i+12);
}
for(int i=0; i<q.size(); i++){
// cout<<q.front();
cout<<q.back();
}*/
q.push(12);
q.push(43);
q.push(44);
// cout<<q.back();
// cout<<q.top();
// cout<<q.front();
// cout<<q.size();
q.pop();
// cout<<q.top();
return 0;
}
|
arganeenterprise/k2-connect-node | lib/tokens.js | 'use strict'
// light-weight server
const unirest = require('unirest')
const dispatch = require('./helpers/dispatch')
const tokenValidate = require('./validate/token').tokenValidate
/**
* Handles oauth2 operations
* @module TokenService
* @constructor
* @param {object} options
* @param {string} options.clientId
* @param {string} options.clientSecret
* @param {string} options.baseUrl
*/
function TokenService(options) {
this.options = options
var clientSecret = this.options.clientSecret
var clientId = this.options.clientId
var baseUrl = this.options.baseUrl
/**
* Handles requests for authorizing an oauth application
* @function getToken
* @memberof TokenService
* @returns {Promise} Promise object having the token_type, access_token and expires_in
*/
this.getToken = function () {
return new Promise(function (resolve, reject) {
var requestBody = {
client_id: clientId,
client_secret: clientSecret,
grant_type: 'client_credentials'
}
const req = unirest.post(baseUrl + '/oauth/token')
req.headers({
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded'
})
req.send(requestBody)
req.end(function (res) {
if (res.status === 200) {
resolve(res.body)
} else if (res.status === 401) {
reject('Unauthorized' || res.error)
} else if (res.status === 500) {
reject(res.body || res.error)
} else {
reject(res.body || res.error)
}
})
})
}
/**
* Handles requests for revoking an access token
* @function revokeToken
* @memberof TokenService
* @param {object} opts
* @param {string} opts.accessToken - The access token to be revoked.
* @returns {Promise} Promise object returning empty body
*/
this.revokeToken = function (opts) {
return new Promise(function (resolve, reject) {
let validationError = tokenValidate(opts)
if (validationError) {
reject(validationError)
}
var requestBody = {
client_id: clientId,
client_secret: clientSecret,
token: opts.accessToken
}
dispatch.sendRequest(requestBody, baseUrl + '/oauth/revoke', null)
.then((response) => {
resolve(response.body)
})
.catch((error) => {
reject(error)
})
})
}
/**
* Handles requests for introspecting an access token
* @function introspectToken
* @memberof TokenService
* @param {object} opts
* @param {string} opts.accessToken - The access token to be revoked.
* @returns {Promise} Promise object having the token_type, client_id, scope, active, exp(expiry time), iat(created time)
*/
this.introspectToken = function (opts) {
return new Promise(function (resolve, reject) {
let validationError = tokenValidate(opts)
if (validationError) {
reject(validationError)
}
var requestBody = {
client_id: clientId,
client_secret: clientSecret,
token: opts.accessToken
}
dispatch.sendRequest(requestBody, baseUrl + '/oauth/introspect', null)
.then((response) => {
resolve(response.body)
})
.catch((error) => {
reject(error)
})
})
}
/**
* Handles requests for getting information on the token
* @function infoToken
* @memberof TokenService
* @param {object} opts
* @param {string} opts.accessToken - The access token to be revoked.
* @returns {Promise} Promise object having the scope, expires_in, application.uid, created_at
*/
this.infoToken = function (opts) {
return new Promise(function (resolve, reject) {
let validationError = tokenValidate(opts)
if (validationError) {
reject(validationError)
}
dispatch.getContent(baseUrl + '/oauth/token/info', opts.accessToken)
.then((response) => {
resolve(response)
})
.catch((error) => {
reject(error)
})
})
}
}
module.exports = {
TokenService
}
|
tmitsuoka0423/obniz | dist/src/obniz/libs/wscommand/WSCommandDisplay.js | <reponame>tmitsuoka0423/obniz
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
/**
* @packageDocumentation
* @ignore
*/
const qr_1 = __importDefault(require("../utils/qr"));
const WSCommand_1 = __importDefault(require("./WSCommand"));
class WSCommandDisplay extends WSCommand_1.default {
constructor() {
super(...arguments);
this.module = 8;
this._CommandClear = 0;
this._CommandPrint = 1;
this._CommandDrawCampusVerticalBytes = 2;
this._CommandDrawCampusHorizonalBytes = 3;
this._CommandDrawIOState = 4;
this._CommandSetPinName = 5;
this._CommandDrawCampusRawColors = 6;
}
// Commands
clear(params) {
this.sendCommand(this._CommandClear, null);
}
print(buf) {
this.sendCommand(this._CommandPrint, buf);
}
printText(text) {
const buf = Buffer.from(text, "utf8");
const result = new Uint8Array(buf);
this.print(result);
}
text(params) {
this.printText(params.text);
}
raw(params) {
if (typeof params.color_depth === "number" && params.color_depth > 1) {
this.drawRawColors(params.raw, params.color_depth);
}
else {
this.drawHorizonally(new Uint8Array(params.raw));
}
}
qr(params) {
const text = params.qr.text;
const correctionLevel = params.qr.correction || "M";
const typeNumber = 0; // auto detect type.
const qr = qr_1.default(typeNumber, correctionLevel);
qr.addData(text);
qr.make();
let size = qr.getModuleCount();
if (size) {
size *= 2;
const modules = qr.getModules();
const vram = new Uint8Array(1024);
vram.fill(0);
for (let row = 0; row < 2; row++) {
for (let col = 0; col < size + 4; col++) {
vram[Math.floor(row * 16 + col / 8)] |= 0x80 >> col % 8;
vram[Math.floor((row + size + 2) * 16 + col / 8)] |= 0x80 >> col % 8;
}
}
for (let row = 2; row < size + 2; row++) {
for (let col = 0; col < 2; col++) {
vram[Math.floor(row * 16 + col / 8)] |= 0x80 >> col % 8;
}
for (let col = size + 2; col < size + 4; col++) {
vram[Math.floor(row * 16 + col / 8)] |= 0x80 >> col % 8;
}
}
for (let row = 0; row < size; row++) {
for (let col = 0; col < size; col++) {
if (!modules[Math.floor(row / 2)][Math.floor(col / 2)]) {
vram[Math.floor((row + 2) * 16 + (col + 2) / 8)] |= 0x80 >> (col + 2) % 8;
}
}
}
this.drawHorizonally(vram);
}
}
pinName(params) {
for (let i = 0; i < 40; i++) {
if (typeof params.pin_assign[i] === "object") {
this.setPinName(i, params.pin_assign[i].module_name || "?", params.pin_assign[i].pin_name || "?");
}
}
}
drawVertically(buf) {
this.sendCommand(this._CommandDrawCampusVerticalBytes, buf);
}
drawHorizonally(buf) {
this.sendCommand(this._CommandDrawCampusHorizonalBytes, buf);
}
drawIOState(val) {
const buf = new Uint8Array([!val ? 1 : 0]);
this.sendCommand(this._CommandDrawIOState, buf);
}
setPinName(no, moduleName, pinName) {
let str = moduleName.slice(0, 4) + " " + pinName;
str = str.slice(0, 9);
const buf = new Uint8Array(1);
buf[0] = no;
const stringarray = new Uint8Array(Buffer.from(str, "utf8"));
const combined = new Uint8Array(buf.length + stringarray.length);
combined.set(buf, 0);
combined.set(stringarray, 1);
this.sendCommand(this._CommandSetPinName, combined);
}
drawRawColors(raw, colorDepth) {
const buf = new Uint8Array(1 + raw.length);
buf[0] = colorDepth;
buf.set(raw, 1);
this.sendCommand(this._CommandDrawCampusRawColors, buf);
}
parseFromJson(json) {
const module = json.display;
if (module === undefined) {
return;
}
const schemaData = [
{ uri: "/request/display/clear", onValid: this.clear },
{ uri: "/request/display/text", onValid: this.text },
{ uri: "/request/display/raw", onValid: this.raw },
{ uri: "/request/display/pin_assign", onValid: this.pinName },
{ uri: "/request/display/qr", onValid: this.qr },
];
const res = this.validateCommandSchema(schemaData, module, "display");
if (res.valid === 0) {
if (res.invalidButLike.length > 0) {
throw new Error(res.invalidButLike[0].message);
}
else {
throw new this.WSCommandNotFoundError(`[display]unknown command`);
}
}
}
}
exports.default = WSCommandDisplay;
//# sourceMappingURL=WSCommandDisplay.js.map
|
hmc-room-draw/room-draw | test/controllers/draw_period_controller_test.rb | <gh_stars>1-10
require 'test_helper'
include Warden::Test::Helpers
Warden.test_mode!
## TODO: write test setup with current_user set
class DrawPeriodControllerTest < ActionDispatch::IntegrationTest
setup do
@draw_period = draw_periods(:one)
@user = User.create(
:first_name => "Bob",
:last_name => "Testerson",
:email => "<EMAIL>",
:is_admin => true,
)
login_as(@user)
# assert.equal(current_user, @user)
end
##
#test "should get index" do
# get draw_periods_url
# assert_response :success
#end
test "should get new" do
get new_draw_period_url
assert_response :success
end
##
#test "should create draw period" do
# assert_difference('DrawPeriod.count') do
# post draw_periods_url,
# params: { draw_period: {
# start_datetime: @draw_period.start_datetime,
# end_datetime: @draw_period.end_datetime,
# last_updated_by: @draw_period.last_updated_by
# }
# }
# end
# assert_redirected_to root_url
#end
##
#test "should show draw period" do
# get draw_period_url(@draw_period)
# assert_response :success
#end
test "should get edit" do
get edit_draw_period_url(@draw_period)
assert_response :success
end
##
#test "should update draw period" do
# patch draw_period_url(@draw_period),
# params: { draw_period: {
# start_datetime: @draw_period.start_datetime,
# end_datetime: @draw_period.end_datetime,
# last_updated_by: @draw_period.last_updated_by
# }
# }
# assert_redirected_to root_url
#end
test "should destroy draw_period" do
assert_difference('DrawPeriod.count', -1) do
delete draw_period_url(@draw_period)
end
assert_redirected_to draw_periods_url
end
end
|
ScalablyTyped/SlinkyTyped | o/office-ui-fabric-react/src/main/scala/typingsSlinky/officeUiFabricReact/shimmerLineBaseMod.scala | <gh_stars>10-100
package typingsSlinky.officeUiFabricReact
import slinky.core.ReactComponentClass
import typingsSlinky.officeUiFabricReact.shimmerLineTypesMod.IShimmerLineProps
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
object shimmerLineBaseMod {
@JSImport("office-ui-fabric-react/lib/components/Shimmer/ShimmerLine/ShimmerLine.base", "ShimmerLineBase")
@js.native
val ShimmerLineBase: ReactComponentClass[IShimmerLineProps] = js.native
}
|
ianmcdaniel/nova-www | src/components/common/ValuesList/index.js | export { default } from './ValuesList';
|
lehjr/MPA-Lib | src/main/java/com/github/lehjr/mpalib/client/render/MPALibRenderState.java | <gh_stars>0
/*
* Copyright (c) 2019 MachineMuse, Lehjr
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 OWNER OR CONTRIBUTORS 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.
*/
package com.github.lehjr.mpalib.client.render;
import com.github.lehjr.mpalib.basemod.MPALibConstants;
import com.mojang.blaze3d.platform.GlStateManager;
import com.mojang.blaze3d.systems.RenderSystem;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.RenderHelper;
import net.minecraft.client.renderer.RenderState;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL13C;
/**
* Author: MachineMuse (<NAME>)
* Created: 2:41 PM, 9/6/13
* <p>
* Ported to Java by lehjr on 10/23/16.
*/
@OnlyIn(Dist.CLIENT)
public final class MPALibRenderState {
public static final RenderState.TransparencyState TRANSLUCENT_TRANSPARENCY = new RenderState.TransparencyState("translucent_transparency_mpalib", () -> {
RenderSystem.enableBlend();
RenderSystem.blendFuncSeparate(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA, GlStateManager.SourceFactor.ONE, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA);
}, () -> {
RenderSystem.disableBlend();
RenderSystem.defaultBlendFunc();
});
public static final RenderState.DiffuseLightingState DIFFUSE_LIGHTING_ENABLED = new RenderState.DiffuseLightingState(true);
public static final RenderState.AlphaState DEFAULT_ALPHA = new RenderState.AlphaState(0.003921569F);
public static final RenderState.LightmapState LIGHTMAP_ENABLED = new RenderState.LightmapState(true);
public static final RenderState.OverlayState OVERLAY_ENABLED = new RenderState.OverlayState(true);
public static RenderType LIGHTNING_TEST() {
RenderType.State state = RenderType.State.getBuilder()
.texture(new RenderState.TextureState(MPALibConstants.LOCATION_MPALIB_GUI_TEXTURE_ATLAS, false, false))
.transparency(TRANSLUCENT_TRANSPARENCY)
.diffuseLighting(DIFFUSE_LIGHTING_ENABLED)
.alpha(DEFAULT_ALPHA)
.lightmap(LIGHTMAP_ENABLED)
.overlay(OVERLAY_ENABLED)
.build(true);
return RenderType.makeType(
"lighting_test",
DefaultVertexFormats.POSITION_COLOR_TEX_LIGHTMAP,
GL11.GL_QUADS, 256, true, true, state);
}
/**
* 2D rendering mode on/off
*/
public static void on2D() {
// GL11.glPushAttrib(GL11.GL_ENABLE_BIT);
// RenderSystem.pushLightingAttributes(); // might work?
glPushAttrib(GL11.GL_ENABLE_BIT);
// GL11.glDisable(GL11.GL_DEPTH_TEST);
RenderSystem.disableDepthTest();
// GL11.glDisable(GL11.GL_CULL_FACE);
RenderSystem.disableCull();
// GL11.glDisable(GL11.GL_LIGHTING);
RenderSystem.disableLighting();
}
public static void off2D() {
RenderSystem.popAttributes();
}
/**
* Arrays on/off
*/
public static void arraysOnColor() {
// GL11.glEnableClientState(GL11.GL_VERTEX_ARRAY);
GlStateManager.enableClientState(GL11.GL_VERTEX_ARRAY);
// GL11.glEnableClientState(GL11.GL_COLOR_ARRAY);
GlStateManager.enableClientState(GL11.GL_COLOR_ARRAY);
}
public static void arraysOnTexture() {
// GL11.glEnableClientState(GL11.GL_VERTEX_ARRAY);
GlStateManager.enableClientState(GL11.GL_VERTEX_ARRAY);
// GL11.glEnableClientState(GL11.GL_TEXTURE_COORD_ARRAY);
GlStateManager.enableClientState(GL11.GL_TEXTURE_COORD_ARRAY);
}
public static void arraysOff() {
// GL11.glDisableClientState(GL11.GL_VERTEX_ARRAY);
GlStateManager.disableClientState(GL11.GL_VERTEX_ARRAY);
// GL11.glDisableClientState(GL11.GL_COLOR_ARRAY);
GlStateManager.disableClientState(GL11.GL_COLOR_ARRAY);
// GL11.glDisableClientState(GL11.GL_TEXTURE_COORD_ARRAY);
GlStateManager.disableClientState(GL11.GL_TEXTURE_COORD_ARRAY);
}
/**
* Call before doing any pure geometry (ie. with colours rather than textures).
*/
public static void texturelessOn() {
// GL11.glDisable(GL11.GL_TEXTURE_2D);
RenderSystem.disableTexture();
}
/**
* Call after doing pure geometry (ie. with colours) to go back to the texture mode (default).
*/
public static void texturelessOff() {
// GL11.glEnable(GL11.GL_TEXTURE_2D);
RenderSystem.enableTexture();
}
/**
* Call before doing anything with alpha blending
*/
public static void blendingOn() {
// GL11.glPushAttrib(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_LIGHTING_BIT);
// if (Minecraft.isFancyGraphicsEnabled()) {
// GL11.glShadeModel(GL11.GL_SMOOTH);
// GL11.glDisable(GL11.GL_ALPHA_TEST);
// GL11.glEnable(GL11.GL_BLEND);
// GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
// }
RenderSystem.enableBlend();
}
/**
* Call after doing anything with alpha blending
*/
public static void blendingOff() {
// RenderSystem.popAttributes();
RenderSystem.disableBlend();
}
//
// public static void glColorPointer(int size, int stride, FloatBuffer pointer) {
// RenderSystem.assertThread(RenderSystem::isOnGameThread);
// GL11.nglColorPointer(size, GL11.GL_FLOAT, stride, memAddress(pointer));
// }
//
// public static void glVertexPointer(int size, int stride, FloatBuffer pointer) {
// RenderSystem.assertThread(RenderSystem::isOnGameThread);
// GL11.nglVertexPointer(size, GL11.GL_FLOAT, stride, memAddress(pointer));
// }
public static void glPushAttrib(int mask) {
RenderSystem.assertThread(RenderSystem::isOnGameThread);
GL11.glPushAttrib(mask);
}
public static void glEnable(int target) {
RenderSystem.assertThread(RenderSystem::isOnGameThread);
GL11.glEnable(target);
}
private static void glScissor(int newx, int newy, int neww, int newh) {
RenderSystem.assertThread(RenderSystem::isOnGameThread);
GL11.glScissor(newx, newy, neww, newh);
}
public static void scissorsOn(double x, double y, double w, double h) {
RenderSystem.assertThread(RenderSystem::isOnGameThread);
glPushAttrib(GL11.GL_ENABLE_BIT | GL11.GL_SCISSOR_BIT);
RenderSystem.pushMatrix();
Minecraft mc = Minecraft.getInstance();
int dh = mc.getMainWindow().getHeight();
double scaleFactor = mc.getMainWindow().getGuiScaleFactor();
double newx = x * scaleFactor;
double newy = dh - h * scaleFactor - y * scaleFactor;
double neww = w * scaleFactor;
double newh = h * scaleFactor;
glEnable(GL11.GL_SCISSOR_TEST);
glScissor((int) newx, (int) newy, (int) neww, (int) newh);
}
public static void scissorsOff() {
RenderSystem.popMatrix();
RenderSystem.popAttributes();
}
/**
* Used primarily for model rendering to make a surface "glow"
*
* Use light map value of something like 0x00F000F0 instead
*/
private static float lightmapLastX = .0f;
private static float lightmapLastY = .0f;
@Deprecated
public static void glowOn() {
glPushAttrib(GL11.GL_LIGHTING_BIT);
lightmapLastX = GlStateManager.lastBrightnessX;
lightmapLastY = GlStateManager.lastBrightnessY;
RenderHelper.disableStandardItemLighting();
GlStateManager.multiTexCoord2f(GL13C.GL_TEXTURE1, 240.0F, 240.0F);
}
@Deprecated
public static void glowOff() {
GlStateManager.multiTexCoord2f(GL13C.GL_TEXTURE1, lightmapLastX, lightmapLastY);
RenderHelper.enableStandardItemLighting();
RenderSystem.popAttributes();
}
} |
LJW123/YiLianMall | YiLian/src/main/java/com/yilian/mall/ctrip/bean/PriceAndLevelSelectBean.java | package com.yilian.mall.ctrip.bean;
import java.util.List;
/**
* ไฝ่
๏ผ้ฉฌ้่ถ
on 2018/11/2 12:03
*/
public class PriceAndLevelSelectBean {
public String MinPrice;
public String MaxPrice;
public List<String> levelId ;
public String minRange;
public String maxRange;
public String getMinPrice() {
return MinPrice;
}
public String getMaxPrice() {
return MaxPrice;
}
public List<String> getLevelId() {
return levelId;
}
public String getMinRange() {
return minRange;
}
public String getMaxRange() {
return maxRange;
}
public void setMinPrice(String minPrice) {
MinPrice = minPrice;
}
public void setMaxPrice(String maxPrice) {
MaxPrice = maxPrice;
}
public void setLevelId(List<String> levelId) {
this.levelId = levelId;
}
public void setMinRange(String minRange) {
this.minRange = minRange;
}
public void setMaxRange(String maxRange) {
this.maxRange = maxRange;
}
}
|
andrei-punko/java-interview | src/test/java/by/andd3dfx/cache/LFUCacheTest.java | package by.andd3dfx.cache;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import by.andd3dfx.cache.LFUCache;
import org.junit.Test;
public class LFUCacheTest {
@Test
public void testCache() {
LFUCache cache = new LFUCache(2);
cache.put(1, 1);
cache.put(2, 2);
assertThat("returns 1", cache.get(1), is(1));
cache.put(3, 3); // evicts key 2
assertThat("returns -1 (not found)", cache.get(2), is(-1));
assertThat("returns 3", cache.get(3), is(3));
cache.put(4, 4); // evicts key 1
assertThat("returns -1 (not found)", cache.get(1), is(-1));
assertThat("returns 3", cache.get(3), is(3));
assertThat("returns 4", cache.get(4), is(4));
}
@Test
public void testCache2() {
LFUCache cache = new LFUCache(2);
cache.put(2, 1);
cache.put(3, 2);
assertThat("returns 2", cache.get(3), is(2));
assertThat("returns 1", cache.get(2), is(1));
cache.put(4, 3);
assertThat("returns 1", cache.get(2), is(1));
assertThat("returns -1", cache.get(3), is(-1));
assertThat("returns 3", cache.get(4), is(3));
}
@Test
public void testCacheForZeroCapacity() {
LFUCache cache = new LFUCache(0);
assertThat("returns -1", cache.get(2), is(-1));
cache.put(2, 1);
assertThat("returns -1", cache.get(2), is(-1));
}
}
|
mehmetalikir/Programlamaya-Giris | Y. Daniel Liang-Java/src/chapter09/Exercise09_04.java | package chapter09;
import java.util.Random;
/**
* # Author: <NAME>
* # Email : <EMAIL>
* # https://github.com/mehmetalikir
* ***********************************
(Use the Random class) Write a program that creates a Random object with seed
1000 and displays the first 50 random integers between 0 and 100 using the
nextInt(100) method.
* ***********************************
*/
public class Exercise09_04 {
public static void main(String[] args) {
Random random1 = new Random(1000);
System.out.print("From random1: ");
for (int i = 0; i <= 50; i++)
System.out.print(random1.nextInt(100) + " ");
System.out.println(" ");
Random random2 = new Random(3);
System.out.print("From random2: ");
for (int i = 0; i <= 50; i++)
System.out.print(random2.nextInt(100) + " ");
}
}
|
Darinth/NaturalFury | Code/Source/LocalPlayerView.cpp | // Name:
// LocalPlayerView.cpp
// Description:
// Implementation file for LocalPlayerView class
// Notes:
// OS-Unaware
#include "CustomMemory.h"
#include "LocalPlayerView.h"
#include "GameEngine.h"
#include "EngineMsg.h"
extern GameEngine *gameEngine;
LocalPlayerView::LocalPlayerView() : PlayerView()//("Game Engine", "GameEngine", false, 800, 450, 32)
{
}
LocalPlayerView::~LocalPlayerView()
{
}
void LocalPlayerView::sendMsg(const shared_ptr<EngineMsg>& msg)
{
}
void LocalPlayerView::windowClosed()
{
//On window close, tell the engine to shut down.
gameEngine->sendMsg(shared_ptr<EngineMsg>(new EngineMsgShutdown()));
}
|
confitarlaburra/pteros2.0 | html/dir_ae2d53ebb4ae191eb5a981cea757ef7a.js | <reponame>confitarlaburra/pteros2.0<gh_stars>0
var dir_ae2d53ebb4ae191eb5a981cea757ef7a =
[
[ "ColPivHouseholderQR.h", "ColPivHouseholderQR_8h_source.html", null ],
[ "ColPivHouseholderQR_LAPACKE.h", "ColPivHouseholderQR__LAPACKE_8h_source.html", null ],
[ "CompleteOrthogonalDecomposition.h", "CompleteOrthogonalDecomposition_8h_source.html", null ],
[ "FullPivHouseholderQR.h", "FullPivHouseholderQR_8h_source.html", null ],
[ "HouseholderQR.h", "HouseholderQR_8h_source.html", null ],
[ "HouseholderQR_LAPACKE.h", "HouseholderQR__LAPACKE_8h_source.html", null ]
]; |
mrodgers25/sap3- | db/migrate/20210314182416_add_queue_position_to_published_items.rb | class AddQueuePositionToPublishedItems < ActiveRecord::Migration[6.1]
def change
add_column :published_items, :queue_position, :integer
add_index :published_items, :queue_position
end
end
|
jsheridanwells/LivePollingInterface | app/controllers/index.js | <filename>app/controllers/index.js
'use strict';
let app = require('../../lib/node_modules/angular').module('LivePolling');
app.controller('navCtrl', require('./navCtrl'));
app.controller('pollCtrl', require('./pollCtrl'));
app.controller('newPresentationCtrl', require('./newPresentationCtrl'));
app.controller('participantCtrl', require('./participantCtrl'));
app.controller('presentationsCtrl', require('./presentationsCtrl'));
app.controller('showPresentationCtrl', require('./showPresentationCtrl'));
app.controller('userCtrl', require('./userCtrl'));
app.controller('editUserCtrl', require('./editUserCtrl'));
|
spivachuk/distributed-compliance-ledger | x/dclgenutil/utils_test.go | package dclgenutil
/*
import (
"encoding/json"
"os"
"path/filepath"
"testing"
"time"
"github.com/stretchr/testify/require"
"github.com/tendermint/tendermint/config"
tmed25519 "github.com/tendermint/tendermint/crypto/ed25519"
"github.com/tendermint/tendermint/privval"
)
func TestExportGenesisFileWithTime(t *testing.T) {
t.Parallel()
fname := filepath.Join(t.TempDir(), "genesis.json")
require.NoError(t, ExportGenesisFileWithTime(fname, "test", nil, json.RawMessage(`{"account_owner": "Bob"}`), time.Now()))
}
func TestInitializeNodeValidatorFilesFromMnemonic(t *testing.T) {
t.Parallel()
cfg := config.TestConfig()
cfg.RootDir = t.TempDir()
require.NoError(t, os.MkdirAll(filepath.Join(cfg.RootDir, "config"), 0755))
tests := []struct {
name string
mnemonic string
expError bool
}{
{
name: "invalid mnemonic returns error",
mnemonic: "side video kiss hotel essence",
expError: true,
},
{
name: "empty mnemonic does not return error",
mnemonic: "",
expError: false,
},
{
name: "valid mnemonic does not return error",
mnemonic: "side video kiss hotel essence door angle student degree during vague adjust submit trick globe muscle frozen vacuum artwork million shield bind useful wave",
expError: false,
},
}
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
_, _, err := InitializeNodeValidatorFilesFromMnemonic(cfg, tt.mnemonic)
if tt.expError {
require.Error(t, err)
} else {
require.NoError(t, err)
if tt.mnemonic != "" {
actualPVFile, _ := privval.LoadFilePV(cfg.PrivValidator.KeyFile(), cfg.PrivValidator.StateFile())
expectedPrivateKey := tmed25519.GenPrivKeyFromSecret([]byte(tt.mnemonic))
expectedFile := privval.NewFilePV(expectedPrivateKey, cfg.PrivValidator.KeyFile(), cfg.PrivValidator.StateFile())
require.Equal(t, expectedFile, actualPVFile)
}
}
})
}
}
*/
|
GianpieroSportelli/ConversationalAgent | src/test/java/test/Tint/TintTest.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package test.Tint;
import configuration.Config;
import edu.stanford.nlp.pipeline.Annotation;
import eu.fbk.dh.tint.runner.TintPipeline;
import eu.fbk.dh.tint.runner.TintRunner;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import org.json.JSONObject;
/**
*
* @author SPORT
*/
public class TintTest {
public static void main(String[] args) throws IOException {
String input = "alle 4 di domaini mattina, ora, tra 1 minuto, per 2 ore, mercoledi prossimo, questa settimana, giovedi scorso, la prossima settimana, il prossimo mese ho speso 200 euro";
String output="";
TintPipeline pipeline = new TintPipeline();
//pipeline.loadDefaultProperties();
System.out.println(Config.PATH_TINTCONF);
pipeline.loadPropertiesFromFile(new File(Config.PATH_TINTCONF));
pipeline.load();
InputStream stream = new ByteArrayInputStream(input.getBytes(StandardCharsets.UTF_8));
ByteArrayOutputStream out=new ByteArrayOutputStream();
pipeline.run(stream, out, TintRunner.OutputFormat.JSON);
output=new String(out.toByteArray());
JSONObject json=new JSONObject(output);
System.out.println(output);
System.out.println("JSON:\n"+json.getJSONArray("sentences").getJSONObject(0).getJSONArray("tokens").toString(4));
}
}
|
rjknight123/p9-skminer | cuda_helper.h | #ifndef CUDA_HELPER_H
#define CUDA_HELPER_H
#ifdef __INTELLISENSE__
#define __launch_bounds__(x)
#endif
#define v32(x,y) ((uint32_t*)(x))[((y) & 1)+2*(((y)/2)*threads+thread)] //hugly but needed to deal with the hash packing
static __device__ uint64_t MAKE_ULONGLONG(uint32_t LO, uint32_t HI)
{
return __double_as_longlong(__hiloint2double(HI, LO));
}
static __device__ uint32_t HIWORD(uint64_t x)
{
return (uint32_t)__double2hiint(__longlong_as_double(x));
}
static __device__ void LOHI(uint32_t &lo, uint32_t &hi, uint64_t x)
{
asm("{\n\t"
"mov.b64 {%0,%1},%2; \n\t"
"}"
: "=r"(lo), "=r"(hi) : "l"(x));
}
static __device__ uint32_t LOWORD(uint64_t x)
{
return (uint32_t)__double2hiint(__longlong_as_double(x));
}
// das Hi Word aus einem 64 Bit Typen extrahieren
#if __CUDA_ARCH__ < 350
// Kepler (Compute 3.0)
#define SPH_ROTL32(x, n) SPH_T32(((x) << (n)) | ((x) >> (32 - (n))))
#define SPH_ROTR32(x, n) (((x) >> (n)) | ((x) << (32 - (n))))
#else
// Kepler (Compute 3.5)
#define SPH_ROTL32(x, n) __funnelshift_l( (x), (x), (n) )
#define SPH_ROTR32(x, n) __funnelshift_r( (x), (x), (n) )
#endif
// das Hi Word in einem 64 Bit Typen ersetzen
static __device__ uint64_t oREPLACE_HIWORD(const uint64_t &x, const uint32_t &y) {
return (x & 0xFFFFFFFFULL) | (((uint64_t)y) << 32ULL);
}
static __host__ uint2 lohi_host(const uint64_t x)
{
uint2 res;
res.x = (uint32_t)(x & 0xFFFFFFFFULL);
res.y = (uint32_t)(x >> 32);
return res;
}
static __host__ uint64_t make64_host(const uint2 x)
{
return (uint64_t)x.x | (((uint64_t)x.y) << 32);
}
static __device__ uint64_t REPLACE_HIWORD(uint64_t x, uint32_t y) {
return (x & 0xFFFFFFFFULL) | (((uint64_t)y) << 32U);
}
static __device__ uint64_t REPLACE_LOWORD(uint64_t x, uint32_t y) {
return (x & 0xFFFFFFFF00000000ULL) | ((uint64_t)y);
}
__forceinline__ __device__ uint64_t sph_t64(uint64_t x)
{
uint64_t result;
asm("{\n\t"
"and.b64 %0,%1,0xFFFFFFFFFFFFFFFF;\n\t"
"}\n\t"
: "=l"(result) : "l"(x));
return result;
}
__forceinline__ __device__ uint32_t sph_t32(uint32_t x)
{
uint32_t result;
asm("{\n\t"
"and.b32 %0,%1,0xFFFFFFFF;\n\t"
"}\n\t"
: "=r"(result) : "r"(x));
return result;
}
__forceinline__ __device__ uint64_t shr_t64(uint64_t x, uint32_t n)
{
uint64_t result;
asm("{\n\t"
"shr.b64 %0,%1,%2;\n\t"
"}\n\t"
: "=l"(result) : "l"(x), "r"(n));
return result;
}
__forceinline__ __device__ uint64_t shl_t64(uint64_t x, uint32_t n)
{
uint64_t result;
asm("{\n\t"
"shl.b64 %0,%1,%2;\n\t"
"}\n\t"
: "=l"(result) : "l"(x), "r"(n));
return result;
}
__forceinline__ __device__ uint32_t shr_t32(uint32_t x, uint32_t n)
{
uint32_t result;
asm("{\n\t"
"shr.b32 %0,%1,%2;\n\t"
"}\n\t"
: "=r"(result) : "r"(x), "r"(n));
return result;
}
__forceinline__ __device__ uint32_t shl_t32(uint32_t x, uint32_t n)
{
uint32_t result;
asm("{\n\t"
"shl.b32 %0,%1,%2;\n\t"
"}\n\t"
: "=r"(result) : "r"(x), "r"(n));
return result;
}
__forceinline__ __device__ uint64_t mul(uint64_t a, uint64_t b)
{
uint64_t result;
asm("{\n\t"
"mul.lo.u64 %0,%1,%2; \n\t"
"}\n\t"
: "=l"(result) : "l"(a), "l"(b));
return result;
}
///uint2 method
#if __CUDA_ARCH__ >= 350
__inline__ __device__ uint2 ROR2(const uint2 a, const int offset) {
uint2 result;
if (offset < 32) {
asm("shf.r.wrap.b32 %0, %1, %2, %3;" : "=r"(result.x) : "r"(a.x), "r"(a.y), "r"(offset));
asm("shf.r.wrap.b32 %0, %1, %2, %3;" : "=r"(result.y) : "r"(a.y), "r"(a.x), "r"(offset));
}
else {
asm("shf.r.wrap.b32 %0, %1, %2, %3;" : "=r"(result.x) : "r"(a.y), "r"(a.x), "r"(offset));
asm("shf.r.wrap.b32 %0, %1, %2, %3;" : "=r"(result.y) : "r"(a.x), "r"(a.y), "r"(offset));
}
return result;
}
#else
__inline__ __device__ uint2 ROR2(const uint2 v, const int n) {
uint2 result;
result.x = (((v.x) >> (n)) | ((v.x) << (64 - (n))));
result.y = (((v.y) >> (n)) | ((v.y) << (64 - (n))));
return result;
}
#endif
#if __CUDA_ARCH__ >= 350
__inline__ __device__ uint2 ROL2(const uint2 a, const int offset) {
uint2 result;
if (offset >= 32) {
asm("shf.l.wrap.b32 %0, %1, %2, %3;" : "=r"(result.x) : "r"(a.x), "r"(a.y), "r"(offset));
asm("shf.l.wrap.b32 %0, %1, %2, %3;" : "=r"(result.y) : "r"(a.y), "r"(a.x), "r"(offset));
}
else {
asm("shf.l.wrap.b32 %0, %1, %2, %3;" : "=r"(result.x) : "r"(a.y), "r"(a.x), "r"(offset));
asm("shf.l.wrap.b32 %0, %1, %2, %3;" : "=r"(result.y) : "r"(a.x), "r"(a.y), "r"(offset));
}
return result;
}
#else
__inline__ __device__ uint2 ROL2(const uint2 v, const int n) {
uint2 result;
result.x = (((v.x) << (n)) | ((v.x) >> (64 - (n))));
result.y = (((v.y) << (n)) | ((v.y) >> (64 - (n))));
return result;
}
#endif
static __forceinline__ __device__ uint64_t devectorize(uint2 v) { return MAKE_ULONGLONG(v.x, v.y); }
static __forceinline__ __device__ uint2 vectorize(uint64_t v) {
uint2 result;
LOHI(result.x, result.y, v);
return result;
}
static __forceinline__ __device__ uint2 xor2(uint2 a, uint2 b) {
uint2 result;
asm("xor.b32 %0, %1, %2;" : "=r"(result.x) : "r"(a.x), "r"(b.x));
asm("xor.b32 %0, %1, %2;" : "=r"(result.y) : "r"(a.y), "r"(b.y));
return result;
}
static __forceinline__ __device__ uint2 operator^ (uint2 a, uint2 b) { return make_uint2(a.x ^ b.x, a.y ^ b.y); }
static __forceinline__ __device__ uint2 operator& (uint2 a, uint2 b) { return make_uint2(a.x & b.x, a.y & b.y); }
static __forceinline__ __device__ uint2 operator| (uint2 a, uint2 b) { return make_uint2(a.x | b.x, a.y | b.y); }
static __forceinline__ __device__ uint2 operator~ (uint2 a) { return make_uint2(~a.x, ~a.y); }
static __forceinline__ __device__ void operator^= (uint2 &a, uint2 b) { a = a ^ b; }
static __device__ __forceinline__ uint2 operator+ (const uint2 a, const uint2 b) {
#if defined(__CUDA_ARCH__) && CUDA_VERSION < 7000
uint2 result;
asm("{\n\t"
"add.cc.u32 %0,%2,%4; \n\t"
"addc.u32 %1,%3,%5; \n\t"
"}\n\t"
: "=r"(result.x), "=r"(result.y) : "r"(a.x), "r"(a.y), "r"(b.x), "r"(b.y));
return result;
#else
return vectorize(devectorize(a) + devectorize(b));
#endif
}
static __forceinline__ __device__ void operator+= (uint2 &a, uint2 b) { a = a + b; }
static __forceinline__ __device__ uint2 operator* (uint2 a, uint2 b)
{ //basic multiplication between 64bit no carry outside that range (ie mul.lo.b64(a*b))
//(what does uint64 "*" operator)
uint2 result;
asm("{\n\t"
"mul.lo.u32 %0,%2,%4; \n\t"
"mul.hi.u32 %1,%2,%4; \n\t"
"mad.lo.cc.u32 %1,%3,%4,%1; \n\t"
"madc.lo.u32 %1,%3,%5,%1; \n\t"
"}\n\t"
: "=r"(result.x), "=r"(result.y) : "r"(a.x), "r"(a.y), "r"(b.x), "r"(b.y));
return result;
}
#if __CUDA_ARCH__ >= 350
static __forceinline__ __device__ uint2 shiftl2(uint2 a, int offset)
{
uint2 result;
if (offset<32) {
asm("{\n\t"
"shf.l.clamp.b32 %1,%2,%3,%4; \n\t"
"shl.b32 %0,%2,%4; \n\t"
"}\n\t"
: "=r"(result.x), "=r"(result.y) : "r"(a.x), "r"(a.y), "r"(offset));
}
else {
asm("{\n\t"
"shf.l.clamp.b32 %1,%2,%3,%4; \n\t"
"shl.b32 %0,%2,%4; \n\t"
"}\n\t"
: "=r"(result.x), "=r"(result.y) : "r"(a.y), "r"(a.x), "r"(offset));
}
return result;
}
static __forceinline__ __device__ uint2 shiftr2(uint2 a, int offset)
{
uint2 result;
if (offset<32) {
asm("{\n\t"
"shf.r.clamp.b32 %0,%2,%3,%4; \n\t"
"shr.b32 %1,%3,%4; \n\t"
"}\n\t"
: "=r"(result.x), "=r"(result.y) : "r"(a.x), "r"(a.y), "r"(offset));
}
else {
asm("{\n\t"
"shf.l.clamp.b32 %0,%2,%3,%4; \n\t"
"shl.b32 %1,%3,%4; \n\t"
"}\n\t"
: "=r"(result.x), "=r"(result.y) : "r"(a.y), "r"(a.x), "r"(offset));
}
return result;
}
#else
static __forceinline__ __device__ uint2 shiftl2(uint2 a, int offset)
{
uint2 result;
asm("{\n\t"
".reg .b64 u,v; \n\t"
"mov.b64 v,{%2,%3}; \n\t"
"shl.b64 u,v,%4; \n\t"
"mov.b64 {%0,%1},v; \n\t"
"}\n\t"
: "=r"(result.x), "=r"(result.y) : "r"(a.x), "r"(a.y), "r"(offset));
return result;
}
static __forceinline__ __device__ uint2 shiftr2(uint2 a, int offset)
{
uint2 result;
asm("{\n\t"
".reg .b64 u,v; \n\t"
"mov.b64 v,{%2,%3}; \n\t"
"shr.b64 u,v,%4; \n\t"
"mov.b64 {%0,%1},v; \n\t"
"}\n\t"
: "=r"(result.x), "=r"(result.y) : "r"(a.x), "r"(a.y), "r"(offset));
return result;
}
#endif
#endif // #ifndef CUDA_HELPER_H
|
sky-bro/AC | leetcode.com/Weekly Contest 223/4/main.cpp | <filename>leetcode.com/Weekly Contest 223/4/main.cpp
#include <bits/stdc++.h>
using namespace std;
static int x = []() {
std::ios::sync_with_stdio(false);
cin.tie(0);
return 0;
}();
typedef long long ll;
int sums[1 << 12], dp[1 << 12];
class Solution {
public:
int minimumTimeRequired(vector<int>& jobs, int k) {
int n = jobs.size();
for (int mask = 1; mask < (1 << n); mask++) {
for (int i = 0; i < n; i++)
if (mask & (1 << i)) {
sums[mask] = dp[mask] = jobs[i] + sums[mask ^ (1 << i)];
break;
}
}
while (--k) {
for (int mask = (1 << n) - 1; mask; mask--) {
int other = mask;
for (int other = mask; other; other = (other - 1) & mask) {
dp[mask] = min(dp[mask], max(dp[mask ^ other], sums[other]));
}
}
}
return dp[(1 << n) - 1];
}
};
int main(int argc, char const* argv[]) {
Solution s;
vector<int> A = {1, 2, 4, 7, 8};
int k = 2;
// A = {5, 15, 4, 9, 15, 8, 8, 9};
// k = 2;
cout << s.minimumTimeRequired(A, k) << endl;
return 0;
}
|
ariefzuhri/Amigo19 | app/src/main/java/com/ariefzuhri/amigo19/response/WCUCountry.java | <filename>app/src/main/java/com/ariefzuhri/amigo19/response/WCUCountry.java
package com.ariefzuhri.amigo19.response;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class WCUCountry {
@SerializedName("name")
@Expose
private String name;
@SerializedName("iso2")
@Expose
private String iso2;
@SerializedName("iso3")
@Expose
private String iso3;
public String getName() {
return name;
}
public String getIso2() {
return iso2;
}
public String getIso3() {
return iso3;
}
}
|
ECOA-developer/Open_Source_ECOA_Toolset_AS5 | osets-eclipse-plugin/src/com/iawg/ecoa/platformgen/pd/servicemanager/ServiceManagerGenerator.java | <gh_stars>1-10
/*
* Copyright 2017, BAE Systems Limited and GE Aviation Limited.
*
* This software and its outputs are not claimed to be fit or safe for any purpose. Any user should
* satisfy themselves that this software or its outputs are appropriate for its intended purpose.
*/
package com.iawg.ecoa.platformgen.pd.servicemanager;
import java.nio.file.Path;
import com.iawg.ecoa.platformgen.PlatformGenerator;
import com.iawg.ecoa.systemmodel.deployment.SM_ProtectionDomain;
public class ServiceManagerGenerator {
private PlatformGenerator platformGenerator;
private SM_ProtectionDomain protectionDomain;
public ServiceManagerGenerator(PlatformGenerator platformGenerator, SM_ProtectionDomain pd) {
this.platformGenerator = platformGenerator;
this.protectionDomain = pd;
}
public void generate() {
Path directory = platformGenerator.getPdOutputDir();
ServiceManagerWriterC servManagerHeaderWriter = new ServiceManagerWriterC(platformGenerator, true, directory.resolve("inc-gen/"), protectionDomain);
ServiceManagerWriterC servManagerBodyWriter = new ServiceManagerWriterC(platformGenerator, false, directory.resolve("src-gen/"), protectionDomain);
// Open the file
servManagerHeaderWriter.open();
servManagerBodyWriter.open();
// Write the start of file
servManagerHeaderWriter.writePreamble();
servManagerBodyWriter.writePreamble();
// Write the definition of the service availability structure
servManagerHeaderWriter.writeServiceAvailabilityStruct();
// Write the declaration of the service availability list
servManagerBodyWriter.writeServiceAvailablityDecl();
// Write the get service availability function
servManagerHeaderWriter.writeGetServiceAvail();
servManagerBodyWriter.writeGetServiceAvail();
// Write the set service availability function
servManagerHeaderWriter.writeSetServiceAvail();
servManagerBodyWriter.writeSetServiceAvail();
// Write the set service availability function
servManagerHeaderWriter.writeSetProviderUnavailable();
servManagerBodyWriter.writeSetProviderUnavailable();
// Write the initialisation function
servManagerHeaderWriter.writeInitialise();
servManagerBodyWriter.writeInitialise();
// Write all the includes
servManagerHeaderWriter.writeIncludes();
servManagerBodyWriter.writeIncludes();
// Close the file.
servManagerHeaderWriter.close();
servManagerBodyWriter.close();
}
}
|
holger-bauer/basex | basex-core/src/main/java/org/basex/query/value/item/Dat.java | package org.basex.query.value.item;
import static org.basex.query.QueryError.*;
import static org.basex.query.QueryText.*;
import org.basex.query.*;
import org.basex.query.value.type.*;
import org.basex.util.*;
/**
* Date item ({@code xs:date}).
*
* @author BaseX Team 2005-20, BSD License
* @author <NAME>
*/
public final class Dat extends ADate {
/**
* Constructor.
* @param value date
*/
public Dat(final ADate value) {
super(AtomType.DATE, value);
clean();
}
/**
* Constructor.
* @param value date
* @param ii input info
* @throws QueryException query exception
*/
public Dat(final byte[] value, final InputInfo ii) throws QueryException {
super(AtomType.DATE);
date(value, XDATE, ii);
}
/**
* Constructor.
* @param value date
* @param dur duration
* @param plus plus/minus flag
* @param ii input info
* @throws QueryException query exception
*/
public Dat(final Dat value, final Dur dur, final boolean plus, final InputInfo ii)
throws QueryException {
this(value);
if(dur instanceof DTDur) {
calc((DTDur) dur, plus);
if(yea <= MIN_YEAR || yea > MAX_YEAR) throw YEARRANGE_X.get(ii, yea);
} else {
calc((YMDur) dur, plus, ii);
}
clean();
}
@Override
public void timeZone(final DTDur zone, final boolean spec, final InputInfo ii)
throws QueryException {
tz(zone, spec, ii);
clean();
}
/**
* Cleans the item and removes invalid components.
*/
private void clean() {
hou = -1;
min = -1;
sec = null;
}
}
|
SilinPavel/grid-engine-api | src/main/java/com/epam/grid/engine/controller/usage/UsageOperationController.java | /*
*
* * Copyright 2022 EPAM Systems, Inc. (https://www.epam.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.epam.grid.engine.controller.usage;
import com.epam.grid.engine.entity.usage.UsageReport;
import com.epam.grid.engine.entity.usage.UsageReportFilter;
import com.epam.grid.engine.service.UsageOperationProviderService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
/**
* This controller handles usage-related requests addressed to preassigned grid engine system.
*/
@RestController
@RequestMapping("/usage")
@RequiredArgsConstructor
public class UsageOperationController {
private static final String NOT_FOUND = "Requested usage report not found";
private static final String INTERNAL_ERROR = "Internal error";
private static final String SUCCESSFULLY_RECEIVED = "Usage report received successfully";
private static final String MISSING_OR_INVALID_REQUEST_BODY = "Missing or invalid request body";
private final UsageOperationProviderService usageOperationProviderService;
/**
* Returns a report containing usage summary information.
*
* @param filter List of keys for setting filters.
* @return the usage report
* @see UsageReport
*/
@PostMapping
@ResponseStatus(HttpStatus.OK)
@ApiOperation(value = "Provides usage report",
notes = "Returns a report containing usage summary information",
produces = MediaType.APPLICATION_JSON_VALUE
)
@ApiResponses(value = {
@ApiResponse(code = 200, message = SUCCESSFULLY_RECEIVED),
@ApiResponse(code = 400, message = MISSING_OR_INVALID_REQUEST_BODY),
@ApiResponse(code = 404, message = NOT_FOUND),
@ApiResponse(code = 500, message = INTERNAL_ERROR)
})
public UsageReport getUsageReport(@RequestBody final UsageReportFilter filter) {
return usageOperationProviderService.getUsageReport(filter);
}
}
|
wujifengcn/binary-proto | binary-proto-java/src/test/java/test/com/jd/binaryproto/contract/PrivilegeModelSetting.java | package test.com.jd.binaryproto.contract;
import com.jd.binaryproto.DataContract;
import com.jd.binaryproto.DataField;
import com.jd.binaryproto.PrimitiveType;
/**
* Created by zhangshuang3 on 2018/7/30.
*/
@DataContract(code=0x0f, name="PrivilegeModelSetting", description ="Privilege Model setting")
public interface PrivilegeModelSetting {
@DataField(order=1, primitiveType= PrimitiveType.INT64)
long getLatestVersion();
//@DataField(order=2, refContract=true)
//Privilege getPrivilege(long version);
}
|
gmwang18/pyscf | pbc/tests/untested/test_diamond_He.py | <filename>pbc/tests/untested/test_diamond_He.py
import scipy
import numpy as np
import ase
import pyscf.pbc.tools
import pyscf.pbc.tools.pyscf_ase as pyscf_ase
import pyscf.pbc.gto as pbcgto
import pyscf.pbc.dft as pbcdft
import pyscf.pbc.scf.kscf
import ase.lattice
from ase.lattice.cubic import Diamond
import ase.dft.kpoints
pi=np.pi
def test_cubic_diamond_He():
"""
Take ASE Diamond structure, input into PySCF and run
"""
ase_atom=Diamond(symbol='He', latticeconstant=3.5)
print ase_atom.get_volume()
cell = pbcgto.Cell()
cell.atom=pyscf_ase.ase_atoms_to_pyscf(ase_atom)
cell.a=ase_atom.cell
cell.basis = {"He" : [[0, (1.0, 1.0)], [0, (0.8, 1.0)]] }
cell.gs = np.array([15,15,15])
# cell.verbose = 7
cell.build(None, None)
mf = pbcdft.RKS(cell)
mf.analytic_int=False
mf.xc = 'lda,vwn'
print mf.scf()
# Diamond cubic: -18.2278622592408
mf = pbcdft.RKS(cell)
mf.analytic_int=True
mf.xc = 'lda,vwn'
print mf.scf()
# Diamond cubic (analytic): -18.2278622592283
# = -4.556965564807075 / cell
# K pt calc
scaled_kpts=ase.dft.kpoints.monkhorst_pack((2,2,2))
abs_kpts=cell.get_abs_kpts(scaled_kpts)
kmf = pyscf.pbc.scf.kscf.KRKS(cell, abs_kpts)
kmf.analytic_int=False
kmf.xc = 'lda,vwn'
print kmf.scf()
# Diamond cubic (2x2x2): -18.1970946252
# = -4.5492736563 / cell
def test_diamond_He():
from ase.lattice import bulk
from ase.dft.kpoints import ibz_points, get_bandpath
He = bulk('He', 'diamond', a=3.5)
cell = pbcgto.Cell()
cell.atom=pyscf_ase.ase_atoms_to_pyscf(He)
cell.a=He.cell
cell.basis = {"He" : [[0, (1.0, 1.0)], [0, (0.8, 1.0)]] }
# cell.pseudo = 'gth-pade'
cell.gs=np.array([15,15,15])
cell.verbose=7
cell.build(None,None)
# replicate cell NxNxN
repcell = pyscf.pbc.tools.replicate_cell(cell, (2,2,2))
mf = pbcdft.RKS(repcell)
mf.analytic_int=False
mf.xc = 'lda,vwn'
# 1x1x1 Gamma -4.59565988176
# 2x2x2 Gamma [10x10x10 grid] -36.4239485658445
# = -4.552993570730562 / cell
# [20x20x20 grid] -4.55312928715 / cell
#
# 3x3x3 Gamma [15x15x15 grid] -4.553523556740741 / cell
# Diamond cubic: -4.56518345190625
scaled_kpts=ase.dft.kpoints.monkhorst_pack((3,3,3))
abs_kpts=cell.get_abs_kpts(scaled_kpts)
kmf = pyscf.pbc.scf.kscf.KRKS(cell, abs_kpts)
kmf.analytic_int=False
kmf.xc = 'lda,vwn'
kmf.scf()
# 2x2x2 K-pt: [15x15x15] grid -4.54824938484
# 3x3x3 K-pt: [15x15x15] grid -4.55034210881
#
# See test_pyscf_He (for diamond Cubic)
# Diamond cubic (2x2x2): -18.1970946252
# = -4.5492736563 / cell
|
RichardBlazek/objsdl | event.h | <reponame>RichardBlazek/objsdl
#pragma once
#include "events/type.h"
#include "events/structures.h"
namespace events
{
class Event
{
private:
SDL_Event event;
Event(const SDL_Event& evt):event(evt){}
public:
friend class Iterator;
enum class Action: uint8
{
Add=SDL_ADDEVENT,
Peek=SDL_PEEKEVENT,
Get=SDL_GETEVENT
};
Event()noexcept=default;
events::MouseWheel MouseWheel()const
{
return events::MouseWheel{event.wheel.windowID, event.wheel.which!=SDL_TOUCH_MOUSEID, Point(event.wheel.x, event.wheel.y)* (event.wheel.direction==SDL_MOUSEWHEEL_FLIPPED?-1:1)};
}
events::MouseMotion MouseMotion()const
{
return events::MouseMotion{event.motion.windowID, event.motion.which!=SDL_TOUCH_MOUSEID, MouseButtonMask(event.motion.state), Point(event.motion.x, event.motion.y), Point(event.motion.xrel, event.motion.yrel)};
}
events::MouseButton MouseButton()const
{
return events::MouseButton{event.button.windowID, event.button.which!=SDL_TOUCH_MOUSEID, SDL::MouseButton(event.button.button), Point(event.button.x, event.button.y), event.button.clicks};
}
events::Keyboard Keyboard()const
{
return events::Keyboard{event.key.windowID, event.key.repeat, Scancode(event.key.keysym.scancode), Keycode(event.key.keysym.sym), Keymod(event.key.keysym.mod)};
}
events::User User()const
{
return events::User{event.user.windowID, event.user.code, event.user.data1, event.user.data2};
}
events::WindowShown WindowShown()const
{
return events::WindowShown{event.window.windowID};
}
events::WindowHidden WindowHidden()const
{
return events::WindowHidden{event.window.windowID};
}
events::WindowExposed WindowExposed()const
{
return events::WindowExposed{event.window.windowID};
}
events::WindowMoved WindowMoved()const
{
return events::WindowMoved{event.window.windowID, Point(event.window.data1, event.window.data2)};
}
events::WindowResized WindowResized()const
{
return events::WindowResized{event.window.windowID, Point(event.window.data1, event.window.data2)};
}
events::WindowSizeChanged WindowSizeChanged()const
{
return events::WindowSizeChanged{event.window.windowID, Point(event.window.data1, event.window.data2)};
}
events::WindowMinimized WindowMinimized()const
{
return events::WindowMinimized{event.window.windowID};
}
events::WindowMaximized WindowMaximized()const
{
return events::WindowMaximized{event.window.windowID};
}
events::WindowRestored WindowRestored()const
{
return events::WindowRestored{event.window.windowID};
}
events::WindowEnter WindowEnter()const
{
return events::WindowEnter{event.window.windowID};
}
events::WindowLeave WindowLeave()const
{
return events::WindowLeave{event.window.windowID};
}
events::WindowFocusGained WindowFocusGained()const
{
return events::WindowFocusGained{event.window.windowID};
}
events::WindowFocusLost WindowFocusLost()const
{
return events::WindowFocusLost{event.window.windowID};
}
events::WindowClose WindowClose()const
{
return events::WindowClose{event.window.windowID};
}
events::WindowTakeFocus WindowTakeFocus()const
{
return events::WindowTakeFocus{event.window.windowID};
}
events::WindowHitTest WindowHitTest()const
{
return events::WindowHitTest{event.window.windowID};
}
events::JoystickAxis JoystickAxis()const
{
return events::JoystickAxis{uint32(event.jaxis.which), event.jaxis.axis, event.jaxis.value};
}
events::JoystickBall JoystickBall()const
{
return events::JoystickBall{uint32(event.jball.which), event.jball.ball, Point(event.jball.xrel, event.jball.yrel)};
}
events::JoystickButton JoystickButton()const
{
return events::JoystickButton{uint32(event.jbutton.which), event.jbutton.button};
}
events::JoystickHat JoystickHat()const
{
return events::JoystickHat{uint32(event.jhat.which), event.jhat.hat, event.jhat.value};
}
events::JoystickDeviceAdded JoystickDeviceAdded()const
{
return events::JoystickDeviceAdded{event.jdevice.which};
}
events::JoystickDeviceRemoved JoystickDeviceRemoved()const
{
return events::JoystickDeviceRemoved{uint32(event.jdevice.which)};
}
events::ControllerAxis ControllerAxis()const
{
return events::ControllerAxis{uint32(event.caxis.which), GameController::Axis(event.caxis.axis), event.caxis.value};
}
events::ControllerButton ControllerButton()const
{
return events::ControllerButton{uint32(event.cbutton.which), GameController::Button(event.cbutton.button)};
}
events::ControllerDeviceAdded ControllerDeviceAdded()const
{
return events::ControllerDeviceAdded{event.cdevice.which};
}
events::ControllerDeviceRemoved ControllerDeviceRemoved()const
{
return events::ControllerDeviceRemoved{uint32(event.cdevice.which)};
}
events::ControllerDeviceRemapped ControllerDeviceRemapped()const
{
return events::ControllerDeviceRemapped{uint32(event.cdevice.which)};
}
events::Drop Drop()const
{
events::Drop result{event.drop.windowID, event.drop.file};
SDL_free(event.drop.file);
return result;
}
events::TouchFinger TouchFinger()const
{
return events::TouchFinger{event.tfinger.touchId, event.tfinger.fingerId, event.tfinger.x, event.tfinger.y, event.tfinger.dx, event.tfinger.dy, event.tfinger.pressure};
}
events::MultiGesture MultiGesture()const
{
return events::MultiGesture{event.mgesture.touchId, event.mgesture.dTheta, event.mgesture.dDist, event.mgesture.x, event.mgesture.y, event.mgesture.numFingers};
}
events::DollarGesture DollarGesture()const
{
return events::DollarGesture{event.dgesture.touchId, event.dgesture.gestureId, event.dgesture.numFingers, event.dgesture.error, event.dgesture.x, event.dgesture.y};
}
events::DollarRecord DollarRecord()const
{
return events::DollarRecord{event.dgesture.touchId, event.dgesture.gestureId};
}
events::AudioDeviceAdded AudioDeviceAdded()const
{
return events::AudioDeviceAdded{event.adevice.which, event.adevice.iscapture};
}
events::AudioDeviceRemoved AudioDeviceRemoved()const
{
return events::AudioDeviceRemoved{event.adevice.which, event.adevice.iscapture};
}
events::TextEditing TextEditing()const
{
return events::TextEditing{event.edit.windowID, event.edit.text, event.edit.start, event.edit.length};
}
events::TextInput TextInput()const
{
return events::TextInput{event.text.windowID, event.text.text};
}
events::WindowManagement WindowManagement()const
{
return events::WindowManagement{*event.syswm.msg};
}
bool Push()
{
return bool(Error::IfNegative(SDL_PushEvent(&event)));
}
events::Type Type()const noexcept
{
auto tmp=event.type;
tmp=(tmp>=(uint32)SDL_USEREVENT)?(uint32)SDL_USEREVENT:tmp;
return events::Type(tmp==SDL_WINDOWEVENT?0x201+event.window.event:tmp);
}
uint32 Timestamp()const noexcept
{
return event.common.timestamp;
}
static Event Wait()
{
SDL_Event event;
Error::IfZero(SDL_WaitEvent(&event));
return Event(event);
}
static Event Wait(uint32 time)
{
SDL_Event event;
Error::IfZero(SDL_WaitEventTimeout(&event, time));
return Event(event);
}
};
}
#include "events/iterator.h"
namespace events
{
void Pump()noexcept
{
SDL_PumpEvents();
}
bool Quit()noexcept
{
return bool(SDL_QuitRequested());
}
bool Has(Type typ)noexcept
{
return SDL_HasEvent(uint32(typ));
}
bool Has(Type first, Type last)noexcept
{
return SDL_HasEvents(uint32(first), uint32(last));
}
void Flush(Type type)noexcept
{
SDL_FlushEvent(uint32(type));
}
void Flush(Type first, Type last)noexcept
{
SDL_FlushEvents(uint32(first), uint32(last));
}
} |
NUC-Liu/thesis | thesis-thesis/src/main/java/cn/nuc/thesis/thesis/service/WeeklyService.java | package cn.nuc.thesis.thesis.service;
import com.baomidou.mybatisplus.extension.service.IService;
import cn.nuc.common.utils.PageUtils;
import cn.nuc.thesis.thesis.entity.WeeklyEntity;
import java.util.Map;
/**
*
*
* @author Liu
* @email <EMAIL>
* @date 2020-05-03 02:54:41
*/
public interface WeeklyService extends IService<WeeklyEntity> {
PageUtils queryPage(Map<String, Object> params);
}
|
Kapersyx/sync-endpoint | src/main/java/org/opendatakit/aggregate/odktables/rest/entity/PropertyEntryJsonList.java | <filename>src/main/java/org/opendatakit/aggregate/odktables/rest/entity/PropertyEntryJsonList.java<gh_stars>1-10
/*
* Copyright (C) 2014 University of Washington
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.opendatakit.aggregate.odktables.rest.entity;
import java.util.ArrayList;
/**
* This holds a list of {@link PropertyEntryJson}.
* This holds the full JSON serialization of the properties.csv
*
* See {@link PropertyEntryXmlList} for the XML variant of this.
*
* @author <EMAIL>
*
*/
public class PropertyEntryJsonList extends ArrayList<PropertyEntryJson> {
/**
*
*/
private static final long serialVersionUID = -922490204257676096L;
/**
* Constructor used by Jackson
*/
public PropertyEntryJsonList() {
}
}
|
nordnet/dev-blog | src/utils/constants.js | <reponame>nordnet/dev-blog<filename>src/utils/constants.js<gh_stars>1-10
export const FILE_TYPE = '.mdx';
export const PREFIX = 'posts';
export const PATH_DIVIDER = '/';
export const FILE_TYPE_REGEX = new RegExp(`\\${FILE_TYPE}?`);
export const IMAGES_PREFIX = '/public'; |
Amirsorouri00/neolej | file_app/models.py | <filename>file_app/models.py
from django.db import models
# def file_directory_path(instance, filename):
# # file will be uploaded to MEDIA_ROOT/user_<id>/<filename>
# return 'user_{0}/{1}'.format(instance.remark, filename)
class File(models.Model):
# file = models.FileField(upload_to=file_directory_path, blank=False, null=False)
remark = models.CharField(max_length=31)
timestamp = models.DateTimeField(auto_now_add=True) |
prafullkotecha/waltz | waltz-ng/client/person/index.js | /*
* Waltz - Enterprise Architecture
* Copyright (C) 2016, 2017, 2018, 2019 Waltz open source project
* See README.md for more information
*
* 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
*
*/
import angular from "angular";
import {registerComponents, registerStore} from "../common/module-utils";
import PersonStore from "./services/person-store";
import PersonChangeSetSection from "./components/person-change-set-section/person-change-set-section"
import PersonOverview from "./components/overview/person-overview";
import PersonAppsSection from "./components/person-apps-section/person-apps-section";
import PersonHierarchySection from "./components/person-hierarchy-section/person-hierarchy-section";
import PersonLink from "./components/person-link/person-link";
import PersonList from "./components/person-list/person-list";
import PersonAppsTable from "./components/person-apps-table/person-apps-table"
import Routes from "./routes";
export default () => {
const module = angular.module("waltz.person", []);
module
.config(Routes);
registerStore(module, PersonStore);
registerComponents(module, [
PersonAppsSection,
PersonChangeSetSection,
PersonHierarchySection,
PersonOverview,
PersonLink,
PersonList,
PersonAppsTable
]);
return module.name;
};
|
armoredsoftware/protocol | measurer/hotspot-measurer/hotspot/src/share/vm/utilities/decoder.hpp | <filename>measurer/hotspot-measurer/hotspot/src/share/vm/utilities/decoder.hpp<gh_stars>0
/*
* Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
#ifndef __DECODER_HPP
#define __DECODER_HPP
#include "memory/allocation.hpp"
#ifdef _WINDOWS
#include <windows.h>
#include <imagehlp.h>
// functions needed for decoding symbols
typedef DWORD (WINAPI *pfn_SymSetOptions)(DWORD);
typedef BOOL (WINAPI *pfn_SymInitialize)(HANDLE, PCTSTR, BOOL);
typedef BOOL (WINAPI *pfn_SymGetSymFromAddr64)(HANDLE, DWORD64, PDWORD64, PIMAGEHLP_SYMBOL64);
typedef DWORD (WINAPI *pfn_UndecorateSymbolName)(const char*, char*, DWORD, DWORD);
#else
class ElfFile;
#endif // _WINDOWS
class Decoder: public StackObj {
public:
// status code for decoding native C frame
enum decoder_status {
no_error, // successfully decoded frames
out_of_memory, // out of memory
file_invalid, // invalid elf file
file_not_found, // could not found symbol file (on windows), such as jvm.pdb or jvm.map
helper_not_found, // could not load dbghelp.dll (Windows only)
helper_func_error, // decoding functions not found (Windows only)
helper_init_error, // SymInitialize failed (Windows only)
symbol_not_found // could not find the symbol
};
public:
Decoder() { initialize(); };
~Decoder() { uninitialize(); };
static bool can_decode_C_frame_in_vm();
static void initialize();
static void uninitialize();
#ifdef _WINDOWS
static decoder_status decode(address addr, char *buf, int buflen, int *offset);
#else
static decoder_status decode(address addr, const char* filepath, char *buf, int buflen, int *offset);
#endif
static bool demangle(const char* symbol, char *buf, int buflen);
static decoder_status get_status() { return _decoder_status; };
#ifndef _WINDOWS
private:
static ElfFile* get_elf_file(const char* filepath);
#endif // _WINDOWS
private:
static decoder_status _decoder_status;
static bool _initialized;
#ifdef _WINDOWS
static HMODULE _dbghelp_handle;
static bool _can_decode_in_vm;
static pfn_SymGetSymFromAddr64 _pfnSymGetSymFromAddr64;
static pfn_UndecorateSymbolName _pfnUndecorateSymbolName;
#else
static ElfFile* _opened_elf_files;
#endif // _WINDOWS
};
#endif // __DECODER_HPP
|
hvpaiva/java-padroes-projeto | singleton/src/main/java/com/hvpaiva/singleton/EnumVencedor.java | <filename>singleton/src/main/java/com/hvpaiva/singleton/EnumVencedor.java
package com.hvpaiva.singleton;
/**
* Implementaรงรฃo Singleton baseado em Enum. Effective Java 2nd Edition (<NAME>) p. 18
*
* Esta implementaรงรฃo รฉ thread-safe, no entanto, ao adicionar qualquer outro mรฉtodo
* seguranรงa por threads รฉ de responsabilidade do desenvolvedor.
*/
enum EnumVencedor {
INSTANCE;
@Override
public String toString() {
return getDeclaringClass().getCanonicalName() + "@" + hashCode();
}
}
|
Eliav2rll2v/suryadev967 | src/main/java/org/wlld/nerveEntity/SoftMax.java | <reponame>Eliav2rll2v/suryadev967
package org.wlld.nerveEntity;
import org.wlld.config.RZ;
import org.wlld.i.OutBack;
import org.wlld.tools.ArithUtil;
import java.util.List;
import java.util.Map;
public class SoftMax extends Nerve {
private OutNerve outNerve;
private boolean isShowLog;
public SoftMax(int id, int upNub, boolean isDynamic, OutNerve outNerve, boolean isShowLog) throws Exception {
super(id, upNub, "softMax", 0, 0, false, null, isDynamic,
false, RZ.NOT_RZ, 0);
this.outNerve = outNerve;
this.isShowLog = isShowLog;
}
@Override
protected void input(long eventId, double parameter, boolean isStudy, Map<Integer, Double> E, OutBack outBack) throws Exception {
boolean allReady = insertParameter(eventId, parameter);
if (allReady) {
double out = softMax(eventId);//่พๅบๅผ
if (isStudy) {//ๅญฆไน
outNub = out;
if (E.containsKey(getId())) {
this.E = E.get(getId());
} else {
this.E = 0;
}
if (isShowLog) {
System.out.println("softMax==" + this.E + ",out==" + out + ",nerveId==" + getId());
}
gradient = -outGradient();//ๅฝๅๆขฏๅบฆๅๅ ๆๆขฏๅบฆ่ฟๅ
features.remove(eventId); //ๆธ
็ฉบๅฝๅไธๅฑ่พๅ
ฅๅๆฐๅๆฐ
outNerve.getGBySoftMax(gradient, eventId, getId());
} else {//่พๅบ
destoryParameter(eventId);
if (outBack != null) {
outBack.getBack(out, getId(), eventId);
} else {
throw new Exception("not find outBack");
}
}
}
}
private double outGradient() {//็ๆ่พๅบๅฑ็ฅ็ปๅ
ๆขฏๅบฆๅๅ
double g = outNub;
if (E == 1) {
//g = ArithUtil.sub(g, 1);
g = g - 1;
}
return g;
}
private double softMax(long eventId) {//่ฎก็ฎๅฝๅ่พๅบ็ปๆ
double sigma = 0;
List<Double> featuresList = features.get(eventId);
double self = featuresList.get(getId() - 1);
double eSelf = Math.exp(self);
for (int i = 0; i < featuresList.size(); i++) {
double value = featuresList.get(i);
// sigma = ArithUtil.add(Math.exp(value), sigma);
sigma = Math.exp(value) + sigma;
}
return eSelf / sigma;//ArithUtil.div(eSelf, sigma);
}
}
|
marklogic-community/corb2 | src/main/java/com/marklogic/developer/corb/PreBatchUpdateFileTask.java | /*
* Copyright (c) 2004-2021 MarkLogic Corporation
*
* 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.
*
* The use of the Apache License does not indicate that this project is
* affiliated with the Apache Software Foundation.
*/
package com.marklogic.developer.corb;
import static com.marklogic.developer.corb.Options.EXPORT_FILE_HEADER_LINE_COUNT;
import static com.marklogic.developer.corb.Options.EXPORT_FILE_TOP_CONTENT;
import com.marklogic.developer.corb.util.FileUtils;
import java.io.*;
/**
* @author <NAME>, MarkLogic Corporation
*/
public class PreBatchUpdateFileTask extends ExportBatchToFileTask {
protected String getTopContent() {
String topContent = getProperty(EXPORT_FILE_TOP_CONTENT);
String batchRef = getProperty(Manager.URIS_BATCH_REF);
if (topContent != null && batchRef != null) {
topContent = topContent.replace('@' + Manager.URIS_BATCH_REF, batchRef);
}
return topContent;
}
private void deleteFileIfExists() throws IOException {
File batchFile = getExportFile();
FileUtils.deleteFile(batchFile);
}
protected void writeTopContent() throws IOException {
String topContent = getTopContent();
writeToExportFile(topContent);
}
private void addLineCountToProps() throws IOException{
int ct = FileUtils.getLineCount(getExportFile());
if (this.properties != null && ct > 0) {
this.properties.setProperty(EXPORT_FILE_HEADER_LINE_COUNT, String.valueOf(ct));
}
}
@Override
public String[] call() throws Exception {
try {
deleteFileIfExists();
writeTopContent();
invokeModule();
addLineCountToProps();
return new String[0];
} finally {
cleanup();
}
}
}
|
xstefank/eap-microprofile-test-suite | microprofile-metrics/src/test/java/org/jboss/eap/qe/microprofile/metrics/ConnectionStressMetricsTest.java | <filename>microprofile-metrics/src/test/java/org/jboss/eap/qe/microprofile/metrics/ConnectionStressMetricsTest.java
package org.jboss.eap.qe.microprofile.metrics;
import static io.restassured.RestAssured.get;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasKey;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.eap.qe.microprofile.metrics.hello.MetricsApp;
import org.jboss.eap.qe.microprofile.tooling.server.configuration.ConfigurationException;
import org.jboss.eap.qe.microprofile.tooling.server.configuration.arquillian.ArquillianContainerProperties;
import org.jboss.eap.qe.microprofile.tooling.server.configuration.arquillian.ArquillianDescriptorWrapper;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import io.restassured.http.ContentType;
@RunWith(Arquillian.class)
public class ConnectionStressMetricsTest {
@ArquillianResource
private URL deploymentUrl;
private static URL metricsURL;
@Deployment
public static WebArchive createDeployment() {
return ShrinkWrap.create(WebArchive.class, ConnectionStressMetricsTest.class.getSimpleName() + ".war")
.addPackage(MetricsApp.class.getPackage())
.addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml");
}
@BeforeClass
public static void composeMetricsEndpointURL() throws MalformedURLException, ConfigurationException {
ArquillianContainerProperties arqProps = new ArquillianContainerProperties(
ArquillianDescriptorWrapper.getArquillianDescriptor());
metricsURL = new URL("http://" + arqProps.getDefaultManagementAddress() + ":" + arqProps.getDefaultManagementPort()
+ "/metrics");
}
private HttpURLConnection getHTTPConn(URL url) throws Exception {
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setReadTimeout(30 * 1000);
connection.connect();
return connection;
}
/**
* @tpTestDetails Negative scenario to verify metrics are available when lots of connections are opened
* @tpPassCrit Counter metric is incremented according to number of invocation of the CDI bean even if there are lots
* of opened connections.
* @tpSince EAP 7.4.0.CD19
*/
@Test
@RunAsClient
public void stressTest() throws Exception {
final List<HttpURLConnection> connections = new ArrayList<>(2000);
try {
for (int i = 0; i < 1000; i++) {
connections.add(getHTTPConn(deploymentUrl));
}
for (int i = 0; i < 1000; i++) {
connections.add(getHTTPConn(metricsURL));
}
for (int i = 0; i < 10; i++) {
get(deploymentUrl.toString()).then().statusCode(200);
}
given()
.baseUri(metricsURL.toString())
.accept(ContentType.JSON)
.get().then()
.contentType(ContentType.JSON)
.header("Content-Type", containsString("application/json"))
.body("$", hasKey("application"),
"application", hasKey("hello-count"),
"application.hello-count", equalTo(10));
} finally {
connections.forEach(HttpURLConnection::disconnect);
}
}
}
|
zhanghai/Douya | app/src/main/java/me/zhanghai/android/douya/broadcast/ui/BroadcastActivity.java | <reponame>zhanghai/Douya<filename>app/src/main/java/me/zhanghai/android/douya/broadcast/ui/BroadcastActivity.java
/*
* Copyright (c) 2015 <NAME> <<EMAIL>>
* All Rights Reserved.
*/
package me.zhanghai.android.douya.broadcast.ui;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import me.zhanghai.android.douya.network.api.info.frodo.Broadcast;
import me.zhanghai.android.douya.ui.FragmentFinishable;
import me.zhanghai.android.douya.util.FragmentUtils;
import me.zhanghai.android.douya.util.TransitionUtils;
public class BroadcastActivity extends AppCompatActivity implements FragmentFinishable {
private static final String KEY_PREFIX = BroadcastActivity.class.getName() + '.';
private static final String EXTRA_BROADCAST_ID = KEY_PREFIX + "broadcast_id";
private static final String EXTRA_BROADCAST = KEY_PREFIX + "broadcast";
private static final String EXTRA_SHOW_SEND_COMMENT = KEY_PREFIX + "show_send_comment";
private static final String EXTRA_TITLE = KEY_PREFIX + "title";
private BroadcastFragment mFragment;
private boolean mShouldFinish;
public static Intent makeIntent(long broadcastId, Context context) {
return new Intent(context, BroadcastActivity.class)
.putExtra(EXTRA_BROADCAST_ID, broadcastId);
}
public static Intent makeIntent(Broadcast broadcast, Context context) {
return makeIntent(broadcast.id, context)
.putExtra(EXTRA_BROADCAST, broadcast);
}
public static Intent makeIntent(Broadcast broadcast, boolean showSendComment, String title,
Context context) {
return makeIntent(broadcast, context)
.putExtra(EXTRA_SHOW_SEND_COMMENT, showSendComment)
.putExtra(EXTRA_TITLE, title);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
TransitionUtils.setupTransitionBeforeDecorate(this);
super.onCreate(savedInstanceState);
// Calls ensureSubDecor().
findViewById(android.R.id.content);
TransitionUtils.postponeTransition(this);
if (savedInstanceState == null) {
Intent intent = getIntent();
long broadcastId = intent.getLongExtra(EXTRA_BROADCAST_ID, -1);
Broadcast broadcast = intent.getParcelableExtra(EXTRA_BROADCAST);
boolean showSendComment = intent.getBooleanExtra(EXTRA_SHOW_SEND_COMMENT, false);
String title = intent.getStringExtra(EXTRA_TITLE);
mFragment = BroadcastFragment.newInstance(broadcastId, broadcast, showSendComment,
title);
FragmentUtils.add(mFragment, this, android.R.id.content);
} else {
mFragment = FragmentUtils.findById(this, android.R.id.content);
}
}
@Override
public void finish() {
if (!mShouldFinish) {
mFragment.onFinish();
return;
}
super.finish();
}
@Override
public void finishAfterTransition() {
if (!mShouldFinish) {
mFragment.onFinish();
return;
}
super.finishAfterTransition();
}
@Override
public void finishFromFragment() {
mShouldFinish = true;
super.finish();
}
@Override
public void finishAfterTransitionFromFragment() {
mShouldFinish = true;
super.supportFinishAfterTransition();
}
}
|
lucaswilliamgomes/QuestionsCompetitiveProgramming | Neps/Problems/Fase - 34.cpp | <filename>Neps/Problems/Fase - 34.cpp
#include <bits/stdc++.h>
using namespace std;
int main () {
int n, m, aux;
cin >> n >> m;
vector <int> arr;
for (int i = 0; i < 1005; i++){
arr.push_back(0);
}
for (int i = 0; i < n; i++){
cin >> arr[i];
}
sort (arr.begin(), arr.end());
reverse(arr.begin(), arr.end());
int ans = m;
int atual = arr[ans-1];
int proximo = arr[ans];
while (proximo == atual){
ans++;
atual = arr[ans-1];
proximo = arr[ans];
}
cout << ans << endl;
return 0;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.