identifier
stringlengths 42
383
| collection
stringclasses 1
value | open_type
stringclasses 1
value | license
stringlengths 0
1.81k
| date
float64 1.99k
2.02k
⌀ | title
stringlengths 0
100
| creator
stringlengths 1
39
| language
stringclasses 157
values | language_type
stringclasses 2
values | word_count
int64 1
20k
| token_count
int64 4
1.32M
| text
stringlengths 5
1.53M
| __index_level_0__
int64 0
57.5k
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|
https://github.com/0xF6/openvino/blob/master/inference-engine/tests_deprecated/functional/vpu/common/layers/myriad_layers_scatter_update_test.cpp
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,020
|
openvino
|
0xF6
|
C++
|
Code
| 479
| 1,008
|
// Copyright (C) 2018-2020 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include "myriad_layers_scatter_update_test.hpp"
using namespace testing;
//----------------------------------------------------------------------
//
// Multi-dimensional input/output and other tensors
//
//----------------------------------------------------------------------
INSTANTIATE_TEST_CASE_P(
nd_tensors,
myriadLayersScatterUpdateTest_smoke,
Values(
// 1-dimensional `indices`
ScatterUpdateTestParams { { 1000 }, { 100000 } },
ScatterUpdateTestParams { { 105 }, { 351, 299 } },
ScatterUpdateTestParams { { 17 }, { 48, 55, 39 } },
ScatterUpdateTestParams { { 10 }, { 23, 14, 19, 17 } },
ScatterUpdateTestParams { { 7 }, { 10, 9, 11, 8, 13 } },
ScatterUpdateTestParams { { 6 }, { 9, 5, 11, 7, 5, 6 } },
ScatterUpdateTestParams { { 5 }, { 7, 6, 5, 7, 6, 3, 4 } },
ScatterUpdateTestParams { { 3 }, { 5, 3, 5, 7, 3, 4, 6, 3 } },
// 2-dimensional `indices`
ScatterUpdateTestParams { { 35, 29 }, { 100000 } },
ScatterUpdateTestParams { { 13, 9 }, { 351, 299 } },
ScatterUpdateTestParams { { 5, 3 }, { 48, 55, 39 } },
ScatterUpdateTestParams { { 3, 3 }, { 23, 14, 19, 17 } },
ScatterUpdateTestParams { { 3, 2 }, { 10, 9, 11, 8, 13 } },
ScatterUpdateTestParams { { 3, 2 }, { 9, 5, 11, 7, 5, 6 } },
ScatterUpdateTestParams { { 2, 2 }, { 7, 6, 5, 7, 6, 3, 4 } },
// 3-dimensional `indices`
ScatterUpdateTestParams { { 13, 11, 7 }, { 100000 } },
ScatterUpdateTestParams { { 5, 7, 3 }, { 351, 299 } },
ScatterUpdateTestParams { { 5, 2, 2 }, { 48, 55, 39 } },
ScatterUpdateTestParams { { 3, 2, 2 }, { 23, 14, 19, 17 } },
ScatterUpdateTestParams { { 2, 2, 2 }, { 10, 9, 11, 8, 13 } },
ScatterUpdateTestParams { { 2, 2, 2 }, { 9, 5, 11, 7, 5, 6 } }
)
);
//----------------------------------------------------------------------
//
// Real-life (or similar) test cases
//
//----------------------------------------------------------------------
INSTANTIATE_TEST_CASE_P(
use_cases,
myriadLayersScatterUpdateTest_smoke,
Values(
// use case from Mask R-CNN: N = 1000, C = 256, HxW = 7x7
ScatterUpdateTestParams { { 32 }, { 1000, 256, 7, 7} },
ScatterUpdateTestParams { { 5, 6 }, { 1000, 256, 7, 7} },
ScatterUpdateTestParams { { 5, 3, 2 }, { 1000, 256, 7, 7} },
// large 1D copy: N=1 (hidden), C=64, D=40, H = W = 112
ScatterUpdateTestParams { { 32 }, { 64, 40, 112, 112 } },
ScatterUpdateTestParams { { 5, 6 }, { 64, 40, 112, 112 } },
ScatterUpdateTestParams { { 5, 3, 2 }, { 64, 40, 112, 112 } },
// many planes for 3D copy: N=16, C=512, H=W=56
ScatterUpdateTestParams { { 12, }, { 16, 512, 56, 56 } },
ScatterUpdateTestParams { { 3, 4, }, { 16, 512, 56, 56 } },
ScatterUpdateTestParams { { 3, 2, 2, }, { 16, 512, 56, 56 } }
)
);
| 14,996
|
https://github.com/xiaoyaofe/activity-fe/blob/master/src/pages/vs_Tw_20191001/acts/act5.pc.scss
|
Github Open Source
|
Open Source
|
Adobe-Glyph
| null |
activity-fe
|
xiaoyaofe
|
SCSS
|
Code
| 784
| 3,778
|
@include mq($pc) {
#act5 {
width: 12rem;
height: 8.34rem;
margin-left: 3.65rem;
}
.act5-title {
position: relative;
$width: 9.22rem;
$height: .81rem;
width: $width;
height: $height;
margin-left: 1.33rem;
margin-top: 1.29rem;
$background-image:url("../../../assets/images/#{$path}/pc/act5-title.png");
$background-size: $width $height;
$background-repeat: no-repeat;
$background-position: center;
background: #{$background-image} #{$background-position}/#{$background-size} #{$background-repeat};
}
.act5_moreBtn {
width: 4em;
position: relative;
left: 46%;
top: 120%;
font-family: HeitiCSEG-Medium-T-GB;
text-decoration: underline;
font-size: .2rem;
font-weight: normal;
font-stretch: normal;
letter-spacing: 0px;
color: #0d3da9;
cursor: pointer;
}
.act5_more {
width: 6.59rem;
height: 4.83rem;
$background-image: url("../../../assets/images/#{$path}/pc/act5-more-gifts.png");
$background-size: 5.94rem 3.86rem;
$background-repeat: no-repeat;
$background-position: .32rem .68rem;
background: #{$background-image} #{$background-position}/#{$background-size} #{$background-repeat};
background-color: #fff;
border: solid .1rem #2094c5;
position: absolute;
top: 160%;
left: 13%;
z-index: $z-index3;
}
.act5_more_close {
$width: .5rem;
$height: .5rem;
width: $width;
height: $height;
// margin-top: 0.16rem;
$background-image: url("../../../assets/images/#{$path}/pc/close.png");
$background-size: $width $height;
$background-repeat: no-repeat;
$background-position: center;
background: #{$background-image} #{$background-position}/#{$background-size} #{$background-repeat};
// border-radius: 50%;
position: absolute;
top: 4px;
right: 9px;
cursor: pointer;
}
// .act5_more_txt {
// font-family: "FZXH1FW--GB1-0";
// font-size: .2rem;
// line-height: .24rem;
// color: #2fa3d0;
// margin-left: .59rem;
// }
// .act5_more_txt1 {
// margin-top: .65rem;
// }
.act5-content {
position: relative;
margin-top: .48rem;
height: 5.05rem;
overflow: hidden;
}
.act5-gifts {
box-sizing: border-box;
$width: 1rem;
$height: 1rem;
width: $width;
height: $height;
padding: 0.02rem;
// $background-image:url("../../../assets/images/#{$path}/pc/act5-gift-bg.png");
// $background-size: .86rem .86rem;
// $background-repeat: no-repeat;
// $background-position: center;
// background: #{$background-image} #{$background-position}/#{$background-size} #{$background-repeat};
overflow: hidden;
position: absolute;
}
// 1
.act5-gifts1 {
top: 2rem;
left: 0;
background: none;
}
// 2
.act5-gifts2 {
top: 1rem;
left: 0;
}
// 3-14
@for $i from 1 through 13 {
.act5-gifts#{$i+2} {
top: 0;
left: #{($i - 1)*1rem};
}
}
// 15-18
@for $i from 1 through 5 {
.act5-gifts#{$i+14} {
top: #{$i * 1rem};
left: #{(12 - 1)*1rem};
}
}
// 19-29
@for $i from 1 through 11 {
.act5-gifts#{$i+18} {
top: 4rem;
left: #{(11 - $i)*1rem};
}
}
// 30
.act5-gifts30 {
top: 3rem;
left: 0;
}
.act5-gift {
text-align: center;
box-sizing: border-box;
width: 100%;
height: 100%;
}
.act5-gift1 {
$background-image:url("../../../assets/images/#{$path}/pc/act5-start.png");
$background-size: .86rem .86rem;
$background-repeat: no-repeat;
$background-position: center;
background: #{$background-image} #{$background-position}/#{$background-size} #{$background-repeat};
}
.act5-gift2 {
$background-image:url("../../../assets/images/#{$path}/pc/act5/act5-gift5.png");
$background-size: .86rem .86rem;
$background-repeat: no-repeat;
$background-position: center;
background: #{$background-image} #{$background-position}/#{$background-size} #{$background-repeat};
}
// 3-10
@for $i from 3 through 11 {
.act5-gift#{$i} {
$background-image:url("../../../assets/images/#{$path}/pc/act5/act5-gift#{$i}.png");
$background-size: .86rem .86rem;
$background-repeat: no-repeat;
$background-position: center;
background: #{$background-image} #{$background-position}/#{$background-size} #{$background-repeat};
}
}
.act5-gift11 {
$background-image:url("../../../assets/images/#{$path}/pc/act5/act5-gift8.png");
$background-size: .86rem .86rem;
$background-repeat: no-repeat;
$background-position: center;
background: #{$background-image} #{$background-position}/#{$background-size} #{$background-repeat};
}
@for $i from 12 through 16 {
.act5-gift#{$i} {
$background-image:url("../../../assets/images/#{$path}/pc/act5/act5-gift#{$i}.png");
$background-size: .86rem .86rem;
$background-repeat: no-repeat;
$background-position: center;
background: #{$background-image} #{$background-position}/#{$background-size} #{$background-repeat};
}
}
.act5-gift17 {
$background-image:url("../../../assets/images/#{$path}/pc/act5/act5-gift14.png");
$background-size: .86rem .86rem;
$background-repeat: no-repeat;
$background-position: center;
background: #{$background-image} #{$background-position}/#{$background-size} #{$background-repeat};
}
@for $i from 18 through 22 {
.act5-gift#{$i} {
$background-image:url("../../../assets/images/#{$path}/pc/act5/act5-gift#{$i}.png");
$background-size: .86rem .86rem;
$background-repeat: no-repeat;
$background-position: center;
background: #{$background-image} #{$background-position}/#{$background-size} #{$background-repeat};
}
}
.act5-gift23 {
$background-image:url("../../../assets/images/#{$path}/pc/act5/act5-gift20.png");
$background-size: .86rem .86rem;
$background-repeat: no-repeat;
$background-position: center;
background: #{$background-image} #{$background-position}/#{$background-size} #{$background-repeat};
}
@for $i from 24 through 30 {
.act5-gift#{$i} {
$background-image:url("../../../assets/images/#{$path}/pc/act5/act5-gift#{$i}.png");
$background-size: .86rem .86rem;
$background-repeat: no-repeat;
$background-position: center;
background: #{$background-image} #{$background-position}/#{$background-size} #{$background-repeat};
}
}
.act5GiftActive .act5-gift {
border: solid 0.02rem #fff223;
}
// .act5GiftActive .act5-gift1 {
// border: none;
// }
$diceWidth:.9rem;
$diceHeight:.9rem;
.act5_dice_wrap {
$width: 1.64rem;
$height: 1.64rem;
width: $width;
height: $height;
position: absolute;
top: 1.5rem;
left: 3rem;
$background-image:url("../../../assets/images/#{$path}/pc/dice-bg.png");
$background-size: $width $height;
$background-repeat: no-repeat;
$background-position: center;
background: #{$background-image} #{$background-position}/#{$background-size} #{$background-repeat};
overflow: hidden;
}
.act5_dice {
width: $diceWidth;
height: $diceHeight;
margin: .37rem auto;
background-image:url("../../../assets/images/#{$path}/pc/dice.png");
background-size: 1rem 10rem;
background-repeat: no-repeat;
overflow: hidden;
}
.act5_dice_1 {
background-position: -0.05rem -0.04rem;
}
.act5_dice_2 {
background-position: -0.05rem -1.07rem;
}
.act5_dice_3 {
background-position: -0.05rem -2.12rem;
}
.act5_dice_4 {
background-position: -0.05rem -3.17rem;
}
.act5_dice_5 {
background-position: -0.05rem -4.27rem;
}
.act5_dice_6 {
background-position: -0.05rem -5.35rem;
}
.act5_dice_t {
background-position: -0.05rem -6.51rem;
}
.act5_dice_s {
background-position: -0.05rem -7.63rem;
}
.act5_dice_e {
background-position: -0.05rem -8.76rem;
}
.act5_dice_mask {
width: $diceWidth;
height: $diceHeight;
background: transparent;
background: #fff;
opacity: 0;
position: absolute;
top: 0;
left: 0;
z-index: $z-index4;
}
.egg_wrap {
$width: 2.35rem;
$height: 2.22rem;
width: $width;
height: $height;
position: absolute;
top: 1.06rem;
right: 2.02rem;
}
.act5_eggs {
$width: 2.35rem;
$height: 2.22rem;
width: $width;
height: $height;
transform-origin: 60% 90%;
transform: rotateZ(0deg);
$background-image:url("../../../assets/images/#{$path}/pc/egg-start.png");
$background-size: $width $height;
$background-repeat: no-repeat;
$background-position: center;
background: #{$background-image} #{$background-position}/#{$background-size} #{$background-repeat};
}
// .act5_egg_gift {
// opacity: 0;
// display: none;
// z-index: 2;
// $width: .8rem;
// $height: .8rem;
// width: $width;
// height: $height;
// position: absolute;
// top: 1.175rem - 0.4rem;
// left: 1.11rem - 0.4rem;
// }
// @for $i from 1 through 12 {
// .act5_egg_gift#{$i} {
// $background-image:url("../../../assets/images/#{$path}/pc/act5/act5-egg#{$i}.png");
// $background-size: .8rem .8rem;
// $background-repeat: no-repeat;
// $background-position: center;
// background: #{$background-image} #{$background-position}/#{$background-size} #{$background-repeat};
// }
// }
.act5_desc {
width: 4rem;
height: .3rem;
line-height: .3rem;
color: #0d3da9;
font-family: "ç»å
";
font-size: .26rem;
font-weight: 700;
position: absolute;
top: 3.4rem;
left: 2.2rem;
text-align: center;
}
.act5_desc1 {
left: 7rem;
}
.act5_desc_span {
display: inline-block;
width: 1.2rem;
color: #fbff06;
}
}
| 21,978
|
https://github.com/strivexj/weather/blob/master/app/src/main/java/example/com/map/example/com/furtherstudy/MusicService.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
weather
|
strivexj
|
Java
|
Code
| 140
| 533
|
package example.com.map.example.com.furtherstudy;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.util.Log;
import example.com.map.R;
public class MusicService extends Service {
private MediaPlayer mediaPlayer=new MediaPlayer();
public MusicService() {
// Log.d("MyService","onMyService executed");
// if(!mediaPlayer.isPlaying()) {
/* new Thread(new Runnable() {
@Override
public void run() {
Log.d("MyService","Thread id is"+Thread.currentThread().getId());
mediaPlayer= MediaPlayer.create(getApplicationContext(), R.raw.music);
mediaPlayer.start();
}
}).start();*///}
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//Log.d("MyService","onStartCommand executed");
if(!mediaPlayer.isPlaying()) {
new Thread(new Runnable() {
@Override
public void run() {
// Log.d("MyService","Thread id is"+Thread.currentThread().getId());
mediaPlayer= MediaPlayer.create(getApplicationContext(), R.raw.music);
// Log.d("Music a",""+mediaPlayer.getDuration());
mediaPlayer.start();
}
}).start();}
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
// Log.d("MyService","onDestroy executed");
if(mediaPlayer!=null){
mediaPlayer.stop();
mediaPlayer.release();
}
super.onDestroy();
}
@Override
public void onCreate() {
super.onCreate();
// Log.d("MyService","onCreate executed");
}
}
| 1,417
|
https://github.com/riednyko/cloudbeaver/blob/master/webapp/packages/core-administration/src/AdministrationSettingsService.ts
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,022
|
cloudbeaver
|
riednyko
|
TypeScript
|
Code
| 94
| 230
|
/*
* CloudBeaver - Cloud Database Manager
* Copyright (C) 2020-2021 DBeaver Corp and others
*
* Licensed under the Apache License, Version 2.0.
* you may not use this file except in compliance with the License.
*/
import { injectable } from '@cloudbeaver/core-di';
import { PluginManagerService } from '@cloudbeaver/core-plugin';
const defaultSettings = {
baseFeatures: [] as string[],
};
export type AdministrationSettings = typeof defaultSettings;
@injectable()
export class AdministrationSettingsService {
readonly settings = this.pluginManagerService.getPluginSettings('core.administration', defaultSettings);
constructor(private pluginManagerService: PluginManagerService) { }
isBase(feature: string): boolean {
return this.getBase().includes(feature);
}
getBase(): string[] {
return this.settings.getValue('baseFeatures');
}
}
| 2,798
|
https://github.com/OCHIENGDAVIS/django1.9/blob/master/posts/migrations/0004_auto_20190311_1111.py
|
Github Open Source
|
Open Source
|
MIT
| null |
django1.9
|
OCHIENGDAVIS
|
Python
|
Code
| 54
| 187
|
# -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2019-03-11 11:11
from __future__ import unicode_literals
import datetime
from django.db import migrations, models
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('posts', '0003_remove_post_publish'),
]
operations = [
migrations.AlterField(
model_name='post',
name='image',
field=models.FileField(default=datetime.datetime(2019, 3, 11, 11, 11, 58, 195629, tzinfo=utc), upload_to=b''),
preserve_default=False,
),
]
| 21,724
|
https://github.com/hidaba/python-plexapi/blob/master/plexapi/media.py
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| null |
python-plexapi
|
hidaba
|
Python
|
Code
| 1,938
| 5,883
|
# -*- coding: utf-8 -*-
from plexapi import log, utils
from plexapi.base import PlexObject
from plexapi.exceptions import BadRequest
from plexapi.utils import cast
@utils.registerPlexObject
class Media(PlexObject):
""" Container object for all MediaPart objects. Provides useful data about the
video this media belong to such as video framerate, resolution, etc.
Attributes:
TAG (str): 'Media'
server (:class:`~plexapi.server.PlexServer`): PlexServer object this is from.
initpath (str): Relative path requested when retrieving specified data.
video (str): Video this media belongs to.
aspectRatio (float): Aspect ratio of the video (ex: 2.35).
audioChannels (int): Number of audio channels for this video (ex: 6).
audioCodec (str): Audio codec used within the video (ex: ac3).
bitrate (int): Bitrate of the video (ex: 1624)
container (str): Container this video is in (ex: avi).
duration (int): Length of the video in milliseconds (ex: 6990483).
height (int): Height of the video in pixels (ex: 256).
id (int): Plex ID of this media item (ex: 46184).
has64bitOffsets (bool): True if video has 64 bit offsets (?).
optimizedForStreaming (bool): True if video is optimized for streaming.
target (str): Media version target name.
title (str): Media version title.
videoCodec (str): Video codec used within the video (ex: ac3).
videoFrameRate (str): Video frame rate (ex: 24p).
videoResolution (str): Video resolution (ex: sd).
videoProfile (str): Video profile (ex: high).
width (int): Width of the video in pixels (ex: 608).
parts (list<:class:`~plexapi.media.MediaPart`>): List of MediaParts in this video.
"""
TAG = 'Media'
def _loadData(self, data):
""" Load attribute values from Plex XML response. """
self._data = data
self.aspectRatio = cast(float, data.attrib.get('aspectRatio'))
self.audioChannels = cast(int, data.attrib.get('audioChannels'))
self.audioCodec = data.attrib.get('audioCodec')
self.bitrate = cast(int, data.attrib.get('bitrate'))
self.container = data.attrib.get('container')
self.duration = cast(int, data.attrib.get('duration'))
self.height = cast(int, data.attrib.get('height'))
self.id = cast(int, data.attrib.get('id'))
self.has64bitOffsets = cast(bool, data.attrib.get('has64bitOffsets'))
self.optimizedForStreaming = cast(bool, data.attrib.get('optimizedForStreaming'))
self.target = data.attrib.get('target')
self.title = data.attrib.get('title')
self.videoCodec = data.attrib.get('videoCodec')
self.videoFrameRate = data.attrib.get('videoFrameRate')
self.videoProfile = data.attrib.get('videoProfile')
self.videoResolution = data.attrib.get('videoResolution')
self.width = cast(int, data.attrib.get('width'))
self.parts = self.findItems(data, MediaPart)
def delete(self):
part = self._initpath + '/media/%s' % self.id
try:
return self._server.query(part, method=self._server._session.delete)
except BadRequest:
log.error("Failed to delete %s. This could be because you havn't allowed "
"items to be deleted" % part)
raise
@utils.registerPlexObject
class MediaPart(PlexObject):
""" Represents a single media part (often a single file) for the media this belongs to.
Attributes:
TAG (str): 'Part'
server (:class:`~plexapi.server.PlexServer`): PlexServer object this is from.
initpath (str): Relative path requested when retrieving specified data.
media (:class:`~plexapi.media.Media`): Media object this part belongs to.
container (str): Container type of this media part (ex: avi).
duration (int): Length of this media part in milliseconds.
file (str): Path to this file on disk (ex: /media/Movies/Cars.(2006)/Cars.cd2.avi)
id (int): Unique ID of this media part.
indexes (str, None): None or SD.
key (str): Key used to access this media part (ex: /library/parts/46618/1389985872/file.avi).
size (int): Size of this file in bytes (ex: 733884416).
streams (list<:class:`~plexapi.media.MediaPartStream`>): List of streams in this media part.
"""
TAG = 'Part'
def _loadData(self, data):
""" Load attribute values from Plex XML response. """
self._data = data
self.container = data.attrib.get('container')
self.duration = cast(int, data.attrib.get('duration'))
self.file = data.attrib.get('file')
self.id = cast(int, data.attrib.get('id'))
self.indexes = data.attrib.get('indexes')
self.key = data.attrib.get('key')
self.size = cast(int, data.attrib.get('size'))
self.decision = data.attrib.get('decision')
self.optimizedForStreaming = cast(bool, data.attrib.get('optimizedForStreaming'))
self.syncItemId = cast(int, data.attrib.get('syncItemId'))
self.syncState = data.attrib.get('syncState')
self.videoProfile = data.attrib.get('videoProfile')
self.streams = self._buildStreams(data)
def _buildStreams(self, data):
streams = []
for elem in data:
for cls in (VideoStream, AudioStream, SubtitleStream):
if elem.attrib.get('streamType') == str(cls.STREAMTYPE):
streams.append(cls(self._server, elem, self._initpath))
return streams
def videoStreams(self):
""" Returns a list of :class:`~plexapi.media.VideoStream` objects in this MediaPart. """
return [stream for stream in self.streams if stream.streamType == VideoStream.STREAMTYPE]
def audioStreams(self):
""" Returns a list of :class:`~plexapi.media.AudioStream` objects in this MediaPart. """
return [stream for stream in self.streams if stream.streamType == AudioStream.STREAMTYPE]
def subtitleStreams(self):
""" Returns a list of :class:`~plexapi.media.SubtitleStream` objects in this MediaPart. """
return [stream for stream in self.streams if stream.streamType == SubtitleStream.STREAMTYPE]
class MediaPartStream(PlexObject):
""" Base class for media streams. These consist of video, audio and subtitles.
Attributes:
server (:class:`~plexapi.server.PlexServer`): PlexServer object this is from.
initpath (str): Relative path requested when retrieving specified data.
part (:class:`~plexapi.media.MediaPart`): Media part this stream belongs to.
codec (str): Codec of this stream (ex: srt, ac3, mpeg4).
codecID (str): Codec ID (ex: XVID).
id (int): Unique stream ID on this server.
index (int): Unknown
language (str): Stream language (ex: English, ไทย).
languageCode (str): Ascii code for language (ex: eng, tha).
selected (bool): True if this stream is selected.
streamType (int): Stream type (1=:class:`~plexapi.media.VideoStream`,
2=:class:`~plexapi.media.AudioStream`, 3=:class:`~plexapi.media.SubtitleStream`).
type (int): Alias for streamType.
"""
def _loadData(self, data):
""" Load attribute values from Plex XML response. """
self._data = data
self.codec = data.attrib.get('codec')
self.codecID = data.attrib.get('codecID')
self.id = cast(int, data.attrib.get('id'))
self.index = cast(int, data.attrib.get('index', '-1'))
self.language = data.attrib.get('language')
self.languageCode = data.attrib.get('languageCode')
self.selected = cast(bool, data.attrib.get('selected', '0'))
self.streamType = cast(int, data.attrib.get('streamType'))
self.type = cast(int, data.attrib.get('streamType'))
@staticmethod
def parse(server, data, initpath): # pragma: no cover seems to be dead code.
""" Factory method returns a new MediaPartStream from xml data. """
STREAMCLS = {1: VideoStream, 2: AudioStream, 3: SubtitleStream}
stype = cast(int, data.attrib.get('streamType'))
cls = STREAMCLS.get(stype, MediaPartStream)
return cls(server, data, initpath)
@utils.registerPlexObject
class VideoStream(MediaPartStream):
""" Respresents a video stream within a :class:`~plexapi.media.MediaPart`.
Attributes:
TAG (str): 'Stream'
STREAMTYPE (int): 1
bitDepth (int): Bit depth (ex: 8).
bitrate (int): Bitrate (ex: 1169)
cabac (int): Unknown
chromaSubsampling (str): Chroma Subsampling (ex: 4:2:0).
colorSpace (str): Unknown
duration (int): Duration of video stream in milliseconds.
frameRate (float): Frame rate (ex: 23.976)
frameRateMode (str): Unknown
hasScallingMatrix (bool): True if video stream has a scaling matrix.
height (int): Height of video stream.
level (int): Videl stream level (?).
profile (str): Video stream profile (ex: asp).
refFrames (int): Unknown
scanType (str): Video stream scan type (ex: progressive).
title (str): Title of this video stream.
width (int): Width of video stream.
"""
TAG = 'Stream'
STREAMTYPE = 1
def _loadData(self, data):
""" Load attribute values from Plex XML response. """
super(VideoStream, self)._loadData(data)
self.bitDepth = cast(int, data.attrib.get('bitDepth'))
self.bitrate = cast(int, data.attrib.get('bitrate'))
self.cabac = cast(int, data.attrib.get('cabac'))
self.chromaSubsampling = data.attrib.get('chromaSubsampling')
self.colorSpace = data.attrib.get('colorSpace')
self.duration = cast(int, data.attrib.get('duration'))
self.frameRate = cast(float, data.attrib.get('frameRate'))
self.frameRateMode = data.attrib.get('frameRateMode')
self.hasScallingMatrix = cast(bool, data.attrib.get('hasScallingMatrix'))
self.height = cast(int, data.attrib.get('height'))
self.level = cast(int, data.attrib.get('level'))
self.profile = data.attrib.get('profile')
self.refFrames = cast(int, data.attrib.get('refFrames'))
self.scanType = data.attrib.get('scanType')
self.title = data.attrib.get('title')
self.width = cast(int, data.attrib.get('width'))
@utils.registerPlexObject
class AudioStream(MediaPartStream):
""" Respresents a audio stream within a :class:`~plexapi.media.MediaPart`.
Attributes:
TAG (str): 'Stream'
STREAMTYPE (int): 2
audioChannelLayout (str): Audio channel layout (ex: 5.1(side)).
bitDepth (int): Bit depth (ex: 16).
bitrate (int): Audio bitrate (ex: 448).
bitrateMode (str): Bitrate mode (ex: cbr).
channels (int): number of channels in this stream (ex: 6).
dialogNorm (int): Unknown (ex: -27).
duration (int): Duration of audio stream in milliseconds.
samplingRate (int): Sampling rate (ex: xxx)
title (str): Title of this audio stream.
"""
TAG = 'Stream'
STREAMTYPE = 2
def _loadData(self, data):
""" Load attribute values from Plex XML response. """
super(AudioStream, self)._loadData(data)
self.audioChannelLayout = data.attrib.get('audioChannelLayout')
self.bitDepth = cast(int, data.attrib.get('bitDepth'))
self.bitrate = cast(int, data.attrib.get('bitrate'))
self.bitrateMode = data.attrib.get('bitrateMode')
self.channels = cast(int, data.attrib.get('channels'))
self.dialogNorm = cast(int, data.attrib.get('dialogNorm'))
self.duration = cast(int, data.attrib.get('duration'))
self.samplingRate = cast(int, data.attrib.get('samplingRate'))
self.title = data.attrib.get('title')
@utils.registerPlexObject
class SubtitleStream(MediaPartStream):
""" Respresents a audio stream within a :class:`~plexapi.media.MediaPart`.
Attributes:
TAG (str): 'Stream'
STREAMTYPE (int): 3
format (str): Subtitle format (ex: srt).
key (str): Key of this subtitle stream (ex: /library/streams/212284).
title (str): Title of this subtitle stream.
"""
TAG = 'Stream'
STREAMTYPE = 3
def _loadData(self, data):
""" Load attribute values from Plex XML response. """
super(SubtitleStream, self)._loadData(data)
self.format = data.attrib.get('format')
self.key = data.attrib.get('key')
self.title = data.attrib.get('title')
@utils.registerPlexObject
class Session(PlexObject):
""" Represents a current session. """
TAG = 'Session'
def _loadData(self, data):
self.id = data.attrib.get('id')
self.bandwidth = utils.cast(int, data.attrib.get('bandwidth'))
self.location = data.attrib.get('location')
@utils.registerPlexObject
class TranscodeSession(PlexObject):
""" Represents a current transcode session.
Attributes:
TAG (str): 'TranscodeSession'
TODO: Document this.
"""
TAG = 'TranscodeSession'
def _loadData(self, data):
""" Load attribute values from Plex XML response. """
self._data = data
self.audioChannels = cast(int, data.attrib.get('audioChannels'))
self.audioCodec = data.attrib.get('audioCodec')
self.audioDecision = data.attrib.get('audioDecision')
self.container = data.attrib.get('container')
self.context = data.attrib.get('context')
self.duration = cast(int, data.attrib.get('duration'))
self.height = cast(int, data.attrib.get('height'))
self.key = data.attrib.get('key')
self.progress = cast(float, data.attrib.get('progress'))
self.protocol = data.attrib.get('protocol')
self.remaining = cast(int, data.attrib.get('remaining'))
self.speed = cast(int, data.attrib.get('speed'))
self.throttled = cast(int, data.attrib.get('throttled'))
self.sourceVideoCodec = data.attrib.get('sourceVideoCodec')
self.videoCodec = data.attrib.get('videoCodec')
self.videoDecision = data.attrib.get('videoDecision')
self.width = cast(int, data.attrib.get('width'))
class MediaTag(PlexObject):
""" Base class for media tags used for filtering and searching your library
items or navigating the metadata of media items in your library. Tags are
the construct used for things such as Country, Director, Genre, etc.
Attributes:
server (:class:`~plexapi.server.PlexServer`): Server this client is connected to.
id (id): Tag ID (This seems meaningless except to use it as a unique id).
role (str): Unknown
tag (str): Name of the tag. This will be Animation, SciFi etc for Genres. The name of
person for Directors and Roles (ex: Animation, Stephen Graham, etc).
<Hub_Search_Attributes>: Attributes only applicable in search results from
PlexServer :func:`~plexapi.server.PlexServer.search()`. They provide details of which
library section the tag was found as well as the url to dig deeper into the results.
* key (str): API URL to dig deeper into this tag (ex: /library/sections/1/all?actor=9081).
* librarySectionID (int): Section ID this tag was generated from.
* librarySectionTitle (str): Library section title this tag was found.
* librarySectionType (str): Media type of the library section this tag was found.
* tagType (int): Tag type ID.
* thumb (str): URL to thumbnail image.
"""
def _loadData(self, data):
""" Load attribute values from Plex XML response. """
self._data = data
self.id = cast(int, data.attrib.get('id'))
self.role = data.attrib.get('role')
self.tag = data.attrib.get('tag')
# additional attributes only from hub search
self.key = data.attrib.get('key')
self.librarySectionID = cast(int, data.attrib.get('librarySectionID'))
self.librarySectionTitle = data.attrib.get('librarySectionTitle')
self.librarySectionType = data.attrib.get('librarySectionType')
self.tagType = cast(int, data.attrib.get('tagType'))
self.thumb = data.attrib.get('thumb')
def items(self, *args, **kwargs):
""" Return the list of items within this tag. This function is only applicable
in search results from PlexServer :func:`~plexapi.server.PlexServer.search()`.
"""
if not self.key:
raise BadRequest('Key is not defined for this tag: %s' % self.tag)
return self.fetchItems(self.key)
@utils.registerPlexObject
class Collection(MediaTag):
""" Represents a single Collection media tag.
Attributes:
TAG (str): 'Collection'
FILTER (str): 'collection'
"""
TAG = 'Collection'
FILTER = 'collection'
@utils.registerPlexObject
class Label(MediaTag):
""" Represents a single label media tag.
Attributes:
TAG (str): 'label'
FILTER (str): 'label'
"""
TAG = 'Label'
FILTER = 'label'
@utils.registerPlexObject
class Country(MediaTag):
""" Represents a single Country media tag.
Attributes:
TAG (str): 'Country'
FILTER (str): 'country'
"""
TAG = 'Country'
FILTER = 'country'
@utils.registerPlexObject
class Director(MediaTag):
""" Represents a single Director media tag.
Attributes:
TAG (str): 'Director'
FILTER (str): 'director'
"""
TAG = 'Director'
FILTER = 'director'
@utils.registerPlexObject
class Genre(MediaTag):
""" Represents a single Genre media tag.
Attributes:
TAG (str): 'Genre'
FILTER (str): 'genre'
"""
TAG = 'Genre'
FILTER = 'genre'
@utils.registerPlexObject
class Mood(MediaTag):
""" Represents a single Mood media tag.
Attributes:
TAG (str): 'Mood'
FILTER (str): 'mood'
"""
TAG = 'Mood'
FILTER = 'mood'
@utils.registerPlexObject
class Producer(MediaTag):
""" Represents a single Producer media tag.
Attributes:
TAG (str): 'Producer'
FILTER (str): 'producer'
"""
TAG = 'Producer'
FILTER = 'producer'
@utils.registerPlexObject
class Role(MediaTag):
""" Represents a single Role (actor/actress) media tag.
Attributes:
TAG (str): 'Role'
FILTER (str): 'role'
"""
TAG = 'Role'
FILTER = 'role'
@utils.registerPlexObject
class Similar(MediaTag):
""" Represents a single Similar media tag.
Attributes:
TAG (str): 'Similar'
FILTER (str): 'similar'
"""
TAG = 'Similar'
FILTER = 'similar'
@utils.registerPlexObject
class Writer(MediaTag):
""" Represents a single Writer media tag.
Attributes:
TAG (str): 'Writer'
FILTER (str): 'writer'
"""
TAG = 'Writer'
FILTER = 'writer'
@utils.registerPlexObject
class Chapter(PlexObject):
""" Represents a single Writer media tag.
Attributes:
TAG (str): 'Chapter'
"""
TAG = 'Chapter'
def _loadData(self, data):
self._data = data
self.id = cast(int, data.attrib.get('id', 0))
self.filter = data.attrib.get('filter') # I couldn't filter on it anyways
self.tag = data.attrib.get('tag')
self.title = self.tag
self.index = cast(int, data.attrib.get('index'))
self.start = cast(int, data.attrib.get('startTimeOffset'))
self.end = cast(int, data.attrib.get('endTimeOffset'))
@utils.registerPlexObject
class Field(PlexObject):
""" Represents a single Field.
Attributes:
TAG (str): 'Field'
"""
TAG = 'Field'
def _loadData(self, data):
self._data = data
self.name = data.attrib.get('name')
self.locked = cast(bool, data.attrib.get('locked'))
| 48,656
|
https://github.com/NREL/Radiance/blob/master/src/gen/genclock.c
|
Github Open Source
|
Open Source
|
BSD-2-Clause
| 2,021
|
Radiance
|
NREL
|
C
|
Code
| 436
| 1,879
|
#ifndef lint
static const char RCSid[] = "$Id: genclock.c,v 2.5 2003/06/08 12:03:09 schorsch Exp $";
#endif
/*
* Generate an analog clock.
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <ctype.h>
#define PI 3.14159265358979323846
#define FACEBITMAP "clockface.hex"
char myfacemat[] = "white_plastic";
double myfacearg[5] = {.85,.85,.85,0,0};
char mycasemat[] = "black_plastic";
double mycasearg[5] = {.08,.08,.08,.03,.04};
char *facemat = myfacemat;
char *casemat = mycasemat;
char *name = "clock";
static void
genmats() /* put out our materials */
{
if (facemat == myfacemat)
printf("\nvoid plastic %s\n0\n0\n5 %f %f %f %f %f\n",
myfacemat, myfacearg[0], myfacearg[1],
myfacearg[2], myfacearg[3], myfacearg[4]);
if (casemat == mycasemat)
printf("\nvoid plastic %s\n0\n0\n5 %f %f %f %f %f\n",
mycasemat, mycasearg[0], mycasearg[1],
mycasearg[2], mycasearg[3], mycasearg[4]);
printf("\n%s brighttext clock_face_paint\n2 hexbit4x1.fnt %s\n",
facemat, FACEBITMAP);
printf("0\n11\n\t0\t-1\t1\n\t0\t.0185\t0\n\t0\t0\t-.00463\n");
printf("\t.02\t1\n");
printf("\nvoid glass clock_crystal\n0\n0\n3 .95 .95 .95\n");
printf("\nvoid plastic hand_paint\n0\n0\n5 .03 .03 .03 0 0\n");
}
static void
genclock() /* put out clock body */
{
printf("\n%s ring %s.case_back\n", casemat, name);
printf("0\n0\n8\t0\t0\t0\n\t-1\t0\t0\n\t0\t1.1\n");
printf("\n%s cylinder %s.case_outer\n", casemat, name);
printf("0\n0\n7\t0\t0\t0\n\t.12\t0\t0\n\t1.1\n");
printf("\n%s ring %s.case_front\n", casemat, name);
printf("0\n0\n8\t.12\t0\t0\n\t1\t0\t0\n\t1\t1.1\n");
printf("\n%s cylinder %s.case_inner\n", casemat, name);
printf("0\n0\n7\t.05\t0\t0\n\t.12\t0\t0\n\t1\n");
printf("\nclock_crystal ring %s.crystal\n", name);
printf("0\n0\n8\t.10\t0\t0\n\t1\t0\t0\n\t0\t1\n");
printf("\nclock_face_paint ring %s.face\n", name);
printf("0\n0\n8\t.05\t0\t0\n\t1\t0\t0\n\t0\t1\n");
}
static void
rvert(x, y, z, ang) /* print rotated vertex */
double x, y, z, ang;
{
static double lastang=0, sa=0, ca=1;
if (ang != lastang) {
sa = sin(-ang);
ca = cos(-ang);
lastang = ang;
}
printf("%15.12g %15.12g %15.12g\n", x, y*ca-z*sa, z*ca+y*sa);
}
static void
genhands(hour) /* generate correct hand positions */
double hour;
{
double hrot, mrot;
hrot = 2.*PI/12. * hour;
mrot = 2.*PI * (hour - floor(hour));
printf("\nhand_paint polygon %s.hour_hand\n", name);
printf("0\n0\n12\n");
rvert(.06, -.03, -.06, hrot);
rvert(.06, .03, -.06, hrot);
rvert(.06, .025, .5, hrot);
rvert(.06, -.025, .5, hrot);
printf("\nhand_paint polygon %s.minute_hand\n", name);
printf("0\n0\n12\n");
rvert(.07, -.02, -.1, mrot);
rvert(.07, .02, -.1, mrot);
rvert(.07, .01, .9, mrot);
rvert(.07, -.01, .9, mrot);
}
int
main(argc, argv)
int argc;
char *argv[];
{
int i, j;
double hour;
for (i = 1; i < argc && argv[i][0] == '-'; i++)
switch (argv[i][1]) {
case 'f':
facemat = argv[++i];
break;
case 'c':
casemat = argv[++i];
break;
case 'n':
name = argv[++i];
break;
default:
goto userr;
}
if (i >= argc)
goto userr;
if (!isdigit(argv[i][0]))
goto userr;
for (j = 1; isdigit(argv[i][j]); j++)
;
if (argv[i][j] == ':')
hour = atoi(argv[i]) + atoi(argv[i]+j+1)/60.0;
else if (!argv[i][j] || argv[i][j] == '.')
hour = atof(argv[i]);
else
goto userr;
putchar('#'); /* print header */
for (i = 0; i < argc; i++) {
putchar(' ');
fputs(argv[i], stdout);
}
putchar('\n');
genmats(); /* print materials */
genclock(); /* generate clock */
genhands(hour); /* generate hands */
exit(0);
userr:
fputs("Usage: ", stderr);
fputs(argv[0], stderr);
fputs(" [-f face_mat][-c case_mat][-n name] {HH:MM | HH.hh}\n", stderr);
exit(1);
}
| 25,816
|
https://github.com/dotfury/aPeoplesCalendarWeb/blob/master/src/volunteer.js
|
Github Open Source
|
Open Source
|
MIT
| null |
aPeoplesCalendarWeb
|
dotfury
|
JavaScript
|
Code
| 140
| 480
|
import React from 'react';
import './volunteer.css';
export function Volunteer() {
return (
<div id='volunteerWrapper'>
<div id='volunteerContent'>
<header id='volunteerHeader'>
<p id='volunteerHeaderText'>Volunteer</p>
</header>
<p className='volunteerText'>Whether you are an expert in African labor history, a developer with feature ideas, or are just someone who can proofread calendar events, we welcome your efforts and suggestions towards helping make our calendar more comprehensive and easier to use.</p>
<ul>
<li>
<p className='volunteerListText'>Are you a history buff who noticed an important figure or event missing from the calendar? <a className='volunteerLink' target='_blank' rel="noopener noreferrer" href='https://docs.google.com/forms/d/e/1FAIpQLScWvVl15jwOMNyltSzl3elc_mEQzRqamlkKy0HpEvX3fYt_sA/viewform'>Make an event suggestion!</a></p>
</li>
<li>
<p className='volunteerListText'>Are you a developer who has a feature idea? <a className='volunteerLink' target='_blank' rel="noopener noreferrer" href='https://github.com/huntzinger92/aPeoplesCalendarWeb'>Our code is open-source</a>.</p>
</li>
<li>
<p className='volunteerListText'>Have a different way to help? Feel free to contact us via <a className='volunteerLink' target='_blank' rel="noopener noreferrer" id='emailLink' href='mailto:apeoplescalendar@gmail.com'>email</a>.
</p>
</li>
</ul>
</div>
</div>
);
};
| 7,205
|
https://github.com/jfeigel/behavioral-beginnings/blob/master/src/stylesheets/base/_contact.sass
|
Github Open Source
|
Open Source
|
MIT
| null |
behavioral-beginnings
|
jfeigel
|
Sass
|
Code
| 61
| 261
|
.contact-container
position: relative
padding-bottom: 3rem
.background
position: absolute
top: 0
left: 0
width: 100%
height: 100%
background-image: url('../images/Southlake.png')
background-position: center
background-size: cover
opacity: .4
z-index: -1
filter: grayscale(100%)
.contact-details
> [class^='col-']
font-weight: 500
text-align: center
.fa
margin-right: 1rem
.row
.row
margin-right: 0
margin-left: 0
form
margin-top: 3rem
.form-group
label
color: $gray
&.is-focused
label
color: $brand-secondary
.form-control
background-image: linear-gradient($brand-secondary, $brand-secondary), linear-gradient($light-gray, $light-gray)
| 46,905
|
https://github.com/jaamal/overclocking/blob/master/sources/Trees/src/avlTree/mergers/AvlTreeArrayRecursiveBlockMerger.java
|
Github Open Source
|
Open Source
|
MIT
| null |
overclocking
|
jaamal
|
Java
|
Code
| 79
| 244
|
package avlTree.mergers;
import avlTree.IAvlTree;
import avlTree.helpers.IRebalancingCounter;
public class AvlTreeArrayRecursiveBlockMerger extends AvlTreeArrayMergerWithStatisticsCollecting {
@Override
protected IAvlTree merge(IAvlTree[] trees, IRebalancingCounter rebalancingCounter) {
final int blockLength = 31;
while (trees.length != 1) {
IAvlTree[] blocks = new IAvlTree[(trees.length + blockLength - 1) / blockLength];
for (int j = 0; j < blocks.length; ++j) {
int offset = j * blockLength;
int count = Math.min(trees.length - offset, blockLength);
blocks[j] = new MergingStrategy(trees, offset, count).apply(rebalancingCounter);
}
trees = blocks;
}
return trees[0];
}
}
| 10,394
|
https://github.com/gustavo-mendel/my-college-projects/blob/master/monitoria-ilp/lista6/N2.py
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
my-college-projects
|
gustavo-mendel
|
Python
|
Code
| 85
| 205
|
n = int(input())
gerais = [e for e in input().split()]
m = int(input())
proib = [e for e in input().split()]
q = int(input())
arr = [e for e in input().split()]
for i in range(q):
key = arr[i]
esq = 0
dir = m-1
achou = False
while esq <= dir:
meio = (esq + dir) // 2
if proib[meio] == key:
achou = True
break
elif key < proib[meio]:
dir = meio - 1
else:
esq = meio + 1
if achou:
print('Proibido')
else:
print('Geral')
| 7,582
|
https://github.com/lhq46688/TinyWeather/blob/master/app/src/main/java/com/peng/tinyweather/data/remote/RemoteDataSource.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,018
|
TinyWeather
|
lhq46688
|
Java
|
Code
| 214
| 787
|
package com.peng.tinyweather.data.remote;
import android.widget.Toast;
import com.peng.tinyweather.data.DataSource;
import com.peng.tinyweather.gson.AQI;
import com.peng.tinyweather.gson.Weather;
import com.peng.tinyweather.util.HttpUtil;
import com.peng.tinyweather.util.Utility;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
/**
* Created by peng on 2018/2/4.
*/
public class RemoteDataSource implements DataSource {
private static final String WEATHER_URL = "https://free-api.heweather.com/s6/weather?" +
"key=34fcb36bcc8a42d2b0fe9b549cce8f8c&location=";
private static final String AQI_URL = "https://free-api.heweather.com/s6/air/now?" +
"key=34fcb36bcc8a42d2b0fe9b549cce8f8c&location=";
@Override
public void loadWeatherData(String city, LoadWeatherDataCallback callback) {
requestWeather(city, callback);
}
@Override
public void loadAQIData(String city, LoadAQIDataCallback callback) {
requestAQI(city, callback);
}
@Override
public void saveWeatherData(String city, String weatherString) {
// current do nothing here
}
@Override
public void saveAQIData(String city, String aqiString) {
// current do nothing here
}
public void requestWeather(final String countyName, final LoadWeatherDataCallback callback) {
String weatherUrl = WEATHER_URL + countyName;
HttpUtil.sendOkHttpRequest(weatherUrl, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
callback.onWeatherDataNotAvailable();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String responseText = response.body().string();
final Weather weather = Utility.handleHeAPIResponse(responseText, Weather.class);
callback.onWeatherDataLoaded(weather);
}
});
//loadBingPicPathFromGuolinAPI();
}
public void requestAQI(final String countyName, final LoadAQIDataCallback callback) {
String aqiUrl = AQI_URL + countyName;
HttpUtil.sendOkHttpRequest(aqiUrl, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
callback.onAQIDataNotAvailable();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String responseText = response.body().string();
final AQI aqi = Utility.handleHeAPIResponse(responseText, AQI.class);
callback.onAQIDataLoaded(aqi);
}
});
}
}
| 48,009
|
https://github.com/darkoverlordofdata/learnopengl/blob/master/lessons/1.4.2.sbti/glm.c
|
Github Open Source
|
Open Source
|
MIT
| null |
learnopengl
|
darkoverlordofdata
|
C
|
Code
| 7,867
| 25,160
|
/*
The MIT License (MIT)
Copyright (c) <2018> <>
Corange definitions used for gl math.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "glm.h"
int rawcast(float x) {
union {
float f;
int i;
} u;
u.f = x;
return u.i;
}
float max(float x, float y) {
return x > y ? x : y;
}
float min(float x, float y) {
return x < y ? x : y;
}
float clamp(float x, float bottom, float top) {
x = max(x, bottom);
x = min(x, top);
return x;
}
bool between(float x, float bottom, float top) {
return (x > bottom) && (x < top);
}
bool between_or(float x, float bottom, float top) {
return (x >= bottom) && (x <= top);
}
float saturate(float x) {
x = max(x, 0.0);
x = min(x, 1.0);
return x;
}
float lerp(float p1, float p2, float amount) {
return (p2 * amount) + (p1 * (1-amount));
}
float smoothstep(float p1, float p2, float amount) {
float scaled_amount = amount*amount*(3 - 2*amount);
return lerp( p1, p2, scaled_amount );
}
float smootherstep(float p1, float p2, float amount) {
float scaled_amount = amount*amount*amount*(amount*(amount*6 - 15) + 10);
return lerp( p1, p2, scaled_amount );
}
float cosine_interp(float p1, float p2, float amount) {
float mu2 = (1-cos(amount*M_PI))/2;
return (p2*(1-mu2)+p1*mu2);
}
float nearest_interp(float p1, float p2, float amount) {
amount = roundf(amount);
if (amount) { return p2; }
else { return p1; }
}
float cubic_interp(float p1, float p2, float p3, float p4, float amount) {
float amount_sqrd = amount * amount;
float amount_cubd = amount * amount * amount;
float a1 = p4 - p3 - p2 + p1;
float a2 = p1 - p2 - a1;
float a3 = p3 - p1;
float a4 = p2;
return (a1 * amount_cubd) + (a2 * amount_sqrd) + (a3 * amount) + a4;
}
float binearest_interp(float tl, float tr, float bl, float br, float x_amount, float y_amount) {
x_amount = roundf(x_amount);
y_amount = roundf(y_amount);
if( x_amount && !y_amount ) { return br; }
if( !x_amount && y_amount ) { return tl; }
if( !x_amount && !y_amount ) { return bl; }
if( x_amount && y_amount ) { return tr; }
return 0.0f;
}
float bilinear_interp(float tl, float tr, float bl, float br, float x_amount, float y_amount) {
float left = lerp(tl, bl, y_amount);
float right = lerp(tr,br, y_amount);
return lerp(right, left, x_amount);
}
float bicosine_interp(float tl, float tr, float bl, float br, float x_amount, float y_amount) {
float left = cosine_interp(tl, bl, y_amount);
float right = cosine_interp(tr, br, y_amount);
return cosine_interp(right, left, x_amount);
}
float bismoothstep_interp(float tl, float tr, float bl, float br, float x_amount, float y_amount) {
float left = smoothstep(tl, bl, y_amount);
float right = smoothstep(tr, br, y_amount);
return smoothstep(right, left, x_amount);
}
float bismootherstep_interp(float tl, float tr, float bl, float br, float x_amount, float y_amount) {
float left = smootherstep(tl, bl, y_amount);
float right = smootherstep(tr, br, y_amount);
return smootherstep(right, left, x_amount);
}
vec2 vec2_new(float x, float y) {
vec2 v;
v.x = x;
v.y = y;
return v;
}
vec2 vec2_zero() {
return vec2_new(0, 0);
}
vec2 vec2_one() {
return vec2_new(1, 1);
}
vec2 vec2_add(vec2 v1, vec2 v2) {
vec2 v;
v.x = v1.x + v2.x;
v.y = v1.y + v2.y;
return v;
}
vec2 vec2_sub(vec2 v1, vec2 v2) {
vec2 v;
v.x = v1.x - v2.x;
v.y = v1.y - v2.y;
return v;
}
vec2 vec2_div(vec2 v, float fac) {
v.x = v.x / fac;
v.y = v.y / fac;
return v;
}
vec2 vec2_div_vec2(vec2 v1, vec2 v2) {
v1.x = v1.x / v2.x;
v1.y = v1.y / v2.y;
return v1;
}
vec2 vec2_mul(vec2 v, float fac) {
v.x = v.x * fac;
v.y = v.y * fac;
return v;
}
vec2 vec2_mul_vec2(vec2 v1, vec2 v2) {
vec2 v;
v.x = v1.x * v2.x;
v.y = v1.y * v2.y;
return v;
}
vec2 vec2_pow(vec2 v, float exp) {
v.x = pow(v.x, exp);
v.y = pow(v.y, exp);
return v;
}
vec2 vec2_neg(vec2 v) {
v.x = -v.x;
v.y = -v.y;
return v;
}
vec2 vec2_abs(vec2 v) {
v.x = fabs(v.x);
v.y = fabs(v.y);
return v;
}
vec2 vec2_floor(vec2 v) {
v.x = floor(v.x);
v.y = floor(v.y);
return v;
}
vec2 vec2_fmod(vec2 v, float val) {
v.x = fmod(v.x, val);
v.y = fmod(v.y, val);
return v;
}
vec2 vec2_max(vec2 v, float x) {
v.x = max(v.x, x);
v.y = max(v.y, x);
return v;
}
vec2 vec2_min(vec2 v, float x) {
v.x = min(v.x, x);
v.y = min(v.y, x);
return v;
}
vec2 vec2_clamp(vec2 v, float b, float t) {
v.x = clamp(v.x, b, t);
v.y = clamp(v.y, b, t);
return v;
}
void vec2_print(vec2 v) {
printf("vec2(%4.2f,%4.2f)", v.x, v.y);
}
float vec2_dot(vec2 v1, vec2 v2) {
return (v1.x * v2.x) + (v1.y * v2.y);
}
float vec2_length_sqrd(vec2 v) {
float length = 0.0;
length += v.x * v.x;
length += v.y * v.y;
return length;
}
float vec2_length(vec2 v) {
return sqrt(vec2_length_sqrd(v));
}
float vec2_dist_sqrd(vec2 v1, vec2 v2) {
return (v1.x - v2.x) * (v1.x - v2.x) +
(v1.y - v2.y) * (v1.y - v2.y);
}
float vec2_dist(vec2 v1, vec2 v2) {
return sqrt(vec2_dist_sqrd(v1, v2));
}
float vec2_dist_manhattan(vec2 v1, vec2 v2) {
return fabs(v1.x - v2.x) + fabs(v1.y - v2.y);
}
vec2 vec2_normalize(vec2 v) {
float len = vec2_length(v);
return vec2_div(v, len);
}
vec2 vec2_reflect(vec2 v1, vec2 v2) {
return vec2_sub(v1, vec2_mul(v2, 2 * vec2_dot(v1, v2)));
}
vec2 vec2_from_string(char* s) {
char* pEnd;
double d1, d2;
d1 = strtod(s,&pEnd);
d2 = strtod(pEnd,NULL);
vec2 v;
v.x = d1;
v.y = d2;
return v;
}
bool vec2_equ(vec2 v1, vec2 v2) {
if(!(v1.x == v2.x)) { return false; }
if(!(v1.y == v2.y)) { return false; }
return true;
}
void vec2_to_array(vec2 v, float* out) {
out[0] = v.x;
out[1] = v.y;
}
int vec2_hash(vec2 v) {
return abs(rawcast(v.x) ^ rawcast(v.y));
}
int vec2_mix_hash(vec2 v) {
int raw_vx = abs(rawcast(v.x));
int raw_vy = abs(rawcast(v.y));
int h1 = raw_vx << 1;
int h2 = raw_vy << 3;
int h3 = raw_vx >> 8;
int h4 = raw_vy << 7;
int h5 = raw_vx >> 12;
int h6 = raw_vy >> 15;
int h7 = raw_vx << 2;
int h8 = raw_vy << 6;
int h9 = raw_vx >> 2;
int h10 = raw_vy << 9;
int h11 = raw_vx >> 21;
int h12 = raw_vy >> 13;
int res1 = h1 ^ h2 ^ h3;
int res2 = h4 ^ h5 ^ h6;
int res3 = h7 ^ h8 ^ h9;
int res4 = h10 ^ h11 ^ h12;
return (res1 * 10252247) ^ (res2 * 70209673) ^ (res3 * 104711) ^ (res4 * 63589);
}
vec2 vec2_saturate(vec2 v) {
v.x = saturate(v.x);
v.y = saturate(v.y);
return v;
}
vec2 vec2_lerp(vec2 v1, vec2 v2, float amount) {
vec2 v;
v.x = lerp(v1.x, v2.x, amount);
v.y = lerp(v1.y, v2.y, amount);
return v;
}
vec2 vec2_smoothstep(vec2 v1, vec2 v2, float amount) {
float scaled_amount = amount*amount*(3 - 2*amount);
return vec2_lerp( v1, v2, scaled_amount );
}
vec2 vec2_smootherstep(vec2 v1, vec2 v2, float amount) {
float scaled_amount = amount*amount*amount*(amount*(amount*6 - 15) + 10);
return vec2_lerp( v1, v2, scaled_amount );
}
/* vec3 */
vec3 vec3_new(float x, float y, float z) {
vec3 v;
v.x = x;
v.y = y;
v.z = z;
return v;
}
vec3 vec3_zero() {
return vec3_new(0, 0, 0);
}
vec3 vec3_one() {
return vec3_new(1, 1, 1);
}
vec3 vec3_red() {
return vec3_new(1, 0, 0);
}
vec3 vec3_green() {
return vec3_new(0, 1, 0);
}
vec3 vec3_blue() {
return vec3_new(0, 0, 1);
}
vec3 vec3_white() {
return vec3_new(1, 1, 1);
}
vec3 vec3_black() {
return vec3_new(0, 0, 0);
}
vec3 vec3_grey() {
return vec3_new(0.5, 0.5, 0.5);
}
vec3 vec3_light_grey() {
return vec3_new(0.75,0.75,0.75);
}
vec3 vec3_dark_grey() {
return vec3_new(0.25,0.25,0.25);
}
vec3 vec3_up() {
return vec3_new(0, 1, 0);
}
vec3 vec3_add(vec3 v1, vec3 v2) {
vec3 v;
v.x = v1.x + v2.x;
v.y = v1.y + v2.y;
v.z = v1.z + v2.z;
return v;
}
vec3 vec3_sub(vec3 v1, vec3 v2) {
vec3 v;
v.x = v1.x - v2.x;
v.y = v1.y - v2.y;
v.z = v1.z - v2.z;
return v;
}
vec3 vec3_div(vec3 v, float fac) {
v.x = v.x / fac;
v.y = v.y / fac;
v.z = v.z / fac;
return v;
}
vec3 vec3_div_vec3(vec3 v1, vec3 v2) {
vec3 v;
v.x = v1.x / v2.x;
v.y = v1.y / v2.y;
v.z = v1.z / v2.z;
return v;
}
vec3 vec3_mul(vec3 v, float fac) {
v.x = v.x * fac;
v.y = v.y * fac;
v.z = v.z * fac;
return v;
}
vec3 vec3_mul_vec3(vec3 v1, vec3 v2) {
vec3 v;
v.x = v1.x * v2.x;
v.y = v1.y * v2.y;
v.z = v1.z * v2.z;
return v;
}
vec3 vec3_pow(vec3 v, float exp) {
v.x = pow(v.x, exp);
v.y = pow(v.y, exp);
v.z = pow(v.z, exp);
return v;
}
vec3 vec3_neg(vec3 v) {
v.x = -v.x;
v.y = -v.y;
v.z = -v.z;
return v;
}
vec3 vec3_abs(vec3 v) {
v.x = fabs(v.x);
v.y = fabs(v.y);
v.z = fabs(v.z);
return v;
}
vec3 vec3_floor(vec3 v) {
v.x = floor(v.x);
v.y = floor(v.y);
v.z = floor(v.z);
return v;
}
vec3 vec3_fmod(vec3 v, float val) {
v.x = fmod(v.x, val);
v.y = fmod(v.y, val);
v.z = fmod(v.z, val);
return v;
}
void vec3_print(vec3 v) {
printf("vec3(%4.2f,%4.2f,%4.2f)", v.x, v.y, v.z);
}
float vec3_dot(vec3 v1, vec3 v2) {
return (v1.x * v2.x) + (v1.y * v2.y) + (v1.z * v2.z);
}
vec3 vec3_cross(vec3 v1, vec3 v2) {
vec3 v;
v.x = (v1.y * v2.z) - (v1.z * v2.y);
v.y = (v1.z * v2.x) - (v1.x * v2.z);
v.z = (v1.x * v2.y) - (v1.y * v2.x);
return v;
}
float vec3_length_sqrd(vec3 v) {
float length = 0.0;
length += v.x * v.x;
length += v.y * v.y;
length += v.z * v.z;
return length;
}
float vec3_length(vec3 v) {
return sqrt(vec3_length_sqrd(v));
}
float vec3_dist_sqrd(vec3 v1, vec3 v2) {
return (v1.x - v2.x) * (v1.x - v2.x) +
(v1.y - v2.y) * (v1.y - v2.y) +
(v1.z - v2.z) * (v1.z - v2.z);
}
float vec3_dist(vec3 v1, vec3 v2) {
return sqrt(vec3_dist_sqrd(v1, v2));
}
float vec3_dist_manhattan(vec3 v1, vec3 v2) {
return fabs(v1.x - v2.x) + fabs(v1.y - v2.y) + fabs(v1.z - v2.z);
}
vec3 vec3_normalize(vec3 v) {
float len = vec3_length(v);
if (len == 0.0) {
return vec3_zero();
} else {
return vec3_div(v, len);
}
}
vec3 vec3_reflect(vec3 v1, vec3 v2) {
return vec3_sub(v1, vec3_mul(v2, 2 * vec3_dot(v1, v2)));
}
vec3 vec3_project(vec3 v1, vec3 v2) {
return vec3_sub(v1, vec3_mul(v2, vec3_dot(v1, v2)));
}
vec3 vec3_from_string(char* s) {
char* pEnd;
double d1, d2, d3;
d1 = strtod(s,&pEnd);
d2 = strtod(pEnd,&pEnd);
d3 = strtod(pEnd,NULL);
vec3 v;
v.x = d1;
v.y = d2;
v.z = d3;
return v;
}
bool vec3_equ(vec3 v1, vec3 v2) {
if (v1.x != v2.x) { return false; }
if (v1.y != v2.y) { return false; }
if (v1.z != v2.z) { return false; }
return true;
}
bool vec3_neq(vec3 v1, vec3 v2) {
if (v1.x != v2.x) { return true; }
if (v1.y != v2.y) { return true; }
if (v1.z != v2.z) { return true; }
return false;
}
void vec3_to_array(vec3 v, float* out) {
out[0] = v.x;
out[1] = v.y;
out[2] = v.z;
}
int vec3_hash(vec3 v) {
return abs( rawcast(v.x) ^ rawcast(v.y) ^ rawcast(v.z) );
}
vec4 vec3_to_homogeneous(vec3 v){
return vec4_new(v.x, v.y, v.z, 1.0);
};
vec3 vec3_saturate(vec3 v) {
v.x = saturate(v.x);
v.y = saturate(v.y);
v.z = saturate(v.z);
return v;
}
vec3 vec3_lerp(vec3 v1, vec3 v2, float amount) {
vec3 v;
v.x = lerp(v1.x, v2.x, amount);
v.y = lerp(v1.y, v2.y, amount);
v.z = lerp(v1.z, v2.z, amount);
return v;
}
vec3 vec3_smoothstep(vec3 v1, vec3 v2, float amount) {
float scaled_amount = amount*amount*(3 - 2*amount);
return vec3_lerp( v1, v2, scaled_amount );
}
vec3 vec3_smootherstep(vec3 v1, vec3 v2, float amount) {
float scaled_amount = amount*amount*amount*(amount*(amount*6 - 15) + 10);
return vec3_lerp( v1, v2, scaled_amount );
}
/* vec4 */
vec4 vec4_new(float x, float y, float z, float w) {
vec4 v;
v.x = x;
v.y = y;
v.z = z;
v.w = w;
return v;
}
vec4 vec4_zero() {
return vec4_new(0, 0, 0, 0);
}
vec4 vec4_one() {
return vec4_new(1, 1, 1, 1);
}
vec4 vec4_red() {
return vec4_new(1,0,0,1);
}
vec4 vec4_green() {
return vec4_new(0,1,0,1);
}
vec4 vec4_blue() {
return vec4_new(0,0,1,1);
}
vec4 vec4_white() {
return vec4_new(1,1,1,1);
}
vec4 vec4_black() {
return vec4_new(0,0,0,1);
}
vec4 vec4_grey() {
return vec4_new(0.5,0.5,0.5, 1);
}
vec4 vec4_light_grey() {
return vec4_new(0.75,0.75,0.75, 1);
}
vec4 vec4_dark_grey() {
return vec4_new(0.25,0.25,0.25, 1);
}
vec4 vec4_add(vec4 v1, vec4 v2) {
vec4 v;
v.x = v1.x + v2.x;
v.y = v1.y + v2.y;
v.z = v1.z + v2.z;
v.w = v1.w + v2.w;
return v;
}
vec4 vec4_sub(vec4 v1, vec4 v2) {
vec4 v;
v.x = v1.x - v2.x;
v.y = v1.y - v2.y;
v.z = v1.z - v2.z;
v.w = v1.w - v2.w;
return v;
}
vec4 vec4_div(vec4 v, float fac) {
v.x = v.x / fac;
v.y = v.y / fac;
v.z = v.z / fac;
v.w = v.w / fac;
return v;
}
vec4 vec4_mul(vec4 v, float fac) {
v.x = v.x * fac;
v.y = v.y * fac;
v.z = v.z * fac;
v.w = v.w * fac;
return v;
}
vec4 vec4_mul_vec4(vec4 v1, vec4 v2) {
vec4 v;
v.x = v1.x * v2.x;
v.y = v1.y * v2.y;
v.z = v1.z * v2.z;
v.w = v1.w * v2.w;
return v;
}
vec4 vec4_pow(vec4 v, float exp) {
v.x = pow(v.x, exp);
v.y = pow(v.y, exp);
v.z = pow(v.z, exp);
v.w = pow(v.w, exp);
return v;
}
vec4 vec4_neg(vec4 v) {
v.x = -v.x;
v.y = -v.y;
v.z = -v.z;
v.w = -v.w;
return v;
}
vec4 vec4_abs(vec4 v) {
v.x = fabs(v.x);
v.y = fabs(v.y);
v.z = fabs(v.z);
v.w = fabs(v.w);
return v;
}
vec4 vec4_floor(vec4 v) {
v.x = floor(v.x);
v.y = floor(v.y);
v.z = floor(v.z);
v.w = floor(v.w);
return v;
}
vec4 vec4_fmod(vec4 v, float val) {
v.x = fmod(v.x, val);
v.y = fmod(v.y, val);
v.z = fmod(v.z, val);
v.w = fmod(v.w, val);
return v;
}
vec4 vec4_sqrt(vec4 v) {
v.x = sqrt(v.x);
v.y = sqrt(v.y);
v.z = sqrt(v.z);
v.w = sqrt(v.w);
return v;
}
void vec4_print(vec4 v) {
printf("vec4(%4.2f, %4.2f, %4.2f, %4.2f)", v.x, v.y, v.z, v.w);
}
float vec4_dot(vec4 v1, vec4 v2) {
return (v1.x * v2.x) + (v1.y * v2.y) + (v1.z * v2.z) + (v1.w * v2.w);
}
float vec4_length_sqrd(vec4 v) {
float length = 0.0;
length += v.x * v.x;
length += v.y * v.y;
length += v.z * v.z;
length += v.w * v.w;
return length;
}
float vec4_length(vec4 v) {
return sqrt(vec4_length_sqrd(v));
}
float vec4_dist_sqrd(vec4 v1, vec4 v2) {
return (v1.x - v2.x) * (v1.x - v2.x) +
(v1.y - v2.y) * (v1.y - v2.y) +
(v1.y - v2.z) * (v1.y - v2.z) +
(v1.y - v2.w) * (v1.y - v2.w);
}
float vec4_dist(vec4 v1, vec4 v2) {
return sqrt(vec4_dist_sqrd(v1, v2));
}
float vec4_dist_manhattan(vec4 v1, vec4 v2) {
return fabs(v1.x - v2.x) + fabs(v1.y - v2.y) + fabs(v1.z - v2.z) + fabs(v1.w - v2.w);
}
vec4 vec4_normalize(vec4 v) {
float len = vec4_length(v);
if (len == 0.0) {
return vec4_zero();
} else {
return vec4_div(v, len);
}
}
vec4 vec4_reflect(vec4 v1, vec4 v2) {
return vec4_sub(v1, vec4_mul(v2, 2 * vec4_dot(v1, v2)));
}
vec4 vec4_from_string(char* s) {
char* end;
double d1, d2, d3, d4;
d1 = strtod(s,&end);
d2 = strtod(end,&end);
d3 = strtod(end,&end);
d4 = strtod(end,NULL);
vec4 v;
v.x = d1;
v.y = d2;
v.z = d3;
v.w = d4;
return v;
}
vec4 vec4_max(vec4 v1, vec4 v2) {
v1.x = max(v1.x, v2.x);
v1.y = max(v1.y, v2.y);
v1.z = max(v1.z, v2.z);
v1.w = max(v1.w, v2.w);
return v1;
}
vec4 vec4_min(vec4 v1, vec4 v2) {
v1.x = min(v1.x, v2.x);
v1.y = min(v1.y, v2.y);
v1.z = min(v1.z, v2.z);
v1.w = min(v1.w, v2.w);
return v1;
}
bool vec4_equ(vec4 v1, vec4 v2) {
if(!(v1.x == v2.x)) { return false; }
if(!(v1.y == v2.y)) { return false; }
if(!(v1.z == v2.z)) { return false; }
if(!(v1.w == v2.w)) { return false; }
return true;
}
void vec4_to_array(vec4 v, float* out) {
out[0] = v.x;
out[1] = v.y;
out[2] = v.z;
out[3] = v.w;
}
vec3 vec4_from_homogeneous(vec4 v) {
vec3 vec = vec3_new(v.x,v.y,v.z);
return vec3_div(vec, v.w);
};
int vec4_hash(vec4 v) {
return abs( rawcast(v.x) ^ rawcast(v.y) ^ rawcast(v.z) ^ rawcast(v.w) );
}
vec4 vec4_saturate(vec4 v) {
v.x = saturate(v.x);
v.y = saturate(v.y);
v.z = saturate(v.z);
v.w = saturate(v.w);
return v;
}
vec4 vec4_lerp(vec4 v1, vec4 v2, float amount) {
vec4 v;
v.x = lerp(v1.x, v2.x, amount);
v.y = lerp(v1.y, v2.y, amount);
v.z = lerp(v1.z, v2.z, amount);
v.w = lerp(v1.w, v2.w, amount);
return v;
}
vec4 vec4_smoothstep(vec4 v1, vec4 v2, float amount) {
float scaled_amount = amount*amount*(3 - 2*amount);
return vec4_lerp( v1, v2, scaled_amount );
}
vec4 vec4_smootherstep(vec4 v1, vec4 v2, float amount) {
float scaled_amount = amount*amount*amount*(amount*(amount*6 - 15) + 10);
return vec4_lerp( v1, v2, scaled_amount );
}
vec4 vec4_nearest_interp(vec4 v1, vec4 v2, float amount) {
vec4 v;
v.w = nearest_interp(v1.w, v2.w, amount);
v.x = nearest_interp(v1.x, v2.x, amount);
v.y = nearest_interp(v1.y, v2.y, amount);
v.z = nearest_interp(v1.z, v2.z, amount);
return v;
}
vec4 vec4_binearest_interp(vec4 tl, vec4 tr, vec4 bl, vec4 br, float x_amount, float y_amount) {
vec4 v;
v.x = binearest_interp( tl.x, tr.x, bl.x, br.x, x_amount, y_amount );
v.y = binearest_interp( tl.y, tr.y, bl.y, br.y, x_amount, y_amount );
v.z = binearest_interp( tl.z, tr.z, bl.z, br.z, x_amount, y_amount );
v.w = binearest_interp( tl.w, tr.w, bl.w, br.w, x_amount, y_amount );
return v;
}
vec4 vec4_bilinear_interp(vec4 tl, vec4 tr, vec4 bl, vec4 br, float x_amount, float y_amount) {
vec4 v;
v.x = bilinear_interp( tl.x, tr.x, bl.x, br.x, x_amount, y_amount );
v.y = bilinear_interp( tl.y, tr.y, bl.y, br.y, x_amount, y_amount );
v.z = bilinear_interp( tl.z, tr.z, bl.z, br.z, x_amount, y_amount );
v.w = bilinear_interp( tl.w, tr.w, bl.w, br.w, x_amount, y_amount );
return v;
}
quat quat_id() {
return quat_new(0, 0, 0, 1);
}
quat quat_new(float x, float y, float z, float w) {
quat q;
q.x = x;
q.y = y;
q.z = z;
q.w = w;
return q;
}
float quat_at(quat q, int i) {
float* values = (float*)(&q);
return values[i];
}
float quat_real(quat q) {
return q.w;
}
vec3 quat_imaginaries(quat q) {
return vec3_new(q.x, q.y, q.z);
}
quat quat_from_euler(vec3 r) {
float fc1 = cosf( r.z / 2.0f );
float fc2 = cosf( r.x / 2.0f );
float fc3 = cosf( r.y / 2.0f );
float fs1 = sinf( r.z / 2.0f );
float fs2 = sinf( r.x / 2.0f );
float fs3 = sinf( r.y / 2.0f );
return quat_new(
fc1 * fc2 * fs3 - fs1 * fs2 * fc3,
fc1 * fs2 * fc3 + fs1 * fc2 * fs3,
fs1 * fc2 * fc3 - fc1 * fs2 * fs3,
fc1 * fc2 * fc3 + fs1 * fs2 * fs3
);
}
quat quat_angle_axis(float angle, vec3 axis) {
float sine = sinf( angle / 2.0f );
float cosine = cosf( angle / 2.0f );
return quat_normalize(quat_new(
axis.x * sine,
axis.y * sine,
axis.z * sine,
cosine));
}
quat quat_rotation_x(float angle) {
return quat_angle_axis(angle, vec3_new(1,0,0));
}
quat quat_rotation_y(float angle) {
return quat_angle_axis(angle, vec3_new(0,1,0));
}
quat quat_rotation_z(float angle) {
return quat_angle_axis(angle, vec3_new(0,0,1));
}
void quat_to_angle_axis(quat q, vec3* axis, float* angle) {
*angle = 2.0f * acosf( q.w );
float divisor = sinf( *angle / 2.0f );
if( fabs( divisor ) < FLT_EPSILON ) {
axis->x = 0.0f;
axis->y = 1.0f;
axis->z = 0.0f;
} else {
axis->x = q.x / divisor;
axis->y = q.y / divisor;
axis->z = q.z / divisor;
*axis = vec3_normalize(*axis);
}
}
vec3 quat_to_euler(quat q) {
float sqrx = q.x * q.x;
float sqry = q.y * q.y;
float sqrz = q.z * q.z;
float sqrw = q.w * q.w;
return vec3_new(
asinf( -2.0f * ( q.x * q.z - q.y * q.w ) ),
atan2f( 2.0f * ( q.y * q.z + q.x * q.w ), (-sqrx - sqry + sqrz + sqrw) ),
atan2f( 2.0f * ( q.x * q.y + q.z * q.w ), ( sqrx - sqry - sqrz + sqrw) ));
}
quat quat_mul_quat(quat q1, quat q2) {
return quat_new(
(q1.w * q2.x) + (q1.x * q2.w) + (q1.y * q2.z) - (q1.z * q2.y),
(q1.w * q2.y) - (q1.x * q2.z) + (q1.y * q2.w) + (q1.z * q2.x),
(q1.w * q2.z) + (q1.x * q2.y) - (q1.y * q2.x) + (q1.z * q2.w),
(q1.w * q2.w) - (q1.x * q2.x) - (q1.y * q2.y) - (q1.z * q2.z));
}
vec3 quat_mul_vec3(quat q, vec3 v) {
quat work = q;
work = quat_mul_quat(work, quat_normalize(quat_new(v.x, v.y, v.z, 0.0)));
work = quat_mul_quat(work, quat_inverse(q));
vec3 res = vec3_new(work.x, work.y, work.z);
return vec3_mul(res, vec3_length(v));
}
quat quat_inverse(quat q) {
float scale = quat_length(q);
quat result = quat_unit_inverse(q);
if ( scale > FLT_EPSILON ) {
result.x /= scale;
result.y /= scale;
result.z /= scale;
result.w /= scale;
}
return result;
}
quat quat_unit_inverse(quat q) {
return quat_new(-q.x, -q.y, -q.z, q.w);
}
float quat_length(quat q) {
return sqrtf(q.x*q.x + q.y*q.y + q.z*q.z + q.w*q.w);
}
quat quat_normalize(quat q) {
float scale = quat_length(q);
if ( scale > FLT_EPSILON ) {
return quat_new(
q.x / scale,
q.y / scale,
q.z / scale,
q.w / scale);
} else {
return quat_new(0,0,0,0);
}
}
quat quat_slerp(quat from, quat to, float amount) {
float scale0, scale1;
float afto1[4];
float cosom = from.x * to.x + from.y * to.y + from.z * to.z + from.w * to.w;
if ( cosom < 0.0f ) {
cosom = -cosom;
afto1[0] = -to.x;
afto1[1] = -to.y;
afto1[2] = -to.z;
afto1[3] = -to.w;
} else {
afto1[0] = to.x;
afto1[1] = to.y;
afto1[2] = to.z;
afto1[3] = to.w;
}
const float QUATERNION_DELTA_COS_MIN = 0.01f;
if ( (1.0f - cosom) > QUATERNION_DELTA_COS_MIN ) {
/* This is a standard case (slerp). */
float omega = acosf(cosom);
float sinom = sinf(omega);
scale0 = sinf((1.0f - amount) * omega) / sinom;
scale1 = sinf(amount * omega) / sinom;
} else {
/* "from" and "to" quaternions are very close */
/* so we can do a linear interpolation. */
scale0 = 1.0f - amount;
scale1 = amount;
}
return quat_new(
(scale0 * from.x) + (scale1 * afto1[0]),
(scale0 * from.y) + (scale1 * afto1[1]),
(scale0 * from.z) + (scale1 * afto1[2]),
(scale0 * from.w) + (scale1 * afto1[3]));
}
float quat_dot(quat q1, quat q2) {
return q1.x * q2.x + q1.y * q2.y + q1.z * q2.z + q1.w * q2.w;
}
quat quat_exp(vec3 w) {
float theta = sqrt(vec3_dot(w, w));
float len = theta < FLT_EPSILON ? 1 : sin(theta) / theta;
vec3 v = vec3_mul(w, len);
return quat_new(v.x, v.y, v.z, cos(theta));
}
vec3 quat_log(quat q) {
float len = vec3_length(quat_imaginaries(q));
float angle = atan2(len, q.w);
len = len > FLT_EPSILON ? angle / len : 1;
return vec3_mul(quat_imaginaries(q), len);
}
static quat quat_get_value(float t, vec3 axis) {
return quat_exp( vec3_mul(axis, t / 2.0) );
}
quat quat_constrain(quat q, vec3 axis) {
const quat orient = quat_new(0, 0, 0, 1);
vec3 vs = quat_imaginaries(q);
vec3 v0 = quat_imaginaries(orient);
float a = q.w * orient.w + vec3_dot(vs, v0);
float b = orient.w * vec3_dot(axis, vs) - q.w * vec3_dot(axis, v0) + vec3_dot(vs, vec3_mul_vec3(axis, v0));
float alpha = atan2(a, b);
float t1 = -2 * alpha + M_PI;
float t2 = -2 * alpha - M_PI;
if ( quat_dot(q, quat_get_value(t1, axis)) >
quat_dot(q, quat_get_value(t2, axis)) ) {
return quat_get_value(t1, axis);
}
return quat_get_value(t2, axis);
}
quat quat_constrain_y(quat q) {
return quat_constrain(q, vec3_new(0, 1, 0));
}
float quat_distance(quat q0, quat q1) {
quat comb = quat_mul_quat(quat_inverse(q0), q1);
return sin(vec3_length(quat_log(comb)));
}
quat quat_neg(quat q) {
q.x = -q.x;
q.y = -q.y;
q.z = -q.z;
q.w = -q.w;
return q;
}
quat quat_scale(quat q, float f) {
q.x = q.x * f;
q.y = q.y * f;
q.z = q.z * f;
q.w = q.w * f;
return q;
}
quat quat_interpolate(quat* qs, float* ws, int count) {
quat ref = quat_id();
quat ref_inv = quat_inverse(ref);
vec3 acc = vec3_zero();
for (int i = 0; i < count; i++ ) {
vec3 qlog0 = quat_log(quat_mul_quat(ref_inv, qs[i]));
vec3 qlog1 = quat_log(quat_mul_quat(ref_inv, quat_neg(qs[i])));
if (vec3_length(qlog0) < vec3_length(qlog1) ) {
acc = vec3_add(acc, vec3_mul(qlog0, ws[i]));
} else {
acc = vec3_add(acc, vec3_mul(qlog1, ws[i]));
}
}
quat res = quat_mul_quat(ref, quat_exp(acc));
return quat_normalize(res);
}
quat_dual quat_dual_new(quat real, quat dual) {
quat_dual qd;
qd.real = real;
qd.dual = dual;
return qd;
}
quat_dual quat_dual_id() {
return quat_dual_new(quat_id(), vec4_zero());
}
quat_dual quat_dual_transform(quat q, vec3 t) {
quat_dual qd;
qd.real = q;
qd.dual = quat_new(
0.5 * ( t.x * q.w + t.y * q.z - t.z * q.y),
0.5 * (-t.x * q.z + t.y * q.w + t.z * q.x),
0.5 * ( t.x * q.y - t.y * q.x + t.z * q.w),
-0.5 * ( t.x * q.x + t.y * q.y + t.z * q.z)
);
return qd;
}
quat_dual quat_dual_mul(quat_dual q0, quat_dual q1) {
return quat_dual_new(
quat_mul_quat(q0.real, q1.real),
vec4_add(
quat_mul_quat(q0.real, q1.dual),
quat_mul_quat(q0.dual, q1.real)));
}
quat_dual quat_dual_normalize(quat_dual q) {
float l = quat_length(q.real);
quat real = vec4_mul(q.real, 1.0 / l);
quat dual = vec4_mul(q.dual, 1.0 / l);
return quat_dual_new(real, vec4_sub(dual, vec4_mul(real, quat_dot(real, dual))));
}
vec3 quat_dual_mul_vec3(quat_dual q, vec3 v) {
vec3 rvc = vec3_cross(quat_imaginaries(q.real), v);
vec3 real = vec3_cross(quat_imaginaries(q.real), vec3_add(rvc, vec3_mul(v, q.real.w)));
vec3 rdc = vec3_cross(quat_imaginaries(q.real), quat_imaginaries(q.dual));
vec3 rimg = vec3_mul(quat_imaginaries(q.real), q.dual.w);
vec3 dimg = vec3_mul(quat_imaginaries(q.dual), q.real.w);
vec3 dual = vec3_sub(rimg, vec3_add(dimg, rdc));
return vec3_add(v, vec3_add(vec3_mul(real, 2), vec3_mul(dual, 2)));
}
vec3 quat_dual_mul_vec3_rot(quat_dual q, vec3 v) {
vec3 rvc = vec3_cross(quat_imaginaries(q.real), v);
vec3 real = vec3_cross(quat_imaginaries(q.real), vec3_add(rvc, vec3_mul(v, q.real.w)));
return vec3_add(v, vec3_mul(real, 2.0));
}
/* Matrix Functions */
mat2 mat2_id() {
mat2 mat;
mat.xx = 1.0f; mat.xy = 0.0f;
mat.yx = 0.0f; mat.yy = 1.0f;
return mat;
}
mat2 mat2_zero() {
mat2 mat;
mat.xx = 0.0f; mat.xy = 0.0f;
mat.yx = 0.0f; mat.yy = 0.0f;
return mat;
}
mat2 mat2_new(float xx, float xy, float yx, float yy) {
mat2 mat;
mat.xx = xx;
mat.xy = xy;
mat.yx = yx;
mat.yy = yy;
return mat;
}
mat2 mat2_mul_mat2(mat2 m1, mat2 m2) {
mat2 mat;
mat.xx = m1.xx * m2.xx + m1.xy * m2.yx;
mat.xy = m1.xx * m2.xy + m1.xy * m2.yy;
mat.yx = m1.yx * m2.xx + m1.yy * m2.yx;
mat.yy = m1.yx * m2.xy + m1.yy * m2.yy;
return mat;
}
vec2 mat2_mul_vec2(mat2 m, vec2 v) {
vec2 vec;
vec.x = v.x * m.xx + v.y * m.xy;
vec.y = v.x * m.yx + v.y * m.yy;
return vec;
}
mat2 mat2_transpose(mat2 m) {
mat2 ret;
ret.xx = m.xx;
ret.xy = m.yx;
ret.yx = m.xy;
ret.yy = m.yy;
return ret;
}
float mat2_det(mat2 m) {
return m.xx * m.yy - m.xy * m.yx;
}
mat2 mat2_inverse(mat2 m) {
float det = mat2_det(m);
float fac = 1.0 / det;
mat2 ret;
ret.xx = fac * m.yy;
ret.xy = fac * -m.xy;
ret.yx = fac * -m.yx;
ret.yy = fac * m.xx;
return ret;
}
void mat2_to_array(mat2 m, float* out) {
out[0] = m.xx;
out[1] = m.xy;
out[2] = m.yx;
out[3] = m.yy;
}
void mat2_print(mat2 m) {
printf("|%4.2f, %4.2f|\n", m.xx, m.xy);
printf("|%4.2f, %4.2f|\n", m.yx, m.yy);
}
mat2 mat2_rotation(float a) {
mat2 m;
m.xx = cos(a);
m.xy = -sin(a);
m.yx = sin(a);
m.yy = cos(a);
return m;
}
/* Matrix 3x3 */
mat3 mat3_zero() {
mat3 mat;
mat.xx = 0.0f;
mat.xy = 0.0f;
mat.xz = 0.0f;
mat.yx = 0.0f;
mat.yy = 0.0f;
mat.yz = 0.0f;
mat.zx = 0.0f;
mat.zy = 0.0f;
mat.zz = 0.0f;
return mat;
}
mat3 mat3_id() {
mat3 mat;
mat.xx = 1.0f;
mat.xy = 0.0f;
mat.xz = 0.0f;
mat.yx = 0.0f;
mat.yy = 1.0f;
mat.yz = 0.0f;
mat.zx = 0.0f;
mat.zy = 0.0f;
mat.zz = 1.0f;
return mat;
}
mat3 mat3_new(float xx, float xy, float xz,
float yx, float yy, float yz,
float zx, float zy, float zz) {
mat3 mat;
mat.xx = xx;
mat.xy = xy;
mat.xz = xz;
mat.yx = yx;
mat.yy = yy;
mat.yz = yz;
mat.zx = zx;
mat.zy = zy;
mat.zz = zz;
return mat;
}
mat3 mat3_mul_mat3(mat3 m1, mat3 m2) {
mat3 mat;
mat.xx = (m1.xx * m2.xx) + (m1.xy * m2.yx) + (m1.xz * m2.zx);
mat.xy = (m1.xx * m2.xy) + (m1.xy * m2.yy) + (m1.xz * m2.zy);
mat.xz = (m1.xx * m2.xz) + (m1.xy * m2.yz) + (m1.xz * m2.zz);
mat.yx = (m1.yx * m2.xx) + (m1.yy * m2.yx) + (m1.yz * m2.zx);
mat.yy = (m1.yx * m2.xy) + (m1.yy * m2.yy) + (m1.yz * m2.zy);
mat.yz = (m1.yx * m2.xz) + (m1.yy * m2.yz) + (m1.yz * m2.zz);
mat.zx = (m1.zx * m2.xx) + (m1.zy * m2.yx) + (m1.zz * m2.zx);
mat.zy = (m1.zx * m2.xy) + (m1.zy * m2.yy) + (m1.zz * m2.zy);
mat.zz = (m1.zx * m2.xz) + (m1.zy * m2.yz) + (m1.zz * m2.zz);
return mat;
}
vec3 mat3_mul_vec3(mat3 m, vec3 v) {
vec3 vec;
vec.x = (m.xx * v.x) + (m.xy * v.y) + (m.xz * v.z);
vec.y = (m.yx * v.x) + (m.yy * v.y) + (m.yz * v.z);
vec.z = (m.zx * v.x) + (m.zy * v.y) + (m.zz * v.z);
return vec;
}
mat3 mat3_transpose(mat3 m) {
mat3 ret;
ret.xx = m.xx;
ret.xy = m.yx;
ret.xz = m.zx;
ret.yx = m.xy;
ret.yy = m.yy;
ret.yz = m.zy;
ret.zx = m.xz;
ret.zy = m.yz;
ret.zz = m.zz;
return ret;
}
float mat3_det(mat3 m) {
return (m.xx * m.yy * m.zz) + (m.xy * m.yz * m.zx) + (m.xz * m.yx * m.zy) -
(m.xz * m.yy * m.zx) - (m.xy * m.yx * m.zz) - (m.xx * m.yz * m.zy);
}
mat3 mat3_inverse(mat3 m) {
float det = mat3_det(m);
float fac = 1.0 / det;
mat3 ret;
ret.xx = fac * mat2_det(mat2_new(m.yy, m.yz, m.zy, m.zz));
ret.xy = fac * mat2_det(mat2_new(m.xz, m.xy, m.zz, m.zy));
ret.xz = fac * mat2_det(mat2_new(m.xy, m.xz, m.yy, m.yz));
ret.yx = fac * mat2_det(mat2_new(m.yz, m.yx, m.zz, m.zx));
ret.yy = fac * mat2_det(mat2_new(m.xx, m.xz, m.zx, m.zz));
ret.yz = fac * mat2_det(mat2_new(m.xz, m.xx, m.yz, m.yx));
ret.zx = fac * mat2_det(mat2_new(m.yx, m.yy, m.zx, m.zy));
ret.zy = fac * mat2_det(mat2_new(m.xy, m.xx, m.zy, m.zx));
ret.zz = fac * mat2_det(mat2_new(m.xx, m.xy, m.yx, m.yy));
return ret;
}
void mat3_to_array(mat3 m, float* out) {
out[0] = m.xx;
out[1] = m.yx;
out[2] = m.zx;
out[3] = m.xy;
out[4] = m.yy;
out[5] = m.zy;
out[6] = m.xz;
out[7] = m.yz;
out[8] = m.zz;
}
void mat3_print(mat3 m) {
printf("|%4.2f, %4.2f, %4.2f|\n", m.xx, m.xy, m.xz);
printf("|%4.2f, %4.2f, %4.2f|\n", m.yx, m.yy, m.yz);
printf("|%4.2f, %4.2f, %4.2f|\n", m.zx, m.zy, m.zz);
}
mat3 mat3_rotation_x(float a) {
mat3 m = mat3_id();
m.yy = cos(a);
m.yz = -sin(a);
m.zy = sin(a);
m.zz = cos(a);
return m;
}
mat3 mat3_scale(vec3 s) {
mat3 m = mat3_id();
m.xx = s.x;
m.yy = s.y;
m.zz = s.z;
return m;
}
mat3 mat3_rotation_y(float a) {
mat3 m = mat3_id();
m.xx = cos(a);
m.xz = sin(a);
m.zx = -sin(a);
m.zz = cos(a);
return m;
}
mat3 mat3_rotation_z(float a) {
mat3 m = mat3_id();
m.xx = cos(a);
m.xy = -sin(a);
m.yx = sin(a);
m.yy = cos(a);
return m;
}
mat3 mat3_rotation_angle_axis(float a, vec3 v) {
mat3 m;
float c = cos(a);
float s = sin(a);
float nc = 1 - c;
m.xx = v.x * v.x * nc + c;
m.xy = v.x * v.y * nc - v.z * s;
m.xz = v.x * v.z * nc + v.y * s;
m.yx = v.y * v.x * nc + v.z * s;
m.yy = v.y * v.y * nc + c;
m.yz = v.y * v.z * nc - v.x * s;
m.zx = v.z * v.x * nc - v.y * s;
m.zy = v.z * v.y * nc + v.x * s;
m.zz = v.z * v.z * nc + c;
return m;
}
/* Matrix 4x4 */
mat4 mat4_zero() {
mat4 mat;
mat.xx = 0.0f;
mat.xy = 0.0f;
mat.xz = 0.0f;
mat.xw = 0.0f;
mat.yx = 0.0f;
mat.yy = 0.0f;
mat.yz = 0.0f;
mat.yw = 0.0f;
mat.zx = 0.0f;
mat.zy = 0.0f;
mat.zz = 0.0f;
mat.zw = 0.0f;
mat.wx = 0.0f;
mat.wy = 0.0f;
mat.wz = 0.0f;
mat.ww = 0.0f;
return mat;
}
mat4 mat4_id(){
mat4 mat = mat4_zero();
mat.xx = 1.0f;
mat.yy = 1.0f;
mat.zz = 1.0f;
mat.ww = 1.0f;
return mat;
}
float mat4_at(mat4 m, int x, int y) {
float* arr = (float*)(&m);
return arr[x + (y*4)];
}
mat4 mat4_set(mat4 m, int x, int y, float v) {
float* arr = (float*)(&m);
arr[x + (y*4)] = v;
return m;
}
mat4 mat4_new(float xx, float xy, float xz, float xw,
float yx, float yy, float yz, float yw,
float zx, float zy, float zz, float zw,
float wx, float wy, float wz, float ww) {
mat4 mat;
mat.xx = xx;
mat.xy = xy;
mat.xz = xz;
mat.xw = xw;
mat.yx = yx;
mat.yy = yy;
mat.yz = yz;
mat.yw = yw;
mat.zx = zx;
mat.zy = zy;
mat.zz = zz;
mat.zw = zw;
mat.wx = wx;
mat.wy = wy;
mat.wz = wz;
mat.ww = ww;
return mat;
}
mat4 mat4_transpose(mat4 m) {
mat4 mat;
mat.xx = m.xx;
mat.xy = m.yx;
mat.xz = m.zx;
mat.xw = m.wx;
mat.yx = m.xy;
mat.yy = m.yy;
mat.yz = m.zy;
mat.yw = m.wy;
mat.zx = m.xz;
mat.zy = m.yz;
mat.zz = m.zz;
mat.zw = m.wz;
mat.wx = m.xw;
mat.wy = m.yw;
mat.wz = m.zw;
mat.ww = m.ww;
return mat;
}
mat4 mat3_to_mat4(mat3 m) {
mat4 mat;
mat.xx = m.xx;
mat.xy = m.xy;
mat.xz = m.xz;
mat.xw = 0.0f;
mat.yx = m.yx;
mat.yy = m.yy;
mat.yz = m.yz;
mat.yw = 0.0f;
mat.zx = m.zx;
mat.zy = m.zy;
mat.zz = m.zz;
mat.zw = 0.0f;
mat.wx = 0.0f;
mat.wy = 0.0f;
mat.wz = 0.0f;
mat.ww = 1.0f;
return mat;
}
mat4 mat4_mul_mat4(mat4 m1, mat4 m2) {
mat4 mat;
mat.xx = (m1.xx * m2.xx) + (m1.xy * m2.yx) + (m1.xz * m2.zx) + (m1.xw * m2.wx);
mat.xy = (m1.xx * m2.xy) + (m1.xy * m2.yy) + (m1.xz * m2.zy) + (m1.xw * m2.wy);
mat.xz = (m1.xx * m2.xz) + (m1.xy * m2.yz) + (m1.xz * m2.zz) + (m1.xw * m2.wz);
mat.xw = (m1.xx * m2.xw) + (m1.xy * m2.yw) + (m1.xz * m2.zw) + (m1.xw * m2.ww);
mat.yx = (m1.yx * m2.xx) + (m1.yy * m2.yx) + (m1.yz * m2.zx) + (m1.yw * m2.wx);
mat.yy = (m1.yx * m2.xy) + (m1.yy * m2.yy) + (m1.yz * m2.zy) + (m1.yw * m2.wy);
mat.yz = (m1.yx * m2.xz) + (m1.yy * m2.yz) + (m1.yz * m2.zz) + (m1.yw * m2.wz);
mat.yw = (m1.yx * m2.xw) + (m1.yy * m2.yw) + (m1.yz * m2.zw) + (m1.yw * m2.ww);
mat.zx = (m1.zx * m2.xx) + (m1.zy * m2.yx) + (m1.zz * m2.zx) + (m1.zw * m2.wx);
mat.zy = (m1.zx * m2.xy) + (m1.zy * m2.yy) + (m1.zz * m2.zy) + (m1.zw * m2.wy);
mat.zz = (m1.zx * m2.xz) + (m1.zy * m2.yz) + (m1.zz * m2.zz) + (m1.zw * m2.wz);
mat.zw = (m1.zx * m2.xw) + (m1.zy * m2.yw) + (m1.zz * m2.zw) + (m1.zw * m2.ww);
mat.wx = (m1.wx * m2.xx) + (m1.wy * m2.yx) + (m1.wz * m2.zx) + (m1.ww * m2.wx);
mat.wy = (m1.wx * m2.xy) + (m1.wy * m2.yy) + (m1.wz * m2.zy) + (m1.ww * m2.wy);
mat.wz = (m1.wx * m2.xz) + (m1.wy * m2.yz) + (m1.wz * m2.zz) + (m1.ww * m2.wz);
mat.ww = (m1.wx * m2.xw) + (m1.wy * m2.yw) + (m1.wz * m2.zw) + (m1.ww * m2.ww);
return mat;
}
vec4 mat4_mul_vec4(mat4 m, vec4 v) {
vec4 vec;
vec.x = (m.xx * v.x) + (m.xy * v.y) + (m.xz * v.z) + (m.xw * v.w);
vec.y = (m.yx * v.x) + (m.yy * v.y) + (m.yz * v.z) + (m.yw * v.w);
vec.z = (m.zx * v.x) + (m.zy * v.y) + (m.zz * v.z) + (m.zw * v.w);
vec.w = (m.wx * v.x) + (m.wy * v.y) + (m.wz * v.z) + (m.ww * v.w);
return vec;
}
vec3 mat4_mul_vec3(mat4 m, vec3 v) {
vec4 v_homo = vec4_new(v.x, v.y, v.z, 1);
v_homo = mat4_mul_vec4(m, v_homo);
v_homo = vec4_div(v_homo, v_homo.w);
return vec3_new(v_homo.x, v_homo.y, v_homo.z);
}
mat3 mat4_to_mat3(mat4 m) {
mat3 mat;
mat.xx = m.xx;
mat.xy = m.xy;
mat.xz = m.xz;
mat.yx = m.yx;
mat.yy = m.yy;
mat.yz = m.yz;
mat.zx = m.zx;
mat.zy = m.zy;
mat.zz = m.zz;
return mat;
}
quat mat4_to_quat(mat4 m) {
float tr = m.xx + m.yy + m.zz;
if (tr > 0.0f) {
float s = sqrtf( tr + 1.0f );
float w = s / 2.0f;
float x = ( mat4_at(m, 1, 2) - mat4_at(m, 2, 1) ) * (0.5f / s);
float y = ( mat4_at(m, 2, 0) - mat4_at(m, 0, 2) ) * (0.5f / s);
float z = ( mat4_at(m, 0, 1) - mat4_at(m, 1, 0) ) * (0.5f / s);
return quat_new(x, y, z, w);
} else {
int nxt[3] = {1, 2, 0};
float q[4];
int i, j, k;
i = 0;
if ( mat4_at(m, 1, 1) > mat4_at(m, 0, 0) ) { i = 1; }
if ( mat4_at(m, 2, 2) > mat4_at(m, i, i) ) { i = 2; }
j = nxt[i];
k = nxt[j];
float s = sqrtf( (mat4_at(m, i, i) - (mat4_at(m, j, j) + mat4_at(m, k, k))) + 1.0f );
q[i] = s * 0.5f;
if ( s != 0.0f ) { s = 0.5f / s; }
q[3] = ( mat4_at(m, j, k) - mat4_at(m, k, j) ) * s;
q[j] = ( mat4_at(m, i, j) + mat4_at(m, j, i) ) * s;
q[k] = ( mat4_at(m, i, k) + mat4_at(m, k, i) ) * s;
return quat_new(q[0], q[1], q[2], q[3]);
}
}
quat_dual mat4_to_quat_dual(mat4 m) {
quat rotation = mat4_to_quat(m);
vec3 translation = mat4_mul_vec3(m, vec3_zero());
return quat_dual_transform(rotation, translation);
}
float mat4_det(mat4 m) {
float cofact_xx = mat3_det(mat3_new(m.yy, m.yz, m.yw, m.zy, m.zz, m.zw, m.wy, m.wz, m.ww));
float cofact_xy = -mat3_det(mat3_new(m.yx, m.yz, m.yw, m.zx, m.zz, m.zw, m.wx, m.wz, m.ww));
float cofact_xz = mat3_det(mat3_new(m.yx, m.yy, m.yw, m.zx, m.zy, m.zw, m.wx, m.wy, m.ww));
float cofact_xw = -mat3_det(mat3_new(m.yx, m.yy, m.yz, m.zx, m.zy, m.zz, m.wx, m.wy, m.wz));
return (cofact_xx * m.xx) + (cofact_xy * m.xy) + (cofact_xz * m.xz) + (cofact_xw * m.xw);
}
mat4 mat4_inverse(mat4 m) {
float det = mat4_det(m);
float fac = 1.0 / det;
mat4 ret;
ret.xx = fac * mat3_det(mat3_new(m.yy, m.yz, m.yw, m.zy, m.zz, m.zw, m.wy, m.wz, m.ww));
ret.xy = fac * -mat3_det(mat3_new(m.yx, m.yz, m.yw, m.zx, m.zz, m.zw, m.wx, m.wz, m.ww));
ret.xz = fac * mat3_det(mat3_new(m.yx, m.yy, m.yw, m.zx, m.zy, m.zw, m.wx, m.wy, m.ww));
ret.xw = fac * -mat3_det(mat3_new(m.yx, m.yy, m.yz, m.zx, m.zy, m.zz, m.wx, m.wy, m.wz));
ret.yx = fac * -mat3_det(mat3_new(m.xy, m.xz, m.xw, m.zy, m.zz, m.zw, m.wy, m.wz, m.ww));
ret.yy = fac * mat3_det(mat3_new(m.xx, m.xz, m.xw, m.zx, m.zz, m.zw, m.wx, m.wz, m.ww));
ret.yz = fac * -mat3_det(mat3_new(m.xx, m.xy, m.xw, m.zx, m.zy, m.zw, m.wx, m.wy, m.ww));
ret.yw = fac * mat3_det(mat3_new(m.xx, m.xy, m.xz, m.zx, m.zy, m.zz, m.wx, m.wy, m.wz));
ret.zx = fac * mat3_det(mat3_new(m.xy, m.xz, m.xw, m.yy, m.yz, m.yw, m.wy, m.wz, m.ww));
ret.zy = fac * -mat3_det(mat3_new(m.xx, m.xz, m.xw, m.yx, m.yz, m.yw, m.wx, m.wz, m.ww));
ret.zz = fac * mat3_det(mat3_new(m.xx, m.xy, m.xw, m.yx, m.yy, m.yw, m.wx, m.wy, m.ww));
ret.zw = fac * -mat3_det(mat3_new(m.xx, m.xy, m.xz, m.yx, m.yy, m.yz, m.wx, m.wy, m.wz));
ret.wx = fac * -mat3_det(mat3_new(m.xy, m.xz, m.xw, m.yy, m.yz, m.yw, m.zy, m.zz, m.zw));
ret.wy = fac * mat3_det(mat3_new(m.xx, m.xz, m.xw, m.yx, m.yz, m.yw, m.zx, m.zz, m.zw));
ret.wz = fac * -mat3_det(mat3_new(m.xx, m.xy, m.xw, m.yx, m.yy, m.yw, m.zx, m.zy, m.zw));
ret.ww = fac * mat3_det(mat3_new(m.xx, m.xy, m.xz, m.yx, m.yy, m.yz, m.zx, m.zy, m.zz));
ret = mat4_transpose(ret);
return ret;
}
void mat4_to_array(mat4 m, float* out) {
out[0] = m.xx;
out[1] = m.yx;
out[2] = m.zx;
out[3] = m.wx;
out[4] = m.xy;
out[5] = m.yy;
out[6] = m.zy;
out[7] = m.wy;
out[8] = m.xz;
out[9] = m.yz;
out[10] = m.zz;
out[11] = m.wz;
out[12] = m.xw;
out[13] = m.yw;
out[14] = m.zw;
out[15] = m.ww;
}
void mat4_to_array_trans(mat4 m, float* out) {
out[0] = m.xx;
out[1] = m.xy;
out[2] = m.xz;
out[3] = m.xw;
out[4] = m.yx;
out[5] = m.yy;
out[6] = m.yz;
out[7] = m.yw;
out[8] = m.zx;
out[9] = m.zy;
out[10] = m.zz;
out[11] = m.zw;
out[12] = m.wx;
out[13] = m.wy;
out[14] = m.wz;
out[15] = m.ww;
}
void mat4_print(mat4 m) {
printf("|%4.2f, %4.2f, %4.2f, %4.2f|\n", m.xx, m.xy, m.xz, m.xw);
printf("|%4.2f, %4.2f, %4.2f, %4.2f|\n", m.yx, m.yy, m.yz, m.yw);
printf("|%4.2f, %4.2f, %4.2f, %4.2f|\n", m.zx, m.zy, m.zz, m.zw);
printf("|%4.2f, %4.2f, %4.2f, %4.2f|\n", m.wx, m.wy, m.wz, m.ww);
}
mat4 mat4_view_look_at(vec3 position, vec3 target, vec3 up) {
vec3 zaxis = vec3_normalize( vec3_sub(target, position) );
vec3 xaxis = vec3_normalize( vec3_cross(up, zaxis) );
vec3 yaxis = vec3_cross(zaxis, xaxis);
mat4 view_matrix = mat4_id();
view_matrix.xx = xaxis.x;
view_matrix.xy = xaxis.y;
view_matrix.xz = xaxis.z;
view_matrix.yx = yaxis.x;
view_matrix.yy = yaxis.y;
view_matrix.yz = yaxis.z;
view_matrix.zx = -zaxis.x;
view_matrix.zy = -zaxis.y;
view_matrix.zz = -zaxis.z;
view_matrix = mat4_mul_mat4(view_matrix, mat4_translation(vec3_neg(position)) );
return view_matrix;
}
mat4 mat4_perspective(float fov, float near_clip, float far_clip, float ratio) {
float right, left, bottom, top;
right = -(near_clip * tanf(fov));
left = -right;
top = ratio * near_clip * tanf(fov);
bottom = -top;
mat4 proj_matrix = mat4_zero();
proj_matrix.xx = (2.0 * near_clip) / (right - left);
proj_matrix.yy = (2.0 * near_clip) / (top - bottom);
proj_matrix.xz = (right + left) / (right - left);
proj_matrix.yz = (top + bottom) / (top - bottom);
proj_matrix.zz = (-far_clip - near_clip) / (far_clip - near_clip);
proj_matrix.wz = -1.0;
proj_matrix.zw = ( -(2.0 * near_clip) * far_clip) / (far_clip - near_clip);
return proj_matrix;
}
mat4 mat4_orthographic(float left, float right, float bottom, float top, float clip_near, float clip_far) {
mat4 m = mat4_id();
m.xx = 2 / (right - left);
m.yy = 2 / (top - bottom);
m.zz = 1 / (clip_near - clip_far);
m.xw = -1 - 2 * left / (right - left);
m.yw = 1 + 2 * top / (bottom - top);
m.zw = clip_near / (clip_near - clip_far);
return m;
}
mat4 mat4_translation(vec3 v) {
mat4 m = mat4_id();
m.xw = v.x;
m.yw = v.y;
m.zw = v.z;
return m;
}
mat4 mat4_scale(vec3 v) {
mat4 m = mat4_id();
m.xx = v.x;
m.yy = v.y;
m.zz = v.z;
return m;
}
mat4 mat4_rotation_x(float a) {
mat4 m = mat4_id();
m.yy = cos(a);
m.yz = -sin(a);
m.zy = sin(a);
m.zz = cos(a);
return m;
}
mat4 mat4_rotation_y(float a) {
mat4 m = mat4_id();
m.xx = cos(a);
m.xz = sin(a);
m.zx = -sin(a);
m.zz = cos(a);
return m;
}
mat4 mat4_rotation_z(float a) {
mat4 m = mat4_id();
m.xx = cos(a);
m.xy = -sin(a);
m.yx = sin(a);
m.yy = cos(a);
return m;
}
mat4 mat4_rotation_axis_angle(vec3 v, float angle) {
mat4 m = mat4_id();
float c = cos(angle);
float s = sin(angle);
float nc = 1 - c;
m.xx = v.x * v.x * nc + c;
m.xy = v.x * v.y * nc - v.z * s;
m.xz = v.x * v.z * nc + v.y * s;
m.yx = v.y * v.x * nc + v.z * s;
m.yy = v.y * v.y * nc + c;
m.yz = v.y * v.z * nc - v.x * s;
m.zx = v.z * v.x * nc - v.y * s;
m.zy = v.z * v.y * nc + v.x * s;
m.zz = v.z * v.z * nc + c;
return m;
}
mat4 mat4_rotation_euler(float x, float y, float z) {
mat4 m = mat4_zero();
float cosx = cos(x);
float cosy = cos(y);
float cosz = cos(z);
float sinx = sin(x);
float siny = sin(y);
float sinz = sin(z);
m.xx = cosy * cosz;
m.yx = -cosx * sinz + sinx * siny * cosz;
m.zx = sinx * sinz + cosx * siny * cosz;
m.xy = cosy * sinz;
m.yy = cosx * cosz + sinx * siny * sinz;
m.zy = -sinx * cosz + cosx * siny * sinz;
m.xz = -siny;
m.yz = sinx * cosy;
m.zz = cosx * cosy;
m.ww = 1;
return m;
}
mat4 mat4_rotation_quat(vec4 q) {
float x2 = q.x + q.x;
float y2 = q.y + q.y;
float z2 = q.z + q.z;
float xx = q.x * x2;
float yy = q.y * y2;
float wx = q.w * x2;
float xy = q.x * y2;
float yz = q.y * z2;
float wy = q.w * y2;
float xz = q.x * z2;
float zz = q.z * z2;
float wz = q.w * z2;
return mat4_new(
1.0f - ( yy + zz ), xy - wz, xz + wy, 0.0f,
xy + wz, 1.0f - ( xx + zz ), yz - wx, 0.0f,
xz - wy, yz + wx, 1.0f - ( xx + yy ), 0.0f,
0.0f, 0.0f, 0.0f, 1.0f);
}
mat4 mat4_rotation_quat_dual(quat_dual q) {
float rx = q.real.x, ry = q.real.y, rz = q.real.z, rw = q.real.w;
float tx = q.dual.x, ty = q.dual.y, tz = q.dual.z, tw = q.dual.w;
mat4 m = mat4_id();
m.xx = rw*rw + rx*rx - ry*ry - rz*rz;
m.xy = 2.f*(rx*ry - rw*rz);
m.xz = 2*(rx*rz + rw*ry);
m.yx = 2*(rx*ry + rw*rz);
m.yy = rw*rw - rx*rx + ry*ry - rz*rz;
m.yz = 2*(ry*rz - rw*rx);
m.zx = 2*(rx*rz - rw*ry);
m.zy = 2*(ry*rz + rw*rx);
m.zz = rw*rw - rx*rx - ry*ry + rz*rz;
m.xw = -2*tw*rx + 2*rw*tx - 2*ty*rz + 2*ry*tz;
m.yw = -2*tw*ry + 2*tx*rz - 2*rx*tz + 2*rw*ty;
m.zw = -2*tw*rz + 2*rx*ty + 2*rw*tz - 2*tx*ry;
return m;
}
mat4 mat4_world(vec3 position, vec3 scale, quat rotation) {
mat4 pos_m, sca_m, rot_m, result;
pos_m = mat4_translation(position);
rot_m = mat4_rotation_quat(rotation);
sca_m = mat4_scale(scale);
result = mat4_id();
result = mat4_mul_mat4( result, pos_m );
result = mat4_mul_mat4( result, rot_m );
result = mat4_mul_mat4( result, sca_m );
return result;
}
mat4 mat4_lerp(mat4 m1, mat4 m2, float amount) {
mat4 m;
m.xx = lerp(m1.xx, m2.xx, amount);
m.xy = lerp(m1.xy, m2.xy, amount);
m.xz = lerp(m1.xz, m2.xz, amount);
m.xw = lerp(m1.xw, m2.xw, amount);
m.yx = lerp(m1.yx, m2.yx, amount);
m.yy = lerp(m1.yy, m2.yy, amount);
m.yz = lerp(m1.yz, m2.yz, amount);
m.yw = lerp(m1.yw, m2.yw, amount);
m.zx = lerp(m1.zx, m2.zx, amount);
m.zy = lerp(m1.zy, m2.zy, amount);
m.zz = lerp(m1.zz, m2.zz, amount);
m.zw = lerp(m1.zw, m2.zw, amount);
m.wx = lerp(m1.wx, m2.wx, amount);
m.wy = lerp(m1.wy, m2.wy, amount);
m.wz = lerp(m1.wz, m2.wz, amount);
m.ww = lerp(m1.ww, m2.ww, amount);
return m;
}
mat4 mat4_smoothstep(mat4 m1, mat4 m2, float amount) {
mat4 m;
m.xx = smoothstep(m1.xx, m2.xx, amount);
m.xy = smoothstep(m1.xy, m2.xy, amount);
m.xz = smoothstep(m1.xz, m2.xz, amount);
m.xw = smoothstep(m1.xw, m2.xw, amount);
m.yx = smoothstep(m1.yx, m2.yx, amount);
m.yy = smoothstep(m1.yy, m2.yy, amount);
m.yz = smoothstep(m1.yz, m2.yz, amount);
m.yw = smoothstep(m1.yw, m2.yw, amount);
m.zx = smoothstep(m1.zx, m2.zx, amount);
m.zy = smoothstep(m1.zy, m2.zy, amount);
m.zz = smoothstep(m1.zz, m2.zz, amount);
m.zw = smoothstep(m1.zw, m2.zw, amount);
m.wx = smoothstep(m1.wx, m2.wx, amount);
m.wy = smoothstep(m1.wy, m2.wy, amount);
m.wz = smoothstep(m1.wz, m2.wz, amount);
m.ww = smoothstep(m1.ww, m2.ww, amount);
return m;
}
| 32,213
|
https://github.com/mat128/wicket/blob/master/wicket-core/src/test/java/org/apache/wicket/markup/html/form/RadioGroupDisabledTestPage.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,020
|
wicket
|
mat128
|
Java
|
Code
| 214
| 529
|
/*
* 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
*
* 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.apache.wicket.markup.html.form;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.model.Model;
/**
* Tests rendering of the RadioGroup and Radio components
*
* @author igor
*/
public class RadioGroupDisabledTestPage extends WebPage
{
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* Constructor
*/
public RadioGroupDisabledTestPage()
{
Form<Void> form = new Form<Void>("form");
RadioGroup<String> group = new RadioGroup<String>("group", new Model<String>("radio2"));
group.setRenderBodyOnly(false);
WebMarkupContainer container = new WebMarkupContainer("container");
Radio<String> radio1 = new Radio<String>("radio1", new Model<String>("radio1"));
Radio<String> radio2 = new Radio<String>("radio2", new Model<String>("radio2"));
add(form);
form.add(group);
group.add(radio1);
group.add(container);
container.add(radio2);
group.setEnabled(false);
}
}
| 10,915
|
https://github.com/chcbz/cyf-api-k/blob/master/src/main/java/cn/jia/task/api/TaskController.java
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
cyf-api-k
|
chcbz
|
Java
|
Code
| 262
| 1,162
|
package cn.jia.task.api;
import cn.jia.core.common.EsSecurityHandler;
import cn.jia.core.entity.JSONRequestPage;
import cn.jia.core.entity.JSONResult;
import cn.jia.core.entity.JSONResultPage;
import cn.jia.core.util.JSONUtil;
import cn.jia.task.entity.TaskItemVO;
import cn.jia.task.entity.TaskItemVOExample;
import cn.jia.task.entity.TaskPlan;
import cn.jia.task.entity.TaskPlanExample;
import cn.jia.task.service.TaskService;
import com.github.pagehelper.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/task")
public class TaskController {
@Autowired
private TaskService taskService;
/**
* 获取任务信息
* @param id
* @return
*/
/*@PreAuthorize("hasAuthority('task-get')")*/
@RequestMapping(value = "/get", method = RequestMethod.GET)
public Object findById(@RequestParam(name = "id") Integer id) throws Exception {
TaskPlan task = taskService.find(id);
return JSONResult.success(task);
}
/**
* 创建任务
* @param task
* @return
*/
/*@PreAuthorize("hasAuthority('task-create')")*/
@RequestMapping(value = "/create", method = RequestMethod.POST)
public Object create(@RequestBody TaskPlan task) {
task.setClientId(EsSecurityHandler.clientId());
taskService.create(task);
return JSONResult.success();
}
/**
* 更新任务信息
* @param task
* @return
*/
/*@PreAuthorize("hasAuthority('task-update')")*/
@RequestMapping(value = "/update", method = RequestMethod.POST)
public Object update(@RequestBody TaskPlan task) {
taskService.update(task);
return JSONResult.success();
}
/**
* 删除任务
* @param id
* @return
*/
/*@PreAuthorize("hasAuthority('task-delete')")*/
@RequestMapping(value = "/delete", method = RequestMethod.GET)
public Object delete(@RequestParam(name = "id") Integer id) {
taskService.delete(id);
return JSONResult.success();
}
/**
* 取消任务
* @param id
* @return
*/
/*@PreAuthorize("hasAuthority('task-cancel')")*/
@RequestMapping(value = "/cancel", method = RequestMethod.GET)
public Object cancel(@RequestParam(name = "id") Integer id) {
taskService.cancel(id);
return JSONResult.success();
}
/**
* 获取所有任务信息
* @return
*/
/*@PreAuthorize("hasAuthority('task-search')")*/
@RequestMapping(value = "/search", method = RequestMethod.POST)
public Object search(@RequestBody JSONRequestPage<String> page) {
TaskPlanExample plan = JSONUtil.fromJson(page.getSearch(), TaskPlanExample.class);
plan.setClientId(EsSecurityHandler.clientId());
Page<TaskPlan> taskList = taskService.search(plan, page.getPageNum(), page.getPageSize());
JSONResultPage<TaskPlan> result = new JSONResultPage<>(taskList.getResult());
result.setPageNum(taskList.getPageNum());
result.setTotal(taskList.getTotal());
return result;
}
/**
* 获取所有任务信息
* @return 任务明细列表
*/
@RequestMapping(value = "/item/search", method = RequestMethod.POST)
public Object searchItem(@RequestBody JSONRequestPage<String> page) {
TaskItemVOExample item = JSONUtil.fromJson(page.getSearch(), TaskItemVOExample.class);
Page<TaskItemVO> taskList = taskService.findItems(item, page.getPageNum(), page.getPageSize());
JSONResultPage<TaskItemVO> result = new JSONResultPage<>(taskList.getResult());
result.setPageNum(taskList.getPageNum());
result.setTotal(taskList.getTotal());
return result;
}
}
| 31,441
|
https://github.com/promlow/books-and-tutorials/blob/master/SpriteBuilder/FlappyFly.spritebuilder/Source/libs/cocos2d-iphone/templates/cocos2d iOS Newton.xctemplate/Newton/Resources/fire.plist
|
Github Open Source
|
Open Source
|
MIT, LicenseRef-scancode-warranty-disclaimer, LicenseRef-scancode-unknown-license-reference, Libpng, CC-BY-NC-SA-2.0, GPL-1.0-or-later, CPL-1.0, GPL-2.0-only, LicenseRef-scancode-public-domain, MPL-2.0, BSD-3-Clause, BSD-2-Clause, Zlib
| 2,019
|
books-and-tutorials
|
promlow
|
XML Property List
|
Code
| 221
| 1,605
|
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>// texture</key>
<string></string>
<key>textureFileName</key>
<string>fire.png</string>
<key>// duration</key>
<string></string>
<key>// -1 = forever</key>
<string></string>
<key>duration</key>
<string>-1</string>
<key>// max particles</key>
<string></string>
<key>maxParticles</key>
<string>75</string>
<key>// life</key>
<string></string>
<key>particleLifespan</key>
<string>1.00</string>
<key>particleLifespanVariance</key>
<string>0.50</string>
<key>// emissionrate = max / life (default)</key>
<string></string>
<key>- emissionRate</key>
<string>100</string>
<key>// blend function</key>
<string></string>
<key>// normal color = 770 + 771 </key>
<string></string>
<key>// additive = 770 + 1</key>
<string></string>
<key>blendFuncSource</key>
<string>770</string>
<key>blendFuncDestination</key>
<string>1</string>
<key>// angle</key>
<string></string>
<key>angle</key>
<string>0</string>
<key>angleVariance</key>
<string>360</string>
<key>// start color</key>
<string></string>
<key>startColorRed</key>
<string>0.50</string>
<key>startColorGreen</key>
<string>0.25</string>
<key>startColorBlue</key>
<string>0</string>
<key>startColorAlpha</key>
<string>0</string>
<key>startColorVarianceRed</key>
<string>0</string>
<key>startColorVarianceGreen</key>
<string>0</string>
<key>startColorVarianceBlue</key>
<string>0</string>
<key>startColorVarianceAlpha</key>
<string>0</string>
<key>// end color</key>
<string></string>
<key>finishColorRed</key>
<string>0.50</string>
<key>finishColorGreen</key>
<string>0.25</string>
<key>finishColorBlue</key>
<string>0</string>
<key>finishColorAlpha</key>
<string>0.50</string>
<key>finishColorVarianceRed</key>
<string>0</string>
<key>finishColorVarianceGreen</key>
<string>0</string>
<key>finishColorVarianceBlue</key>
<string>0</string>
<key>finishCOlorVarianceAlpha</key>
<string>0</string>
<key>// start particle size</key>
<string></string>
<key>startParticleSize</key>
<string>100</string>
<key>startParticleSizeVariance</key>
<string>50</string>
<key>// end particle size</key>
<string></string>
<key>finishParticleSize</key>
<string>0</string>
<key>finishParticleSizeVariance</key>
<string>0</string>
<key>// start position</key>
<string></string>
<key>sourcePositionx</key>
<string>0</string>
<key>sourcePositionVariancex</key>
<string>30</string>
<key>sourcePositiony</key>
<string>0</string>
<key>sourcePositionVariancey</key>
<string>20</string>
<key>// start rotation</key>
<string></string>
<key>rotationStart</key>
<string>0</string>
<key>rotationStartVariance</key>
<string>90</string>
<key>// end rotation</key>
<string></string>
<key>rotationEnd</key>
<string>0</string>
<key>rotationEndVariance</key>
<string>180</string>
<key>// emitter type</key>
<string></string>
<key>// 0 = gravity</key>
<string></string>
<key>// 1 = radius</key>
<string></string>
<key>emitterType</key>
<string>0</string>
<key>// gravity data</key>
<string></string>
<key>gravityx</key>
<string>0</string>
<key>gravityy</key>
<string>125</string>
<key>speed</key>
<string>0</string>
<key>speedVariance</key>
<string>0</string>
<key>radialAcceleration</key>
<string>0</string>
<key>radialAccelVariance</key>
<string>0</string>
<key>tangentialAcceleration</key>
<string>0</string>
<key>tangentialAccelVariation</key>
<string>0</string>
<key>// radius data</key>
<string></string>
<key>maxRadius</key>
<string>0</string>
<key>maxradiusVariance</key>
<string>0</string>
<key>minRadius</key>
<string>0</string>
<key>rotatePerSecond</key>
<string>0</string>
<key>rotatePerSecondVariance</key>
<string>0</string>
</dict>
</plist>
| 20,709
|
https://github.com/eran1205/Radio-Stations-MS/blob/master/src/radiostation.interface.ts
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
Radio-Stations-MS
|
eran1205
|
TypeScript
|
Code
| 28
| 60
|
import { Document } from 'mongoose';
export interface RadioStation extends Document {
readonly title: string;
readonly description: string;
readonly logo: string;
readonly src: string;
readonly created_at: Date;
}
| 11,506
|
https://github.com/ebanfa/logix/blob/master/src/main/java/com/cloderia/helion/server/endpoint/RatingtypeEndPointImpl.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
logix
|
ebanfa
|
Java
|
Code
| 137
| 711
|
/**
*
*/
package com.cloderia.helion.server.endpoint;
import java.util.List;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import com.cloderia.helion.client.shared.model.Ratingtype;
import com.cloderia.helion.client.shared.ops.RatingtypeOperation;
import com.cloderia.helion.client.shared.endpoint.RatingtypeEndPoint;
import com.cloderia.helion.client.shared.service.RatingtypeService;
import com.cloderia.helion.client.shared.service.BaseEntityService;
/**
* @author Edward Banfa
*
*/
@Stateless
public class RatingtypeEndPointImpl extends
BaseEntityEndPointImpl<Ratingtype, RatingtypeOperation> implements RatingtypeEndPoint {
@Inject
RatingtypeService entityService;
public List<Ratingtype> findAll(){
return findAllImpl();
}
public Ratingtype findById(Long id){
return findByIdImpl(id);
}
public Response createEntity(Ratingtype entity) {
entity = createEntityImpl(entity);
return Response.created(UriBuilder.fromResource(RatingtypeEndPoint.class)
.path(String.valueOf(entity.getId())).build()).build();
}
public Response createOperation(RatingtypeOperation entityOperation){
Ratingtype entity = createOperationImpl(entityOperation);
return Response.created(UriBuilder.fromResource(RatingtypeEndPoint.class)
.path(String.valueOf(entity.getId())).build()).build();
}
public Response updateEntity(Ratingtype entity) {
entity = updateEntityImpl(entity);
return Response.created(UriBuilder.fromResource(RatingtypeEndPoint.class)
.path(String.valueOf(entity.getId())).build()).build();
}
public Response updateOperation(RatingtypeOperation entityOperation) {
Ratingtype entity = updateOperationImpl(entityOperation);
return Response.created(UriBuilder.fromResource(RatingtypeEndPoint.class)
.path(String.valueOf(entity.getId())).build()).build();
}
public Response deleteEntity(Long id){
deleteEntityImpl(id);
return Response.noContent().build();
}
public Response deleteOperation(RatingtypeOperation entityOperation){
Long id = deleteOperationImpl(entityOperation);
return Response.created(UriBuilder.fromResource(RatingtypeEndPoint.class)
.path(String.valueOf(id)).build()).build();
}
@Override
public BaseEntityService<Ratingtype, RatingtypeOperation> getEntityService() {
return entityService;
}
}
| 37,460
|
https://github.com/zanzo420/drywetmidi/blob/master/DryWetMidi.Tests/Utilities/TimedObjectMethods.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
drywetmidi
|
zanzo420
|
C#
|
Code
| 46
| 162
|
using System.Collections;
using Melanchall.DryWetMidi.Interaction;
namespace Melanchall.DryWetMidi.Tests.Utilities
{
public abstract class TimedObjectMethods<TObject>
where TObject : ITimedObject
{
#region Methods
public void SetTime(TObject obj, ITimeSpan time, TempoMap tempoMap)
{
SetTime(obj, TimeConverter.ConvertFrom(time, tempoMap));
}
public abstract void SetTime(TObject obj, long time);
public abstract TObject Clone(TObject obj);
#endregion
}
}
| 41,593
|
https://github.com/MarkWattsBoomi/DataTable/blob/master/src/DataTable/DataTableRow.tsx
|
Github Open Source
|
Open Source
|
MIT
| null |
DataTable
|
MarkWattsBoomi
|
TypeScript
|
Code
| 102
| 325
|
import * as React from 'react';
import DataTable from './DataTable';
import './DataTable.css';
import DataTableCell from './DataTableCell';
import { Field, Row } from './Entities';
export default class DataTableRow extends React.Component<any, any> {
selectedItem: string = null;
constructor(props: any) {
super(props);
this.buildColumns = this.buildColumns.bind(this);
}
componentDidMount() {
}
buildColumns(): any[] {
const parent: DataTable = this.props.parent;
const rowId: number = this.props.rowId;
const row: Row = parent.fileEntries.rows.get(rowId);
const results: any[] = [];
row.fields.forEach((col: Field) => {
results.push(
<DataTableCell
parent={this}
root={this.props.parent}
rowId={rowId}
colName={col.fieldName}
/>,
);
});
return results;
}
render() {
const cols: any[] = this.buildColumns();
return (
<tr
className="dt-tb-tr"
>
{cols}
</tr>
);
}
}
| 9,741
|
https://github.com/coppelia517/orlov/blob/master/orlov/libs/minicap/process.py
|
Github Open Source
|
Open Source
|
MIT
| null |
orlov
|
coppelia517
|
Python
|
Code
| 679
| 2,554
|
""" Orlov Plugins : Minicap Process Utility. """
import os
import io
import sys
import time
import logging
import threading
from queue import Queue
import cv2
from PIL import Image
import numpy as np
import fasteners
from orlov.libs.picture import Picture, Ocr
PATH = os.path.abspath(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
if not PATH in sys.path:
sys.path.insert(0, PATH)
MAX_SIZE = 5
L = logging.getLogger(__name__)
class SearchObject(object):
""" Search Object.
Attributes:
function(str): target get function.
target(str): target image filepath.
box(tuple): target position(x, y)
"""
def __init__(self, _function, _target, _box):
self.func = _function
self.target = _target
self.box = _box
def __repr__(self):
return 'SearchObject()'
def __str__(self):
return 'Target, Box : %s, %s' % (os.path.basename(self.target), self.box)
# pylint: disable=E1101
class MinicapProc(object):
""" Minicap Process
Attributes:
stream(MinicapStream): Minicap Stream Object.
service(MinicapService): Minicap Service Object.
debug(bool): Debug flag.
"""
def __init__(self, _stream, _service, debug=False):
self.module = {}
self.module['stream'] = _stream
self.module['service'] = _service
self.space = {}
self.output = Queue()
self._loop_flag = True
self._debug = debug
self._search = None
self.search_result = Queue()
self.counter = 1
self.lock = fasteners.InterProcessLock('.lockfile')
def start(self, _adb, _workspace, _package=None):
""" Minicap Process Start.
Arguments:
_adb(Android): android adaptor object.
_workspace(Workspace): workspace adaptor object.
- log : workspace.log
- tmp : workspace.tmp
- evidence : workspace.tmp.evidence
- reference : workspace.tmp.reference
"""
self.module['adb'] = _adb
self.module['workspace'] = _workspace
self.module['workspace'].mkdir('tmp')
self.space['log'] = self.module['workspace'].mkdir('log')
if _package is None:
self.space['tmp'] = self.module['workspace'].mkdir('tmp')
self.space['tmp.evidence'] = self.module['workspace'].mkdir('tmp\\evidence')
self.space['tmp.reference'] = self.module['workspace'].mkdir('tmp\\reference')
self.space['tmp.video'] = self.module['workspace'].mkdir('tmp\\video')
else:
self.space['tmp'] = self.module['workspace'].mkdir('tmp\\%s' % _package)
self.space['tmp.evidence'] = self.module['workspace'].mkdir('tmp\\%s\\evidence' % _package)
self.space['tmp.reference'] = self.module['workspace'].mkdir('tmp\\%s\\reference' % _package)
self.space['tmp.video'] = self.module['workspace'].mkdir('tmp\\%s\\video' % _package)
self.module['service'].start(self.module['adb'], self.space['log'])
time.sleep(1)
self.module['adb'].forward('tcp:%s localabstract:minicap' % str(self.module['stream'].get_port()))
self.module['stream'].start()
threading.Thread(target=self.main_loop).start()
def finish(self):
""" Minicap Process Finish.
"""
self._loop_flag = False
time.sleep(1)
self.module['stream'].finish()
if 'service' in self.module and self.module['service'] is not None:
self.module['service'].stop()
def get_d(self) -> int:
""" Get output queue size.
Returns:
size(int): output queue size.
"""
return self.output.qsize()
def get_frame(self) -> object:
""" Get frame image in output.
Returns:
objects(object): image data.
"""
return self.output.get()
def __save(self, filename, data):
""" Save framedata in files.
Arguments:
filename(str): saved filename.
data(object): save framedata.
"""
with open(filename, 'wb') as f:
f.write(data)
f.flush()
def __save_cv(self, filename, img_cv) -> str:
""" Save framedata in files. (opencv)
Arguments:
filename(str): saved filename.
img_cv(numpy.ndarray): framedata(opencv).
Returns:
filepath(str): filepath
"""
return filename if cv2.imwrite(filename, img_cv) else None
def __save_evidence(self, number, data):
""" Save Evidence Data.
Arguments:
number(int): counter number.
data(object): save framedata.
"""
zpnum = '{0:08d}'.format(int(number))
if 'tmp.evidence' in self.space:
self.__save_cv(os.path.join(self.space['tmp.evidence'], 'image_%s.png' % str(zpnum)), data)
def __search(self, func, target, box=None, _timeout=5) -> object:
""" Search Object.
Arguments:
func(str): function name.
- capture, patternmatch, ocr.
target(object): Target Object. only capture, filename.
box(tuple): box object. (x, y, width, height)
_timeout(int): Expired Time. default : 5.
Returns:
result(object): return target.
"""
with self.lock:
self._search = SearchObject(func, target, box)
result = self.search_result.get(timeout=_timeout)
self._search = None
return result
def capture_image(self, filename, _timeout=5) -> str:
""" Capture Image File.
Arguments:
filename(str): filename.
_timeout(int): Expired Time. default : 5.
Returns:
result(str): filename
"""
return self.__search('capture', filename, None)
def search_pattern(self, target, box=None, _timeout=5):
""" Search Pattern Match File.
Arguments:
target(str): target file path.
box(tuple): target search box.
_timeout(int): timeout.
Returns:
result(tuple): search pattern point.
"""
return self.__search('patternmatch', target, box, _timeout)
def search_ocr(self, box=None, _timeout=5):
""" Search OCR File.
Arguments:
box(tuple): target search box.
_timeout(int): timeout.
Returns:
result(tuple): search pattern point.
"""
return self.__search('ocr', 'dummy', box, _timeout)
def main_loop(self):
""" Minicap Process Main Loop.
"""
if self._debug:
cv2.namedWindow('debug')
while self._loop_flag:
data = self.module['stream'].picture.get()
save_flag = False
image_pil = Image.open(io.BytesIO(data))
image_cv = cv2.cvtColor(np.asarray(image_pil), cv2.COLOR_RGB2BGR)
if self._search is not None:
if self._search.func == 'capture':
outputfile = os.path.join(self.space['tmp'], self._search.target)
result = self.__save_cv(outputfile, image_cv)
self.search_result.put(result)
elif self._search.func == 'patternmatch':
result, image_cv = Picture.search_pattern(image_cv, self._search.target, self._search.box,
self.space['tmp'])
self.search_result.put(result)
save_flag = True
elif self._search.func == 'ocr':
result, image_cv = Ocr.img_to_string(image_cv, self._search.box, self.space['tmp'])
self.search_result.put(result)
save_flag = True
else:
L.warning('Could not find function : %s', self._search.func)
if (not self.counter % 5) or save_flag:
self.__save_evidence(self.counter / 5, image_cv)
if self._debug:
if self.module['adb'] is None:
resize_image_cv = cv2.resize(image_cv, (640, 360))
else:
h = int(int(self.module['adb'].get().MINICAP_WIDTH) / 2)
w = int(int(self.module['adb'].get().MINICAP_HEIGHT) / 2)
if not int(self.module['adb'].get().ROTATE):
resize_image_cv = cv2.resize(image_cv, (h, w))
else:
resize_image_cv = cv2.resize(image_cv, (w, h))
cv2.imshow('debug', resize_image_cv)
key = cv2.waitKey(5)
if key == 27:
break
self.counter += 1
if self._debug:
cv2.destroyAllWindows()
| 41,746
|
https://github.com/yep365/messenger/blob/master/src/components/Sidebar/Sidebar.scss
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
messenger
|
yep365
|
SCSS
|
Code
| 13
| 53
|
.modal-create-dialog {
.ant-modal-body {
padding-top: 5px;
}
.ant-select-selector {
margin-bottom: 5px;
}
}
| 1,751
|
https://github.com/segef/LiarsPoker/blob/master/LiarsPoker/src/PlayerSettings.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,017
|
LiarsPoker
|
segef
|
Java
|
Code
| 675
| 3,132
|
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.Random;
public class PlayerSettings extends JFrame {
Integer[] nums = { 3, 4, 5, 6, 7, 8, 9, 10 };
String[] plyrs = { "Player", "Computer" };
String[] ais = { "Medium" };
String[] possNames = { "Rueger", "Rueggeberg", "Schwarzburger", "Bismark", "Feiten", "Schultz", "Tadken", "Langrock", "Schwarzkopf", "Terzi" };
JComboBox<Integer> numOfPlayers;
JLabel numberOfPlayers,music,soundEffects;
JButton startGame,mus,settings,home;
JPanel panel, panel1, panel3, set;
JPanel[] panels;
JComboBox<String>[] playerSorts, aiSorts;
JTextArea[] names;
Sounds sound;
private int musicVol;
Settings sett;
public PlayerSettings(Sounds s, int musicV, Settings s2) {
sett = s2;
musicVol = musicV;
sound = s;
setLayout(new FlowLayout());
setTitle("Settings");
setSize(1150, 730);
JLabel back = new JLabel(new ImageIcon(getClass().getResource("backMainPlatform.jpg")));
back.setLayout(new FlowLayout());
playerArrange();
panel = new JPanel(new FlowLayout());
panel.setOpaque(false);
panel.setPreferredSize(new Dimension(1120, 680));
mus = new JButton();
mus.setPreferredSize(new Dimension(44, 44));
try {
if(musicVol==2){
mus.setIcon(new ImageIcon(getClass().getResource("sound2.jpg")));
}else if(musicVol==3){
mus.setIcon(new ImageIcon(getClass().getResource("sound3.jpg")));
}else if(musicVol==0){
mus.setIcon(new ImageIcon(getClass().getResource("mute.jpg")));
}else{
mus.setIcon(new ImageIcon(getClass().getResource("sound1.jpg")));
}
} catch (Exception e) {
e.printStackTrace();
}
mus.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
if(musicVol == 2){
try {
mus.setIcon(new ImageIcon(getClass().getResource("sound3.jpg")));
} catch (Exception e) {
e.printStackTrace();
}
sound.volume3();
musicVol = 3;
}else if(musicVol == 3){
try {
mus.setIcon(new ImageIcon(getClass().getResource("mute.jpg")));
} catch (Exception e) {
e.printStackTrace();
}
sound.stop();
musicVol = 0;
}else if(musicVol == 0){
try {
mus.setIcon(new ImageIcon(getClass().getResource("sound1.jpg")));
} catch (Exception e) {
e.printStackTrace();
}
sound.start();
sound.volume1();
musicVol = 1;
}else{
try {
mus.setIcon(new ImageIcon(getClass().getResource("sound2.jpg")));
} catch (Exception e) {
e.printStackTrace();
}
sound.volume2();
musicVol = 2;
}
}
});
settings = new JButton();
settings.setPreferredSize(new Dimension(44, 44));
try {
settings.setIcon(new ImageIcon(getClass().getResource("settings.jpg")));
} catch (Exception e) {
e.printStackTrace();
}
settings.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
sett.setVisible(true);
}
});
home = new JButton();
home.setPreferredSize(new Dimension(44, 44));
try {
home.setIcon(new ImageIcon(getClass().getResource("home.jpg")));
} catch (Exception e) {
e.printStackTrace();
}
home.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
MainPage m = new MainPage(sett,sound,musicVol);
dispose();
}
});
JPanel tmp = new JPanel(new BorderLayout());
tmp.setOpaque(false);
set = new JPanel(new BorderLayout());
set.setOpaque(false);
tmp.setPreferredSize(new Dimension(1100, 44));
tmp.add(set, BorderLayout.LINE_END);
set.setPreferredSize(new Dimension(132, 44));
set.add(home,BorderLayout.LINE_END);
set.add(mus,BorderLayout.CENTER);
set.add(settings,BorderLayout.LINE_START);
panel1 = new JPanel(new GridLayout(11, 1, 2, 2));
panel1.setPreferredSize(new Dimension(1100, 400));
panel1.setBackground(new Color(221, 167, 237));
panel1.setOpaque(false);
panel3 = new JPanel(new BorderLayout());
panel3.setPreferredSize(new Dimension(1100, 200));
panel3.setBackground(new Color(181, 172, 253));
panel3.setOpaque(false);
panel.add(panel1);
panel.add(panel3);
panel.add(tmp);
JPanel p1 = new JPanel(new FlowLayout());
p1.setOpaque(false);
numberOfPlayers = new JLabel("Number Of Players:");
numberOfPlayers.setFont(new Font("Verdana", Font.BOLD, 18));
numberOfPlayers.setForeground(new Color(228, 206, 99));
numberOfPlayers.setPreferredSize(new Dimension(200, 30));
p1.add(numberOfPlayers);
numOfPlayers = new JComboBox<>(nums);
numOfPlayers.setPreferredSize(new Dimension(50, 30));
numOfPlayers.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
for (int i = 0; i < (int) (numOfPlayers.getSelectedItem()); i++) {
panels[i].setVisible(true);
}
for (int i = (int) (numOfPlayers.getSelectedItem()); i<10 ; i++){
panels[i].setVisible(false);
}
}
});
p1.add(numOfPlayers);
panel1.add(p1);
panels = new JPanel[10];
playerSorts = new JComboBox[10];
aiSorts = new JComboBox[10];
names = new JTextArea[10];
arrange();
startGame = new JButton("Start Game");
startGame.setPreferredSize(new Dimension(500, 50));
startGame.setFont(new Font("Verdana", Font.BOLD, 50));
startGame.setBackground(new Color(171, 244, 136));
startGame.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
sound.click();
Player[] players = new Player[(int)(numOfPlayers.getSelectedItem())];
for(int i = 0;i<players.length;i++){
if(playerSorts[i].getSelectedIndex()==0){
players[i] = new Player(names[i].getText(), 2);
}else{
players[i] = new AI(names[i].getText(), 2);
}
}
for(int i = 0; i<players.length;i++){
players[i].setNextPlayer(players[(i+1)%players.length]);
}
Platform p = new Platform(sound,players,musicVol,sett);
// p.setDeck();
// p.setCards();
// p.writeConsoleTurn();
dispose();
}
});
panel3.add(startGame,BorderLayout.CENTER);
back.add(panel);
add(back);
setExtendedState(JFrame.MAXIMIZED_BOTH);
setUndecorated(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public void arrange() {
for (int i = 0; i < 10; i++) {
int x = i;
playerSorts[i] = new JComboBox<String>(plyrs);
playerSorts[i].setFont(new Font("Verdana", 0, 18));
playerSorts[i].setPreferredSize(new Dimension(150, 30));
playerSorts[x].addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (playerSorts[x].getSelectedItem().equals("Computer")) {
aiSorts[x].setVisible(true);
names[x].setEditable(false);
names[x].setText(possNames[x]);
} else {
aiSorts[x].setVisible(false);
names[x].setEditable(true);
names[x].setText("Player" + x);
}
}
});
panels[i] = new JPanel(new FlowLayout());
panels[i].setOpaque(false);
panels[i].add(playerSorts[i]);
aiSorts[x] = new JComboBox<>(ais);
aiSorts[x].setFont(new Font("Verdana", 0, 18));
aiSorts[x].setPreferredSize(new Dimension(100, 30));
aiSorts[x].setVisible(false);
panels[x].add(aiSorts[x]);
names[x] = new JTextArea(1, 13);
names[x].setEditable(true);
names[x].setFont(new Font("Verdana", 0, 18));
names[x].setPreferredSize(new Dimension(100, 30));
names[x].setText("Player" + x);
panels[x].add(names[x]);
panel1.add(panels[i]);
}
for (JPanel p : panels) {
p.setVisible(false);
}
for (int i = 0; i < (int) (numOfPlayers.getSelectedItem()); i++) {
panels[i].setVisible(true);
}
}
private void playerArrange(){
Random ran = new Random();
for(int i = 0; i<possNames.length ; i++){
int rand = ran.nextInt(possNames.length);
String a = possNames[i];
possNames[i] = possNames[rand];
possNames[rand] = a;
}
}
}
| 41,679
|
https://github.com/BuloZB/serverZero/blob/master/ServerFiles/warden/17E3A1C32BFDC91B0E6746DC11C6AB20.vb
|
Github Open Source
|
Open Source
|
OpenSSL
| null |
serverZero
|
BuloZB
|
Visual Basic
|
Code
| 147
| 409
|
' Warden module script.
'
'Module name: 17E3A1C32BFDC91B0E6746DC11C6AB20
Imports System
Imports Microsoft.VisualBasic
Imports vWoW.WorldServer
Namespace Scripts
Public Module Main
'http://paste2.org/p/474089
Public MD5 As Byte() = New Byte() {&H17, &HE3, &HA1, &HC3, &H2B, &HFD, &HC9, &H1B, &HE, &H67, &H46, &HDC, &H11, &HC6, &HAB, &H20}
Public RC4 As Byte() = New Byte() {&H75, &HA4, &HD9, &H7B, &H23, &H5A, &H69, &H97, &H0, &HCE, &H52, &H2B, &H40, &HAE, &H2D, &H0}
Public Size As Integer = 18508
Public MEM_CHECK As Byte = &H59
Public PAGE_CHECK_A As Byte = &H3D 'This might be B and the one below might be A
Public PAGE_CHECK_B As Byte = &H36
Public MPQ_CHECK As Byte = &H78
Public LUA_STR_CHECK As Byte = &H91
Public DRIVER_CHECK As Byte = &H23
Public TIMING_CHECK As Byte = &H75
Public PROC_CHECK As Byte = &H8A
Public MODULE_CHECK As Byte = &H0 'Unknown
Public Sub Scan()
End Sub
End Module
End namespace
| 28,709
|
https://github.com/ask-izzy/ask-izzy/blob/master/flow/interfaces/iss.js
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
ask-izzy
|
ask-izzy
|
JavaScript
|
Code
| 342
| 1,189
|
/* @flow */
type issArea = {
"name": string,
"kind": string,
"postcode": string,
"state": string,
"suburb": string,
};
type email = string;
type issAgeGroup = "unspecified" |
"prenatal" |
"baby" |
"toddler" |
"preschool" |
"schoolage" |
"earlyadolescent" |
"midadolescent" |
"lateadolescent" |
"youngadult" |
"adult" |
"middleagedadult" |
"preretirementage";
type issAccessibility = "noaccess" |
"access" |
"fullaccess";
type endpoint = {};
type ymdWithDashesDate = string;
type hmsWithColonsTime = string;
type isoDateAndTime = string;
type state = string;
type dayOfWeek = 'Monday' |
'Tuesday' |
'Wednesday' |
'Thursday' |
'Friday' |
'Saturday' |
'Sunday';
type issPoint = {
"lat": number,
"lon": number
};
type issLocation = {
"building": string,
"flat_unit": string,
"level": string,
"point"?: issPoint,
"postcode": string,
"state": state,
"street_name": string,
"street_number": string,
"street_suffix": string,
"street_type": string,
"suburb": string,
};
type travelTime = {
"duration": {"text": string, "value": number},
"distance": {"text": string, "value": number},
"mode": string,
"status": string,
};
type issSite = {
"id": number,
"name": string,
"organisation": {
"id": number,
"name": string
}
};
type issOpeningHours = {
"close": hmsWithColonsTime,
"day": dayOfWeek,
"note"?: string,
"open": hmsWithColonsTime,
};
type phone = {
"comment": string,
"kind": string,
"number": string,
}
type issGender = 'u' | 'f' | 'm' | 'x';
type issPostalAddress = {
"line1": string,
"line2": string,
"postcode": string,
"state": state,
"suburb": string
};
type issEntityType = 'organisation' |
'site' |
'service' |
'practitioner';
type urlString = string;
type issNowOpen = {
"local_time": isoDateAndTime,
"notes": string,
"now_open": ?boolean
};
type issEmail = {
"comment": string,
"email": email
};
type issService = {
"abn": string,
"accessibility": issAccessibility,
"accessibility_details": string,
"accreditation": Array<string>,
"age_groups": Array<issAgeGroup>,
"also_known_as": Array<string>,
"assessment_criteria": string,
"availability": string,
"billing_method": string,
"capacity": {
"status": string,
"status_text": string,
},
"catchment": string,
"cost": string,
"crisis": boolean,
"description": string,
"eligibility_info": string,
"emails": Array<issEmail>,
"endpoints": Array<endpoint>,
"funding_body": string,
"show_in_askizzy_health": boolean,
"id": number,
"ineligibility_info": string,
"intake_info": string,
"intake_point": string,
"is_bulk_billing": boolean,
"languages": Array<string>,
"last_updated": ymdWithDashesDate,
"location": ?issLocation,
"name": string,
"ndis_approved": boolean,
"now_open": issNowOpen,
"opening_hours": Array<issOpeningHours>,
"parking_info": string,
"phones": Array<phone>,
"postal_address": Array<issPostalAddress>,
"public_transport_info": string,
"referral_info": string,
"service_type": Array<string>,
"site": issSite,
"special_requirements": string,
"target_gender": issGender,
"type": issEntityType,
"web": urlString,
}
| 199
|
https://github.com/scantineau/knx2mqtt/blob/master/src/main/java/com/tellerulam/knx2mqtt/SyslogHandler.java
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
knx2mqtt
|
scantineau
|
Java
|
Code
| 337
| 1,162
|
package com.tellerulam.knx2mqtt;
import java.io.File;
import java.io.IOException;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.LogRecord;
@SuppressWarnings("boxing")
public class SyslogHandler extends Handler {
private final DatagramSocket ds;
private final Map<Level, Integer> levels = new HashMap<>();
private String hostname;
private String pidSuffix;
{
levels.put(Level.SEVERE, 3);
levels.put(Level.WARNING, 4);
levels.put(Level.INFO, 5);
levels.put(Level.CONFIG, 5);
levels.put(Level.FINE, 6);
levels.put(Level.FINER, 7);
levels.put(Level.FINEST, 7);
}
public SyslogHandler() throws SocketException, UnknownHostException {
ds = new DatagramSocket();
String syslogHost = LogManager.getLogManager().getProperty(getClass().getName() + ".host");
String syslogPort = LogManager.getLogManager().getProperty(getClass().getName() + ".port");
ds.connect(new InetSocketAddress(
syslogHost != null ? syslogHost : "localhost",
syslogPort != null ? Integer.parseInt(syslogPort) : 514
));
try {
hostname = InetAddress.getLocalHost().getHostName();
int domainIndex = hostname.indexOf('.');
if (domainIndex > 0)
hostname = hostname.substring(0, domainIndex);
} catch (UnknownHostException e) {
hostname = InetAddress.getLocalHost().getHostAddress();
}
try {
pidSuffix = "[" + new File("/proc/self").getCanonicalFile().getName() + "]";
} catch (NumberFormatException | IOException e) {
pidSuffix = "";
}
}
static void readConfig() throws SecurityException, IOException {
if (System.getProperty("java.util.logging.config.file") == null) {
LogManager.getLogManager().readConfiguration(SyslogHandler.class.getResourceAsStream("/logging.properties"));
}
}
@Override
public void close() throws SecurityException {
if (ds != null)
ds.close();
}
@Override
public void flush() {
/* Nothing to do, we sent immediately */
}
private void sendSyslogMessage(StringBuilder msg) {
if (ds == null)
return;
byte[] msgData = msg.toString().getBytes(StandardCharsets.US_ASCII);
try {
ds.send(new DatagramPacket(msgData, msgData.length));
} catch (IOException e) {
/* Ignore */
}
}
@Override
public void publish(LogRecord r) {
if (ds == null)
return; // We are disabled
int facility = 23; // Local 23
// Convert priority
int pri = levels.get(r.getLevel());
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(r.getMillis());
StringBuilder m = new StringBuilder();
m.append('<');
m.append(facility * 8 + pri);
m.append("> ");
Formatter dateFormatter = new Formatter(m, Locale.US);
dateFormatter.format("%1$tb %2$2d %1$TT", cal, cal.get(Calendar.DAY_OF_MONTH));
dateFormatter.close();
m.append(" ");
m.append(hostname);
m.append(" knx2mqtt");
m.append(pidSuffix);
m.append(": ");
int prefixLength = m.length();
for (char ch : r.getMessage().toCharArray()) {
if (ch == '\r')
continue;
if (ch == '\n') {
sendSyslogMessage(m);
m.setLength(prefixLength);
continue;
}
if (m.length() == 1020) {
m.append("...");
}
if (m.length() == 1023)
continue;
if (ch >= 126)
m.append('_');
else
m.append(ch);
}
if (m.length() != prefixLength)
sendSyslogMessage(m);
}
}
| 24,251
|
https://github.com/karthickvalentino/handn/blob/master/assets/AppAsset.php
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,018
|
handn
|
karthickvalentino
|
PHP
|
Code
| 97
| 557
|
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace app\assets;
use yii\web\AssetBundle;
/**
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class AppAsset extends AssetBundle
{
public $basePath = '@webroot';
public $baseUrl = '@web';
public $css = [
//'css/site.css',
'css/style.css',
// 'css/base.css',
// 'css/responsive.css',
//chat css,
'css/colors/green.css',
//'css1/chat.css',
//'css/screen.css',
//end of chat css,
'css/fbchat',
];
public $js = [
'scripts/custom.js',
'scripts/jquery.superfish.js',
'scripts/jquery.themepunch.tools.min.js',
'scripts/jquery.themepunch.revolution.min.js',
'scripts/jquery.themepunch.showbizpro.min.js',
'scripts/jquery.flexslider-min.js',
'scripts/chosen.jquery.min.js',
'scripts/jquery.magnific-popup.min.js',
'scripts/waypoints.min.js',
'scripts/jquery.counterup.min.js',
'scripts/jquery.jpanelmenu.js',
'scripts/stacktable.js',
'scripts/headroom.min.js',
//'scripts/jquery.sceditor.bbcode.min.js',
'scripts/jquery.sceditor.js',
// 'js1/chat.js',
'scripts/editor.js',
'js/script.js'
];
public $depends = [
'yii\web\YiiAsset',
'yii\bootstrap\BootstrapAsset',
];
}
| 43,958
|
https://github.com/mbatc/atLib/blob/master/projects/atLib/include/IO/Streams/atWriteStream.h
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
atLib
|
mbatc
|
C
|
Code
| 314
| 757
|
// -----------------------------------------------------------------------------
// The MIT License
//
// Copyright(c) 2020 Michael Batchelor,
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files(the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions :
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// -----------------------------------------------------------------------------
#ifndef atWriteStream_h__
#define atWriteStream_h__
#include "atStreamSeekable.h"
#define atTrivialStreamWrite(type) inline int64_t atStreamWrite(atWriteStream *pStream, const type *pData, const int64_t count) { return atStreamWrite(pStream, (const void*)pData, (int64_t)sizeof(type) * count); }
class atWriteStream : public atStreamSeekable
{
public:
// Writes pData to the file
virtual int64_t Write(const void *pData, const int64_t len) = 0;
template<typename T> int64_t Write(const T *pData, const int64_t count = 1);
template<typename T> int64_t Write(const T &data);
};
int64_t atStreamWrite(atWriteStream *pStream, const void *pData, const int64_t count);
template<typename T> int64_t atWriteStream::Write(const T *pData, const int64_t count) { return atStreamWrite(this, pData, count); }
template<typename T> int64_t atWriteStream::Write(const T &data) { return Write(&data, 1); }
atTrivialStreamWrite(int64_t);
atTrivialStreamWrite(int32_t);
atTrivialStreamWrite(int16_t);
atTrivialStreamWrite(int8_t);
atTrivialStreamWrite(uint64_t);
atTrivialStreamWrite(uint32_t);
atTrivialStreamWrite(uint16_t);
atTrivialStreamWrite(uint8_t);
atTrivialStreamWrite(bool)
atTrivialStreamWrite(wchar_t);
atTrivialStreamWrite(char);
atTrivialStreamWrite(double);
atTrivialStreamWrite(float);
#endif // atWriteStream_h__
| 8,846
|
https://github.com/kitsunekeyboards/shapeshifter4060/blob/master/pcb/Laptreus_v1/CommonPartsLibrary.pretty/XCVR_SPU0409HD5H-PB.kicad_mod
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
shapeshifter4060
|
kitsunekeyboards
|
KiCad Layout
|
Code
| 206
| 709
|
(module XCVR_SPU0409HD5H-PB (layer F.Cu) (tedit 0)
(solder_mask_margin 0.1)
(attr smd)
(fp_text reference XCVR_SPU0409HD5H-PB (at 1.365 -2.885) (layer F.SilkS)
(effects (font (size 1 1) (thickness 0.05)))
)
(fp_text value VAL** (at 1.85 3.065) (layer F.SilkS)
(effects (font (size 1 1) (thickness 0.05)))
)
(fp_line (start -1.475 -1.88) (end 1.475 -1.88) (layer F.SilkS) (width 0.127))
(fp_line (start 1.475 -1.88) (end 1.475 1.88) (layer F.SilkS) (width 0.127))
(fp_line (start 1.475 1.88) (end -1.475 1.88) (layer F.SilkS) (width 0.127))
(fp_line (start -1.475 1.88) (end -1.475 -1.88) (layer F.SilkS) (width 0.127))
(fp_line (start -1.75 -2.15) (end 1.75 -2.15) (layer Dwgs.User) (width 0.05))
(fp_line (start 1.75 -2.15) (end 1.75 2.15) (layer Dwgs.User) (width 0.05))
(fp_line (start 1.75 2.15) (end -1.75 2.15) (layer Dwgs.User) (width 0.05))
(fp_line (start -1.75 2.15) (end -1.75 -2.15) (layer Dwgs.User) (width 0.05))
(fp_circle (center 2.125 -1.275) (end 2.2927 -1.275) (layer F.SilkS) (width 0.2))
(pad 1 smd rect (at 0.85 -1.23) (size 0.8 0.8) (layers F.Cu F.Paste F.Mask)
(solder_mask_margin 0.2))
(pad 2 smd rect (at 0.85 1.23) (size 0.8 0.8) (layers F.Cu F.Paste F.Mask)
(solder_mask_margin 0.2))
(pad 3 smd rect (at -0.85 1.23) (size 0.8 0.8) (layers F.Cu F.Paste F.Mask)
(solder_mask_margin 0.2))
(pad 4 smd rect (at -0.85 -1.23) (size 0.8 0.8) (layers F.Cu F.Paste F.Mask)
(solder_mask_margin 0.2))
)
| 38,860
|
https://github.com/fuzzley/fSpider/blob/master/scripts/spider/fSpider.debug.js
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
fSpider
|
fuzzley
|
JavaScript
|
Code
| 116
| 623
|
var fSpider = fSpider || {};
fSpider.Debug = (function (Debug, undefined) {
'use strict';
//constructor
Debug = function (board) {
this.board = board;
};
//fields
Debug.prototype.board = null;
//functions
Debug.prototype.prepareDrawCompleteSequenceTest = function () {
Debug.prepareDrawCompleteSequenceTest.call(this.board);
};
Debug.prepareDrawCompleteSequenceTest = function (b) {
b.tableauPiles.forEach(function (tPile) {
b.stockPile.transferCards(tPile.cards);
});
var cards = [];
for (var i = fSpider.PlayingCard.CARD_TYPES.king; i >= fSpider.PlayingCard.CARD_TYPES.ace; i--)
{
for (var j = 0; j < b.deck.getSize(); j++)
{
if (b.deck.cards[j].getType() === i) {
cards.push(b.deck.cards[j]);
b.deck.cards[j].setFaceUp(true);
break;
}
}
}
b.tableauPiles[0].transferCards(cards.slice(0, 12));
b.tableauPiles[0].arrangeCards(fSpider.board.settings.extendAnimate(false));
b.tableauPiles[0].resetListening();
b.tableauPiles[0].resetDraggable();
b.stockPile.cards.splice(b.stockPile.cards.indexOf(cards[12]), 1);
b.stockPile.cards.push(cards[12]);
b.stockPile.resetCardFaces();
b.stockPile.resetListening();
b.stockPile.resetDraggable();
b.stockPile.arrangeCards();
b.stockPile.moveAllCardsToGroup();
b.tableauPiles.forEach(function (tPile, index) {
if (index != 0) {
tPile.transferCards([b.stockPile.cards[0]]);
tPile.resetCardFaces();
tPile.resetListening();
tPile.resetDraggable();
}
});
b.redraw();
};
return Debug;
})(fSpider.Debug || {});
| 29,969
|
https://github.com/milesmatthias/TS_DetailedGuides/blob/master/TableViews/build/iphone/build/TableViews.build/Debug-iphonesimulator/TableViews-universal.build/Objects-normal/i386/CAXException.d
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,012
|
TS_DetailedGuides
|
milesmatthias
|
Makefile
|
Code
| 7
| 80
|
dependencies: \
/Users/miels/TableViews/build/iphone/Classes/CAXException.cpp \
/Users/miels/TableViews/build/iphone/Classes/CAXException.h \
/Users/miels/TableViews/build/iphone/Classes/CADebugMacros.h
| 30,503
|
https://github.com/hannahPhys/starter-gatsby-blog/blob/master/src/templates/blog-post.module.scss
|
Github Open Source
|
Open Source
|
MIT
| null |
starter-gatsby-blog
|
hannahPhys
|
SCSS
|
Code
| 106
| 392
|
@import '../components/primary.scss';
.blogPost {
padding-bottom: 40px;
.hero {
display: flex;
justify-content: center;
align-items: center;
background: #e1e1e1;
font-size: 2em;
overflow: hidden;
img {
width: 140%;
margin: 0;
max-width: unset;
}
}
h1 {
line-height: 49px;
font-family: 'BebasNeue';
color: $fernGreen;
text-align: center;
font-size: 60px;
}
@media(min-width: 1000px) {
.blogImageWrapper {
width: 25vw;
}
}
.wrapper {
width: calc(96% - 10vmin);
margin: 0 auto;
}
img {
width: auto;
max-width: 100%;
margin: 10px auto;
}
.blogImageWrapper {
margin: 0 auto;
}
@media(min-width: 470px) {
.blogImageWrapper {
width: 30vw;
float: right;
margin: 5px;
}
}
@media(min-width: 1000px) {
.blogImageWrapper {
width: 25vw;
}
}
.blogText {
font-family: 'montserrat-light';
}
}
| 17,573
|
https://github.com/dorabelme/Guess-Who/blob/master/guess-who/src/App.js
|
Github Open Source
|
Open Source
|
MIT
| null |
Guess-Who
|
dorabelme
|
JavaScript
|
Code
| 242
| 809
|
import React from "react";
import { connect } from "react-redux";
import { Route, Redirect } from "react-router-dom";
import Login from "./components/Login/Login";
import Register from "./components/Login/Register";
import MainPage from "./components/DashBoard/Dashboard";
import QuestionList from "./components/Question/QuestionList";
import ProfileCard from "./components/Profile/ProfileCard";
import {
getTweets,
postScore,
setNewHighScore,
getUser,
login,
signup
} from "./actions/index";
import "./App.css";
// authorization
const protectRoute = Component => props => {
if (localStorage.getItem("token")) {
return <Component {...props} />;
} else {
return <Redirect to="/" />;
}
};
const ProtectedMainPage = protectRoute(MainPage);
const ProtectedQuestionList = protectRoute(QuestionList);
const ProtectedProfileCard = protectRoute(ProfileCard);
// App
function App(props) {
const getLogin = values => {
props.login(values).then(res => {
props.history.push("/guesswho");
return true;
});
};
const getSignup = values => {
props.signup(values).then(res => {
props.history.push("/guesswho");
return true;
});
};
// useEffect(() => {
// axiosWithAuth()
// .get(`https://lambda-guess-who.herokuapp.com/api/user/highscore/${state.userId}`)
// .then(res => {
// setState(setState({ ...initialState, highScore: res.data })
// )
// })
// .catch(err => console.log(err.response));
// }, []);
console.log("the set data", props.username);
return (
<div className="App">
<Route
exact
path="/"
render={props => <Login {...props} getLogin={getLogin} />}
/>
<Route
exact
path="/register"
render={props => <Register {...props} getSignup={getSignup} />}
/>
<Route
path="/guesswho"
render={props => <ProtectedMainPage {...props} />}
/>
<Route
path="/questions"
render={props => <ProtectedQuestionList {...props} />}
/>
<Route
path="/profile"
render={props => <ProtectedProfileCard {...props} />}
/>
</div>
);
}
const mapStateToProps = state => {
return {
tweet: state.tweet,
tweeters: state.tweeters,
highScore: state.highScore,
username: state.username,
userId: state.userId,
token: state.token,
personalHighScore: state.personalHighScore
};
};
export default connect(
mapStateToProps,
{ getTweets, postScore, setNewHighScore, getUser, login, signup }
)(App);
| 44,265
|
https://github.com/tosuke/dotfiles.old/blob/master/deploy.fish
|
Github Open Source
|
Open Source
|
MIT
| 2,018
|
dotfiles.old
|
tosuke
|
Fish
|
Code
| 125
| 338
|
function deploy
set -l source $argv[1]
set -l dest $argv[2]
for path in (find $source | string replace $source '' | string replace -r '^/' '' | string match -v '')
if test -d $source/$path
mkdir -p $dest/$path
else
if test -L $dest/$path
if test (realpath $dest/$path) = (realpath $source/$path)
continue
end
end
if test -e $dest/$path
rm $dest/$path
end
ln -sfnv (realpath $source/$path) $dest/$path
end
end
end
set -l list 'common' $argv
echo 'Deploy files'
for type in $list
deploy $type/home $HOME
deploy $type/config $HOME/.config
end
if not which nodebrew ^&1 >/dev/null
echo 'Install nodebrew'
curl -L git.io/nodebrew | perl - setup
end
if not contains fisher (functions)
echo 'Install fisher'
curl -Lo ~/.config/fish/functions/fisher.fish --create-dirs https://git.io/fisher
end
echo "Install fish plugins"
fisher install (pwd)/fish/*
| 21,354
|
https://github.com/nathalialb/ufsc-tcc-sin-guia-facetado/blob/master/app/Models/ApproachesEntities.php
|
Github Open Source
|
Open Source
|
MIT
| null |
ufsc-tcc-sin-guia-facetado
|
nathalialb
|
PHP
|
Code
| 31
| 95
|
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class ApproachesEntities extends Model
{
/** @var int PUBLISHED */
const PUBLISHED = 1;
protected $table = 'approaches_entities';
protected $fillable = [
'approach_id',
'entity_id',
];
}
| 20,106
|
https://github.com/tanahiro/quaternion/blob/master/test/minitest_helper.rb
|
Github Open Source
|
Open Source
|
MIT
| 2,018
|
quaternion
|
tanahiro
|
Ruby
|
Code
| 37
| 156
|
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'quaternion'
require 'minitest/autorun'
module MinitestHelper
def quaternion_assert_in_delta expected, actual, delta = 0.001, message = nil
assert_in_delta(expected[:w], actual[:w], delta, message)
assert_in_delta(expected[:x], actual[:x], delta, message)
assert_in_delta(expected[:y], actual[:y], delta, message)
assert_in_delta(expected[:z], actual[:z], delta, message)
end
end
| 36,220
|
https://github.com/webfactorybulgaria/shop/blob/master/src/resources/views/public/confirmation.blade.php
|
Github Open Source
|
Open Source
|
MIT
| null |
shop
|
webfactorybulgaria
|
PHP
|
Code
| 39
| 187
|
@extends('pages::public.master')
@section('bodyClass', 'body-shop body-shop-confirmation body-page body-page-'.$page->id)
@section('main')
<div class="container">
@if($order->statusCode == 'completed')
<h1>@lang('db.Purchase has been successfully created')</h1>
@else
<h1>@lang('db.Purchase has been canceled')</h1>
@endif
Order No: # {{ $order->id }}
@if(!empty($order->items) && $order->items->count())
@include('shop::public._summary', ['cart' => $order])
@endif
</div>
@endsection
| 42,428
|
https://github.com/xuwei-k/cloudformal/blob/master/src/main/scala/com/github/mshibuya/cloudformal/aws/glue/GrokClassifier.scala
|
Github Open Source
|
Open Source
|
MIT
| 2,018
|
cloudformal
|
xuwei-k
|
Scala
|
Code
| 45
| 205
|
package com.github.mshibuya.cloudformal.aws.glue
import com.github.mshibuya.cloudformal.model._
/**
* http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-classifier-grokclassifier.html
*/
case class GrokClassifier(
customPatterns: Property[String] = Empty,
grokPattern: NonEmptyProperty[String],
classification: NonEmptyProperty[String],
name: Property[String] = Empty) extends Expression[GrokClassifier] {
def render: Formattable = Value(
"CustomPatterns" -> customPatterns,
"GrokPattern" -> grokPattern,
"Classification" -> classification,
"Name" -> name
)
}
| 7,376
|
https://github.com/Mariliad/UMLGraph/blob/master/GUI/src/umlgraph_gui/RelationshipDialog.java
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,014
|
UMLGraph
|
Mariliad
|
Java
|
Code
| 289
| 1,118
|
package umlgraph_gui;
import javax.swing.JPanel;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.Button;
import java.awt.FlowLayout;
public class RelationshipDialog extends JPanel implements ActionListener {
JFrame frame;
JPanel mainpanel;
String reltext;
public RelationshipDialog(JFrame frame) {
super();
setLayout(new BorderLayout(10, 10));
JPanel panel = new JPanel();
add(panel, BorderLayout.CENTER);
panel.setBorder(new EmptyBorder(20, 10, 10, 10));
panel.setLayout(new BorderLayout(10, 10));
JLabel lblChooseTheSource = new JLabel("Choose the source class's relationship:");
lblChooseTheSource.setHorizontalAlignment(SwingConstants.CENTER);
panel.add(lblChooseTheSource, BorderLayout.NORTH);
String[] relName = { "Implementation", "Generalization", "Association", "Navigable association",
"Aggregation", "Navigable aggregation", "Composition", "Navigable composition", "Dependency" };
JComboBox relList = new JComboBox(relName);
relList.setSelectedIndex(8);
relList.addActionListener(this);
panel.add(relList, BorderLayout.WEST);
JPanel panelAd = new JPanel();
panelAd.setBorder(new EmptyBorder(5, 5, 5, 5));
panel.add(panelAd, BorderLayout.CENTER);
panelAd.setLayout(new BorderLayout(5, 5));
String[] sourceAdornments = { "1", "2", "3", "4", "5", "*" };
JComboBox sourceAdList = new JComboBox(sourceAdornments);
sourceAdList.setEditable(true);
sourceAdList.setSelectedIndex(5);
sourceAdList.addActionListener(this);
panelAd.add(sourceAdList, BorderLayout.WEST);
String[] targetAdornments = { "1", "2", "3", "4", "5", "*" };
JComboBox comboBox = new JComboBox(targetAdornments);
comboBox.setEditable(true);
panelAd.add(comboBox, BorderLayout.CENTER);
textField = new JTextField();
textField.setToolTipText("Target class's name");
panelAd.add(textField, BorderLayout.EAST);
textField.setColumns(10);
JPanel panel_1 = new JPanel();
panel.add(panel_1, BorderLayout.SOUTH);
panel_1.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
JButton btnOk = new JButton("OK");
panel_1.add(btnOk);
}
public void actionPerformed(ActionEvent e) {
// Menu item actions
String command = e.getActionCommand();
}
// May delete the next line
private static final long serialVersionUID = 1L;
private JTextField textField;
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("Relationships");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
RelationshipDialog newContentPane = new RelationshipDialog(frame);
newContentPane.setVisible(true); //content panes must be opaque
frame.setContentPane(newContentPane);
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
| 20,258
|
https://github.com/hschwane/offline_production/blob/master/PROPOSAL/public/PROPOSAL/math/RandomGenerator.h
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
offline_production
|
hschwane
|
C
|
Code
| 389
| 892
|
/******************************************************************************
* *
* This file is part of the simulation tool PROPOSAL. *
* *
* Copyright (C) 2017 TU Dortmund University, Department of Physics, *
* Chair Experimental Physics 5b *
* *
* This software may be modified and distributed under the terms of a *
* modified GNU Lesser General Public Licence version 3 (LGPL), *
* copied verbatim in the file "LICENSE". *
* *
* Modifcations to the LGPL License: *
* *
* 1. The user shall acknowledge the use of PROPOSAL by citing the *
* following reference: *
* *
* J.H. Koehne et al. Comput.Phys.Commun. 184 (2013) 2070-2090 DOI: *
* 10.1016/j.cpc.2013.04.001 *
* *
* 2. The user should report any bugs/errors or improvments to the *
* current maintainer of PROPOSAL or open an issue on the *
* GitHub webpage *
* *
* "https://github.com/tudo-astroparticlephysics/PROPOSAL" *
* *
******************************************************************************/
#pragma once
#include <functional>
#include <random>
#include <iostream>
#ifdef ICECUBE_PROJECT
#include <phys-services/I3RandomService.h>
#endif
namespace PROPOSAL {
// ----------------------------------------------------------------------------
/// @brief Random number generator
// ----------------------------------------------------------------------------
class RandomGenerator
{
public:
static RandomGenerator& Get()
{
static RandomGenerator instance;
return instance;
}
// ----------------------------------------------------------------------------
/// @brief Execute the given rng to get a random number
///
/// @return random number
// ----------------------------------------------------------------------------
double RandomDouble();
void SetSeed(int seed);
// ----------------------------------------------------------------------------
/// @brief Serialize the rng to a stream
///
/// Useful for debuging to save a specific state.
/// Only supported for internal used rng from the standard libraries.
///
/// @param std::ostream
// ----------------------------------------------------------------------------
void Serialize(std::ostream&);
// ----------------------------------------------------------------------------
/// @brief Deserialize the rng from a stream
///
/// Useful for debuging to get back a specific state.
/// Only supported for internal used rng from the standard libraries.
///
/// @param std::ostream
// ----------------------------------------------------------------------------
void Deserialize(std::istream&);
/** @brief Set a custom random number generator
*
* Classes that contain other subclasses of MathModel should
* override this to pass the new RNG on to their members.
*/
virtual void SetRandomNumberGenerator(std::function<double()>& f);
#ifdef ICECUBE_PROJECT
virtual void SetI3RandomNumberGenerator(I3RandomServicePtr random);
#endif
/** @brief Set a the default random number generator
*
* The default random number generator is the
* std mersenne twister std::mt19937.
*/
virtual void SetDefaultRandomNumberGenerator();
private:
RandomGenerator();
virtual ~RandomGenerator();
static double DefaultRandomDouble();
static std::mt19937 rng_;
static std::uniform_real_distribution<double> uniform_distribution;
std::function<double()> random_function;
#ifdef ICECUBE_PROJECT
I3RandomService* i3random_gen_;
#endif
};
} // namespace PROPOSAL
| 13,494
|
https://github.com/thealexhoar/pymodoro/blob/master/main.py
|
Github Open Source
|
Open Source
|
MIT
| null |
pymodoro
|
thealexhoar
|
Python
|
Code
| 501
| 1,488
|
import alert
import configparser
from datetime import datetime, timedelta
import getopt
import sys
import time
def wait(minutes):
seconds = minutes * 60
time.sleep(seconds)
# Produces from string the longest substring
# that starts at index and is an integer
def get_contiguous_number(string, index):
length = len(string)
end = length
while end > index:
substring = string[index:end]
if substring.isdigit():
return substring
end -= 1
return ''
# Parses a timing pattern and returns a list of (char, int) tuples
# where the char is either 'w' for work or 'b' for break
def parse_pattern(raw_pattern):
pattern = raw_pattern.replace(' ', '')
length = len(pattern)
index = 0
output = []
while index < length:
next_char = pattern[index]
if next_char == 'w' or next_char == 'b':
# work period
num_str = get_contiguous_number(pattern, index + 1)
if len(num_str) == 0:
raise ValueError(
'No number found after char {} at index {} in pattern {}'.format(
next_char,
index,
raw_pattern
)
)
time = int(num_str)
output.append((next_char, time))
index += len(num_str) + 1
else:
raise ValueError(
'Unexpected char {} at index {} in pattern {}'.format(
next_char,
index,
raw_pattern
)
)
return output
# Cleans up a parsed timing pattern in the [('w'|'b', time)*] format
# Return type is the same
def clean_pattern(pattern):
length = len(pattern)
if length == 0 or length == 1:
return pattern
output = []
last_type, last_time = pattern[0]
for i in range(1, length):
current_type, current_time = pattern[i]
if current_type == last_type:
last_time += current_time
else:
output.append((last_type, last_time))
last_type = current_type
last_time = current_time
output.append((last_type, last_time))
return output
def main():
args = sys.argv[1:]
options = 'ne:p:' # empty string would only accept long options
long_options = [
'email-conf=',
'pattern=',
'no-notifcation'
]
config_vals = {
'email_conf': None,
'pattern': 'w25b5w25b5w25b5',
'no-notification': False
}
try:
opt_vals, args = getopt.getopt(args, options, long_options)
except getopt.GetoptError as err:
print('Encountered option error!')
print(str(err))
sys.exit()
#print(opt_vals)
for opt, arg in opt_vals:
if opt == '--no-notifcation' or opt == '-n':
config_vals['no-notification'] = True
if opt == '--email-conf' or opt == '-e':
config_vals['email_conf'] = arg
if opt == '--pattern' or opt == '-p':
config_vals['pattern'] = arg
if config_vals['pattern'] is None:
print('Pymodoro requires a pattern!')
sys.exit()
try:
parsed_pattern = parse_pattern(config_vals['pattern'])
cleaned_pattern = clean_pattern(parsed_pattern)
except Exception as err:
print("Could not parse pattern!")
print(str(err))
sys.exit()
if config_vals['email_conf'] is not None:
conf_parser = configparser.ConfigParser()
conf_path = r'email.conf'
conf_parser.read(conf_path)
from_address = conf_parser.get('email', 'fromAddress')
to_address = conf_parser.get('email', 'toAddress')
login = conf_parser.get('email', 'login')
password = conf_parser.get('email', 'password')
server = conf_parser.get('email', 'smtpserver')
subject = 'Pymodoro Alert!'
for task, duration in cleaned_pattern:
task_string = ''
if task == 'b':
task_string = 'break period'
elif task == 'w':
task_string = 'work period'
time = datetime.now()
time_str = time.strftime('%H:%M')
endtime = time + timedelta(minutes=duration)
endtime_str = endtime.strftime('%H:%M')
print('[{}] Beginning {} minute {} until {}!'.format(time_str, duration, task_string, endtime_str))
wait(duration)
time_str = datetime.now().strftime('%H:%M')
print('[{}] Completed {}!'.format(time_str, task_string))
notification_string = 'Your {} is complete!'.format(task_string)
if not config_vals['no-notification']:
alert.notify_desktop('Pymodoro', notification_string)
if config_vals['email_conf'] is not None:
alert.send_email(
from_addr = from_address,
to_addr_list = [to_address],
subject = subject,
message = notification_string,
login = login,
password = password,
smtpserver = server
)
if __name__ == '__main__':
main()
| 47,266
|
https://github.com/Opentrons/opentrons/blob/master/step-generation/src/commandCreators/atomic/dispense.ts
|
Github Open Source
|
Open Source
|
LicenseRef-scancode-warranty-disclaimer, Apache-2.0
| 2,023
|
opentrons
|
Opentrons
|
TypeScript
|
Code
| 296
| 1,385
|
import * as errorCreators from '../../errorCreators'
import {
modulePipetteCollision,
thermocyclerPipetteCollision,
pipetteIntoHeaterShakerLatchOpen,
pipetteIntoHeaterShakerWhileShaking,
getIsHeaterShakerEastWestWithLatchOpen,
pipetteAdjacentHeaterShakerWhileShaking,
getLabwareSlot,
getIsHeaterShakerEastWestMultiChannelPipette,
getIsHeaterShakerNorthSouthOfNonTiprackWithMultiChannelPipette,
uuid,
} from '../../utils'
import type { CreateCommand } from '@opentrons/shared-data'
import type { DispenseParams } from '@opentrons/shared-data/protocol/types/schemaV3'
import type { CommandCreator, CommandCreatorError } from '../../types'
/** Dispense with given args. Requires tip. */
export const dispense: CommandCreator<DispenseParams> = (
args,
invariantContext,
prevRobotState
) => {
const {
pipette,
volume,
labware,
well,
offsetFromBottomMm,
flowRate,
isAirGap,
} = args
const actionName = 'dispense'
const errors: CommandCreatorError[] = []
const pipetteSpec = invariantContext.pipetteEntities[pipette]?.spec
const isFlexPipette =
(pipetteSpec?.displayCategory === 'FLEX' || pipetteSpec?.channels === 96) ??
false
const slotName = getLabwareSlot(
labware,
prevRobotState.labware,
prevRobotState.modules
)
if (!pipetteSpec) {
errors.push(
errorCreators.pipetteDoesNotExist({
actionName,
pipette,
})
)
}
if (
modulePipetteCollision({
pipette,
labware,
invariantContext,
prevRobotState,
})
) {
errors.push(errorCreators.modulePipetteCollisionDanger())
}
if (!prevRobotState.tipState.pipettes[pipette]) {
errors.push(
errorCreators.noTipOnPipette({
actionName,
pipette,
labware,
well,
})
)
}
if (!labware || !prevRobotState.labware[labware]) {
errors.push(
errorCreators.labwareDoesNotExist({
actionName,
labware,
})
)
} else if (prevRobotState.labware[labware].slot === 'offDeck') {
errors.push(errorCreators.labwareOffDeck())
}
if (
thermocyclerPipetteCollision(
prevRobotState.modules,
prevRobotState.labware,
labware
)
) {
errors.push(errorCreators.thermocyclerLidClosed())
}
if (
pipetteIntoHeaterShakerLatchOpen(
prevRobotState.modules,
prevRobotState.labware,
labware
)
) {
errors.push(errorCreators.heaterShakerLatchOpen())
}
if (
pipetteIntoHeaterShakerWhileShaking(
prevRobotState.modules,
prevRobotState.labware,
labware
)
) {
errors.push(errorCreators.heaterShakerIsShaking())
}
if (!isFlexPipette) {
if (
pipetteAdjacentHeaterShakerWhileShaking(prevRobotState.modules, slotName)
) {
errors.push(errorCreators.heaterShakerNorthSouthEastWestShaking())
}
if (
getIsHeaterShakerEastWestWithLatchOpen(prevRobotState.modules, slotName)
) {
errors.push(errorCreators.heaterShakerEastWestWithLatchOpen())
}
if (
getIsHeaterShakerEastWestMultiChannelPipette(
prevRobotState.modules,
slotName,
pipetteSpec
)
) {
errors.push(errorCreators.heaterShakerEastWestOfMultiChannelPipette())
}
if (
getIsHeaterShakerNorthSouthOfNonTiprackWithMultiChannelPipette(
prevRobotState.modules,
slotName,
pipetteSpec,
invariantContext.labwareEntities[labware]
)
) {
errors.push(
errorCreators.heaterShakerNorthSouthOfNonTiprackWithMultiChannelPipette()
)
}
}
if (errors.length > 0) {
return {
errors,
}
}
const commands: CreateCommand[] = [
{
commandType: 'dispense',
key: uuid(),
params: {
pipetteId: pipette,
volume,
labwareId: labware,
wellName: well,
wellLocation: {
origin: 'bottom',
offset: {
z: offsetFromBottomMm,
},
},
flowRate,
},
...(isAirGap && { meta: { isAirGap } }),
},
]
return {
commands,
}
}
| 41,684
|
https://github.com/sukkla01/swsolary/blob/master/vendor/guzzlehttp/guzzle/tests/FunctionsTest.php
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,018
|
swsolary
|
sukkla01
|
PHP
|
Code
| 426
| 1,653
|
<?php
namespace GuzzleHttp\Tests;
use GuzzleHttp\Client;
use GuzzleHttp\Event\BeforeEvent;
use GuzzleHttp\Event\CompleteEvent;
use GuzzleHttp\Event\ErrorEvent;
use GuzzleHttp\Message\Response;
use GuzzleHttp\Subscriber\Mock;
class FunctionsTest extends \PHPUnit_Framework_TestCase
{
public function testExpandsTemplate()
{
$this->assertEquals('foo/123', \GuzzleHttp\uri_template('foo/{bar}', ['bar' => '123']));
}
public function noBodyProvider()
{
return [['get'], ['head'], ['delete']];
}
/**
* @dataProvider noBodyProvider
*/
public function testSendsNoBody($method)
{
Server::flush();
Server::enqueue([new Response(200)]);
call_user_func("GuzzleHttp\\{$method}", Server::$url, [
'headers' => ['foo' => 'bar'],
'query' => ['a' => '1']
]);
$sent = Server::received(true)[0];
$this->assertEquals(strtoupper($method), $sent->getMethod());
$this->assertEquals('/?a=1', $sent->getResource());
$this->assertEquals('bar', $sent->getHeader('foo'));
}
public function testSendsOptionsRequest()
{
Server::flush();
Server::enqueue([new Response(200)]);
\GuzzleHttp\options(Server::$url, ['headers' => ['foo' => 'bar']]);
$sent = Server::received(true)[0];
$this->assertEquals('OPTIONS', $sent->getMethod());
$this->assertEquals('/', $sent->getResource());
$this->assertEquals('bar', $sent->getHeader('foo'));
}
public function hasBodyProvider()
{
return [['put'], ['post'], ['patch']];
}
/**
* @dataProvider hasBodyProvider
*/
public function testSendsWithBody($method)
{
Server::flush();
Server::enqueue([new Response(200)]);
call_user_func("GuzzleHttp\\{$method}", Server::$url, [
'headers' => ['foo' => 'bar'],
'body' => 'test',
'query' => ['a' => '1']
]);
$sent = Server::received(true)[0];
$this->assertEquals(strtoupper($method), $sent->getMethod());
$this->assertEquals('/?a=1', $sent->getResource());
$this->assertEquals('bar', $sent->getHeader('foo'));
$this->assertEquals('test', $sent->getBody());
}
/**
* @expectedException \PHPUnit_Framework_Error_Deprecated
* @expectedExceptionMessage GuzzleHttp\Tests\HasDeprecations::baz() is deprecated and will be removed in a future version. Update your code to use the equivalent GuzzleHttp\Tests\HasDeprecations::foo() method instead to avoid breaking changes when this shim is removed.
*/
public function testManagesDeprecatedMethods()
{
$d = new HasDeprecations();
$d->baz();
}
/**
* @expectedException \BadMethodCallException
*/
public function testManagesDeprecatedMethodsAndHandlesMissingMethods()
{
$d = new HasDeprecations();
$d->doesNotExist();
}
public function testBatchesRequests()
{
$client = new Client();
$responses = [
new Response(301, ['Location' => 'http://foo.com/bar']),
new Response(200),
new Response(200),
new Response(404)
];
$client->getEmitter()->attach(new Mock($responses));
$requests = [
$client->createRequest('GET', 'http://foo.com/baz'),
$client->createRequest('HEAD', 'http://httpbin.org/get'),
$client->createRequest('PUT', 'http://httpbin.org/put'),
];
$a = $b = $c = 0;
$result = \GuzzleHttp\batch($client, $requests, [
'before' => function (BeforeEvent $e) use (&$a) { $a++; },
'complete' => function (CompleteEvent $e) use (&$b) { $b++; },
'error' => function (ErrorEvent $e) use (&$c) { $c++; },
]);
$this->assertEquals(4, $a);
$this->assertEquals(2, $b);
$this->assertEquals(1, $c);
$this->assertCount(3, $result);
foreach ($result as $i => $request) {
$this->assertSame($requests[$i], $request);
}
// The first result is actually the second (redirect) response.
$this->assertSame($responses[1], $result[$requests[0]]);
// The second result is a 1:1 request:response map
$this->assertSame($responses[2], $result[$requests[1]]);
// The third entry is the 404 RequestException
$this->assertSame($responses[3], $result[$requests[2]]->getResponse());
}
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage Invalid event format
*/
public function testBatchValidatesTheEventFormat()
{
$client = new Client();
$requests = [$client->createRequest('GET', 'http://foo.com/baz')];
\GuzzleHttp\batch($client, $requests, ['complete' => 'foo']);
}
public function testJsonDecodes()
{
$data = \GuzzleHttp\json_decode('true');
$this->assertTrue($data);
}
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage Unable to parse JSON data: JSON_ERROR_SYNTAX - Syntax error, malformed JSON
*/
public function testJsonDecodesWithErrorMessages()
{
\GuzzleHttp\json_decode('!narf!');
}
}
class HasDeprecations
{
function foo()
{
return 'abc';
}
function __call($name, $arguments)
{
return \GuzzleHttp\deprecation_proxy($this, $name, $arguments, [
'baz' => 'foo'
]);
}
}
| 30,985
|
https://github.com/isabella232/dashboard.aptible.com/blob/master/app/organization/admin/environments/index/route.js
|
Github Open Source
|
Open Source
|
MIT
| 2,016
|
dashboard.aptible.com
|
isabella232
|
JavaScript
|
Code
| 29
| 110
|
import Ember from 'ember';
export default Ember.Route.extend({
model() {
let context = this.modelFor('organization');
let organization = context.get('organization');
return this.store.findStacksFor(organization);
},
setupController(controller, model) {
controller.set('model', model);
controller.set('organization', this.modelFor('organization').get('organization'));
}
});
| 780
|
https://github.com/Blakeinstein/Circle-Network/blob/master/.gitignore
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
Circle-Network
|
Blakeinstein
|
Ignore List
|
Code
| 7
| 71
|
example.py
output.png
QTDesign.ui
test.py
src/main/python/__pycache__/circleshape.cpython-37.pyc
Output.pdf
src/main/python/__pycache__/shapes.cpython-37.pyc
| 36,257
|
https://github.com/dwestheide/stryker4s/blob/master/core/src/main/scala/stryker4s/run/MutantRunner.scala
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
stryker4s
|
dwestheide
|
Scala
|
Code
| 204
| 795
|
package stryker4s.run
import java.nio.file.Path
import better.files.File
import grizzled.slf4j.Logging
import stryker4s.config.Config
import stryker4s.extension.FileExtensions._
import stryker4s.extension.score.MutationScoreCalculator
import stryker4s.model._
import stryker4s.mutants.findmutants.SourceCollector
import stryker4s.report.Reporter
import scala.concurrent.duration.{Duration, MILLISECONDS}
abstract class MutantRunner(sourceCollector: SourceCollector, reporter: Reporter)(implicit config: Config)
extends InitialTestRun
with MutationScoreCalculator
with Logging {
val tmpDir: File = {
val targetFolder = config.baseDir / "target"
targetFolder.createDirectoryIfNotExists()
File.newTemporaryDirectory("stryker4s-", Some(targetFolder))
}
def apply(mutatedFiles: Iterable[MutatedFile]): MutantRunResults = {
prepareEnv(mutatedFiles)
initialTestRun(tmpDir)
val startTime = System.currentTimeMillis()
val runResults = runMutants(mutatedFiles)
val duration = Duration(System.currentTimeMillis() - startTime, MILLISECONDS)
val detected = runResults collect { case d: Detected => d }
val result = MutantRunResults(runResults, calculateMutationScore(runResults.size, detected.size), duration)
reporter.reportRunFinished(result)
result
}
private def prepareEnv(mutatedFiles: Iterable[MutatedFile]): Unit = {
val files = sourceCollector.filesToCopy
debug("Using temp directory: " + tmpDir)
files.foreach(copyFile)
// Overwrite files to mutated files
mutatedFiles.foreach(writeMutatedFile)
}
private def copyFile(file: File): Unit = {
val filePath = tmpDir / file.relativePath.toString
filePath.createIfNotExists(file.isDirectory, createParents = true)
file.copyTo(filePath, overwrite = true)
}
private def writeMutatedFile(mutatedFile: MutatedFile): File = {
val filePath = mutatedFile.fileOrigin.inSubDir(tmpDir)
filePath.overwrite(mutatedFile.tree.syntax)
}
private def runMutants(mutatedFiles: Iterable[MutatedFile]): Iterable[MutantRunResult] = {
val totalMutants = mutatedFiles.flatMap(_.mutants).size
for {
mutatedFile <- mutatedFiles
subPath = mutatedFile.fileOrigin.relativePath
mutant <- mutatedFile.mutants
} yield {
reporter.reportMutationStart(mutant)
val result = runMutant(mutant, tmpDir)(subPath)
reporter.reportMutationComplete(result, totalMutants)
result
}
}
def runMutant(mutant: Mutant, workingDir: File): Path => MutantRunResult
}
| 4,470
|
https://github.com/cavo789/vbs_utilities/blob/master/src/files/find/find.vbs
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
vbs_utilities
|
cavo789
|
Visual Basic
|
Code
| 174
| 471
|
' -----------------------------------------------------------------
'
' Take advantage of Windows Desktop Search and very fast,
' get the list of MS Access applications present on the computer
' (local drives so also return files present, f.i. on a D: drive if
' you run the script from the C: drive; don't scan network drives).
'
' Source : https://blogs.technet.microsoft.com/heyscriptingguy/2006/12/15/how-can-i-list-all-the-access-database-files-on-a-computer/
'
' Output : This script will display the list (absolute filenames)
' of MS Access files like f.i.
'
' C:\Temp\Inventory.accdb
' D:\Dev\SubFolder\BigApp.mdb
'
' Note : just change searched extensions like .xlsx, .png, ...
' for searching other type of files
'
' -----------------------------------------------------------------
Set objConnection = CreateObject("ADODB.Connection")
Set objRecordSet = CreateObject("ADODB.Recordset")
objConnection.Open "Provider=Search.CollatorDSO;Extended Properties='Application=Windows';"
' Just change extensions for searching for other files like .xlsx f.i.
objRecordSet.Open _
"SELECT System.ItemPathDisplay " & _
"FROM SYSTEMINDEX " & _
"WHERE (System.FileExtension='.accdb') OR " & _
"(System.FileExtension='.mdb')", objConnection
objRecordSet.MoveFirst
wScript.echo "List of files retrieved :"
wScript.echo "========================="
wScript.echo ""
Do Until objRecordset.EOF
wScript.Echo objRecordset.Fields.Item("System.ItemPathDisplay")
objRecordset.MoveNext
Loop
objRecordSet.Close
Set objRecordSet = Nothing
objConnection.Close
Set objConnection = Nothing
| 40,412
|
https://github.com/axelonet/muzei/blob/master/main/src/main/java/com/google/android/apps/muzei/sources/SourceSetupActivity.kt
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
muzei
|
axelonet
|
Kotlin
|
Code
| 210
| 606
|
/*
* Copyright 2018 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.muzei.sources
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.support.v4.app.FragmentActivity
import com.google.android.apps.muzei.api.MuzeiArtSource
import com.google.android.apps.muzei.room.MuzeiDatabase
import com.google.android.apps.muzei.util.observe
class SourceSetupActivity : FragmentActivity() {
companion object {
private const val REQUEST_CHOOSE_SOURCE = 1
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
MuzeiDatabase.getInstance(this).sourceDao().currentSource.observe(this) { source ->
if (source != null) {
setResult(Activity.RESULT_OK)
finish()
} else {
// Push the user to the SourceSettingsActivity to select a source
val intent = Intent(this@SourceSetupActivity,
SourceSettingsActivity::class.java)
if (getIntent().getBooleanExtra(
MuzeiArtSource.EXTRA_FROM_MUZEI_SETTINGS, false)) {
intent.putExtra(MuzeiArtSource.EXTRA_FROM_MUZEI_SETTINGS, true)
}
startActivityForResult(intent, REQUEST_CHOOSE_SOURCE)
}
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode != REQUEST_CHOOSE_SOURCE) {
return
}
// Pass on the resultCode from the SourceSettingsActivity onto Muzei
setResult(resultCode)
finish()
}
}
| 39,364
|
https://github.com/tanaka-takurou/serverless-contact-page-go/blob/master/api/main.go
|
Github Open Source
|
Open Source
|
MIT
| null |
serverless-contact-page-go
|
tanaka-takurou
|
Go
|
Code
| 212
| 770
|
package main
import (
"os"
"fmt"
"log"
"context"
"encoding/json"
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/service/sns"
)
type APIResponse struct {
Message string `json:"message"`
}
type Response events.APIGatewayProxyResponse
var snsClient *sns.Client
const layout string = "2006-01-02 15:04"
func HandleRequest(ctx context.Context, request events.APIGatewayProxyRequest) (Response, error) {
var jsonBytes []byte
var err error
d := make(map[string]string)
json.Unmarshal([]byte(request.Body), &d)
if v, ok := d["action"]; ok {
switch v {
case "sendmessage" :
if n, ok := d["name"]; ok {
if b, ok := d["message"]; ok {
if m, ok := d["mail"]; ok {
err = sendmessage(ctx, n, b, m)
}
}
}
}
}
log.Print(request.RequestContext.Identity.SourceIP)
if err != nil {
log.Print(err)
jsonBytes, _ = json.Marshal(APIResponse{Message: fmt.Sprint(err)})
return Response{
StatusCode: 500,
Body: string(jsonBytes),
}, nil
}
jsonBytes, _ = json.Marshal(APIResponse{Message: "Success"})
return Response {
StatusCode: 200,
Body: string(jsonBytes),
}, nil
}
func sendmessage(ctx context.Context, name string, message string, mail string) error {
if snsClient == nil {
snsClient = sns.NewFromConfig(getConfig(ctx))
}
input := &sns.PublishInput{
Subject: aws.String("Serverless Contact"),
Message: aws.String("[Name]\n" + name + "\n\n[Mail]\n" + mail + "\n\n[Message]\n" + message),
TopicArn: aws.String(os.Getenv("TOPIC_ARN")),
}
_, err := snsClient.Publish(ctx, input)
return err
}
func getConfig(ctx context.Context) aws.Config {
var err error
cfg, err := config.LoadDefaultConfig(ctx, config.WithRegion(os.Getenv("REGION")))
if err != nil {
log.Print(err)
}
return cfg
}
func main() {
lambda.Start(HandleRequest)
}
| 33,430
|
https://github.com/wangdx66/SportPage/blob/master/iso/SportsPage/SportsPage/SPSportsSysNotificationTableViewCell.h
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,019
|
SportPage
|
wangdx66
|
C
|
Code
| 33
| 119
|
//
// SPSportsSysNotificationTableViewCell.h
// SportsPage
//
// Created by Qin on 2016/12/11.
// Copyright © 2016年 Absolute. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "SPSportsNotificationResponseModel.h"
@interface SPSportsSysNotificationTableViewCell : UITableViewCell
- (void)setUpWithModel:(SPSportsNotificationModel *)model;
@end
| 6,090
|
https://github.com/gaoyoubo/vditor/blob/master/src/ts/editor/turndown-plugin-gfm.ts
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
vditor
|
gaoyoubo
|
TypeScript
|
Code
| 336
| 906
|
const rules: { [key: string]: ITurndownRule } = {
vditorDelete: {
filter: ["del", "s", "strike"],
replacement: (content: string) => {
return "~~" + content + "~~";
},
},
vditorListItem: {
filter: "li",
replacement: (content: string, node: HTMLInputElement) => {
content = content
.replace(/^\n+/, "") // remove leading newlines
.replace(/\n+$/, "\n") // replace trailing newlines with just a single one
.replace(/\n/gm, "\n "); // indent
let prefix = "* ";
const parent = node.parentNode as HTMLOListElement;
if (parent.nodeName === "OL") {
const start = parent.getAttribute("start");
const index = Array.prototype.indexOf.call(parent.children, node);
prefix = (start ? Number(start) + index : index + 1) + ". ";
}
return (
prefix + content + (node.nextSibling && !/\n$/.test(content) ? "\n" : "")
);
},
},
vditorTableCell: {
filter: ["td", "th"],
replacement: (content, node) => {
return genCell(content, node);
},
},
vditorTableSection: {
filter: ["thead", "tbody", "tfoot"],
replacement: (content) => {
return content;
},
},
vditorTaskListItems: {
filter: (node: HTMLInputElement) => {
return node.type === "checkbox" && node.parentNode.nodeName === "LI";
},
replacement: (content: string, node: HTMLInputElement) => {
return (node.checked ? "[x]" : "[ ]") + " ";
},
},
vditorTr: {
filter: "tr",
replacement: (content, node) => {
let thCells = "";
const alignMap: { [key: string]: string } = {left: ":--", right: "--:", center: ":-:"};
const parentNode = node.parentNode;
let fistTr: HTMLElement;
if (parentNode.nodeName === "THEAD" || node.nodeName === "TH") {
fistTr = (parentNode.parentNode.querySelectorAll("tbody > tr")[0]) as HTMLElement;
}
if (parentNode.nodeName === "TABLE" && !node.previousElementSibling) {
fistTr = node;
}
if (fistTr) {
fistTr.childNodes.forEach((cell: HTMLTableCellElement) => {
const cellAlign = cell.style.textAlign || cell.getAttribute("align") || "";
thCells += genCell(alignMap[cellAlign.toLowerCase()] || "---", cell);
});
}
return "\n" + content + thCells;
},
},
};
const genCell = (content: string, node: HTMLElement) => {
let prefix = "| ";
let suffix = " |\n";
if (node.previousElementSibling) {
prefix = " ";
}
if (node.nextElementSibling) {
suffix = " | ";
}
return prefix + content + suffix;
};
export const gfm = (turndownService: ITurndown) => {
Object.keys(rules).forEach((key) => {
turndownService.addRule(key, rules[key]);
});
};
| 19,525
|
https://github.com/duniapay/oracle-server/blob/master/src/domain/common/utils/error/HttpError.ts
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
oracle-server
|
duniapay
|
TypeScript
|
Code
| 12
| 29
|
import InvalidRequestError from './InvalidRequestError';
class HttpError extends InvalidRequestError {}
export default HttpError;
| 4,897
|
https://github.com/vpaleshnikov/SoftUni-TechModule/blob/master/ProgrammingFundamentals/08.MethodsDebuggingAndTroubleshootingCode-Exercises/05.FibonacciNumbers/FibonacciNumbers.cs
|
Github Open Source
|
Open Source
|
MIT
| null |
SoftUni-TechModule
|
vpaleshnikov
|
C#
|
Code
| 60
| 168
|
using System;
namespace _05.FibonacciNumbers
{
class FibonacciNumbers
{
static void Main(string[] args)
{
var number = int.Parse(Console.ReadLine());
Console.WriteLine(FibonacciNumber(number));
}
static long FibonacciNumber(int number)
{
int firstNumber = 0;
int secondNumber = 1;
for (int i = 0; i < number; i++)
{
int temp = firstNumber;
firstNumber = secondNumber;
secondNumber = temp + secondNumber;
}
return secondNumber;
}
}
}
| 23,497
|
https://github.com/ZhihongShao/cotk/blob/master/docs/meta/update_doc.py
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
cotk
|
ZhihongShao
|
Python
|
Code
| 146
| 442
|
import os
import path
def get_location(text):
lines = text.split("\n")
res = []
for line in lines:
if not line.startswith("~~ location"):
break
_, _, key, path = line.split()
res.append((key, path))
return res
def render(text, key):
lines = text.split("\n")
res = []
in_flag = True
for line in lines:
if not line.startswith("~~"):
if in_flag:
res.append(line)
continue
args = line.split()
if args[1] == "location":
continue
elif args[1] == "contentstart":
if args[2] != key:
in_flag = False
elif args[1] == "contentend":
if args[2] != key:
in_flag = True
elif args[1] == "include":
res.extend(render(open(args[2], 'r', encoding='utf-8').read(), key))
else:
raise RuntimeError("Unknown tags %s" % args[1])
return res
if __name__ == "__main__":
for filename in os.listdir("./"):
if not filename.endswith(".md") and not filename.endswith(".rst"):
continue
print(filename)
file = open(filename, "r", encoding='utf-8').read()
locations = get_location(file)
for key, path in locations:
text = render(file, key)
open(path, 'w', encoding='utf-8').write("\n".join(text) + "\n")
print("render %s with %s" % (path, key))
| 48,090
|
https://github.com/aeharding/ppg-rap/blob/master/src/services/position.ts
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
ppg-rap
|
aeharding
|
TypeScript
|
Code
| 50
| 216
|
export function getPosition(
options?: PositionOptions
): Promise<GeolocationPosition> {
return new Promise((resolve, reject) =>
navigator.geolocation.getCurrentPosition(
(pos) => resolve(objectify(pos)),
reject,
options
)
);
}
function objectify(geoposition: GeolocationPosition): GeolocationPosition {
return {
timestamp: geoposition.timestamp,
coords: {
accuracy: geoposition.coords.accuracy,
altitude: geoposition.coords.altitude,
altitudeAccuracy: geoposition.coords.altitudeAccuracy,
heading: geoposition.coords.heading,
latitude: geoposition.coords.latitude,
longitude: geoposition.coords.longitude,
speed: geoposition.coords.speed,
},
};
}
| 27,029
|
https://github.com/DrItanium/ImageProcessingApplication/blob/master/src/lib/Filter/FilterMenuToolStripItem.cs
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| null |
ImageProcessingApplication
|
DrItanium
|
C#
|
Code
| 61
| 175
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Libraries.Filter
{
public class FilterToolStripMenuItem : ToolStripMenuItem
{
public Guid TargetFilter { get; set; }
public IFilterCallback Callback { get; set; }
public FilterToolStripMenuItem(Guid targetFilter, IFilterCallback callback)
{
TargetFilter = targetFilter;
Callback = callback;
}
protected override void OnClick(EventArgs e)
{
base.OnClick(e);
Callback.CurrentFilter = TargetFilter; //set this
}
}
}
| 40,862
|
https://github.com/aydinkim/opencv3-modified/blob/master/platforms/build_android_arm/modules/rgbd/CMakeFiles/opencv_rgbd.dir/cmake_clean_target.cmake
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,015
|
opencv3-modified
|
aydinkim
|
CMake
|
Code
| 3
| 35
|
FILE(REMOVE_RECURSE
"../../lib/armeabi-v7a/libopencv_rgbd.a"
)
| 23,661
|
https://github.com/bartoszkordek/AGH-Praca-inzynierska-back-end/blob/master/trainings/src/test/java/com/healthy/gym/trainings/utils/GroupTrainingMapperTest.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
AGH-Praca-inzynierska-back-end
|
bartoszkordek
|
Java
|
Code
| 346
| 2,128
|
package com.healthy.gym.trainings.utils;
import com.healthy.gym.trainings.data.document.GroupTrainingDocument;
import com.healthy.gym.trainings.data.document.LocationDocument;
import com.healthy.gym.trainings.data.document.TrainingTypeDocument;
import com.healthy.gym.trainings.data.document.UserDocument;
import com.healthy.gym.trainings.dto.GroupTrainingDTO;
import com.healthy.gym.trainings.dto.GroupTrainingWithoutParticipantsDTO;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import static org.assertj.core.api.Assertions.assertThat;
class GroupTrainingMapperTest {
private String trainerId1;
private String trainerId2;
private String userId;
private String reserveUserId1;
private String reserveUserId2;
private String groupTrainingId;
private GroupTrainingDocument groupTrainingToCreate;
@BeforeEach
void setUp() {
TrainingTypeDocument trainingType = new TrainingTypeDocument(
UUID.randomUUID().toString(),
"TestTrainingType",
"Test description",
null,
null
);
List<UserDocument> trainers = new ArrayList<>();
trainerId1 = UUID.randomUUID().toString();
trainers.add(
new UserDocument(
"TrainerName1",
"TrainerSUrname1",
"testemail1",
"testPhoneNumber1",
null,
trainerId1
)
);
trainerId2 = UUID.randomUUID().toString();
trainers.add(
new UserDocument(
"TrainerName2",
"TrainerSUrname2",
"testemail2",
"testPhoneNumber2",
null,
trainerId2
)
);
List<UserDocument> basicList = new ArrayList<>();
userId = UUID.randomUUID().toString();
basicList.add(
new UserDocument(
"UserName2",
"UserSUrname2",
"testemail2",
"testPhoneNumber2",
null,
userId
)
);
List<UserDocument> reserveList = new ArrayList<>();
reserveUserId1 = UUID.randomUUID().toString();
reserveList.add(
new UserDocument(
"UserName3",
"UserSUrname3",
"testemail3",
"testPhoneNumber3",
null,
reserveUserId1
)
);
reserveUserId2 = UUID.randomUUID().toString();
reserveList.add(
new UserDocument(
"UserName4",
"UserSUrname4",
"testemail4",
"testPhoneNumber4",
null,
reserveUserId2
)
);
LocalDateTime startDate = LocalDateTime.parse("2021-07-30T10:10", DateTimeFormatter.ISO_LOCAL_DATE_TIME);
LocalDateTime endDate = LocalDateTime.parse("2021-07-30T11:00", DateTimeFormatter.ISO_LOCAL_DATE_TIME);
LocationDocument location = new LocationDocument(UUID.randomUUID().toString(), "Room no 2");
groupTrainingId = UUID.randomUUID().toString();
groupTrainingToCreate = new GroupTrainingDocument(
groupTrainingId,
trainingType,
trainers,
startDate,
endDate,
location,
10,
basicList,
reserveList
);
}
@Nested
class WhenMapGroupTrainingsDocumentToDTO {
private GroupTrainingDTO groupTrainingDTO;
@BeforeEach
void setUp() {
groupTrainingDTO = GroupTrainingMapper.mapGroupTrainingsDocumentToDTO(groupTrainingToCreate);
}
@Test
void shouldHaveProperGroupTrainingId() {
assertThat(groupTrainingDTO.getGroupTrainingId()).isEqualTo(groupTrainingId);
}
@Test
void shouldHaveProperTrainers() {
var trainerList = groupTrainingDTO.getTrainers();
assertThat(trainerList.size()).isEqualTo(2);
assertThat(groupTrainingDTO.getTrainers().get(0).getUserId()).isEqualTo(trainerId1);
assertThat(groupTrainingDTO.getTrainers().get(1).getUserId()).isEqualTo(trainerId2);
}
@Test
void shouldHaveProperTitle() {
assertThat(groupTrainingDTO.getTitle()).isEqualTo("TestTrainingType");
}
@Test
void shouldHaveProperLocation() {
assertThat(groupTrainingDTO.getLocation()).isEqualTo("Room no 2");
}
@Test
void shouldHaveProperStartAndEndDate() {
assertThat(groupTrainingDTO.getStartDate()).isEqualTo("2021-07-30T10:10");
assertThat(groupTrainingDTO.getEndDate()).isEqualTo("2021-07-30T11:00");
}
@Test
void shouldHaveProperBasicList() {
var basicList = groupTrainingDTO.getParticipants().getBasicList();
assertThat(basicList.size()).isEqualTo(1);
assertThat(basicList.get(0).getUserId()).isEqualTo(userId);
assertThat(basicList.get(0).getName()).isEqualTo("UserName2");
assertThat(basicList.get(0).getSurname()).isEqualTo("UserSUrname2");
assertThat(basicList.get(0).getAvatarUrl()).isNull();
}
@Test
void shouldHaveProperReserveList() {
var reserveList = groupTrainingDTO.getParticipants().getReserveList();
assertThat(reserveList.size()).isEqualTo(2);
var personDetails1 = reserveList.get(0);
assertThat(personDetails1.getUserId()).isEqualTo(reserveUserId1);
assertThat(personDetails1.getName()).isEqualTo("UserName3");
assertThat(personDetails1.getSurname()).isEqualTo("UserSUrname3");
assertThat(personDetails1.getAvatarUrl()).isNull();
var personDetails2 = reserveList.get(1);
assertThat(personDetails2.getUserId()).isEqualTo(reserveUserId2);
assertThat(personDetails2.getName()).isEqualTo("UserName4");
assertThat(personDetails2.getSurname()).isEqualTo("UserSUrname4");
assertThat(personDetails2.getAvatarUrl()).isNull();
}
}
@Nested
class WhenMapGroupTrainingsDocumentToDTOWithoutParticipants {
private GroupTrainingWithoutParticipantsDTO groupTrainingDTO;
@BeforeEach
void setUp() {
groupTrainingDTO = GroupTrainingMapper
.mapGroupTrainingsDocumentToDTOWithoutParticipants(groupTrainingToCreate);
}
@Test
void shouldHaveProperGroupTrainingId() {
assertThat(groupTrainingDTO.getGroupTrainingId()).isEqualTo(groupTrainingId);
}
@Test
void shouldHaveProperTrainers() {
var trainerList = groupTrainingDTO.getTrainers();
assertThat(trainerList.size()).isEqualTo(2);
assertThat(groupTrainingDTO.getTrainers().get(0).getUserId()).isEqualTo(trainerId1);
assertThat(groupTrainingDTO.getTrainers().get(1).getUserId()).isEqualTo(trainerId2);
}
@Test
void shouldHaveProperTitle() {
assertThat(groupTrainingDTO.getTitle()).isEqualTo("TestTrainingType");
}
@Test
void shouldHaveProperLocation() {
assertThat(groupTrainingDTO.getLocation()).isEqualTo("Room no 2");
}
@Test
void shouldHaveProperStartAndEndDate() {
assertThat(groupTrainingDTO.getStartDate()).isEqualTo("2021-07-30T10:10");
assertThat(groupTrainingDTO.getEndDate()).isEqualTo("2021-07-30T11:00");
}
}
}
| 34,506
|
https://github.com/PMArkive/HyoutaTools/blob/master/HyoutaToolsLib/Tales/Vesperia/TO8CHLI/SkitConditionForwarder.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
HyoutaTools
|
PMArkive
|
C#
|
Code
| 47
| 171
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HyoutaUtils;
namespace HyoutaTools.Tales.Vesperia.TO8CHLI {
public class SkitConditionForwarder {
public ulong SkitConditionReference;
public uint SkitConditionCount;
public SkitConditionForwarder( System.IO.Stream stream, EndianUtils.Endianness endian, BitUtils.Bitness bits ) {
SkitConditionReference = stream.ReadUInt( bits, endian );
SkitConditionCount = stream.ReadUInt32().FromEndian( endian );
}
}
}
| 17,771
|
https://github.com/jeffbrown/grails-core/blob/master/grails-core/src/main/groovy/org/codehaus/groovy/grails/commons/metaclass/LazyMetaPropertyMap.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
grails-core
|
jeffbrown
|
Java
|
Code
| 707
| 1,963
|
/*
* Copyright 2004-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.codehaus.groovy.grails.commons.metaclass;
import groovy.lang.GroovySystem;
import groovy.lang.MetaBeanProperty;
import groovy.lang.MetaClass;
import groovy.lang.MetaProperty;
import groovy.util.MapEntry;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.codehaus.groovy.grails.commons.GrailsDomainClassProperty;
import org.codehaus.groovy.grails.commons.GrailsDomainConfigurationUtil;
import org.springframework.util.Assert;
/**
* A map implementation that reads an objects properties lazily using Groovy's MetaClass.
*
* @author Graeme Rocher
*/
@SuppressWarnings({"unchecked","rawtypes"})
public class LazyMetaPropertyMap implements Map {
private MetaClass metaClass;
private Object instance;
private static List<String> EXCLUDES = Arrays.asList("properties", GrailsDomainClassProperty.IDENTITY, GrailsDomainClassProperty.VERSION, "domainClass", "dirty", GrailsDomainClassProperty.ERRORS, "dirtyPropertyNames");
/**
* Constructs the map
* @param o The object to inspect
*/
public LazyMetaPropertyMap(Object o) {
Assert.notNull(o, "Object cannot be null");
instance = o;
metaClass = GroovySystem.getMetaClassRegistry().getMetaClass(o.getClass());
}
/**
* {@inheritDoc}
* @see java.util.Map#size()
*/
public int size() {
return keySet().size();
}
/**
* {@inheritDoc}
* @see java.util.Map#isEmpty()
*/
public boolean isEmpty() {
return false; // will never be empty
}
/**
* {@inheritDoc}
* @see java.util.Map#containsKey(java.lang.Object)
*/
public boolean containsKey(Object propertyName) {
if (propertyName instanceof CharSequence) propertyName = propertyName.toString();
Assert.isInstanceOf(String.class, propertyName, "This map implementation only supports String based keys!");
String pn = propertyName.toString();
return !GrailsDomainConfigurationUtil.isConfigurational(pn) && metaClass.getMetaProperty(pn) != null;
}
/**
* Checks whether the specified value is contained within the Map. Note that because this implementation
* lazily initialises property values the behaviour may not be consistent with the actual values of the
* contained object unless they have already been initialised by calling get(Object)
*
* @see java.util.Map#containsValue(Object)
*/
public boolean containsValue(Object o) {
return values().contains(o);
}
/**
* Obtains the value of an object's properties on demand using Groovy's MOP.
*
* @param propertyName The name of the property
* @return The property value or null
*/
public Object get(Object propertyName) {
if (propertyName instanceof CharSequence) {
propertyName = propertyName.toString();
}
if (propertyName instanceof List) {
Map submap = new HashMap();
List propertyNames = (List)propertyName;
for (Object currentName : propertyNames) {
if (currentName != null) {
currentName = currentName.toString();
if (containsKey(currentName)) {
submap.put(currentName, get(currentName));
}
}
}
return submap;
}
if (GrailsDomainConfigurationUtil.isConfigurational(propertyName.toString())) {
return null;
}
Object val = null;
MetaProperty mp = metaClass.getMetaProperty(propertyName.toString());
if (mp != null) {
val = mp.getProperty(instance);
}
return val;
}
public Object put(Object propertyName, Object propertyValue) {
if (propertyName instanceof CharSequence) {
propertyName = propertyName.toString();
}
Object old = null;
MetaProperty mp = metaClass.getMetaProperty((String)propertyName);
if (mp != null && !isExcluded(mp)) {
old = mp.getProperty(instance);
if (propertyValue instanceof Map) {
propertyValue = ((Map)propertyValue).get(propertyName);
}
mp.setProperty(instance, propertyValue);
}
return old;
}
/**
* @throws UnsupportedOperationException
*/
public Object remove(Object o) {
throw new UnsupportedOperationException("Method remove(Object o) is not supported by this implementation");
}
public void putAll(Map map) {
for (Iterator i = map.keySet().iterator(); i.hasNext();) {
Object key = i.next();
put(key, map.get(key));
}
}
/**
* @throws UnsupportedOperationException
*/
public void clear() {
throw new UnsupportedOperationException("Method clear() is not supported by this implementation");
}
public Set<String> keySet() {
Set<String> names = new HashSet<String>();
for (MetaProperty mp : metaClass.getProperties()) {
if (isExcluded(mp)) continue;
names.add(mp.getName());
}
return names;
}
public Collection<Object> values() {
Collection<Object> values = new ArrayList<Object>();
for (MetaProperty mp : metaClass.getProperties()) {
if (isExcluded(mp)) continue;
values.add(mp.getProperty(instance));
}
return values;
}
@Override
public int hashCode() {
return instance.hashCode();
}
@Override
public boolean equals(Object o) {
if (o instanceof LazyMetaPropertyMap) {
LazyMetaPropertyMap other = (LazyMetaPropertyMap)o;
return instance.equals(other.getInstance());
}
return false;
}
/**
* Returns the wrapped instance.
*
* @return The wrapped instance
*/
public Object getInstance() {
return instance;
}
public Set<MapEntry> entrySet() {
Set<MapEntry> entries = new HashSet<MapEntry>();
for (MetaProperty mp : metaClass.getProperties()) {
if (isExcluded(mp)) continue;
entries.add(new MapEntry(mp.getName(), mp.getProperty(instance)));
}
return entries;
}
private boolean isExcluded(MetaProperty mp) {
return
Modifier.isStatic(mp.getModifiers()) ||
EXCLUDES.contains(mp.getName()) ||
GrailsDomainConfigurationUtil.isConfigurational(mp.getName()) ||
(mp instanceof MetaBeanProperty) && (((MetaBeanProperty) mp).getGetter()) == null;
}
}
| 6,053
|
https://github.com/kaazing/java.client/blob/master/amqp-0-9-1/amqp/src/main/java/org/kaazing/net/ws/amqp/impl/AsyncClient.java
|
Github Open Source
|
Open Source
|
Apache-2.0, BSD-3-Clause, BSD-2-Clause
| 2,017
|
java.client
|
kaazing
|
Java
|
Code
| 345
| 1,039
|
/**
* Copyright 2007-2015, Kaazing Corporation. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kaazing.net.ws.amqp.impl;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.kaazing.net.ws.amqp.AmqpChannel;
import org.kaazing.net.ws.amqp.AmqpEvent;
import org.kaazing.net.ws.amqp.ChannelEvent;
public final class AsyncClient {
private List<Action> actions = Collections.synchronizedList(new ArrayList<Action>());
StateMachine stateMachine;
Object waitingAction;
/**
* AsyncClient provides base structure and functionality for asynchronous network clients
*/
public AsyncClient()
{
this.stateMachine = null;
}
public synchronized void processActions()
{
Action action = null;
if (this.actions.size() > 0) {
action = this.actions.remove(0);
}
if (action == null) {
return;
}
try
{
Boolean movedSuccessfully = this.stateMachine.feedInput(action.actionName + "Action", action);
if (movedSuccessfully)
{
if (action.func.equalsIgnoreCase("write")) {
ClientStateMachineListener csmListener = stateMachine.getClientStateMachineListener();
try {
csmListener.createAndSendFrame(csmListener.getClient(), action.args);
}
catch (Exception ex1) {
ex1.printStackTrace();
if (action.error != null) {
AmqpEvent e = new ChannelEvent(csmListener.getClient(),
ChannelEvent.Kind.ERROR,
ex1.getMessage());
action.error.error(e);
}
}
}
else {
ChannelStateMachineListener chsmListener = stateMachine.getChannelStateMachineListener();
AmqpChannel channel = chsmListener.getChannel();
try {
chsmListener.createAndSendFrame(channel, action.args);
}
catch (Exception ex2) {
ex2.printStackTrace();
if (action.error != null) {
AmqpEvent e = new ChannelEvent(channel, ChannelEvent.Kind.ERROR, ex2.getMessage());
action.error.error(e);
}
}
}
}
else
{
this.actions.add(0,action);
}
}
catch (Exception e)
{
throw new IllegalStateException(e.getMessage());
}
}
public synchronized void enqueueAction(String actionName, String func, Object[] args, Continuation callback, ErrorHandler error)
{
Action action = new Action();
action.actionName = actionName;
action.func = func;
action.args = args;
if(callback != null){
action.continuation=callback;
}
if(error != null){
action.error=error;
}
this.actions.add(action);
this.processActions();
}
public void initAsyncClient()
{
this.stateMachine = new StateMachine(this);
}
public StateMachine getStateMachine()
{
return this.stateMachine;
}
public Object getWaitingAction()
{
return this.waitingAction;
}
public synchronized void setWaitingAction(Object waitingAction)
{
this.waitingAction = waitingAction;
}
}
| 35,749
|
https://github.com/sasinduthashmira/JavaFirstProgram/blob/master/class Sasindu.java
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
JavaFirstProgram
|
sasinduthashmira
|
Java
|
Code
| 36
| 129
|
class Sasindu{
public static void main (String args[]){
mySpace();
printDetails();
mySpace();
}
private static void printDetails() {
System.out.println("Hello World!");
System.out.println("I'm Sasindu Thashmira ");
}
private static void mySpace() {
System.out.println(" ");
System.out.println("<-------------------------------->");
System.out.println(" ");
}
}
| 6,321
|
https://github.com/chaiwanlin/tp/blob/master/src/main/java/seedu/edrecord/model/assignment/Grade.java
|
Github Open Source
|
Open Source
|
MIT
| null |
tp
|
chaiwanlin
|
Java
|
Code
| 232
| 622
|
package seedu.edrecord.model.assignment;
import static seedu.edrecord.commons.util.AppUtil.checkArgument;
import static seedu.edrecord.commons.util.CollectionUtil.requireAllNonNull;
import java.util.Objects;
import java.util.Optional;
/**
* Represents an Grade under a Student in EdRecord.
* Guarantees: immutable, details are present and not null.
*/
public class Grade {
public enum GradeStatus { NOT_SUBMITTED, SUBMITTED, GRADED }
public static final String MESSAGE_CONSTRAINTS = "Status should be \"not submitted\", \"submitted\" or \"graded\".";
public static final String MESSAGE_STATUS_SCORE_MISMATCH = "Score should only be present if status is \"graded\"";
private final Optional<Score> score;
private final GradeStatus status;
/**
* Constructs a {@code Grade}. Every field must be present and not null.
*
* @param score Score of the grade
* @param status Status of the grade.
*/
public Grade(Optional<Score> score, GradeStatus status) {
requireAllNonNull(score);
checkArgument(isValidGrade(status, score), MESSAGE_STATUS_SCORE_MISMATCH);
this.score = score;
this.status = status;
}
public Optional<Score> getScore() {
return score;
}
public GradeStatus getStatus() {
return status;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Status: ").append(status);
if (score.isPresent()) {
builder.append(", Score: ");
score.ifPresent(builder::append);
}
return builder.toString();
}
/**
* Checks if the given grade is valid.
*/
public static boolean isValidGrade(GradeStatus status, Optional<Score> score) {
return score.isEmpty() || status.equals(GradeStatus.GRADED);
}
@Override
public boolean equals(Object other) {
return other == this // short circuit if same object
|| (other instanceof Grade // instanceof handles nulls
&& score.equals(((Grade) other).score)
&& status.equals(((Grade) other).status)); // state check
}
@Override
public int hashCode() {
return Objects.hash(score, status);
}
}
| 19,982
|
https://github.com/hendrikdelarey/appcampus/blob/master/AppCampus.Website/app/controllers/profileController.js
|
Github Open Source
|
Open Source
|
MIT
| null |
appcampus
|
hendrikdelarey
|
JavaScript
|
Code
| 93
| 345
|
app.controller("profileController", function ($scope, $rootScope, userService, errorHandler, toastr) {
$(".content").slimscroll({
height: window.innerHeight - 135,
alwaysVisible: true,
size: "3px"
});
userService.$resource().get({ userId: userService.getUserId() }, function success(user) {
$scope.user = user;
}, errorHandler.handleError);
$scope.updateUserDetails = function (form) {
$scope.updatingUserDetails = true;
$scope.user.$update({}, function success() {
$scope.updatingUserDetails = false;
toastr.success("User information updated");
$rootScope.$broadcast("userInfoUpdate");
}, function error(error) {
$scope.updatingPassword = false;
errorHandler.handleError(error);
});
};
$scope.updatePassword = function (form) {
$scope.updatingPassword = true;
if (form.$invalid) {
return false;
}
$scope.user.$updatePassword({}, function success(user) {
toastr.success("Password changed");
$scope.updatingPassword = false;
}, function error(error) {
$scope.updatingPassword = false;
errorHandler.handleError(error);
});
};
});
| 11,201
|
https://github.com/nobe4/HexClock.sh/blob/master/HexaClock.sh
|
Github Open Source
|
Open Source
|
MIT
| null |
HexClock.sh
|
nobe4
|
Shell
|
Code
| 141
| 425
|
# echo 'HexaClock v0.1 \n';
# detecting terminal size
lineNumbers="$(tput lines)";
columnNumbers="$(tput cols)";
# echo 'Terminal size : ' $lineNumbers '*' $columnNumbers
# setting text size
textSize=6 # hhmmss
# calculating the text position
textY=$(( $lineNumbers/2 ))
textX=$(( $columnNumbers/2 - $textSize/2 - 1))
# echo 'Text position ' $textY ' ' $textX
# getting current time
hours="$(date +%H)"
minutes="$(date +%M)"
seconds="$(date +%S)"
# convert to hex
hours=$(echo "obase=16; $hours" | bc)
if [ $(date +%H) -lt 16 ];then
hours=$(echo "0")$hours
textX=$(($textX - 1))
fi
minutes=$(echo "obase=16; $minutes" | bc)
secondes=$(echo "obase=16; $seconds" | bc)
# display text
# first linebreak before printing anything
echo '\n'
for ((i=1;i<=lineNumbers;i++)); do
if [ $i -eq $textY ] ; then
for ((j=1;j<=textX;j++)); do
printf '_'
done
printf $hours:$minutes:$seconds
for ((j=1;j<=textX;j++)); do
printf '_'
done
else
for ((j=1;j<=columnNumbers;j++)); do
printf '_'
done
fi
printf '\n'
done
| 36,910
|
https://github.com/saifulapm/dotfiles-18/blob/master/.config/bspwm/bspwmrc
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
dotfiles-18
|
saifulapm
|
Shell
|
Code
| 292
| 793
|
#!/bin/sh
##### Autostart #####
# Set cursor
xsetroot -cursor_name left_ptr &
# Shortcuts
if ! pgrep -x "sxhkd" >/dev/null; then
sxhkd &
fi
# Start pipewire
if ! pgrep -x "pipewire-pulse" >/dev/null; then
pipewire &
fi
# Start compositor, set wallpaper and colors
if ! pgrep -x "compton" >/dev/null; then
# Enable blur in compton
compton --backend glx --blur-method kawase --blur-background --blur-strength 6 &
# Set the wallpaper
feh --bg-scale $HOME/Imágenes/Wallpapers/onedark.png &
# Set the colors based on the wallpaper
wal -n -i $HOME/Imágenes/Wallpapers/onedark.png &
xset -b & # For annoying beeping sounds
fi
# Start KWallet for passwords (including wiif passwords)
if ! pgrep -x "kwalletd5" >/dev/null; then
kwalletd5 &
fi
# Start NetworkManager applet for polybar
if ! pgrep -x "nm-applet" >/dev/null; then
nm-applet &
fi
# Start dunst notifications with wal colors
if ! pgrep -x "dunst" >/dev/null; then
$HOME/.config/dunst/dunstwal.sh &
fi
# Start polybar
if ! pgrep -x "polybar" >/dev/null; then
$HOME/.config/polybar/launch.sh &
fi
##### Workspaces and Borders #####
bspc monitor -d I II III IV V
bspc config border_width 2
bspc config window_gap 15
bspc config split_ratio 0.5
bspc config borderless_monocle true
bspc config gapless_monocle true
bspc config top_padding 40
bspc config bottom_padding 20
bspc config left_padding 20
bspc config right_padding 20
bspc rule -a Emacs state=tiled follow=on
bspc rule -a Codium state=tiled follow=off
bspc rule -a Chrome state=tiled follow=on
bspc rule -a Kitty state=tiled follow=on
bspc rule -a Discord state=tiled follow=off
bspc rule -a Dolphin state=floating follow=on
bspc rule -a Telegram state=tiled follow=off
# Focus on pointer
bspc config focus_follows_pointer true
bspc config pointer_follows_focus true
# Use wallpaper colors
. "${HOME}/.cache/wal/colors.sh"
# Set the border colors.
bspc config normal_border_color "#373d48"
bspc config active_border_color "#98c379"
bspc config focused_border_color "#373d48"
bspc config urgent_border_color "#e06c75"
bspc config presel_feedback_color "#abb2bf"
| 30,457
|
https://github.com/andrzejszywala/oop/blob/master/src/main/java/pl/andrzejszywala/oop/dziedziczenie/Dziedziczenie.java
|
Github Open Source
|
Open Source
|
MIT
| null |
oop
|
andrzejszywala
|
Java
|
Code
| 70
| 247
|
package pl.andrzejszywala.oop.dziedziczenie;
public class Dziedziczenie {
public static void main(String[] args) {
new BMW().wlacz();
new Mercedes().wlacz();
}
}
class Pojazd {
public void wlacz() {
System.out.println("Włączam pojazd");
}
}
class Samochod extends Pojazd {
public void wlacz() {
super.wlacz();
System.out.println("Włączam samochod");
}
}
class BMW extends Samochod {
public void wlacz() {
super.wlacz();
System.out.println("Włączam BMW");
}
}
class Mercedes extends Samochod {
public void wlacz() {
System.out.println("Włączam Mercedesa");
}
}
| 22,354
|
https://github.com/haocxy/mirror-googlesource-dawn-tint/blob/master/src/reader/spirv/function_composite_test.cc
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
mirror-googlesource-dawn-tint
|
haocxy
|
C++
|
Code
| 3,839
| 14,449
|
// Copyright 2020 The Tint Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "gmock/gmock.h"
#include "src/reader/spirv/function.h"
#include "src/reader/spirv/parser_impl_test_helper.h"
#include "src/reader/spirv/spirv_tools_helpers_test.h"
namespace tint {
namespace reader {
namespace spirv {
namespace {
using ::testing::Eq;
using ::testing::HasSubstr;
std::string Caps() {
return R"(
OpCapability Shader
OpMemoryModel Logical Simple
OpEntryPoint GLCompute %100 "main"
OpExecutionMode %100 LocalSize 1 1 1
)";
}
std::string CommonTypes() {
return R"(
%void = OpTypeVoid
%voidfn = OpTypeFunction %void
%uint = OpTypeInt 32 0
%int = OpTypeInt 32 1
%float = OpTypeFloat 32
%uint_10 = OpConstant %uint 10
%uint_20 = OpConstant %uint 20
%uint_3 = OpConstant %uint 3
%uint_4 = OpConstant %uint 4
%uint_5 = OpConstant %uint 5
%int_1 = OpConstant %int 1
%int_30 = OpConstant %int 30
%int_40 = OpConstant %int 40
%float_50 = OpConstant %float 50
%float_60 = OpConstant %float 60
%float_70 = OpConstant %float 70
%v2uint = OpTypeVector %uint 2
%v3uint = OpTypeVector %uint 3
%v4uint = OpTypeVector %uint 4
%v2int = OpTypeVector %int 2
%v2float = OpTypeVector %float 2
%m3v2float = OpTypeMatrix %v2float 3
%m3v2float_0 = OpConstantNull %m3v2float
%s_v2f_u_i = OpTypeStruct %v2float %uint %int
%a_u_5 = OpTypeArray %uint %uint_5
%v2uint_3_4 = OpConstantComposite %v2uint %uint_3 %uint_4
%v2uint_4_3 = OpConstantComposite %v2uint %uint_4 %uint_3
%v2float_50_60 = OpConstantComposite %v2float %float_50 %float_60
%v2float_60_50 = OpConstantComposite %v2float %float_60 %float_50
%v2float_70_70 = OpConstantComposite %v2float %float_70 %float_70
)";
}
std::string Preamble() {
return Caps() + CommonTypes();
}
using SpvParserTest_Composite_Construct = SpvParserTest;
TEST_F(SpvParserTest_Composite_Construct, Vector) {
const auto assembly = Preamble() + R"(
%100 = OpFunction %void None %voidfn
%entry = OpLabel
%1 = OpCompositeConstruct %v2uint %uint_10 %uint_20
%2 = OpCompositeConstruct %v2int %int_30 %int_40
%3 = OpCompositeConstruct %v2float %float_50 %float_60
OpReturn
OpFunctionEnd
)";
auto p = parser(test::Assemble(assembly));
ASSERT_TRUE(p->BuildAndParseInternalModuleExceptFunctions()) << assembly;
auto fe = p->function_emitter(100);
EXPECT_TRUE(fe.EmitBody()) << p->error();
EXPECT_THAT(ToString(p->builder(), fe.ast_body()),
HasSubstr(R"(VariableDeclStatement{
VariableConst{
x_1
none
undefined
__vec_2__u32
{
TypeConstructor[not set]{
__vec_2__u32
ScalarConstructor[not set]{10u}
ScalarConstructor[not set]{20u}
}
}
}
}
VariableDeclStatement{
VariableConst{
x_2
none
undefined
__vec_2__i32
{
TypeConstructor[not set]{
__vec_2__i32
ScalarConstructor[not set]{30}
ScalarConstructor[not set]{40}
}
}
}
}
VariableDeclStatement{
VariableConst{
x_3
none
undefined
__vec_2__f32
{
TypeConstructor[not set]{
__vec_2__f32
ScalarConstructor[not set]{50.000000}
ScalarConstructor[not set]{60.000000}
}
}
}
})"));
}
TEST_F(SpvParserTest_Composite_Construct, Matrix) {
const auto assembly = Preamble() + R"(
%100 = OpFunction %void None %voidfn
%entry = OpLabel
%1 = OpCompositeConstruct %m3v2float %v2float_50_60 %v2float_60_50 %v2float_70_70
OpReturn
OpFunctionEnd
)";
auto p = parser(test::Assemble(assembly));
ASSERT_TRUE(p->BuildAndParseInternalModuleExceptFunctions()) << assembly;
auto fe = p->function_emitter(100);
EXPECT_TRUE(fe.EmitBody()) << p->error();
EXPECT_THAT(ToString(p->builder(), fe.ast_body()), HasSubstr(R"(
VariableConst{
x_1
none
undefined
__mat_2_3__f32
{
TypeConstructor[not set]{
__mat_2_3__f32
TypeConstructor[not set]{
__vec_2__f32
ScalarConstructor[not set]{50.000000}
ScalarConstructor[not set]{60.000000}
}
TypeConstructor[not set]{
__vec_2__f32
ScalarConstructor[not set]{60.000000}
ScalarConstructor[not set]{50.000000}
}
TypeConstructor[not set]{
__vec_2__f32
ScalarConstructor[not set]{70.000000}
ScalarConstructor[not set]{70.000000}
}
}
}
})"));
}
TEST_F(SpvParserTest_Composite_Construct, Array) {
const auto assembly = Preamble() + R"(
%100 = OpFunction %void None %voidfn
%entry = OpLabel
%1 = OpCompositeConstruct %a_u_5 %uint_10 %uint_20 %uint_3 %uint_4 %uint_5
OpReturn
OpFunctionEnd
)";
auto p = parser(test::Assemble(assembly));
ASSERT_TRUE(p->BuildAndParseInternalModuleExceptFunctions()) << assembly;
auto fe = p->function_emitter(100);
EXPECT_TRUE(fe.EmitBody()) << p->error();
EXPECT_THAT(ToString(p->builder(), fe.ast_body()), HasSubstr(R"(
VariableConst{
x_1
none
undefined
__array__u32_5
{
TypeConstructor[not set]{
__array__u32_5
ScalarConstructor[not set]{10u}
ScalarConstructor[not set]{20u}
ScalarConstructor[not set]{3u}
ScalarConstructor[not set]{4u}
ScalarConstructor[not set]{5u}
}
}
})"));
}
TEST_F(SpvParserTest_Composite_Construct, Struct) {
const auto assembly = Preamble() + R"(
%100 = OpFunction %void None %voidfn
%entry = OpLabel
%1 = OpCompositeConstruct %s_v2f_u_i %v2float_50_60 %uint_5 %int_30
OpReturn
OpFunctionEnd
)";
auto p = parser(test::Assemble(assembly));
ASSERT_TRUE(p->BuildAndParseInternalModuleExceptFunctions()) << assembly;
auto fe = p->function_emitter(100);
EXPECT_TRUE(fe.EmitBody()) << p->error();
EXPECT_THAT(ToString(p->builder(), fe.ast_body()), HasSubstr(R"(
VariableConst{
x_1
none
undefined
__type_name_S
{
TypeConstructor[not set]{
__type_name_S
TypeConstructor[not set]{
__vec_2__f32
ScalarConstructor[not set]{50.000000}
ScalarConstructor[not set]{60.000000}
}
ScalarConstructor[not set]{5u}
ScalarConstructor[not set]{30}
}
}
})"));
}
using SpvParserTest_CompositeExtract = SpvParserTest;
TEST_F(SpvParserTest_CompositeExtract, Vector) {
const auto assembly = Preamble() + R"(
%100 = OpFunction %void None %voidfn
%entry = OpLabel
%1 = OpCompositeExtract %float %v2float_50_60 1
OpReturn
OpFunctionEnd
)";
auto p = parser(test::Assemble(assembly));
ASSERT_TRUE(p->BuildAndParseInternalModuleExceptFunctions()) << assembly;
auto fe = p->function_emitter(100);
EXPECT_TRUE(fe.EmitBody()) << p->error();
EXPECT_THAT(ToString(p->builder(), fe.ast_body()), HasSubstr(R"(
VariableConst{
x_1
none
undefined
__f32
{
MemberAccessor[not set]{
TypeConstructor[not set]{
__vec_2__f32
ScalarConstructor[not set]{50.000000}
ScalarConstructor[not set]{60.000000}
}
Identifier[not set]{y}
}
}
})"));
}
TEST_F(SpvParserTest_CompositeExtract, Vector_IndexTooBigError) {
const auto assembly = Preamble() + R"(
%100 = OpFunction %void None %voidfn
%entry = OpLabel
%1 = OpCompositeExtract %float %v2float_50_60 900
OpReturn
OpFunctionEnd
)";
auto p = parser(test::Assemble(assembly));
ASSERT_TRUE(p->BuildAndParseInternalModuleExceptFunctions()) << assembly;
auto fe = p->function_emitter(100);
EXPECT_FALSE(fe.EmitBody());
EXPECT_THAT(p->error(), Eq("OpCompositeExtract %1 index value 900 is out of "
"bounds for vector of 2 elements"));
}
TEST_F(SpvParserTest_CompositeExtract, Matrix) {
const auto assembly = Preamble() + R"(
%ptr = OpTypePointer Function %m3v2float
%100 = OpFunction %void None %voidfn
%entry = OpLabel
%var = OpVariable %ptr Function
%1 = OpLoad %m3v2float %var
%2 = OpCompositeExtract %v2float %1 2
OpReturn
OpFunctionEnd
)";
auto p = parser(test::Assemble(assembly));
ASSERT_TRUE(p->BuildAndParseInternalModuleExceptFunctions()) << assembly;
auto fe = p->function_emitter(100);
EXPECT_TRUE(fe.EmitBody()) << p->error();
EXPECT_THAT(ToString(p->builder(), fe.ast_body()), HasSubstr(R"(
VariableConst{
x_2
none
undefined
__vec_2__f32
{
ArrayAccessor[not set]{
Identifier[not set]{x_1}
ScalarConstructor[not set]{2u}
}
}
})"));
}
TEST_F(SpvParserTest_CompositeExtract, Matrix_IndexTooBigError) {
const auto assembly = Preamble() + R"(
%ptr = OpTypePointer Function %m3v2float
%100 = OpFunction %void None %voidfn
%entry = OpLabel
%var = OpVariable %ptr Function
%1 = OpLoad %m3v2float %var
%2 = OpCompositeExtract %v2float %1 3
OpReturn
OpFunctionEnd
)";
auto p = parser(test::Assemble(assembly));
ASSERT_TRUE(p->BuildAndParseInternalModuleExceptFunctions()) << assembly;
auto fe = p->function_emitter(100);
EXPECT_FALSE(fe.EmitBody()) << p->error();
EXPECT_THAT(p->error(), Eq("OpCompositeExtract %2 index value 3 is out of "
"bounds for matrix of 3 elements"));
}
TEST_F(SpvParserTest_CompositeExtract, Matrix_Vector) {
const auto assembly = Preamble() + R"(
%ptr = OpTypePointer Function %m3v2float
%100 = OpFunction %void None %voidfn
%entry = OpLabel
%var = OpVariable %ptr Function
%1 = OpLoad %m3v2float %var
%2 = OpCompositeExtract %float %1 2 1
OpReturn
OpFunctionEnd
)";
auto p = parser(test::Assemble(assembly));
ASSERT_TRUE(p->BuildAndParseInternalModuleExceptFunctions()) << assembly;
auto fe = p->function_emitter(100);
EXPECT_TRUE(fe.EmitBody()) << p->error();
EXPECT_THAT(ToString(p->builder(), fe.ast_body()), HasSubstr(R"(
VariableConst{
x_2
none
undefined
__f32
{
MemberAccessor[not set]{
ArrayAccessor[not set]{
Identifier[not set]{x_1}
ScalarConstructor[not set]{2u}
}
Identifier[not set]{y}
}
}
})"));
}
TEST_F(SpvParserTest_CompositeExtract, Array) {
const auto assembly = Preamble() + R"(
%ptr = OpTypePointer Function %a_u_5
%100 = OpFunction %void None %voidfn
%entry = OpLabel
%var = OpVariable %ptr Function
%1 = OpLoad %a_u_5 %var
%2 = OpCompositeExtract %uint %1 3
OpReturn
OpFunctionEnd
)";
auto p = parser(test::Assemble(assembly));
ASSERT_TRUE(p->BuildAndParseInternalModuleExceptFunctions()) << assembly;
auto fe = p->function_emitter(100);
EXPECT_TRUE(fe.EmitBody()) << p->error();
EXPECT_THAT(ToString(p->builder(), fe.ast_body()), HasSubstr(R"(
VariableConst{
x_2
none
undefined
__u32
{
ArrayAccessor[not set]{
Identifier[not set]{x_1}
ScalarConstructor[not set]{3u}
}
}
})"));
}
TEST_F(SpvParserTest_CompositeExtract, RuntimeArray_IsError) {
const auto assembly = Preamble() + R"(
%rtarr = OpTypeRuntimeArray %uint
%ptr = OpTypePointer Function %rtarr
%100 = OpFunction %void None %voidfn
%entry = OpLabel
%var = OpVariable %ptr Function
%1 = OpLoad %rtarr %var
%2 = OpCompositeExtract %uint %1 3
OpReturn
OpFunctionEnd
)";
auto p = parser(test::Assemble(assembly));
ASSERT_TRUE(p->BuildAndParseInternalModuleExceptFunctions()) << assembly;
auto fe = p->function_emitter(100);
EXPECT_FALSE(fe.EmitBody()) << p->error();
EXPECT_THAT(p->error(),
HasSubstr("can't do OpCompositeExtract on a runtime array: "));
}
TEST_F(SpvParserTest_CompositeExtract, Struct) {
const auto assembly = Preamble() + R"(
%ptr = OpTypePointer Function %s_v2f_u_i
%100 = OpFunction %void None %voidfn
%entry = OpLabel
%var = OpVariable %ptr Function
%1 = OpLoad %s_v2f_u_i %var
%2 = OpCompositeExtract %int %1 2
OpReturn
OpFunctionEnd
)";
auto p = parser(test::Assemble(assembly));
ASSERT_TRUE(p->BuildAndParseInternalModuleExceptFunctions()) << assembly;
auto fe = p->function_emitter(100);
EXPECT_TRUE(fe.EmitBody()) << p->error();
EXPECT_THAT(ToString(p->builder(), fe.ast_body()), HasSubstr(R"(
VariableConst{
x_2
none
undefined
__i32
{
MemberAccessor[not set]{
Identifier[not set]{x_1}
Identifier[not set]{field2}
}
}
})"));
}
TEST_F(SpvParserTest_CompositeExtract, Struct_DifferOnlyInMemberName) {
const std::string assembly = R"(
OpCapability Shader
OpMemoryModel Logical Simple
OpEntryPoint Fragment %100 "main"
OpExecutionMode %100 OriginUpperLeft
OpMemberName %s0 0 "algo"
OpMemberName %s1 0 "rithm"
%void = OpTypeVoid
%voidfn = OpTypeFunction %void
%uint = OpTypeInt 32 0
%s0 = OpTypeStruct %uint
%s1 = OpTypeStruct %uint
%ptr0 = OpTypePointer Function %s0
%ptr1 = OpTypePointer Function %s1
%100 = OpFunction %void None %voidfn
%entry = OpLabel
%var0 = OpVariable %ptr0 Function
%var1 = OpVariable %ptr1 Function
%1 = OpLoad %s0 %var0
%2 = OpCompositeExtract %uint %1 0
%3 = OpLoad %s1 %var1
%4 = OpCompositeExtract %uint %3 0
OpReturn
OpFunctionEnd
)";
auto p = parser(test::Assemble(assembly));
ASSERT_TRUE(p->BuildAndParseInternalModuleExceptFunctions()) << assembly;
auto fe = p->function_emitter(100);
EXPECT_TRUE(fe.EmitBody()) << p->error();
auto got = fe.ast_body();
EXPECT_THAT(ToString(p->builder(), got), HasSubstr(R"(
VariableConst{
x_2
none
undefined
__u32
{
MemberAccessor[not set]{
Identifier[not set]{x_1}
Identifier[not set]{algo}
}
}
})"))
<< ToString(p->builder(), got);
EXPECT_THAT(ToString(p->builder(), got), HasSubstr(R"(
VariableConst{
x_4
none
undefined
__u32
{
MemberAccessor[not set]{
Identifier[not set]{x_3}
Identifier[not set]{rithm}
}
}
})"))
<< ToString(p->builder(), got);
p->SkipDumpingPending("crbug.com/tint/863");
}
TEST_F(SpvParserTest_CompositeExtract, Struct_IndexTooBigError) {
const auto assembly = Preamble() + R"(
%ptr = OpTypePointer Function %s_v2f_u_i
%100 = OpFunction %void None %voidfn
%entry = OpLabel
%var = OpVariable %ptr Function
%1 = OpLoad %s_v2f_u_i %var
%2 = OpCompositeExtract %int %1 40
OpReturn
OpFunctionEnd
)";
auto p = parser(test::Assemble(assembly));
ASSERT_TRUE(p->BuildAndParseInternalModuleExceptFunctions()) << assembly;
auto fe = p->function_emitter(100);
EXPECT_FALSE(fe.EmitBody());
EXPECT_THAT(p->error(), Eq("OpCompositeExtract %2 index value 40 is out of "
"bounds for structure %26 having 3 members"));
}
TEST_F(SpvParserTest_CompositeExtract, Struct_Array_Matrix_Vector) {
const auto assembly = Preamble() + R"(
%a_mat = OpTypeArray %m3v2float %uint_3
%s = OpTypeStruct %uint %a_mat
%ptr = OpTypePointer Function %s
%100 = OpFunction %void None %voidfn
%entry = OpLabel
%var = OpVariable %ptr Function
%1 = OpLoad %s %var
%2 = OpCompositeExtract %float %1 1 2 0 1
OpReturn
OpFunctionEnd
)";
auto p = parser(test::Assemble(assembly));
ASSERT_TRUE(p->BuildAndParseInternalModuleExceptFunctions()) << assembly;
auto fe = p->function_emitter(100);
EXPECT_TRUE(fe.EmitBody()) << p->error();
EXPECT_THAT(ToString(p->builder(), fe.ast_body()), HasSubstr(R"(
VariableConst{
x_2
none
undefined
__f32
{
MemberAccessor[not set]{
ArrayAccessor[not set]{
ArrayAccessor[not set]{
MemberAccessor[not set]{
Identifier[not set]{x_1}
Identifier[not set]{field1}
}
ScalarConstructor[not set]{2u}
}
ScalarConstructor[not set]{0u}
}
Identifier[not set]{y}
}
}
})"));
}
using SpvParserTest_CompositeInsert = SpvParserTest;
TEST_F(SpvParserTest_CompositeInsert, Vector) {
const auto assembly = Preamble() + R"(
%100 = OpFunction %void None %voidfn
%entry = OpLabel
%1 = OpCompositeInsert %v2float %float_70 %v2float_50_60 1
OpReturn
OpFunctionEnd
)";
auto p = parser(test::Assemble(assembly));
ASSERT_TRUE(p->BuildAndParseInternalModuleExceptFunctions()) << assembly;
auto fe = p->function_emitter(100);
EXPECT_TRUE(fe.EmitBody()) << p->error();
auto got = ToString(p->builder(), fe.ast_body());
const auto* expected =
R"(VariableDeclStatement{
Variable{
x_1_1
none
undefined
__vec_2__f32
{
TypeConstructor[not set]{
__vec_2__f32
ScalarConstructor[not set]{50.000000}
ScalarConstructor[not set]{60.000000}
}
}
}
}
Assignment{
MemberAccessor[not set]{
Identifier[not set]{x_1_1}
Identifier[not set]{y}
}
ScalarConstructor[not set]{70.000000}
}
VariableDeclStatement{
VariableConst{
x_1
none
undefined
__vec_2__f32
{
Identifier[not set]{x_1_1}
}
}
}
Return{}
)";
EXPECT_EQ(got, expected);
}
TEST_F(SpvParserTest_CompositeInsert, Vector_IndexTooBigError) {
const auto assembly = Preamble() + R"(
%100 = OpFunction %void None %voidfn
%entry = OpLabel
%1 = OpCompositeInsert %v2float %float_70 %v2float_50_60 900
OpReturn
OpFunctionEnd
)";
auto p = parser(test::Assemble(assembly));
ASSERT_TRUE(p->BuildAndParseInternalModuleExceptFunctions()) << assembly;
auto fe = p->function_emitter(100);
EXPECT_FALSE(fe.EmitBody());
EXPECT_THAT(p->error(), Eq("OpCompositeInsert %1 index value 900 is out of "
"bounds for vector of 2 elements"));
}
TEST_F(SpvParserTest_CompositeInsert, Matrix) {
const auto assembly = Preamble() + R"(
%ptr = OpTypePointer Function %m3v2float
%100 = OpFunction %void None %voidfn
%entry = OpLabel
%var = OpVariable %ptr Function
%1 = OpLoad %m3v2float %var
%2 = OpCompositeInsert %m3v2float %v2float_50_60 %1 2
OpReturn
OpFunctionEnd
)";
auto p = parser(test::Assemble(assembly));
ASSERT_TRUE(p->BuildAndParseInternalModuleExceptFunctions()) << assembly;
auto fe = p->function_emitter(100);
EXPECT_TRUE(fe.EmitBody()) << p->error();
auto body_str = ToString(p->builder(), fe.ast_body());
EXPECT_THAT(body_str, HasSubstr(R"(VariableDeclStatement{
Variable{
x_2_1
none
undefined
__mat_2_3__f32
{
Identifier[not set]{x_1}
}
}
}
Assignment{
ArrayAccessor[not set]{
Identifier[not set]{x_2_1}
ScalarConstructor[not set]{2u}
}
TypeConstructor[not set]{
__vec_2__f32
ScalarConstructor[not set]{50.000000}
ScalarConstructor[not set]{60.000000}
}
}
VariableDeclStatement{
VariableConst{
x_2
none
undefined
__mat_2_3__f32
{
Identifier[not set]{x_2_1}
}
}
})")) << body_str;
}
TEST_F(SpvParserTest_CompositeInsert, Matrix_IndexTooBigError) {
const auto assembly = Preamble() + R"(
%ptr = OpTypePointer Function %m3v2float
%100 = OpFunction %void None %voidfn
%entry = OpLabel
%var = OpVariable %ptr Function
%1 = OpLoad %m3v2float %var
%2 = OpCompositeInsert %m3v2float %v2float_50_60 %1 3
OpReturn
OpFunctionEnd
)";
auto p = parser(test::Assemble(assembly));
ASSERT_TRUE(p->BuildAndParseInternalModuleExceptFunctions()) << assembly;
auto fe = p->function_emitter(100);
EXPECT_FALSE(fe.EmitBody()) << p->error();
EXPECT_THAT(p->error(), Eq("OpCompositeInsert %2 index value 3 is out of "
"bounds for matrix of 3 elements"));
}
TEST_F(SpvParserTest_CompositeInsert, Matrix_Vector) {
const auto assembly = Preamble() + R"(
%ptr = OpTypePointer Function %m3v2float
%100 = OpFunction %void None %voidfn
%entry = OpLabel
%var = OpVariable %ptr Function
%1 = OpLoad %m3v2float %var
%2 = OpCompositeInsert %m3v2float %v2float_50_60 %1 2
OpReturn
OpFunctionEnd
)";
auto p = parser(test::Assemble(assembly));
ASSERT_TRUE(p->BuildAndParseInternalModuleExceptFunctions()) << assembly;
auto fe = p->function_emitter(100);
EXPECT_TRUE(fe.EmitBody()) << p->error();
auto body_str = ToString(p->builder(), fe.ast_body());
EXPECT_THAT(body_str, HasSubstr(R"(VariableDeclStatement{
Variable{
x_2_1
none
undefined
__mat_2_3__f32
{
Identifier[not set]{x_1}
}
}
}
Assignment{
ArrayAccessor[not set]{
Identifier[not set]{x_2_1}
ScalarConstructor[not set]{2u}
}
TypeConstructor[not set]{
__vec_2__f32
ScalarConstructor[not set]{50.000000}
ScalarConstructor[not set]{60.000000}
}
}
VariableDeclStatement{
VariableConst{
x_2
none
undefined
__mat_2_3__f32
{
Identifier[not set]{x_2_1}
}
}
})")) << body_str;
}
TEST_F(SpvParserTest_CompositeInsert, Array) {
const auto assembly = Preamble() + R"(
%ptr = OpTypePointer Function %a_u_5
%100 = OpFunction %void None %voidfn
%entry = OpLabel
%var = OpVariable %ptr Function
%1 = OpLoad %a_u_5 %var
%2 = OpCompositeInsert %a_u_5 %uint_20 %1 3
OpReturn
OpFunctionEnd
)";
auto p = parser(test::Assemble(assembly));
ASSERT_TRUE(p->BuildAndParseInternalModuleExceptFunctions()) << assembly;
auto fe = p->function_emitter(100);
EXPECT_TRUE(fe.EmitBody()) << p->error();
auto body_str = ToString(p->builder(), fe.ast_body());
EXPECT_THAT(body_str, HasSubstr(R"(VariableDeclStatement{
Variable{
x_2_1
none
undefined
__array__u32_5
{
Identifier[not set]{x_1}
}
}
}
Assignment{
ArrayAccessor[not set]{
Identifier[not set]{x_2_1}
ScalarConstructor[not set]{3u}
}
ScalarConstructor[not set]{20u}
}
VariableDeclStatement{
VariableConst{
x_2
none
undefined
__array__u32_5
{
Identifier[not set]{x_2_1}
}
}
})")) << body_str;
}
TEST_F(SpvParserTest_CompositeInsert, RuntimeArray_IsError) {
const auto assembly = Preamble() + R"(
%rtarr = OpTypeRuntimeArray %uint
%ptr = OpTypePointer Function %rtarr
%100 = OpFunction %void None %voidfn
%entry = OpLabel
%var = OpVariable %ptr Function
%1 = OpLoad %rtarr %var
%2 = OpCompositeInsert %rtarr %uint_20 %1 3
OpReturn
OpFunctionEnd
)";
auto p = parser(test::Assemble(assembly));
ASSERT_TRUE(p->BuildAndParseInternalModuleExceptFunctions()) << assembly;
auto fe = p->function_emitter(100);
EXPECT_FALSE(fe.EmitBody()) << p->error();
EXPECT_THAT(p->error(),
HasSubstr("can't do OpCompositeInsert on a runtime array: "));
}
TEST_F(SpvParserTest_CompositeInsert, Struct) {
const auto assembly = Preamble() + R"(
%ptr = OpTypePointer Function %s_v2f_u_i
%100 = OpFunction %void None %voidfn
%entry = OpLabel
%var = OpVariable %ptr Function
%1 = OpLoad %s_v2f_u_i %var
%2 = OpCompositeInsert %s_v2f_u_i %int_30 %1 2
OpReturn
OpFunctionEnd
)";
auto p = parser(test::Assemble(assembly));
ASSERT_TRUE(p->BuildAndParseInternalModuleExceptFunctions()) << assembly;
auto fe = p->function_emitter(100);
EXPECT_TRUE(fe.EmitBody()) << p->error();
auto body_str = ToString(p->builder(), fe.ast_body());
EXPECT_THAT(body_str, HasSubstr(R"(VariableDeclStatement{
Variable{
x_35
none
undefined
__type_name_S
}
}
VariableDeclStatement{
VariableConst{
x_1
none
undefined
__type_name_S
{
Identifier[not set]{x_35}
}
}
}
VariableDeclStatement{
Variable{
x_2_1
none
undefined
__type_name_S
{
Identifier[not set]{x_1}
}
}
}
Assignment{
MemberAccessor[not set]{
Identifier[not set]{x_2_1}
Identifier[not set]{field2}
}
ScalarConstructor[not set]{30}
}
VariableDeclStatement{
VariableConst{
x_2
none
undefined
__type_name_S
{
Identifier[not set]{x_2_1}
}
}
})")) << body_str;
}
TEST_F(SpvParserTest_CompositeInsert, Struct_DifferOnlyInMemberName) {
const std::string assembly = R"(
OpCapability Shader
OpMemoryModel Logical Simple
OpEntryPoint Fragment %100 "main"
OpExecutionMode %100 OriginUpperLeft
OpName %var0 "var0"
OpName %var1 "var1"
OpMemberName %s0 0 "algo"
OpMemberName %s1 0 "rithm"
%void = OpTypeVoid
%voidfn = OpTypeFunction %void
%uint = OpTypeInt 32 0
%uint_10 = OpConstant %uint 10
%uint_11 = OpConstant %uint 11
%s0 = OpTypeStruct %uint
%s1 = OpTypeStruct %uint
%ptr0 = OpTypePointer Function %s0
%ptr1 = OpTypePointer Function %s1
%100 = OpFunction %void None %voidfn
%entry = OpLabel
%var0 = OpVariable %ptr0 Function
%var1 = OpVariable %ptr1 Function
%1 = OpLoad %s0 %var0
%2 = OpCompositeInsert %s0 %uint_10 %1 0
%3 = OpLoad %s1 %var1
%4 = OpCompositeInsert %s1 %uint_11 %3 0
OpReturn
OpFunctionEnd
)";
auto p = parser(test::Assemble(assembly));
ASSERT_TRUE(p->BuildAndParseInternalModuleExceptFunctions()) << assembly;
auto fe = p->function_emitter(100);
EXPECT_TRUE(fe.EmitBody()) << p->error();
const auto got = ToString(p->builder(), fe.ast_body());
const std::string expected = R"(VariableDeclStatement{
Variable{
var0
none
undefined
__type_name_S
}
}
VariableDeclStatement{
Variable{
var1
none
undefined
__type_name_S_1
}
}
VariableDeclStatement{
VariableConst{
x_1
none
undefined
__type_name_S
{
Identifier[not set]{var0}
}
}
}
VariableDeclStatement{
Variable{
x_2_1
none
undefined
__type_name_S
{
Identifier[not set]{x_1}
}
}
}
Assignment{
MemberAccessor[not set]{
Identifier[not set]{x_2_1}
Identifier[not set]{algo}
}
ScalarConstructor[not set]{10u}
}
VariableDeclStatement{
VariableConst{
x_2
none
undefined
__type_name_S
{
Identifier[not set]{x_2_1}
}
}
}
VariableDeclStatement{
VariableConst{
x_3
none
undefined
__type_name_S_1
{
Identifier[not set]{var1}
}
}
}
VariableDeclStatement{
Variable{
x_4_1
none
undefined
__type_name_S_1
{
Identifier[not set]{x_3}
}
}
}
Assignment{
MemberAccessor[not set]{
Identifier[not set]{x_4_1}
Identifier[not set]{rithm}
}
ScalarConstructor[not set]{11u}
}
VariableDeclStatement{
VariableConst{
x_4
none
undefined
__type_name_S_1
{
Identifier[not set]{x_4_1}
}
}
}
Return{}
)";
EXPECT_EQ(got, expected) << got;
}
TEST_F(SpvParserTest_CompositeInsert, Struct_IndexTooBigError) {
const auto assembly = Preamble() + R"(
%ptr = OpTypePointer Function %s_v2f_u_i
%100 = OpFunction %void None %voidfn
%entry = OpLabel
%var = OpVariable %ptr Function
%1 = OpLoad %s_v2f_u_i %var
%2 = OpCompositeInsert %s_v2f_u_i %uint_10 %1 40
OpReturn
OpFunctionEnd
)";
auto p = parser(test::Assemble(assembly));
ASSERT_TRUE(p->BuildAndParseInternalModuleExceptFunctions()) << assembly;
auto fe = p->function_emitter(100);
EXPECT_FALSE(fe.EmitBody());
EXPECT_THAT(p->error(), Eq("OpCompositeInsert %2 index value 40 is out of "
"bounds for structure %26 having 3 members"));
}
TEST_F(SpvParserTest_CompositeInsert, Struct_Array_Matrix_Vector) {
const auto assembly = Preamble() + R"(
%a_mat = OpTypeArray %m3v2float %uint_3
%s = OpTypeStruct %uint %a_mat
%ptr = OpTypePointer Function %s
%100 = OpFunction %void None %voidfn
%entry = OpLabel
%var = OpVariable %ptr Function
%1 = OpLoad %s %var
%2 = OpCompositeInsert %s %float_70 %1 1 2 0 1
OpReturn
OpFunctionEnd
)";
auto p = parser(test::Assemble(assembly));
ASSERT_TRUE(p->BuildAndParseInternalModuleExceptFunctions()) << assembly;
auto fe = p->function_emitter(100);
EXPECT_TRUE(fe.EmitBody()) << p->error();
auto body_str = ToString(p->builder(), fe.ast_body());
EXPECT_THAT(body_str, HasSubstr(R"(VariableDeclStatement{
Variable{
x_37
none
undefined
__type_name_S_1
}
}
VariableDeclStatement{
VariableConst{
x_1
none
undefined
__type_name_S_1
{
Identifier[not set]{x_37}
}
}
}
VariableDeclStatement{
Variable{
x_2_1
none
undefined
__type_name_S_1
{
Identifier[not set]{x_1}
}
}
}
Assignment{
MemberAccessor[not set]{
ArrayAccessor[not set]{
ArrayAccessor[not set]{
MemberAccessor[not set]{
Identifier[not set]{x_2_1}
Identifier[not set]{field1}
}
ScalarConstructor[not set]{2u}
}
ScalarConstructor[not set]{0u}
}
Identifier[not set]{y}
}
ScalarConstructor[not set]{70.000000}
}
VariableDeclStatement{
VariableConst{
x_2
none
undefined
__type_name_S_1
{
Identifier[not set]{x_2_1}
}
}
})")) << body_str;
}
using SpvParserTest_CopyObject = SpvParserTest;
TEST_F(SpvParserTest_CopyObject, Scalar) {
const auto assembly = Preamble() + R"(
%100 = OpFunction %void None %voidfn
%entry = OpLabel
%1 = OpCopyObject %uint %uint_3
%2 = OpCopyObject %uint %1
OpReturn
OpFunctionEnd
)";
auto p = parser(test::Assemble(assembly));
ASSERT_TRUE(p->BuildAndParseInternalModuleExceptFunctions()) << assembly;
auto fe = p->function_emitter(100);
EXPECT_TRUE(fe.EmitBody()) << p->error();
EXPECT_THAT(ToString(p->builder(), fe.ast_body()),
HasSubstr(R"(VariableDeclStatement{
VariableConst{
x_1
none
undefined
__u32
{
ScalarConstructor[not set]{3u}
}
}
}
VariableDeclStatement{
VariableConst{
x_2
none
undefined
__u32
{
Identifier[not set]{x_1}
}
}
})"));
}
TEST_F(SpvParserTest_CopyObject, Pointer) {
const auto assembly = Preamble() + R"(
%ptr = OpTypePointer Function %uint
%100 = OpFunction %void None %voidfn
%entry = OpLabel
%10 = OpVariable %ptr Function
%1 = OpCopyObject %ptr %10
%2 = OpCopyObject %ptr %1
OpReturn
OpFunctionEnd
)";
auto p = parser(test::Assemble(assembly));
ASSERT_TRUE(p->BuildAndParseInternalModuleExceptFunctions()) << assembly;
auto fe = p->function_emitter(100);
EXPECT_TRUE(fe.EmitBody()) << p->error();
EXPECT_THAT(ToString(p->builder(), fe.ast_body()),
HasSubstr(R"(VariableDeclStatement{
VariableConst{
x_1
none
undefined
__ptr_function__u32
{
UnaryOp[not set]{
address-of
Identifier[not set]{x_10}
}
}
}
}
VariableDeclStatement{
VariableConst{
x_2
none
undefined
__ptr_function__u32
{
Identifier[not set]{x_1}
}
}
})"));
}
using SpvParserTest_VectorShuffle = SpvParserTest;
TEST_F(SpvParserTest_VectorShuffle, FunctionScopeOperands_UseBoth) {
// Note that variables are generated for the vector operands.
const auto assembly = Preamble() + R"(
%100 = OpFunction %void None %voidfn
%entry = OpLabel
%1 = OpCopyObject %v2uint %v2uint_3_4
%2 = OpIAdd %v2uint %v2uint_4_3 %v2uint_3_4
%10 = OpVectorShuffle %v4uint %1 %2 3 2 1 0
OpReturn
OpFunctionEnd
)";
auto p = parser(test::Assemble(assembly));
ASSERT_TRUE(p->BuildAndParseInternalModuleExceptFunctions()) << assembly;
auto fe = p->function_emitter(100);
EXPECT_TRUE(fe.EmitBody()) << p->error();
EXPECT_THAT(ToString(p->builder(), fe.ast_body()), HasSubstr(R"(VariableConst{
x_10
none
undefined
__vec_4__u32
{
TypeConstructor[not set]{
__vec_4__u32
MemberAccessor[not set]{
Identifier[not set]{x_2}
Identifier[not set]{y}
}
MemberAccessor[not set]{
Identifier[not set]{x_2}
Identifier[not set]{x}
}
MemberAccessor[not set]{
Identifier[not set]{x_1}
Identifier[not set]{y}
}
MemberAccessor[not set]{
Identifier[not set]{x_1}
Identifier[not set]{x}
}
}
}
}
})"));
}
TEST_F(SpvParserTest_VectorShuffle, ConstantOperands_UseBoth) {
const auto assembly = Preamble() + R"(
%100 = OpFunction %void None %voidfn
%entry = OpLabel
%10 = OpVectorShuffle %v4uint %v2uint_3_4 %v2uint_4_3 3 2 1 0
OpReturn
OpFunctionEnd
)";
auto p = parser(test::Assemble(assembly));
ASSERT_TRUE(p->BuildAndParseInternalModuleExceptFunctions()) << assembly;
auto fe = p->function_emitter(100);
EXPECT_TRUE(fe.EmitBody()) << p->error();
EXPECT_THAT(ToString(p->builder(), fe.ast_body()), HasSubstr(R"(VariableConst{
x_10
none
undefined
__vec_4__u32
{
TypeConstructor[not set]{
__vec_4__u32
MemberAccessor[not set]{
TypeConstructor[not set]{
__vec_2__u32
ScalarConstructor[not set]{4u}
ScalarConstructor[not set]{3u}
}
Identifier[not set]{y}
}
MemberAccessor[not set]{
TypeConstructor[not set]{
__vec_2__u32
ScalarConstructor[not set]{4u}
ScalarConstructor[not set]{3u}
}
Identifier[not set]{x}
}
MemberAccessor[not set]{
TypeConstructor[not set]{
__vec_2__u32
ScalarConstructor[not set]{3u}
ScalarConstructor[not set]{4u}
}
Identifier[not set]{y}
}
MemberAccessor[not set]{
TypeConstructor[not set]{
__vec_2__u32
ScalarConstructor[not set]{3u}
ScalarConstructor[not set]{4u}
}
Identifier[not set]{x}
}
}
}
})"));
}
TEST_F(SpvParserTest_VectorShuffle, ConstantOperands_AllOnesMapToNull) {
const auto assembly = Preamble() + R"(
%100 = OpFunction %void None %voidfn
%entry = OpLabel
%1 = OpCopyObject %v2uint %v2uint_4_3
%10 = OpVectorShuffle %v2uint %1 %1 0xFFFFFFFF 1
OpReturn
OpFunctionEnd
)";
auto p = parser(test::Assemble(assembly));
ASSERT_TRUE(p->BuildAndParseInternalModuleExceptFunctions()) << assembly;
auto fe = p->function_emitter(100);
EXPECT_TRUE(fe.EmitBody()) << p->error();
EXPECT_THAT(ToString(p->builder(), fe.ast_body()), HasSubstr(R"(VariableConst{
x_10
none
undefined
__vec_2__u32
{
TypeConstructor[not set]{
__vec_2__u32
ScalarConstructor[not set]{0u}
MemberAccessor[not set]{
Identifier[not set]{x_1}
Identifier[not set]{y}
}
}
}
})"));
}
TEST_F(SpvParserTest_VectorShuffle, IndexTooBig_IsError) {
const auto assembly = Preamble() + R"(
%100 = OpFunction %void None %voidfn
%entry = OpLabel
%10 = OpVectorShuffle %v4uint %v2uint_3_4 %v2uint_4_3 9 2 1 0
OpReturn
OpFunctionEnd
)";
auto p = parser(test::Assemble(assembly));
ASSERT_TRUE(p->BuildAndParseInternalModuleExceptFunctions()) << assembly;
auto fe = p->function_emitter(100);
EXPECT_FALSE(fe.EmitBody()) << p->error();
EXPECT_THAT(p->error(),
Eq("invalid vectorshuffle ID %10: index too large: 9"));
}
using SpvParserTest_VectorExtractDynamic = SpvParserTest;
TEST_F(SpvParserTest_VectorExtractDynamic, SignedIndex) {
const auto assembly = Preamble() + R"(
%100 = OpFunction %void None %voidfn
%entry = OpLabel
%1 = OpCopyObject %v2uint %v2uint_3_4
%2 = OpCopyObject %int %int_1
%10 = OpVectorExtractDynamic %uint %1 %2
OpReturn
OpFunctionEnd
)";
auto p = parser(test::Assemble(assembly));
ASSERT_TRUE(p->BuildAndParseInternalModuleExceptFunctions()) << assembly;
auto fe = p->function_emitter(100);
EXPECT_TRUE(fe.EmitBody()) << p->error();
const auto got = ToString(p->builder(), fe.ast_body());
EXPECT_THAT(got, HasSubstr(R"(VariableConst{
x_10
none
undefined
__u32
{
ArrayAccessor[not set]{
Identifier[not set]{x_1}
Identifier[not set]{x_2}
}
}
}
})")) << got;
}
TEST_F(SpvParserTest_VectorExtractDynamic, UnsignedIndex) {
const auto assembly = Preamble() + R"(
%100 = OpFunction %void None %voidfn
%entry = OpLabel
%1 = OpCopyObject %v2uint %v2uint_3_4
%2 = OpCopyObject %uint %uint_3
%10 = OpVectorExtractDynamic %uint %1 %2
OpReturn
OpFunctionEnd
)";
auto p = parser(test::Assemble(assembly));
ASSERT_TRUE(p->BuildAndParseInternalModuleExceptFunctions()) << assembly;
auto fe = p->function_emitter(100);
EXPECT_TRUE(fe.EmitBody()) << p->error();
const auto got = ToString(p->builder(), fe.ast_body());
EXPECT_THAT(got, HasSubstr(R"(VariableConst{
x_10
none
undefined
__u32
{
ArrayAccessor[not set]{
Identifier[not set]{x_1}
Identifier[not set]{x_2}
}
}
}
})")) << got;
}
using SpvParserTest_VectorInsertDynamic = SpvParserTest;
TEST_F(SpvParserTest_VectorInsertDynamic, Sample) {
const auto assembly = Preamble() + R"(
%100 = OpFunction %void None %voidfn
%entry = OpLabel
%1 = OpCopyObject %v2uint %v2uint_3_4
%2 = OpCopyObject %uint %uint_3
%3 = OpCopyObject %int %int_1
%10 = OpVectorInsertDynamic %v2uint %1 %2 %3
OpReturn
OpFunctionEnd
)";
auto p = parser(test::Assemble(assembly));
ASSERT_TRUE(p->BuildAndParseInternalModuleExceptFunctions()) << assembly;
auto fe = p->function_emitter(100);
EXPECT_TRUE(fe.EmitBody()) << p->error();
const auto got = ToString(p->builder(), fe.ast_body());
EXPECT_THAT(got, HasSubstr(R"(
VariableDeclStatement{
Variable{
x_10_1
none
undefined
__vec_2__u32
{
Identifier[not set]{x_1}
}
}
}
Assignment{
ArrayAccessor[not set]{
Identifier[not set]{x_10_1}
Identifier[not set]{x_3}
}
Identifier[not set]{x_2}
}
VariableDeclStatement{
VariableConst{
x_10
none
undefined
__vec_2__u32
{
Identifier[not set]{x_10_1}
}
}
})")) << got
<< assembly;
}
TEST_F(SpvParserTest, DISABLED_WorkgroupSize_Overridable) {
// TODO(dneto): Support specializable workgroup size. crbug.com/tint/504
const auto* assembly = R"(
OpCapability Shader
OpMemoryModel Logical Simple
OpEntryPoint GLCompute %100 "main"
OpDecorate %1 BuiltIn WorkgroupSize
OpDecorate %uint_2 SpecId 0
OpDecorate %uint_4 SpecId 1
OpDecorate %uint_8 SpecId 2
%uint = OpTypeInt 32 0
%uint_2 = OpSpecConstant %uint 2
%uint_4 = OpSpecConstant %uint 4
%uint_8 = OpSpecConstant %uint 8
%v3uint = OpTypeVector %uint 3
%1 = OpSpecConstantComposite %v3uint %uint_2 %uint_4 %uint_8
%void = OpTypeVoid
%voidfn = OpTypeFunction %void
%100 = OpFunction %void None %voidfn
%entry = OpLabel
%10 = OpCopyObject %v3uint %1
%11 = OpCopyObject %uint %uint_2
%12 = OpCopyObject %uint %uint_4
%13 = OpCopyObject %uint %uint_8
OpReturn
OpFunctionEnd
)";
auto p = parser(test::Assemble(assembly));
ASSERT_TRUE(p->BuildAndParseInternalModuleExceptFunctions()) << assembly;
auto fe = p->function_emitter(100);
EXPECT_TRUE(fe.Emit()) << p->error();
const auto got = p->program().to_str();
EXPECT_THAT(got, HasSubstr(R"(
VariableConst{
Decorations{
OverrideDecoration{0}
}
x_2
none
__u32
{
ScalarConstructor[not set]{2}
}
}
VariableConst{
Decorations{
OverrideDecoration{1}
}
x_3
none
__u32
{
ScalarConstructor[not set]{4}
}
}
VariableConst{
Decorations{
OverrideDecoration{2}
}
x_4
none
__u32
{
ScalarConstructor[not set]{8}
}
}
)")) << got;
EXPECT_THAT(got, HasSubstr(R"(
VariableDeclStatement{
VariableConst{
x_10
none
__vec_3__u32
{
TypeConstructor[not set]{
__vec_3__u32
ScalarConstructor[not set]{2}
ScalarConstructor[not set]{4}
ScalarConstructor[not set]{8}
}
}
}
}
VariableDeclStatement{
VariableConst{
x_11
none
__u32
{
Identifier[not set]{x_2}
}
}
}
VariableDeclStatement{
VariableConst{
x_12
none
__u32
{
Identifier[not set]{x_3}
}
}
}
VariableDeclStatement{
VariableConst{
x_13
none
__u32
{
Identifier[not set]{x_4}
}
}
})"))
<< got << assembly;
}
} // namespace
} // namespace spirv
} // namespace reader
} // namespace tint
| 27,167
|
https://github.com/pyricau/BuilderGen/blob/master/buildergen/src/test/java/info/piwai/buildergen/validation/IsValidTest.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,018
|
BuilderGen
|
pyricau
|
Java
|
Code
| 54
| 203
|
package info.piwai.buildergen.validation;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class IsValidTest {
@Test
public void initialStateIsValid() {
IsValid valid = new IsValid();
assertTrue(valid.isValid());
}
@Test
public void invalidateInvalidates() {
IsValid valid = new IsValid();
valid.invalidate();
assertFalse(valid.isValid());
}
@Test
public void doubleInvalidateInvalidates() {
IsValid valid = new IsValid();
valid.invalidate();
valid.invalidate();
assertFalse(valid.isValid());
}
}
| 26,756
|
https://github.com/TeamMentor/TM_Website/blob/master/test/services/Graph-Service.test.coffee
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
TM_Website
|
TeamMentor
|
CoffeeScript
|
Code
| 388
| 1,793
|
require('fluentnode')
fs = require('fs' )
http = require('http' )
expect = require('chai' ).expect
spawn = require('child_process').spawn
Graph_Service = require('./../../src/services/Graph-Service')
Server = http.Server
describe '| services | Graph-Service.test |', ->
test_Port = null
test_Ip = '127.0.0.1'
test_Data = 'mocked server'
test_Server = null
server = null
graphService = null
before (done)->
test_Port = 45566 + Math.floor((Math.random() * 1000) + 1)
test_Server = "http://#{test_Ip}:#{test_Port}"
test_Server.assert_Contains(test_Ip).assert_Contains(test_Port)
server = http.createServer(null)
server.listen_OnPort_Saying test_Port, test_Data, ()=>
graphService = new Graph_Service( { server: test_Server})
done()
after (done)->
server.close_And_Destroy_Sockets ()->
done()
it 'article_Html (bad id)', (done)->
graphService.article_Html null, (data)=>
data.assert_Is ''
done()
it 'article_Html (good id)', (done)->
server.respond_With_Request_Url()
article_Id = 'abc_'.add_5_Letters()
graphService.article_Html article_Id, (data)=>
data.url.assert_Is "/data/article_Html/#{article_Id}"
done()
it 'article', (done)->
server.respond_With_Request_Url()
ref = 'abc_'.add_5_Letters()
graphService.article ref, (data)=>
data.url.assert_Is "/data/article/#{ref}"
done()
it 'articles', (done)->
graphService.articles (data)=>
data.assert_Is { url: '/data/articles/' }
done()
it 'graphDataFromGraphDB (no queryId and no filters)', (done)->
graphService.graphDataFromGraphDB null, null, (searchData)=>
searchData.assert_Is {}
done()
it 'graphDataFromGraphDB (with queryId and no filters)', (done)->
server.respond_With_Request_Url()
query_Id = 'AAAAAA'.add_5_Letters()
graphService.graphDataFromGraphDB query_Id, null, (data)=>
data.url.assert_Is "/data/query_tree/#{query_Id}"
server.respond_With_String_As_Text(null)
graphService.graphDataFromGraphDB query_Id, null, (data)=>
data.assert_Is {}
done()
it 'graphDataFromGraphDB (with queryId no filters)', (done)->
server.respond_With_Request_Url()
query_Id = 'AAAAAA'.add_5_Letters()
filters = 'AAAAAA'.add_5_Letters()
graphService.graphDataFromGraphDB query_Id, filters, (data)=>
data.url.assert_Is "/data/query_tree_filtered/#{query_Id}/#{filters}"
done()
it 'graphDataFromGraphDB (with queryId no filters)', (done)->
server.respond_With_Request_Url()
query_Id = 'abc_'.add_5_Letters()
filters = 'abc_'.add_5_Letters()
graphService.graphDataFromGraphDB query_Id, filters, (data)=>
data.url.assert_Is "/data/query_tree_filtered/#{query_Id}/#{filters}"
done()
it 'library_Query',(done)->
graphService.library_Query (data)->
data.url.assert_Is '/data/library_Query'
done()
it 'resolve_To_Ids', (done)->
values = 'abc_'.add_5_Letters()
graphService.resolve_To_Ids values, (data)=>
data.url.assert_Is "/convert/to_ids/#{values}"
done()
it 'root_Queries', (done)->
graphService.root_Queries (data)=>
data.url.assert_Is "/data/query_tree/Root-Queries"
done()
it 'query_From_Text_Search (bad text)', (done)->
graphService.query_From_Text_Search null, (data)=>
assert_Is_Null data
done()
it 'query_From_Text_Search (to_ids returns a valid mapping with "query-")', (done)->
mappings = {'aaa': id :'query-'.add_5_Letters()}
server.respond_With_Object_As_Json mappings
text = 'abc_'.add_5_Letters()
graphService.query_From_Text_Search text, (data)=>
data.assert_Is mappings.aaa.id
done()
it 'query_From_Text_Search (to_ids returns a string)', (done)->
server.respond_With_Request_Url()
text = 'abc_'.add_5_Letters()
graphService.query_From_Text_Search text, (data)=>
data.json_Parse().url.assert_Is "/search/query_from_text_search/#{text}"
done()
it 'node_Data (bad id)', (done)->
graphService.node_Data null, (data)=>
data.assert_Is ''
done()
it 'node_Data (good id)', (done)->
server.respond_With_Request_Url()
article_Id = 'abc_'.add_5_Letters()
graphService.node_Data article_Id, (data)=>
data.assert_Is "/data/id/#{article_Id}"
done()
it 'node_Data (good id, bad response)', (done)->
server.respond_With_String_As_Text 'aaaa'
article_Id = 'abc_'.add_5_Letters()
graphService.node_Data article_Id, (data)=>
data.assert_Is {}
done()
it 'server_Online (on live server)', (done)->
using graphService,->
@.server.assert_Is test_Server
@.server_Online (online)->
online.assert_True()
done()
it 'server_Online (on not live server)', (done)->
using new Graph_Service({ server: 'http://aaaa.bbbb.ccc.ddd'}),->
@.server_Online (online)->
online.assert_False()
done()
it 'Issue 595 - Bug in GraphDB Service resolve_To_Ids method', (done)->
graphService.resolve_To_Ids undefined, (data)=>
data.assert_Is {}
done()
| 45,844
|
https://github.com/flatomoya/TVTComment/blob/master/TVTComment/ViewModels/ChatCollectServiceCreationOptionControl/TwitterLiveChatCollectServiceCreationOptionControlViewModel.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
TVTComment
|
flatomoya
|
C#
|
Code
| 103
| 364
|
using Prism.Commands;
using System;
using System.Windows.Input;
using TVTComment.Model.ChatCollectServiceEntry;
using static TVTComment.Model.ChatCollectServiceEntry.TwitterLiveChatCollectServiceEntry.ChatCollectServiceCreationOption;
namespace TVTComment.ViewModels.ChatCollectServiceCreationOptionControl
{
class TwitterLiveChatCollectServiceCreationOptionControlViewModel : ChatCollectServiceCreationOptionControlViewModel
{
private string searchWord;
public string SearchWord
{
get { return searchWord; }
set { SetProperty(ref searchWord, value); }
}
public ICommand OkCommand { get; }
private ModeSelectMethod method;
public ModeSelectMethod Method
{
get { return method; }
set { SetProperty(ref method, value); }
}
public override event EventHandler Finished;
public TwitterLiveChatCollectServiceCreationOptionControlViewModel()
{
OkCommand = new DelegateCommand(() => Finished(this, new EventArgs()));
Method = ModeSelectMethod.Auto;
}
public override IChatCollectServiceCreationOption GetChatCollectServiceCreationOption()
{
if (string.IsNullOrWhiteSpace(searchWord) && ModeSelectMethod.Manual == Method)
return null;
return new TwitterLiveChatCollectServiceEntry.ChatCollectServiceCreationOption(Method, searchWord);
}
}
}
| 37,976
|
https://github.com/SeraphinEveles/SotnRandoTools/blob/master/SotnRandoTools/src/Khaos/Models/EventAddAction.cs
|
Github Open Source
|
Open Source
|
MIT
| null |
SotnRandoTools
|
SeraphinEveles
|
C#
|
Code
| 23
| 57
|
namespace SotnRandoTools.Khaos.Models
{
public class EventAddAction
{
public string Command { get; set; }
public string UserName { get; set; }
}
}
| 16,334
|
https://github.com/SpaceWalkerRS/redstone-tweaks/blob/master/src/main/java/redstonetweaks/world/client/NeighborUpdateVisualizer.java
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
redstone-tweaks
|
SpaceWalkerRS
|
Java
|
Code
| 2,553
| 9,019
|
package redstonetweaks.world.client;
import org.lwjgl.opengl.GL11;
import com.mojang.blaze3d.systems.RenderSystem;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.render.BufferBuilder;
import net.minecraft.client.render.Camera;
import net.minecraft.client.render.Tessellator;
import net.minecraft.client.render.VertexFormats;
import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Matrix4f;
import net.minecraft.util.math.Vec3d;
import redstonetweaks.world.common.UpdateType;
public class NeighborUpdateVisualizer {
private static final float BLOCK_UPDATE_RED = 1.0F;
private static final float BLOCK_UPDATE_GREEN = 0.9F;
private static final float BLOCK_UPDATE_BLUE = 0.4F;
private static final float BLOCK_UPDATE_ALPHA = 0.4F;
private static final float COMPARATOR_UPDATE_RED = 1.0F;
private static final float COMPARATOR_UPDATE_GREEN = 0.0F;
private static final float COMPARATOR_UPDATE_BLUE = 0.0F;
private static final float COMPARATOR_UPDATE_ALPHA = 0.4F;
private static final float SHAPE_UPDATE_RED = 0.2F;
private static final float SHAPE_UPDATE_GREEN = 0.3F;
private static final float SHAPE_UPDATE_BLUE = 1.0F;
private static final float SHAPE_UPDATE_ALPHA = 0.4F;
private static final float NOTIFIER_RED = 1.0F;
private static final float NOTIFIER_GREEN = 1.0F;
private static final float NOTIFIER_BLUE = 1.0F;
private static final float NOTIFIER_ALPHA = 0.4F;
private static final float SOURCE_RED = 1.0F;
private static final float SOURCE_GREEN = 1.0F;
private static final float SOURCE_BLUE = 1.0F;
private static final float SOURCE_ALPHA = 0.4F;
private final MinecraftClient client;
private BlockPos pos = null;
private BlockPos notifierPos = null;
private BlockPos sourcePos = null;
private UpdateType updateType = UpdateType.NONE;
public NeighborUpdateVisualizer(MinecraftClient client) {
this.client = client;
}
public void draw(MatrixStack matrices) {
RenderSystem.disableTexture();
RenderSystem.disableDepthTest();
RenderSystem.enableBlend();
RenderSystem.defaultBlendFunc();
RenderSystem.disableCull();
matrices.push();
Camera camera = client.gameRenderer.getCamera();
Vec3d cameraPos = camera.getPos();
matrices.translate(-cameraPos.x, -cameraPos.y, -cameraPos.z);
Tessellator tessellator = Tessellator.getInstance();
BufferBuilder builder = tessellator.getBuffer();
builder.begin(GL11.GL_QUADS, VertexFormats.POSITION_COLOR);
if (sourcePos != null) {
drawFancyBoxOutline(builder, matrices, sourcePos, SOURCE_RED, SOURCE_GREEN, SOURCE_BLUE, SOURCE_ALPHA);
}
tessellator.draw();
RenderSystem.enableCull();
builder.begin(GL11.GL_QUADS, VertexFormats.POSITION_COLOR);
if (notifierPos != null) {
drawBox(builder, matrices, notifierPos, NOTIFIER_RED, NOTIFIER_GREEN, NOTIFIER_BLUE, NOTIFIER_ALPHA);
}
if (pos != null) {
drawBox(builder, matrices, pos, getRed(), getGreen(), getBlue(), getAlpha());
}
tessellator.draw();
matrices.pop();
RenderSystem.disableBlend();
RenderSystem.enableDepthTest();
RenderSystem.enableTexture();
}
private void drawFancyBoxOutline(BufferBuilder builder, MatrixStack matrices, BlockPos pos, float r, float g, float b, float a) {
Matrix4f model = matrices.peek().getModel();
float x0 = pos.getX();
float y0 = pos.getY();
float z0 = pos.getZ();
float x1 = pos.getX() + 1;
float y1 = pos.getY() + 1;
float z1 = pos.getZ() + 1;
float l = 0.3f;
float d = 0.02f;
// Back face
builder.vertex(model, x0, y0, z0).color(r, g, b, a).next();
builder.vertex(model, x0, y0, z0 + l).color(r, g, b, a).next();
builder.vertex(model, x0, y0 + d, z0 + l).color(r, g, b, a).next();
builder.vertex(model, x0, y0 + d, z0).color(r, g, b, a).next();
builder.vertex(model, x0, y0, z1 - l).color(r, g, b, a).next();
builder.vertex(model, x0, y0, z1 - d).color(r, g, b, a).next();
builder.vertex(model, x0, y0 + d, z1 - d).color(r, g, b, a).next();
builder.vertex(model, x0, y0 + d, z1 - l).color(r, g, b, a).next();
builder.vertex(model, x0, y0, z1 - d).color(r, g, b, a).next();
builder.vertex(model, x0, y0, z1).color(r, g, b, a).next();
builder.vertex(model, x0, y0 + l, z1).color(r, g, b, a).next();
builder.vertex(model, x0, y0 + l, z1 - d).color(r, g, b, a).next();
builder.vertex(model, x0, y1 - l, z1 - d).color(r, g, b, a).next();
builder.vertex(model, x0, y1 - l, z1).color(r, g, b, a).next();
builder.vertex(model, x0, y1 - d, z1).color(r, g, b, a).next();
builder.vertex(model, x0, y1 - d, z1 - d).color(r, g, b, a).next();
builder.vertex(model, x0, y1 - d, z1 - l).color(r, g, b, a).next();
builder.vertex(model, x0, y1 - d, z1).color(r, g, b, a).next();
builder.vertex(model, x0, y1, z1).color(r, g, b, a).next();
builder.vertex(model, x0, y1, z1 - l).color(r, g, b, a).next();
builder.vertex(model, x0, y1 - d, z0).color(r, g, b, a).next();
builder.vertex(model, x0, y1 - d, z0 + l).color(r, g, b, a).next();
builder.vertex(model, x0, y1, z0 + l).color(r, g, b, a).next();
builder.vertex(model, x0, y1, z0).color(r, g, b, a).next();
builder.vertex(model, x0, y1 - l, z0).color(r, g, b, a).next();
builder.vertex(model, x0, y1 - l, z0 + d).color(r, g, b, a).next();
builder.vertex(model, x0, y1 - d, z0 + d).color(r, g, b, a).next();
builder.vertex(model, x0, y1 - d, z0).color(r, g, b, a).next();
builder.vertex(model, x0, y0 + d, z0).color(r, g, b, a).next();
builder.vertex(model, x0, y0 + d, z0 + d).color(r, g, b, a).next();
builder.vertex(model, x0, y0 + l, z0 + d).color(r, g, b, a).next();
builder.vertex(model, x0, y0 + l, z0).color(r, g, b, a).next();
// Front face
builder.vertex(model, x1, y0 + d, z0 + d).color(r, g, b, a).next();
builder.vertex(model, x1, y0 + d, z0).color(r, g, b, a).next();
builder.vertex(model, x1, y0 + l, z0).color(r, g, b, a).next();
builder.vertex(model, x1, y0 + l, z0 + d).color(r, g, b, a).next();
builder.vertex(model, x1, y1 - l, z0 + d).color(r, g, b, a).next();
builder.vertex(model, x1, y1 - l, z0).color(r, g, b, a).next();
builder.vertex(model, x1, y1, z0).color(r, g, b, a).next();
builder.vertex(model, x1, y1, z0 + d).color(r, g, b, a).next();
builder.vertex(model, x1, y1 - d, z0 + l).color(r, g, b, a).next();
builder.vertex(model, x1, y1 - d, z0 + d).color(r, g, b, a).next();
builder.vertex(model, x1, y1, z0 + d).color(r, g, b, a).next();
builder.vertex(model, x1, y1, z0 + l).color(r, g, b, a).next();
builder.vertex(model, x1, y1 - d, z1 - d).color(r, g, b, a).next();
builder.vertex(model, x1, y1 - d, z1 - l).color(r, g, b, a).next();
builder.vertex(model, x1, y1, z1 - l).color(r, g, b, a).next();
builder.vertex(model, x1, y1, z1 - d).color(r, g, b, a).next();
builder.vertex(model, x1, y1 - l, z1).color(r, g, b, a).next();
builder.vertex(model, x1, y1 - l, z1 - d).color(r, g, b, a).next();
builder.vertex(model, x1, y1, z1 - d).color(r, g, b, a).next();
builder.vertex(model, x1, y1, z1).color(r, g, b, a).next();
builder.vertex(model, x1, y0 + d, z1).color(r, g, b, a).next();
builder.vertex(model, x1, y0 + d, z1 - d).color(r, g, b, a).next();
builder.vertex(model, x1, y0 + l, z1 - d).color(r, g, b, a).next();
builder.vertex(model, x1, y0 + l, z1).color(r, g, b, a).next();
builder.vertex(model, x1, y0, z1).color(r, g, b, a).next();
builder.vertex(model, x1, y0, z1 - l).color(r, g, b, a).next();
builder.vertex(model, x1, y0 + d, z1 - l).color(r, g, b, a).next();
builder.vertex(model, x1, y0 + d, z1).color(r, g, b, a).next();
builder.vertex(model, x1, y0, z0 + l).color(r, g, b, a).next();
builder.vertex(model, x1, y0, z0).color(r, g, b, a).next();
builder.vertex(model, x1, y0 + d, z0).color(r, g, b, a).next();
builder.vertex(model, x1, y0 + d, z0 + l).color(r, g, b, a).next();
// Right face
builder.vertex(model, x0 + d, y0, z0).color(r, g, b, a).next();
builder.vertex(model, x0, y0, z0).color(r, g, b, a).next();
builder.vertex(model, x0, y0 + l, z0).color(r, g, b, a).next();
builder.vertex(model, x0 + d, y0 + l, z0).color(r, g, b, a).next();
builder.vertex(model, x0 + d, y1 - l, z0).color(r, g, b, a).next();
builder.vertex(model, x0, y1 - l, z0).color(r, g, b, a).next();
builder.vertex(model, x0, y1 - d, z0).color(r, g, b, a).next();
builder.vertex(model, x0 + d, y1 - d, z0).color(r, g, b, a).next();
builder.vertex(model, x0 + l, y1 - d, z0).color(r, g, b, a).next();
builder.vertex(model, x0, y1 - d, z0).color(r, g, b, a).next();
builder.vertex(model, x0, y1, z0).color(r, g, b, a).next();
builder.vertex(model, x0 + l, y1, z0).color(r, g, b, a).next();
builder.vertex(model, x1 - d, y1 - d, z0).color(r, g, b, a).next();
builder.vertex(model, x1 - l, y1 - d, z0).color(r, g, b, a).next();
builder.vertex(model, x1 - l, y1, z0).color(r, g, b, a).next();
builder.vertex(model, x1 - d, y1, z0).color(r, g, b, a).next();
builder.vertex(model, x1, y1 - l, z0).color(r, g, b, a).next();
builder.vertex(model, x1 - d, y1 - l, z0).color(r, g, b, a).next();
builder.vertex(model, x1 - d, y1, z0).color(r, g, b, a).next();
builder.vertex(model, x1, y1, z0).color(r, g, b, a).next();
builder.vertex(model, x1, y0 + d, z0).color(r, g, b, a).next();
builder.vertex(model, x1 - d, y0 + d, z0).color(r, g, b, a).next();
builder.vertex(model, x1 - d, y0 + l, z0).color(r, g, b, a).next();
builder.vertex(model, x1, y0 + l, z0).color(r, g, b, a).next();
builder.vertex(model, x1, y0, z0).color(r, g, b, a).next();
builder.vertex(model, x1 - l, y0, z0).color(r, g, b, a).next();
builder.vertex(model, x1 - l, y0 + d, z0).color(r, g, b, a).next();
builder.vertex(model, x1, y0 + d, z0).color(r, g, b, a).next();
builder.vertex(model, x0 + l, y0, z0).color(r, g, b, a).next();
builder.vertex(model, x0 + d, y0, z0).color(r, g, b, a).next();
builder.vertex(model, x0 + d, y0 + d, z0).color(r, g, b, a).next();
builder.vertex(model, x0 + l, y0 + d, z0).color(r, g, b, a).next();
// Left face
builder.vertex(model, x0, y0, z1).color(r, g, b, a).next();
builder.vertex(model, x0 + l, y0, z1).color(r, g, b, a).next();
builder.vertex(model, x0 + l, y0 + d, z1).color(r, g, b, a).next();
builder.vertex(model, x0, y0 + d, z1).color(r, g, b, a).next();
builder.vertex(model, x1 - l, y0, z1).color(r, g, b, a).next();
builder.vertex(model, x1 - d, y0, z1).color(r, g, b, a).next();
builder.vertex(model, x1 - d, y0 + d, z1).color(r, g, b, a).next();
builder.vertex(model, x1 - l, y0 + d, z1).color(r, g, b, a).next();
builder.vertex(model, x1 - d, y0, z1).color(r, g, b, a).next();
builder.vertex(model, x1, y0, z1).color(r, g, b, a).next();
builder.vertex(model, x1, y0 + l, z1).color(r, g, b, a).next();
builder.vertex(model, x1 - d, y0 + l, z1).color(r, g, b, a).next();
builder.vertex(model, x1 - d, y1 - l, z1).color(r, g, b, a).next();
builder.vertex(model, x1, y1 - l, z1).color(r, g, b, a).next();
builder.vertex(model, x1, y1 - d, z1).color(r, g, b, a).next();
builder.vertex(model, x1 - d, y1 - d, z1).color(r, g, b, a).next();
builder.vertex(model, x1 - l, y1 - d, z1).color(r, g, b, a).next();
builder.vertex(model, x1, y1 - d, z1).color(r, g, b, a).next();
builder.vertex(model, x1, y1, z1).color(r, g, b, a).next();
builder.vertex(model, x1 - l, y1, z1).color(r, g, b, a).next();
builder.vertex(model, x0 + d, y1 - d, z1).color(r, g, b, a).next();
builder.vertex(model, x0 + l, y1 - d, z1).color(r, g, b, a).next();
builder.vertex(model, x0 + l, y1, z1).color(r, g, b, a).next();
builder.vertex(model, x0 + d, y1, z1).color(r, g, b, a).next();
builder.vertex(model, x0, y1 - l, z1).color(r, g, b, a).next();
builder.vertex(model, x0 + d, y1 - l, z1).color(r, g, b, a).next();
builder.vertex(model, x0 + d, y1, z1).color(r, g, b, a).next();
builder.vertex(model, x0, y1, z1).color(r, g, b, a).next();
builder.vertex(model, x0, y0 + d, z1).color(r, g, b, a).next();
builder.vertex(model, x0 + d, y0 + d, z1).color(r, g, b, a).next();
builder.vertex(model, x0 + d, y0 + l, z1).color(r, g, b, a).next();
builder.vertex(model, x0, y0 + l, z1).color(r, g, b, a).next();
// Bottom face
builder.vertex(model, x0, y0, z0).color(r, g, b, a).next();
builder.vertex(model, x0 + l, y0, z0).color(r, g, b, a).next();
builder.vertex(model, x0 + l, y0, z0 + d).color(r, g, b, a).next();
builder.vertex(model, x0, y0, z0 + d).color(r, g, b, a).next();
builder.vertex(model, x1 - l, y0, z0).color(r, g, b, a).next();
builder.vertex(model, x1 - d, y0, z0).color(r, g, b, a).next();
builder.vertex(model, x1 - d, y0, z0 + d).color(r, g, b, a).next();
builder.vertex(model, x1 - l, y0, z0 + d).color(r, g, b, a).next();
builder.vertex(model, x1 - d, y0, z0).color(r, g, b, a).next();
builder.vertex(model, x1, y0, z0).color(r, g, b, a).next();
builder.vertex(model, x1, y0, z0 + l).color(r, g, b, a).next();
builder.vertex(model, x1 - d, y0, z0 + l).color(r, g, b, a).next();
builder.vertex(model, x1 - d, y0, z1 - l).color(r, g, b, a).next();
builder.vertex(model, x1, y0, z1 - l).color(r, g, b, a).next();
builder.vertex(model, x1, y0, z1 - d).color(r, g, b, a).next();
builder.vertex(model, x1 - d, y0, z1 - d).color(r, g, b, a).next();
builder.vertex(model, x1 - l, y0, z1 - d).color(r, g, b, a).next();
builder.vertex(model, x1, y0, z1 - d).color(r, g, b, a).next();
builder.vertex(model, x1, y0, z1).color(r, g, b, a).next();
builder.vertex(model, x1 - l, y0, z1).color(r, g, b, a).next();
builder.vertex(model, x0 + d, y0, z1 - d).color(r, g, b, a).next();
builder.vertex(model, x0 + l, y0, z1 - d).color(r, g, b, a).next();
builder.vertex(model, x0 + l, y0, z1).color(r, g, b, a).next();
builder.vertex(model, x0 + d, y0, z1).color(r, g, b, a).next();
builder.vertex(model, x0, y0, z1 - l).color(r, g, b, a).next();
builder.vertex(model, x0 + d, y0, z1 - l).color(r, g, b, a).next();
builder.vertex(model, x0 + d, y0, z1).color(r, g, b, a).next();
builder.vertex(model, x0, y0, z1).color(r, g, b, a).next();
builder.vertex(model, x0, y0, z0 + d).color(r, g, b, a).next();
builder.vertex(model, x0 + d, y0, z0 + d).color(r, g, b, a).next();
builder.vertex(model, x0 + d, y0, z0 + l).color(r, g, b, a).next();
builder.vertex(model, x0, y0, z0 + l).color(r, g, b, a).next();
// Top face
builder.vertex(model, x0, y1, z0).color(r, g, b, a).next();
builder.vertex(model, x0, y1, z0 + l).color(r, g, b, a).next();
builder.vertex(model, x0 + d, y1, z0 + l).color(r, g, b, a).next();
builder.vertex(model, x0 + d, y1, z0).color(r, g, b, a).next();
builder.vertex(model, x0, y1, z1 - l).color(r, g, b, a).next();
builder.vertex(model, x0, y1, z1 - d).color(r, g, b, a).next();
builder.vertex(model, x0 + d, y1, z1 - d).color(r, g, b, a).next();
builder.vertex(model, x0 + d, y1, z1 - l).color(r, g, b, a).next();
builder.vertex(model, x0, y1, z1 - d).color(r, g, b, a).next();
builder.vertex(model, x0, y1, z1).color(r, g, b, a).next();
builder.vertex(model, x0 + l, y1, z1).color(r, g, b, a).next();
builder.vertex(model, x0 + l, y1, z1 - d).color(r, g, b, a).next();
builder.vertex(model, x1 - l, y1, z1 - d).color(r, g, b, a).next();
builder.vertex(model, x1 - l, y1, z1).color(r, g, b, a).next();
builder.vertex(model, x1 - d, y1, z1).color(r, g, b, a).next();
builder.vertex(model, x1 - d, y1, z1 - d).color(r, g, b, a).next();
builder.vertex(model, x1 - d, y1, z1 - l).color(r, g, b, a).next();
builder.vertex(model, x1 - d, y1, z1).color(r, g, b, a).next();
builder.vertex(model, x1, y1, z1).color(r, g, b, a).next();
builder.vertex(model, x1, y1, z1 - l).color(r, g, b, a).next();
builder.vertex(model, x1 - d, y1, z0 + d).color(r, g, b, a).next();
builder.vertex(model, x1 - d, y1, z0 + l).color(r, g, b, a).next();
builder.vertex(model, x1, y1, z0 + l).color(r, g, b, a).next();
builder.vertex(model, x1, y1, z0 + d).color(r, g, b, a).next();
builder.vertex(model, x1 - l, y1, z0).color(r, g, b, a).next();
builder.vertex(model, x1 - l, y1, z0 + d).color(r, g, b, a).next();
builder.vertex(model, x1, y1, z0 + d).color(r, g, b, a).next();
builder.vertex(model, x1, y1, z0).color(r, g, b, a).next();
builder.vertex(model, x0 + d, y1, z0).color(r, g, b, a).next();
builder.vertex(model, x0 + d, y1, z0 + d).color(r, g, b, a).next();
builder.vertex(model, x0 + l, y1, z0 + d).color(r, g, b, a).next();
builder.vertex(model, x0 + l, y1, z0).color(r, g, b, a).next();
}
private void drawBox(BufferBuilder builder, MatrixStack matrices, BlockPos pos, float r, float g, float b, float a) {
Matrix4f model = matrices.peek().getModel();
float x0 = pos.getX();
float y0 = pos.getY();
float z0 = pos.getZ();
float x1 = pos.getX() + 1;
float y1 = pos.getY() + 1;
float z1 = pos.getZ() + 1;
// Back Face
builder.vertex(model, x0, y0, z0).color(r, g, b, a).next();
builder.vertex(model, x0, y0, z1).color(r, g, b, a).next();
builder.vertex(model, x0, y1, z1).color(r, g, b, a).next();
builder.vertex(model, x0, y1, z0).color(r, g, b, a).next();
// Front Face
builder.vertex(model, x1, y0, z0).color(r, g, b, a).next();
builder.vertex(model, x1, y1, z0).color(r, g, b, a).next();
builder.vertex(model, x1, y1, z1).color(r, g, b, a).next();
builder.vertex(model, x1, y0, z1).color(r, g, b, a).next();
// Right Face
builder.vertex(model, x0, y0, z0).color(r, g, b, a).next();
builder.vertex(model, x0, y1, z0).color(r, g, b, a).next();
builder.vertex(model, x1, y1, z0).color(r, g, b, a).next();
builder.vertex(model, x1, y0, z0).color(r, g, b, a).next();
// Left Face
builder.vertex(model, x0, y0, z1).color(r, g, b, a).next();
builder.vertex(model, x1, y0, z1).color(r, g, b, a).next();
builder.vertex(model, x1, y1, z1).color(r, g, b, a).next();
builder.vertex(model, x0, y1, z1).color(r, g, b, a).next();
// Bottom Face
builder.vertex(model, x0, y0, z0).color(r, g, b, a).next();
builder.vertex(model, x1, y0, z0).color(r, g, b, a).next();
builder.vertex(model, x1, y0, z1).color(r, g, b, a).next();
builder.vertex(model, x0, y0, z1).color(r, g, b, a).next();
// Top Face
builder.vertex(model, x0, y1, z0).color(r, g, b, a).next();
builder.vertex(model, x0, y1, z1).color(r, g, b, a).next();
builder.vertex(model, x1, y1, z1).color(r, g, b, a).next();
builder.vertex(model, x1, y1, z0).color(r, g, b, a).next();
}
private float getRed() {
switch (updateType) {
case BLOCK_UPDATE:
return BLOCK_UPDATE_RED;
case COMPARATOR_UPDATE:
return COMPARATOR_UPDATE_RED;
case SHAPE_UPDATE:
return SHAPE_UPDATE_RED;
default:
return 0.0F;
}
}
private float getGreen() {
switch (updateType) {
case BLOCK_UPDATE:
return BLOCK_UPDATE_GREEN;
case COMPARATOR_UPDATE:
return COMPARATOR_UPDATE_GREEN;
case SHAPE_UPDATE:
return SHAPE_UPDATE_GREEN;
default:
return 0.0F;
}
}
private float getBlue() {
switch (updateType) {
case BLOCK_UPDATE:
return BLOCK_UPDATE_BLUE;
case COMPARATOR_UPDATE:
return COMPARATOR_UPDATE_BLUE;
case SHAPE_UPDATE:
return SHAPE_UPDATE_BLUE;
default:
return 0.0F;
}
}
private float getAlpha() {
switch (updateType) {
case BLOCK_UPDATE:
return BLOCK_UPDATE_ALPHA;
case COMPARATOR_UPDATE:
return COMPARATOR_UPDATE_ALPHA;
case SHAPE_UPDATE:
return SHAPE_UPDATE_ALPHA;
default:
return 0.0F;
}
}
public void updateBoxPositions(BlockPos pos, BlockPos notifierPos, BlockPos sourcePos, UpdateType updateType) {
this.pos = pos;
this.notifierPos = notifierPos;
this.sourcePos = sourcePos;
this.updateType = updateType;
}
public void onDisconnect() {
updateBoxPositions(null, null, null, UpdateType.NONE);
}
}
| 47,318
|
https://github.com/ThiagoBarradas/MundiAPI-JAVA/blob/master/src/main/java/com/mundipagg/api/models/GetCardTokenResponse.java
|
Github Open Source
|
Open Source
|
MIT
| null |
MundiAPI-JAVA
|
ThiagoBarradas
|
Java
|
Code
| 298
| 952
|
/*
* MundiAPILib
*
* This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ).
*/
package com.mundipagg.api.models;
import com.fasterxml.jackson.annotation.JsonGetter;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonSetter;
@JsonInclude(Include.ALWAYS)
public class GetCardTokenResponse
implements java.io.Serializable {
private static final long serialVersionUID = 7915153816906755285L;
private String lastFourDigits;
private String holderName;
private String holderDocument;
private String expMonth;
private String expYear;
private String brand;
private String type;
private String label;
/** GETTER
*
*/
@JsonGetter("last_four_digits")
public String getLastFourDigits ( ) {
return this.lastFourDigits;
}
/** SETTER
*
*/
@JsonSetter("last_four_digits")
public void setLastFourDigits (String value) {
this.lastFourDigits = value;
}
/** GETTER
*
*/
@JsonGetter("holder_name")
public String getHolderName ( ) {
return this.holderName;
}
/** SETTER
*
*/
@JsonSetter("holder_name")
public void setHolderName (String value) {
this.holderName = value;
}
/** GETTER
*
*/
@JsonGetter("holder_document")
public String getHolderDocument ( ) {
return this.holderDocument;
}
/** SETTER
*
*/
@JsonSetter("holder_document")
public void setHolderDocument (String value) {
this.holderDocument = value;
}
/** GETTER
*
*/
@JsonGetter("exp_month")
public String getExpMonth ( ) {
return this.expMonth;
}
/** SETTER
*
*/
@JsonSetter("exp_month")
public void setExpMonth (String value) {
this.expMonth = value;
}
/** GETTER
*
*/
@JsonGetter("exp_year")
public String getExpYear ( ) {
return this.expYear;
}
/** SETTER
*
*/
@JsonSetter("exp_year")
public void setExpYear (String value) {
this.expYear = value;
}
/** GETTER
*
*/
@JsonGetter("brand")
public String getBrand ( ) {
return this.brand;
}
/** SETTER
*
*/
@JsonSetter("brand")
public void setBrand (String value) {
this.brand = value;
}
/** GETTER
*
*/
@JsonGetter("type")
public String getType ( ) {
return this.type;
}
/** SETTER
*
*/
@JsonSetter("type")
public void setType (String value) {
this.type = value;
}
/** GETTER
*
*/
@JsonGetter("label")
public String getLabel ( ) {
return this.label;
}
/** SETTER
*
*/
@JsonSetter("label")
public void setLabel (String value) {
this.label = value;
}
}
| 789
|
https://github.com/jessica-galvan/FancyBeauty/blob/master/app/TipoProducto.php
|
Github Open Source
|
Open Source
|
MIT
| null |
FancyBeauty
|
jessica-galvan
|
PHP
|
Code
| 25
| 86
|
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class TipoProducto extends Model{
public $table = 'tipoproductos';
public $fillable = [];
public function producto(){
return $this->belongsTo('App\Producto', 'tipoProducto_id');
}
}
| 31,712
|
https://github.com/IPVS-AS/MMP-Backend/blob/master/model/src/test/java/de/unistuttgart/ipvs/as/mmp/model/v1/controller/ModelFileControllerTest.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
MMP-Backend
|
IPVS-AS
|
Java
|
Code
| 424
| 2,614
|
package de.unistuttgart.ipvs.as.mmp.model.v1.controller;
import de.unistuttgart.ipvs.as.mmp.common.domain.DBFile;
import de.unistuttgart.ipvs.as.mmp.common.domain.Model;
import de.unistuttgart.ipvs.as.mmp.common.domain.ModelFile;
import de.unistuttgart.ipvs.as.mmp.common.domain.ModelMetadata;
import de.unistuttgart.ipvs.as.mmp.common.exception.MMPExceptionHandler;
import de.unistuttgart.ipvs.as.mmp.common.util.DefaultDataBuilder;
import de.unistuttgart.ipvs.as.mmp.model.service.ModelFileService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.restdocs.RestDocumentationContextProvider;
import org.springframework.restdocs.RestDocumentationExtension;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Optional;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document;
import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.prettyPrint;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
@ExtendWith({SpringExtension.class, RestDocumentationExtension.class})
@WebMvcTest(controllers = {ModelFileController.class})
public class ModelFileControllerTest extends ControllerTest {
private static final Long EXISITNG_ID = 123L;
private static final Long EXISITNG_MODEL_ID = 1234L;
private static final Long EXISITNG_PROJECT_ID = 12345L;
private static final String ALL_MODELS_PATH = "/v1/projects/" + EXISITNG_PROJECT_ID + "/models";
private static final String GET_MODEL_FILE = ALL_MODELS_PATH + "/" + EXISITNG_MODEL_ID + "/file";
private static final String PARSE_MODEL_FILE_PATH = ALL_MODELS_PATH + "/file" + "/parse";
private static final String MODEL_FILE_ID_PATH = GET_MODEL_FILE + "/" + EXISITNG_ID;
private static final String MODEL_FILE_RAW_PATTER = MODEL_FILE_ID_PATH + "/raw";
MockMvc rest;
@MockBean
private ModelFileService modelFileService;
@Autowired
private ModelFileController modelFileController;
private ModelMetadata testModelMetadata = DefaultDataBuilder.getNewMetadataBuilder().build();
private Model testModel = Model.builder().modelMetadata(testModelMetadata).build();
private MultipartFile testMultipartFile = new MockMultipartFile("file", "filename.xml", "text/plain", "some xml".getBytes());
private DBFile testDbFile = DBFile.builder().fileName("filename.xml").fileType("text/plain").build();
private ModelFile testModelFile = ModelFile.builder().model(testModel).dbFile(testDbFile).build();
private MultipartFile testRMultipartFile = new MockMultipartFile("file", "filename.rds", "text/plain", "some r code".getBytes());
private MultipartFile testPklMultipartFile = new MockMultipartFile("file", "filename.pkl", "text/plain", "some pkl file".getBytes());
@BeforeEach
public void setUp(RestDocumentationContextProvider restDocumentation) throws IOException {
this.rest = MockMvcBuilders.standaloneSetup(this.modelFileController)
.setControllerAdvice(new MMPExceptionHandler(), this.modelFileService)
.apply(documentationConfiguration(restDocumentation).
operationPreprocessors()
.withRequestDefaults(prettyPrint())
.withResponseDefaults(prettyPrint()))
.build();
testDbFile.setData(testMultipartFile.getBytes());
}
@Test
public void shouldGetModelFileById() throws Exception {
given(modelFileService.getModelFileById(EXISITNG_ID))
.willReturn(Optional.of(testModelFile));
rest.perform(get(MODEL_FILE_ID_PATH))
.andExpect(status().isOk())
.andExpect(jsonPath("$.dbFile.fileName")
.value(testModelFile.getDbFile().getFileName()))
.andDo(document("model-file-get"));
}
@Test
public void shouldGetModelFileRawById() throws Exception {
given(modelFileService.getModelFileRaw(EXISITNG_ID))
.willReturn(Optional.of(testDbFile));
rest.perform(get(MODEL_FILE_RAW_PATTER))
.andExpect(status().isOk())
.andExpect(content().string("some xml"))
.andExpect(content().contentType(MediaType.TEXT_PLAIN))
.andDo(document("model-file-get-raw"));
}
@Test
public void shouldSaveModelFile() throws Exception {
testModelFile.setId(EXISITNG_ID);
given(modelFileService.saveModelFile(any(), any(), any()))
.willReturn(testModelFile);
rest.perform(MockMvcRequestBuilders.multipart(GET_MODEL_FILE)
.file((MockMultipartFile) testMultipartFile))
.andDo(print())
.andExpect(status().isCreated())
.andExpect(redirectedUrl(GET_MODEL_FILE + "/" + EXISITNG_ID))
.andDo(document("model-file-create"));
}
@Test
public void shouldParseModelFile() throws Exception {
testModelFile.setId(EXISITNG_ID);
byte[] json = json(testModel).getBytes(StandardCharsets.UTF_8);
MockMultipartFile jsonModelPart = new MockMultipartFile("model", "json", "text/plain", json);
given(modelFileService.parsePMMLModelFileInModel(any(), any()))
.willReturn(testModel);
rest.perform(MockMvcRequestBuilders.multipart(PARSE_MODEL_FILE_PATH)
.file((MockMultipartFile) testMultipartFile).file(jsonModelPart))
.andExpect(status().isOk())
.andExpect(jsonPath("$.modelMetadata.name").value(testModel.getModelMetadata().getName()))
.andDo(document("model-file-parse"));
}
@Test
public void shouldParseRModelFile() throws Exception {
testModelFile.setId(EXISITNG_ID);
byte[] json = json(testModel).getBytes(StandardCharsets.UTF_8);
MockMultipartFile jsonModelPart = new MockMultipartFile("model", "json", "text/plain", json);
given(modelFileService.parseRModelFileInModel(any(), any()))
.willReturn(testModel);
rest.perform(MockMvcRequestBuilders.multipart(PARSE_MODEL_FILE_PATH)
.file((MockMultipartFile) testRMultipartFile).file(jsonModelPart))
.andExpect(status().isOk())
.andExpect(jsonPath("$.modelMetadata.name").value(testModel.getModelMetadata().getName()))
.andDo(document("model-file-parse-r"));
}
@Test
public void shouldParsePickleModelFile() throws Exception {
testModelFile.setId(EXISITNG_ID);
byte[] json = json(testModel).getBytes(StandardCharsets.UTF_8);
MockMultipartFile jsonModelPart = new MockMultipartFile("model", "json", "text/plain", json);
given(modelFileService.parsePickleFileInModel(any(), any()))
.willReturn(testModel);
rest.perform(MockMvcRequestBuilders.multipart(PARSE_MODEL_FILE_PATH)
.file((MockMultipartFile) testPklMultipartFile).file(jsonModelPart))
.andExpect(status().isOk())
.andExpect(jsonPath("$.modelMetadata.name").value(testModel.getModelMetadata().getName()))
.andDo(document("model-file-parse-pickle"));
}
@Test
public void shouldDeleteModelFile() throws Exception {
given(modelFileService.deleteModelFile(EXISITNG_ID, EXISITNG_MODEL_ID, EXISITNG_PROJECT_ID))
.willReturn(true);
rest.perform(delete(MODEL_FILE_ID_PATH))
.andExpect(status().isNoContent())
.andDo(document("model-file-delete"));
}
@Test
public void shouldNotDeleteModelFile() throws Exception {
given(modelFileService.deleteModelFile(EXISITNG_ID, EXISITNG_PROJECT_ID, EXISITNG_MODEL_ID))
.willReturn(false);
rest.perform(delete(MODEL_FILE_ID_PATH))
.andExpect(status().isNotFound());
}
}
| 4,908
|
https://github.com/ZhnZhn/ta-chart/blob/master/js/components/zhn-charts/tooltip/MovingAverage.js
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,023
|
ta-chart
|
ZhnZhn
|
JavaScript
|
Code
| 200
| 797
|
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
exports.__esModule = true;
exports["default"] = void 0;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _uiApi = require("../../uiApi");
var _TooltipText = _interopRequireDefault(require("./TooltipText"));
var _TooltipTSpan = _interopRequireDefault(require("./TooltipTSpan"));
var _utils = require("../utils");
var _jsxRuntime = require("react/jsx-runtime");
var MovingAverage = function MovingAverage(_ref) {
var color = _ref.color,
displayName = _ref.displayName,
fontSize = _ref.fontSize,
fontFamily = _ref.fontFamily,
fontWeight = _ref.fontWeight,
textFill = _ref.textFill,
labelFill = _ref.labelFill,
labelFontWeight = _ref.labelFontWeight,
value = _ref.value,
origin = _ref.origin,
onClick = _ref.onClick,
forChart = _ref.forChart,
options = _ref.options;
var _onClick = (0, _uiApi.useCallback)(function (event) {
if (onClick !== undefined) {
onClick(event, (0, _extends2["default"])({
chartId: forChart
}, options));
}
}, [onClick, forChart, options]),
translate = (0, _utils.crCssTranslate)(origin);
return /*#__PURE__*/(0, _jsxRuntime.jsxs)("g", {
transform: translate,
children: [/*#__PURE__*/(0, _jsxRuntime.jsx)("line", {
x1: 0,
y1: 2,
x2: 0,
y2: 28,
stroke: color,
strokeWidth: 4
}), /*#__PURE__*/(0, _jsxRuntime.jsxs)(_TooltipText["default"], {
x: 5,
y: 11,
fontFamily: fontFamily,
fontSize: fontSize,
fontWeight: fontWeight,
children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_TooltipTSpan["default"], {
fill: labelFill,
fontWeight: labelFontWeight,
children: displayName
}), /*#__PURE__*/(0, _jsxRuntime.jsx)("tspan", {
x: 5,
dy: 15,
fill: textFill,
children: value
})]
}), /*#__PURE__*/(0, _jsxRuntime.jsx)("rect", {
x: 0,
y: 0,
width: 55,
height: 30,
fill: "none",
stroke: "none",
onClick: _onClick
})]
});
};
var _default = MovingAverage;
exports["default"] = _default;
//# sourceMappingURL=MovingAverage.js.map
| 31,966
|
https://github.com/blaulaub/jback-frontend/blob/master/src/app/person/person-with-password-draft.ts
|
Github Open Source
|
Open Source
|
MIT
| null |
jback-frontend
|
blaulaub
|
TypeScript
|
Code
| 21
| 49
|
import { PersonDraft } from './person-draft';
export class PersonWithPasswordDraft extends PersonDraft {
username: string = null;
password: string = null;
}
| 27,649
|
https://github.com/seoss/scs_core/blob/master/tests/aqcsv/specification/qc_test.py
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
scs_core
|
seoss
|
Python
|
Code
| 75
| 274
|
#!/usr/bin/env python3
"""
Created on 4 Mar 2019
@author: Bruno Beloff (bruno.beloff@southcoastscience.com)
"""
from scs_core.aqcsv.specification.qc import QC
from scs_core.data.json import JSONify
# --------------------------------------------------------------------------------------------------------------------
print("list...")
for qc in QC.instances():
print(qc)
print("-")
print("find...")
code = 99
qc = QC.instance(code)
print("code:%s qc:%s" % (code, qc))
print("-")
code = 0
qc = QC.instance(code)
print("code:%s qc:%s" % (code, qc))
jdict = qc.as_json()
print(JSONify.dumps(qc))
print("-")
remade = QC.construct_from_jdict(jdict)
print(remade)
equality = remade == qc
print("remade == qc: %s" % equality)
print("-")
| 24,160
|
https://github.com/AhemdHegazy/nxt.cranriggertest/blob/master/public/backend/js/scroll-top.js
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
nxt.cranriggertest
|
AhemdHegazy
|
JavaScript
|
Code
| 24
| 406
|
(function()
{window.setTimeout=window.setTimeout;})();var smoothScr={iterr:300,tm:null,stopShow:function()
{clearTimeout(this.tm);this.iterr=30;},getRealTop:function(el)
{var elm=el;var realTop=0;do
{realTop+=elm.offsetTop;elm=elm.offsetParent;}
while(elm);return realTop;},getPageScroll:function()
{var pgYoff=window.pageYOffset||document.body.scrollTop||document.documentElement.scrollTop;return pgYoff;},anim:function(id)
{this.stopShow();var eOff,pOff,tOff,scrVal,pos,dir,step;eOff=document.getElementById(id).offsetTop;tOff=this.getRealTop(document.getElementById(id).parentNode);pOff=this.getPageScroll();if(pOff===null||isNaN(pOff)||pOff==='undefined')pOff=0;scrVal=eOff-pOff;if(scrVal>tOff)
{pos=(eOff-tOff-pOff);dir=1;}
if(scrVal<tOff)
{pos=(pOff+tOff)-eOff;dir=-1;}
if(scrVal!==tOff)
{step=~~((pos/4)+1)*dir;if(this.iterr>1)this.iterr-=1;else this.itter=0;window.scrollBy(0,step);this.tm=window.setTimeout(function()
{smoothScr.anim(id);},this.iterr);}
if(scrVal===tOff)
{this.stopShow();return;}}}
| 28,070
|
https://github.com/eFishery/react-gulp-laravel-boilerplate/blob/master/resources/assets/js/container/OrderContainer.js
|
Github Open Source
|
Open Source
|
MIT
| null |
react-gulp-laravel-boilerplate
|
eFishery
|
JavaScript
|
Code
| 89
| 297
|
import { connect } from 'react-redux'
import * as OrderActions from '../redux/OrderActions'
import OrderPage from '../component/OrderPage'
const mapStateToProps = (state) => {
return {
sectionNumber: state.orderPageSwitch.sectionNumber,
feederState: state.orderFeederUpdate
}
}
const mapDispatchToProps = (dispatch) => {
return {
onButtonClick: (text) => {
if (text == "prev") {
console.log("prev");
dispatch(OrderActions.prevPage())
}
else {
console.log("next");
dispatch(OrderActions.nextPage())
}
},
onFeederChange: (id, num) => {
dispatch(OrderActions.addToSummary(id, num))
},
onSubmitOrder: () => {
dispatch(OrderActions.checkoutOrder())
},
onInit: () => {
console.log("init")
dispatch(OrderActions.initPage())
}
}
}
const OrderContainer = connect(
mapStateToProps,
mapDispatchToProps
)(OrderPage)
export default OrderContainer
| 26,217
|
https://github.com/DearbhailRicePA/gateway-web/blob/master/src/pages/commonComponents/workflowReviewStepsModal/WorkflowReviewStepsModal.js
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,022
|
gateway-web
|
DearbhailRicePA
|
JavaScript
|
Code
| 476
| 1,408
|
import React, { useState, useEffect, Fragment } from 'react';
import _ from 'lodash';
import uniqid from 'uniqid';
import { Modal } from 'react-bootstrap';
import ModalHeader from './ModalHeader';
import WorkflowReviewStep from './WorkflowReviewStep';
import { updateStepToggle } from '../../../utils/Workflows.util';
import './WorkflowReviewStepsModal.scss';
const WorkflowReviewStepsModal = ({ open, close, workflow = {} }) => {
const [workflowObj, setWorkflow] = useState({});
const onClickAction = (e, action = false) => {
e.preventDefault();
close('', action);
};
const buildWorkflow = () => {
// 1. deconstruct workflow
let { steps = [] } = workflow;
if (!_.isEmpty(steps)) {
const stepsArr = formatSteps(steps);
let workflowObj = {
...workflow,
steps: stepsArr,
};
setWorkflow(workflowObj);
} else {
setWorkflow(workflow);
}
};
const formatSteps = steps => {
if (!_.isEmpty(steps)) {
return [...steps].reduce((arr, step) => {
if (!_.isEmpty(step)) {
// 1. extract reviewers as own entity
let { reviewers, recommendations, _id, active } = step;
// 2. each item add expand state and reviewers expand
let item = {
...step,
closed: active ? false : true,
reviews: buildReviews(_id, reviewers, recommendations),
};
// 3. return new array
arr.push(item);
}
return arr;
}, []);
}
return [];
};
const buildReviews = (stepId = '', reviewers = [], recommendations = []) => {
if (!_.isEmpty(reviewers)) {
return [...reviewers].map(rev => {
let comment = { approved: null, comments: '', createdDate: '' };
let review = recommendations.find(r => r.reviewer === rev._id) || {};
if (!_.isEmpty(review)) comment = review;
return {
...rev,
...comment,
id: uniqid(),
stepId,
closed: true,
};
});
}
return [];
};
const toggleStep = (step = {}) => {
if (!_.isEmpty(workflowObj) && !_.isEmpty(step)) {
let steps = updateStepToggle([...workflowObj.steps], step);
let workflow = {
...workflowObj,
steps,
};
setWorkflow(workflow);
}
};
const toggleReview = (review = {}) => {
const steps = setToggleReview(review);
let workflow = {
...workflowObj,
steps,
};
setWorkflow(workflow);
};
const setToggleReview = (review = {}) => {
let { steps } = workflowObj;
let modifiedSteps = [...steps].reduce((arr, step) => {
let modifiedReviews = [];
let { reviews } = { ...step };
if (!_.isEmpty(reviews)) {
modifiedReviews = mapToggleReviews(reviews, review);
}
arr.push({
...step,
reviews: modifiedReviews,
});
return arr;
}, []);
return modifiedSteps;
};
const mapToggleReviews = (reviews = [], review) => {
if (!_.isEmpty(reviews) && !_.isEmpty(review)) {
return [...reviews].map(r => {
return {
...r,
closed: r.id === review.id ? !r.closed : r.closed,
};
});
}
return [];
};
const renderSteps = () => {
let { steps = [] } = workflowObj;
if (!_.isEmpty(steps)) {
return steps.map((step, i) => {
return <WorkflowReviewStep key={`step-${i}`} index={i} step={step} toggleStep={toggleStep} toggleReview={toggleReview} />;
});
}
return 'No Steps currently assigned';
};
useEffect(() => {
if (!_.isEmpty(workflow)) buildWorkflow();
}, [workflow]);
return (
<Fragment>
<Modal show={open} onHide={close} size='lg' aria-labelledby='contained-modal-title-vcenter' centered className='workflowReview'>
<ModalHeader workflowName={workflowObj.workflowName} onClickAction={onClickAction} />
<div className='workflowReview-body'>{renderSteps()}</div>
{workflowObj.canOverrideStep ? (
<div className='workflowReview-footer'>
<button className='button-tertiary' onClick={e => onClickAction(e, true)}>
Complete and skip to the next phase
</button>
</div>
) : (
''
)}
</Modal>
</Fragment>
);
};
export default WorkflowReviewStepsModal;
| 23,077
|
https://github.com/opxcms/admin-admins/blob/master/src/AdminAdmins.php
|
Github Open Source
|
Open Source
|
MIT
| null |
admin-admins
|
opxcms
|
PHP
|
Code
| 76
| 189
|
<?php
namespace Modules\Admin\Admins;
use Illuminate\Support\Facades\Facade;
/**
* @method static array getAdminsList()
* @method static array saveAdmin(array $admin)
* @method static string name()
* @method static string get($key)
* @method static string path($path = '')
* @method static array|string|null config($key = null)
* @method static mixed view($view)
*/
class AdminAdmins extends Facade
{
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor(): string
{
return 'admin_admins';
}
}
| 48,974
|
https://github.com/nortiero/sdl2_nim/blob/master/sdl2/private/rect.nim
|
Github Open Source
|
Open Source
|
Zlib
| 2,017
|
sdl2_nim
|
nortiero
|
Nim
|
Code
| 522
| 1,159
|
#
# Simple DirectMedia Layer
# Copyright (C) 1997-2016 Sam Lantinga <slouken@libsdl.org>
#
# This software is provided 'as-is', without any express or implied
# warranty. In no event will the authors be held liable for any damages
# arising from the use of this software.
#
# Permission is granted to anyone to use this software for any purpose,
# including commercial applications, and to alter it and redistribute it
# freely, subject to the following restrictions:
#
# 1. The origin of this software must not be misrepresented; you must not
# claim that you wrote the original software. If you use this software
# in a product, an acknowledgment in the product documentation would be
# appreciated but is not required.
# 2. Altered source versions must be plainly marked as such, and must not be
# misrepresented as being the original software.
# 3. This notice may not be removed or altered from any source distribution.
#
## rect.nim
## ========
##
## Header file for Rect definition and management procedures.
type
Point* = object ## \
## The object that defines a point
##
## See also:
##
## ``enclosePoints()``
##
## ``pointInRect()``
x*: cint
y*: cint
type
Rect* = object ## \
## A rectangle, with the origin at the upper left.
##
## See also:
##
## ``rectEmpty()``
##
## ``rectEquals()``
##
## ``hasIntersection()``
##
## ``intersectRect()``
##
## ``unionRect()``
##
## ``enclosePoints()``
x*: cint
y*: cint
w*: cint
h*: cint
template pointInRect*(p, r: untyped): bool = ## \
## ``Return`` `true` if point resides inside a rectangle.
((p.x >= r.x) and (p.x < (r.x + r.w)) and
(p.y >= r.y) and (p.y < (r.y + r.h)))
template rectEmpty*(r: untyped): bool = ## \
## ``Return`` `true` if the rectangle has no area.
((not r) or (r.w <= 0) or (r.h <= 0))
template rectEquals*(a, b: untyped): bool = ## \
## ``Return`` `true` if the two rectangles are equal.
(a and b and
(a.x == b.x) and (a.y == b.y) and
(a.w == b.w) and (a.h == b.h))
proc hasIntersection*(a: ptr Rect; b: ptr Rect): bool {.
cdecl, importc: "SDL_HasIntersection", dynlib: SDL2_LIB.}
## Determine whether two rectangles intersect.
##
## ``Return`` `true` if there is an intersection, `false` otherwise.
proc intersectRect*(a: ptr Rect; b: ptr Rect; result: ptr Rect): bool {.
cdecl, importc: "SDL_IntersectRect", dynlib: SDL2_LIB.}
## Calculate the intersection of two rectangles.
##
## ``Return`` `true` if there is an intersection, `false` otherwise.
proc unionRect*(a: ptr Rect; b: ptr Rect; result: ptr Rect) {.
cdecl, importc: "SDL_UnionRect", dynlib: SDL2_LIB.}
## Calculate the union of two rectangles.
proc enclosePoints*(
points: ptr Point; count: cint; clip: ptr Rect; result: ptr Rect): bool {.
cdecl, importc: "SDL_EnclosePoints", dynlib: SDL2_LIB.}
## Calculate a minimal rectangle enclosing a set of points.
##
## ``Return`` `true` if any points were within the clipping rect.
proc intersectRectAndLine*(
rect: ptr Rect;
x1: ptr cint; y1: ptr cint;
x2: ptr cint; y2: ptr cint): bool {.
cdecl, importc: "SDL_IntersectRectAndLine", dynlib: SDL2_LIB.}
## Calculate the intersection of a rectangle and line segment.
##
## ``Return`` `true` if there is an intersection, `false` otherwise.
| 50,636
|
https://github.com/Acidburn0zzz/antlr4cs/blob/master/runtime/CSharp/Antlr4.Runtime/Misc/Utils.cs
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,022
|
antlr4cs
|
Acidburn0zzz
|
C#
|
Code
| 574
| 1,349
|
/*
* [The "BSD license"]
* Copyright (c) 2013 Terence Parr
* Copyright (c) 2013 Sam Harwell
* 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.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
*/
using System;
using System.Collections.Generic;
using System.Text;
using Antlr4.Runtime.Misc;
using Antlr4.Runtime.Sharpen;
namespace Antlr4.Runtime.Misc
{
public class Utils
{
public static string Join<T>(string separator, IEnumerable<T> items)
{
#if NET40PLUS
return string.Join(separator, items);
#else
List<string> elements = new List<string>();
foreach (T item in items)
{
if (item == null)
elements.Add("");
else
elements.Add(item.ToString());
}
return string.Join(separator, elements.ToArray());
#endif
}
public static int NumNonnull(object[] data)
{
int n = 0;
if (data == null)
{
return n;
}
foreach (object o in data)
{
if (o != null)
{
n++;
}
}
return n;
}
public static void RemoveAllElements<T>(ICollection<T> data, T value)
{
if (data == null)
{
return;
}
while (data.Contains(value))
{
data.Remove(value);
}
}
public static string EscapeWhitespace(string s, bool escapeSpaces)
{
StringBuilder buf = new StringBuilder();
foreach (char c in s.ToCharArray())
{
if (c == ' ' && escapeSpaces)
{
buf.Append('\u00B7');
}
else
{
if (c == '\t')
{
buf.Append("\\t");
}
else
{
if (c == '\n')
{
buf.Append("\\n");
}
else
{
if (c == '\r')
{
buf.Append("\\r");
}
else
{
buf.Append(c);
}
}
}
}
}
return buf.ToString();
}
public static void RemoveAll<T>(IList<T> list, Predicate<T> predicate)
{
int j = 0;
for (int i = 0; i < list.Count; i++)
{
T item = list[i];
if (!predicate(item))
{
if (j != i)
{
list[j] = item;
}
j++;
}
}
while (j < list.Count)
{
list.RemoveAt(list.Count - 1);
}
}
/// <summary>Convert array of strings to string→index map.</summary>
/// <remarks>
/// Convert array of strings to string→index map. Useful for
/// converting rulenames to name→ruleindex map.
/// </remarks>
public static IDictionary<string, int> ToMap(string[] keys)
{
IDictionary<string, int> m = new Dictionary<string, int>();
for (int i = 0; i < keys.Length; i++)
{
m[keys[i]] = i;
}
return m;
}
public static char[] ToCharArray(List<int> data)
{
if (data == null)
{
return null;
}
char[] cdata = new char[data.Count];
for (int i = 0; i < data.Count; i++)
{
cdata[i] = (char)data[i];
}
return cdata;
}
}
}
| 20,866
|
https://github.com/lauth/blockchain/blob/master/content/page.go
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| null |
blockchain
|
lauth
|
Go
|
Code
| 174
| 448
|
package content
import (
"fmt"
"github.com/ponzu-cms/ponzu/management/editor"
"github.com/ponzu-cms/ponzu/system/item"
)
type Page struct {
item.Item
Title string `json:"title"`
Body string `json:"body"`
}
// MarshalEditor writes a buffer of html to edit a Page within the CMS
// and implements editor.Editable
func (p *Page) MarshalEditor() ([]byte, error) {
view, err := editor.Form(p,
// Take note that the first argument to these Input-like functions
// is the string version of each Page field, and must follow
// this pattern for auto-decoding and auto-encoding reasons:
editor.Field{
View: editor.Input("Title", p, map[string]string{
"label": "Title",
"type": "text",
"placeholder": "Enter the Title here",
}),
},
editor.Field{
View: editor.Richtext("Body", p, map[string]string{
"label": "Body",
"placeholder": "Enter the Body here",
}),
},
)
if err != nil {
return nil, fmt.Errorf("Failed to render Page editor view: %s", err.Error())
}
return view, nil
}
func init() {
item.Types["Page"] = func() interface{} { return new(Page) }
}
// String defines how a Page is printed. Update it using more descriptive
// fields from the Page struct type
func (p *Page) String() string {
return fmt.Sprintf("Page: %s", p.UUID)
}
| 739
|
https://github.com/mkpetrov/Programming-Fundamentals-SoftUni-Jan2017/blob/master/Exam Preparation/Spyfer/Spyfer.cs
|
Github Open Source
|
Open Source
|
MIT
| null |
Programming-Fundamentals-SoftUni-Jan2017
|
mkpetrov
|
C#
|
Code
| 99
| 325
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Spyfer
{
public class Spyfer
{
public static void Main()
{
var inputLine = Console.ReadLine().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToList();
for (int i = 0; i < inputLine.Count; i++)
{
var currentNumber = inputLine[i];
if (i==0 && currentNumber == inputLine[i + 1])
{
inputLine.RemoveAt(i + 1);
i = 0;
}
else if (i !=0 && i !=inputLine.Count-1 && currentNumber==inputLine[i-1]+inputLine[i+1])
{
inputLine.RemoveAt(i + 1);
inputLine.RemoveAt(i-1);
i = 0;
}
else if (i==inputLine.Count-1 && inputLine[i-1]==currentNumber)
{
inputLine.RemoveAt(i - 1);
i = 0;
}
}
Console.WriteLine(string.Join(" ", inputLine));
}
}
}
| 50,606
|
https://github.com/qianchenzhumeng/matrix/blob/master/benches/lib.rs
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
matrix
|
qianchenzhumeng
|
Rust
|
Code
| 15
| 40
|
#![feature(test)]
extern crate matrix;
extern crate random;
extern crate test;
#[cfg(feature = "accelerate")]
mod format;
| 3,875
|
https://github.com/aebadirad/mlhackathon/blob/master/starwars/src/app/search/search.component.ts
|
Github Open Source
|
Open Source
|
MIT
| null |
mlhackathon
|
aebadirad
|
TypeScript
|
Code
| 121
| 380
|
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
import { AppService } from '../app.service';
@Component({
selector: 'app-search',
templateUrl: './search.component.html',
styleUrls: ['./search.component.scss']
})
export class SearchComponent implements OnInit {
results: any;
constructor(private appService: AppService) { }
searchForm: FormGroup = new FormGroup({
q: new FormControl('')
});
ngOnInit() {
this.search();
}
search() {
this.appService.search(this.searchForm.value.q).subscribe(res => {
this.results = res;
});
}
getIcon(result): string {
let icon;
if (result.type === 'character') {
if (result.gender && result.gender !== 'none') {
icon = `fa-${result.gender}`;
}
else {
icon = 'fa-user';
}
}
else if (result.type === 'planet') {
icon = 'fa-globe';
}
else if (result.type === 'starship') {
icon = 'fa-space-shuttle';
}
return icon;
}
getImageUrl(name) {
return `url('/assets/images/${encodeURIComponent(name)}.png')`;
}
}
| 16,663
|
https://github.com/ezhivitsa/microservices-starter/blob/master/src/backend-services/authorization/src/tests/integration/cancel-registration.test.ts
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
microservices-starter
|
ezhivitsa
|
TypeScript
|
Code
| 57
| 150
|
import { cleanDB } from '../utils/db-utils';
import { registerUser, getUserById } from '../fixtures/users';
import { cancelRegistration } from '../commands';
describe('command /v1/cancel-registration', () => {
beforeAll(async () => {
await cleanDB();
});
it('should successfully delete user', async () => {
const user = await registerUser();
await cancelRegistration({
id: user.id,
});
const userById = await getUserById(user.id);
expect(userById).toBeNull();
});
});
| 11,102
|
https://github.com/joshua-curtis-smith/xdi2/blob/master/transport-http/src/main/java/xdi2/transport/impl/http/factory/MessagingTargetFactory.java
|
Github Open Source
|
Open Source
|
MIT
| 2,014
|
xdi2
|
joshua-curtis-smith
|
Java
|
Code
| 198
| 551
|
package xdi2.transport.impl.http.factory;
import java.util.Iterator;
import xdi2.core.xri3.XDI3SubSegment;
import xdi2.messaging.exceptions.Xdi2MessagingException;
import xdi2.messaging.target.MessagingTarget;
import xdi2.transport.exceptions.Xdi2TransportException;
import xdi2.transport.impl.http.registry.HttpMessagingTargetRegistry;
/**
* A MessagingTargetFactory can dynamically create MessagingTargets to process incoming XDI messages..
*
* @author Markus
*/
public interface MessagingTargetFactory {
/*
* Init and shutdown
*/
/**
* This method gets called when the MessagingTargetFactory is initialized.
*/
public void init() throws Exception;
/**
* This method gets called when the MessagingTargetFactory is no longer needed.
*/
public void shutdown() throws Exception;
/*
* Basic methods for mounting and updating
*/
/**
* Mount a new MessagingTarget.
*/
public MessagingTarget mountMessagingTarget(HttpMessagingTargetRegistry httpMessagingTargetRegistry, String messagingTargetFactoryPath, String requestPath) throws Xdi2TransportException, Xdi2MessagingException;
/**
* Updates a MessagingTarget.
*/
public MessagingTarget updateMessagingTarget(HttpMessagingTargetRegistry httpMessagingTargetRegistry, String messagingTargetFactoryPath, String requestPath, MessagingTarget messagingTarget) throws Xdi2TransportException, Xdi2MessagingException;
/*
* Advanced methods
*/
/**
* Returns a list of all owner peer root XRIs of the MessagingTargets this
* MessagingTargetFactory can create. Not all MessagingTargetFactorys may
* support this.
*/
public Iterator<XDI3SubSegment> getOwnerPeerRootXris();
/**
* Returns the request path at which this MessagingTargetFactory is able to
* mount a MessagingTarget with a given owner peer root XRI. Not all MessagingTargetFactorys
* may support this.
*/
public String getRequestPath(String messagingTargetFactoryPath, XDI3SubSegment ownerPeerRootXri);
}
| 42,092
|
https://github.com/soongo/soon/blob/master/soon_test.go
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
soon
|
soongo
|
Go
|
Code
| 79
| 223
|
// Copyright 2020 Guoyao Wu. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.
package soon
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestApp_Run(t *testing.T) {
app, c := New(), make(chan struct{})
go func() {
c <- struct{}{}
app.Run(":54321")
}()
<-c
app.GET("/", func(c *Context) {
c.Send("hello")
})
statusCode, _, body, err := request("GET", "http://localhost:54321", nil)
assert := assert.New(t)
assert.Nil(err)
assert.Equal(200, statusCode)
assert.Equal("hello", body)
}
| 44,749
|
https://github.com/andreww/fox/blob/master/common/test/test_xml_namecheck_7.f90
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,021
|
fox
|
andreww
|
Fortran Free Form
|
Code
| 40
| 234
|
program test
use m_common_charset, only : XML1_0, XML1_1
use m_common_struct, only : xml_doc_state
use m_common_namecheck, only : checkSystemID
implicit none
type(xml_doc_state) :: xds
write(*,'(l1)') checkSystemID('abcd')
write(*,'(l1)') checkSystemID('1abcd /"()+,/=?;!*#@$%')
write(*,'(l1)') checkSystemID('1abcd /"()+,/=?;!*#@$%'//achar(13))
write(*,'(l1)') checkSystemID('1abcd /(")+,/=?;!*#@$%&')
write(*,'(l1)') checkSystemID('1abcd /(")+,/=?;!*#@$%&'//"'")
end program test
| 413
|
https://github.com/paras55/officialWebsite/blob/master/officialWebsite/members/migrations/0007_member_email.py
|
Github Open Source
|
Open Source
|
MIT
| null |
officialWebsite
|
paras55
|
Python
|
Code
| 29
| 115
|
# Generated by Django 2.2.8 on 2019-12-24 10:06
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('members', '0006_auto_20191224_1521'),
]
operations = [
migrations.AddField(model_name='member', name='email', field=models.EmailField(blank=True, max_length=254),),
]
| 35,804
|
https://github.com/santiagobiach/Algo3_tp2/blob/master/src/main/java/edu/fiuba/algo3/controladores/botones/BotonReagruparHandler.java
|
Github Open Source
|
Open Source
|
MIT
| null |
Algo3_tp2
|
santiagobiach
|
Java
|
Code
| 136
| 719
|
package edu.fiuba.algo3.controladores.botones;
import edu.fiuba.algo3.modelo.Juego;
import edu.fiuba.algo3.modelo.Pais;
import edu.fiuba.algo3.vistas.MenuFaseDeReagrupación;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.Spinner;
public class BotonReagruparHandler implements EventHandler<ActionEvent> {
private Juego juego;
private MenuFaseDeReagrupación menu;
private Spinner SPTropas;
private Label tropasPaisDeOrigen;
private Label tropasPaisDeDestino;
private ComboBox<String> CBPaisDeOrigen;
private ComboBox<String> CBPaisDeDestino;
public BotonReagruparHandler(ComboBox<String> CBPaisDeOrigen, ComboBox CBPaisDeDestino,
Spinner SPTropas, Label tropasPaisDeOrigen, Label tropasPaisDeDestino, Juego juego){
this.SPTropas = SPTropas;
this.menu = menu;
this.juego = juego;
this.tropasPaisDeDestino = tropasPaisDeDestino;
this.tropasPaisDeOrigen = tropasPaisDeOrigen;
this.CBPaisDeDestino = CBPaisDeDestino;
this.CBPaisDeOrigen = CBPaisDeOrigen;
}
@Override
public void handle(ActionEvent actionEvent) {
Pais paisDeOrigen = null;
Pais paisDeDestino = null;
if (!CBPaisDeOrigen.getItems().isEmpty())
paisDeOrigen = juego.getTablero().getPais((CBPaisDeOrigen.getSelectionModel().getSelectedItem()));
if (!CBPaisDeDestino.getItems().isEmpty())
paisDeDestino = juego.getTablero().getPais((CBPaisDeDestino.getSelectionModel().getSelectedItem()));
Integer cantidad = 0;
try{
cantidad = (Integer)SPTropas.getValue();
} catch (Exception e){};
if(paisDeDestino != null && paisDeOrigen != null){
paisDeOrigen.moverTropasA(paisDeDestino, cantidad);
tropasPaisDeOrigen.setText("Tropas: " + String.valueOf(paisDeOrigen.getCantidadDeTropas()));
tropasPaisDeDestino.setText("Tropas: " + String.valueOf(paisDeDestino.getCantidadDeTropas()));
}
}
}
| 48,204
|
https://github.com/OpenQuake/backend/blob/master/app/app.php
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,017
|
backend
|
OpenQuake
|
PHP
|
Code
| 46
| 82
|
<?php
/*
User application main file
This file is the main file of your application.
Inside this file you can develop your application or call an autoloader.
DO NOT DELETE THIS FILE otherwise your application will not be loaded.
*/
// Application main module
$azzurro->app("app", []);
| 34,265
|
https://github.com/CoOwner/VisualPvP/blob/master/org/apache/maven/model/BuildBase.java
|
Github Open Source
|
Open Source
|
MIT
| null |
VisualPvP
|
CoOwner
|
Java
|
Code
| 282
| 1,058
|
package org.apache.maven.model;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class BuildBase
extends PluginConfiguration
implements Serializable, Cloneable
{
private String defaultGoal;
private List<Resource> resources;
private List<Resource> testResources;
private String directory;
private String finalName;
private List<String> filters;
public BuildBase() {}
public void addFilter(String string)
{
getFilters().add(string);
}
public void addResource(Resource resource)
{
getResources().add(resource);
}
public void addTestResource(Resource resource)
{
getTestResources().add(resource);
}
public BuildBase clone()
{
try
{
BuildBase copy = (BuildBase)super.clone();
if (resources != null)
{
resources = new ArrayList();
for (Resource item : resources)
{
resources.add(item.clone());
}
}
if (testResources != null)
{
testResources = new ArrayList();
for (Resource item : testResources)
{
testResources.add(item.clone());
}
}
if (filters != null)
{
filters = new ArrayList();
filters.addAll(filters);
}
return copy;
}
catch (Exception ex)
{
throw ((RuntimeException)new UnsupportedOperationException(getClass().getName() + " does not support clone()").initCause(ex));
}
}
public String getDefaultGoal()
{
return defaultGoal;
}
public String getDirectory()
{
return directory;
}
public List<String> getFilters()
{
if (filters == null)
{
filters = new ArrayList();
}
return filters;
}
public String getFinalName()
{
return finalName;
}
public List<Resource> getResources()
{
if (resources == null)
{
resources = new ArrayList();
}
return resources;
}
public List<Resource> getTestResources()
{
if (testResources == null)
{
testResources = new ArrayList();
}
return testResources;
}
public void removeFilter(String string)
{
getFilters().remove(string);
}
public void removeResource(Resource resource)
{
getResources().remove(resource);
}
public void removeTestResource(Resource resource)
{
getTestResources().remove(resource);
}
public void setDefaultGoal(String defaultGoal)
{
this.defaultGoal = defaultGoal;
}
public void setDirectory(String directory)
{
this.directory = directory;
}
public void setFilters(List<String> filters)
{
this.filters = filters;
}
public void setFinalName(String finalName)
{
this.finalName = finalName;
}
public void setResources(List<Resource> resources)
{
this.resources = resources;
}
public void setTestResources(List<Resource> testResources)
{
this.testResources = testResources;
}
}
| 37,000
|
https://github.com/S2-group/mobilesoft-2020-iam-replication-package/blob/master/dataset/Top APKs Java Files/com.chegal.alarm-com-chegal-alarm-rate-IntentHelper.java
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
mobilesoft-2020-iam-replication-package
|
S2-group
|
Java
|
Code
| 661
| 2,506
|
package com.chegal.alarm.rate;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.util.Log;
import androidx.annotation.NonNull;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
final class IntentHelper
{
private static final String AMAZON_APPSTORE_PACKAGE_NAME = "com.amazon.venezia";
private static final String BLACKBERRY_WORLD_PACKAGE_NAME = "net.rim.bb.appworld";
private static final String[] BROWSERS_PACKAGES_NAMES = { "com.android.chrome", "org.mozilla.firefox", "com.opera.browser", "com.opera.mini.native", "com.sec.android.app.sbrowser", "com.UCMobile.intl", "com.tencent.mtt", "com.android.browser" };
private static final String CAFE_BAZAAR_PACKAGE_NAME = "com.farsitel.bazaar";
private static final String[] CHINESE_STORES_PACKAGES_NAMES = { "com.tencent.android.qqdownloader", "com.qihoo.appstore", "com.xiaomi.market", "com.huawei.appmarket", "com.baidu.appsearch", "com.oppo.market", "zte.com.market", "com.bbk.appstore", "com.wandoujia.phoenix2", "com.pp.assistant", "com.hiapk.marketpho", "com.dragon.android.pandaspace", "com.yingyonghui.market", "com.tencent.qqpimsecure", "com.mappn.gfan", "cn.goapk.market", "com.yulong.android.coolmart", "com.lenovo.leos.appstore", "com.coolapk.market" };
public static final String[] EMPTY_STRING_ARRAY = new String[0];
private static final String GOOGLE_PLAY_PACKAGE_NAME = "com.android.vending";
private static final String MI_PACKAGE_NAME = "com.xiaomi.market";
private static final String SAMSUNG_GALAXY_APPS_PACKAGE_NAME = "com.sec.android.app.samsungapps";
private static final String SLIDEME_MARKETPLACE_PACKAGE_NAME = "com.slideme.sam.manager";
private static final String TENCENT_PACKAGE_NAME = "com.tencent.android.qqdownloader";
private static final String YANDEX_STORE_PACKAGE_NAME = "com.yandex.store";
private IntentHelper()
{
throw new UnsupportedOperationException("IntentHelper");
}
@NonNull
static Intent[] createIntentsForStore(@NonNull Context paramContext, UriHelper.StoreType paramStoreType, @NonNull String paramString)
{
int i = 0;
if ((paramContext != null) && (paramString != null))
{
boolean bool1 = getNeedStorePackageFlagForStore(paramStoreType);
boolean bool2 = getHasWebUriIntentFlagForStore(paramStoreType);
String[] arrayOfString2 = getPackagesNamesForStore(paramStoreType);
String[] arrayOfString1 = isPackagesExists(paramContext, arrayOfString2);
int j = (byte)arrayOfString1.length;
if (j > 0)
{
if (bool2)
{
paramContext = new Intent[j + 1];
paramContext[j] = new Intent("android.intent.action.VIEW", UriHelper.getStoreWebUri(paramStoreType, paramString));
}
else
{
paramContext = new Intent[j];
}
for (;;)
{
localObject = paramContext;
if (i >= j) {
break;
}
paramContext[i] = new Intent("android.intent.action.VIEW", UriHelper.getStoreUri(paramStoreType, paramString));
setIntentForStore(paramContext[i]);
paramContext[i].setPackage(arrayOfString1[i]);
i = (byte)(i + 1);
}
}
if (!bool1)
{
localObject = new Intent[1];
localObject[0] = new Intent("android.intent.action.VIEW", UriHelper.getStoreWebUri(paramStoreType, paramString));
if (paramStoreType == UriHelper.StoreType.APPLE)
{
paramContext = isPackagesExists(paramContext, BROWSERS_PACKAGES_NAMES);
if (paramContext.length > 0) {
localObject[0].setPackage(paramContext[0]);
}
}
return localObject;
}
Object localObject = new Intent[0];
if (bool2)
{
paramContext = new StringBuilder();
paramContext.append(Arrays.toString(arrayOfString2));
paramContext.append(" not exist on the user device and the user device can't start the app store (");
paramContext.append(paramStoreType);
paramContext.append(") web (http/https) uri activity without it.");
Log.w("IntentHelper", paramContext.toString());
return localObject;
}
paramContext = new StringBuilder();
paramContext.append(Arrays.toString(arrayOfString2));
paramContext.append(" not exist on the user device and the app store (");
paramContext.append(paramStoreType);
paramContext.append(") hasn't web (http/https) uri.");
Log.w("IntentHelper", paramContext.toString());
return localObject;
}
if (paramContext == null) {
Log.w("IntentHelper", "can't check the availability of stores packages on the user device (context == null).");
}
if (paramString == null) {
Log.w("IntentHelper", "can't get store Uri/WebUri (paramName == null).");
}
return new Intent[0];
}
private static boolean getHasWebUriIntentFlagForStore(UriHelper.StoreType paramStoreType)
{
return paramStoreType != UriHelper.StoreType.CHINESESTORES;
}
private static boolean getNeedStorePackageFlagForStore(UriHelper.StoreType paramStoreType)
{
switch (1.$SwitchMap$com$chegal$alarm$rate$UriHelper$StoreType[paramStoreType.ordinal()])
{
default:
return false;
}
return true;
}
@NonNull
private static String[] getPackagesNamesForStore(UriHelper.StoreType paramStoreType)
{
switch (1.$SwitchMap$com$chegal$alarm$rate$UriHelper$StoreType[paramStoreType.ordinal()])
{
default:
return new String[] { "com.android.vending" };
case 9:
return new String[] { "com.tencent.android.qqdownloader" };
case 8:
return new String[] { "com.slideme.sam.manager" };
case 7:
return new String[] { "com.xiaomi.market" };
case 6:
return new String[] { "net.rim.bb.appworld" };
case 5:
return new String[] { "com.farsitel.bazaar" };
case 4:
return new String[] { "com.amazon.venezia" };
case 3:
return new String[] { "com.yandex.store" };
case 2:
return new String[] { "com.sec.android.app.samsungapps" };
}
return CHINESE_STORES_PACKAGES_NAMES;
}
static String[] isPackagesExists(@NonNull Context paramContext, @NonNull String[] paramArrayOfString)
{
if ((paramContext != null) && (paramArrayOfString != null) && (paramArrayOfString.length != 0))
{
paramContext = paramContext.getPackageManager().getInstalledApplications(0);
if (paramArrayOfString.length == 1)
{
if ((paramArrayOfString[0] != null) && (paramArrayOfString[0].hashCode() != "".hashCode()))
{
paramContext = paramContext.iterator();
while (paramContext.hasNext())
{
localObject = (ApplicationInfo)paramContext.next();
if (paramArrayOfString[0].equals(((ApplicationInfo)localObject).packageName)) {
return new String[] { paramArrayOfString[0] };
}
}
}
return EMPTY_STRING_ARRAY;
}
Object localObject = new ArrayList();
int j = paramArrayOfString.length;
int i = 0;
while (i < j)
{
String str = paramArrayOfString[i];
if ((str != null) && (str.hashCode() != "".hashCode()))
{
Iterator localIterator = paramContext.iterator();
while (localIterator.hasNext()) {
if (str.equals(((ApplicationInfo)localIterator.next()).packageName)) {
((ArrayList)localObject).add(str);
}
}
}
i += 1;
}
return (String[])((ArrayList)localObject).toArray(new String[0]);
}
if (paramContext == null) {
Log.i("IntentHelper", "Failed to get installed applications.");
}
if (paramArrayOfString == null) {
Log.i("IntentHelper", "Null pointer to an array of target packages.");
}
return EMPTY_STRING_ARRAY;
}
private static void setIntentForStore(Intent paramIntent)
{
paramIntent.addFlags(268435456);
paramIntent.addFlags(2097152);
paramIntent.addFlags(67108864);
}
}
| 22,161
|
https://github.com/apupier/wsdl2rest/blob/master/impl/src/main/java/org/jboss/fuse/wsdl2rest/impl/codegen/JavaTypeGenerator.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,017
|
wsdl2rest
|
apupier
|
Java
|
Code
| 132
| 498
|
package org.jboss.fuse.wsdl2rest.impl.codegen;
import java.io.File;
import java.net.URL;
import java.nio.file.Path;
import org.apache.cxf.tools.common.ToolContext;
import org.apache.cxf.tools.common.model.JavaInterface;
import org.apache.cxf.tools.common.model.JavaModel;
import org.apache.cxf.tools.common.model.JavaServiceClass;
import org.apache.cxf.tools.wsdlto.WSDLToJava;
/**
* Generate Java Types from WSDL using Apache CXF WSDL2Java
*
* http://cxf.apache.org/docs/wsdl-to-java.html
*
* @since 10-Nov-2016
* @author tdiesler@redhat.com
*/
public class JavaTypeGenerator {
private final URL wsdlURL;
private final Path outpath;
public JavaTypeGenerator(Path outpath, URL wsdlURL) {
this.wsdlURL = wsdlURL;
this.outpath = outpath;
}
public void execute() throws Exception {
String args[] = new String[] {
"-d", outpath.toString(),
wsdlURL.toExternalForm(),
};
ToolContext ctx = new ToolContext();
new WSDLToJava(args).run(ctx);
JavaModel javaModel = ctx.getJavaModel();
for (JavaInterface aux : javaModel.getInterfaces().values()) {
File auxFile = outpath.resolve(aux.getPackageName().replace('.', '/') + "/" + aux.getName() + ".java").toFile();
auxFile.delete();
}
for (JavaServiceClass aux : javaModel.getServiceClasses().values()) {
File auxFile = outpath.resolve(aux.getPackageName().replace('.', '/') + "/" + aux.getName() + ".java").toFile();
auxFile.delete();
}
}
}
| 28,806
|
https://github.com/billionshang/gem5/blob/master/build/x86/debug/VtoPhys.hh
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,022
|
gem5
|
billionshang
|
C++
|
Code
| 28
| 80
|
/*
* DO NOT EDIT THIS FILE! Automatically generated by SCons.
*/
#ifndef __DEBUG_VtoPhys_HH__
#define __DEBUG_VtoPhys_HH__
namespace Debug {
class SimpleFlag;
extern SimpleFlag VtoPhys;
}
#endif // __DEBUG_VtoPhys_HH__
| 11,839
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.