hexsha stringlengths 40 40 | size int64 5 1.05M | ext stringclasses 98
values | lang stringclasses 21
values | max_stars_repo_path stringlengths 3 945 | max_stars_repo_name stringlengths 4 118 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses listlengths 1 10 | max_stars_count int64 1 368k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 945 | max_issues_repo_name stringlengths 4 118 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 10 | max_issues_count int64 1 134k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 945 | max_forks_repo_name stringlengths 4 135 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 10 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 5 1.05M | avg_line_length float64 1 1.03M | max_line_length int64 2 1.03M | alphanum_fraction float64 0 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
e154aa2f16979d96e202859009b1835394b4215c | 3,398 | lua | Lua | mod_ood_proxy/lib/ood/nginx_stage.lua | hmdc/ondemand | ac39be63d89abfd9d538876466cc643858cc3f05 | [
"MIT"
] | 82 | 2019-04-15T16:38:06.000Z | 2022-03-30T05:07:32.000Z | mod_ood_proxy/lib/ood/nginx_stage.lua | hmdc/ondemand | ac39be63d89abfd9d538876466cc643858cc3f05 | [
"MIT"
] | 1,312 | 2017-11-12T16:16:28.000Z | 2022-03-31T21:36:38.000Z | mod_ood_proxy/lib/ood/nginx_stage.lua | hmdc/ondemand | ac39be63d89abfd9d538876466cc643858cc3f05 | [
"MIT"
] | 71 | 2019-05-31T20:25:11.000Z | 2022-03-23T22:02:35.000Z |
--[[
pun
Start PUN process for given user
--]]
function pun(r, bin, user, app_init_url, exports, pre_hook_root_cmd)
local cmd = bin .. " pun -u '" .. r:escape(user) .. "'"
local err
if app_init_url then
cmd = cmd .. " -a '" .. r:escape(app_init_url) .. "'"
end
if pre_hook_root_cmd then
local env_table = exports_to_table(r, exports)
cmd = cmd .. " -P '" .. r:escape(pre_hook_root_cmd) .. "'"
err = capture2e_with_env(cmd, env_table)
else
err = capture2e(cmd)
end
if err == "" then
return nil -- success
else
return err -- fail
end
end
--[[
app
Initialize an app config & restart PUN
--]]
function app(r, bin, user, request, sub_uri)
local cmd = bin .. " app -u '" .. r:escape(user) .. "' -r '" .. r:escape(request) .. "'"
if sub_uri then
cmd = cmd .. " -i '" .. r:escape(sub_uri) .. "'"
end
local err = capture2e(cmd)
if err == "" then
return nil -- success
else
return err -- fail
end
end
--[[
nginx
Send the per-user nginx a signal
--]]
function nginx(r, bin, user, signal)
local cmd = bin .. " nginx -u '" .. r:escape(user) .. "'"
if signal then
cmd = cmd .. " -s '" .. r:escape(signal) .. "'"
end
local err = capture2e(cmd)
if err == "" then
return nil -- success
else
return err -- fail
end
end
--[[
capture2
Give a string for a command, get a string for stdout
--]]
function capture2(cmd)
local handle = io.popen(cmd, "r")
local output = handle:read("*a")
handle:close()
return output
end
--[[
capture2e
Give a string for a command, get a string for merged stdout and stderr
--]]
function capture2e(cmd)
return capture2(cmd .. " 2>&1")
end
--[[
capture2e_with_env
fork this process, modify the environment of the child and execute the
command. This returns a string that is the stdout & stderr combined.
--]]
function capture2e_with_env(cmd, env_table)
local posix = require 'posix'
local read_pipe, write_pipe = posix.pipe()
local childpid, errmsg = posix.fork()
if childpid == nil then
return "failed to fork " .. cmd .. " with error message: '" .. errmsg .. "'"
-- child pid
elseif childpid == 0 then
posix.close(read_pipe)
for key,value in pairs(env_table) do
posix.setenv("OOD_" .. key, value) -- sudo rules allow for OOD_* env vars
end
local output = capture2e(cmd)
posix.write(write_pipe, output)
posix.close(write_pipe)
os.exit(0)
-- child pid
else
posix.close(write_pipe)
posix.wait(childpid)
-- FIXME: probably a better way than to read byte by byte
local output = ""
local b = posix.read(read_pipe, 1)
while #b == 1 do
output = output .. b
b = posix.read(read_pipe, 1)
end
posix.close(read_pipe)
return output
end
end
--[[
export_table
Given exports to be a comma seperated list of environment variable
names: split that string, extract the variable values from the request's
environment and return a table of the environment variable key:value pairs
--]]
function exports_to_table(r, exports)
local export_table = {}
if exports then
for key in string.gmatch(exports, '([^,]+)') do
value = r.subprocess_env[key]
if value then
export_table[key] = value
end
end
end
return export_table
end
return {
pun = pun,
app = app,
nginx = nginx
}
| 20.593939 | 90 | 0.625956 |
b7250f1b2116533efcb88d791f80b1698d9651e2 | 174 | sql | SQL | engine/sql/api/012_pipelinebuild_commits.sql | jqueguiner/cds | b629b7e18108142440dcc06fafca420001384511 | [
"BSD-3-Clause"
] | 4,040 | 2016-10-11T08:46:07.000Z | 2022-03-31T10:59:41.000Z | engine/sql/api/012_pipelinebuild_commits.sql | jqueguiner/cds | b629b7e18108142440dcc06fafca420001384511 | [
"BSD-3-Clause"
] | 2,582 | 2016-10-12T12:14:21.000Z | 2022-03-31T16:46:07.000Z | engine/sql/api/012_pipelinebuild_commits.sql | jqueguiner/cds | b629b7e18108142440dcc06fafca420001384511 | [
"BSD-3-Clause"
] | 436 | 2016-10-11T08:46:16.000Z | 2022-03-21T09:08:44.000Z | -- +migrate Up
ALTER TABLE pipeline_build ADD COLUMN commits JSONB;
UPDATE pipeline_build set commits='[]';
-- +migrate Down
ALTER TABLE pipeline_build DROP COLUMN commits;
| 24.857143 | 52 | 0.781609 |
c6c2b568a4ab2d7c6f53dbaadb1bc82e025fedfd | 251 | rb | Ruby | lib/ssource/source/extension.rb | Draveness/ssource | b33e039c5ce8a7ce7d2ed1b6b6af9e28876144ba | [
"MIT"
] | null | null | null | lib/ssource/source/extension.rb | Draveness/ssource | b33e039c5ce8a7ce7d2ed1b6b6af9e28876144ba | [
"MIT"
] | null | null | null | lib/ssource/source/extension.rb | Draveness/ssource | b33e039c5ce8a7ce7d2ed1b6b6af9e28876144ba | [
"MIT"
] | null | null | null | require_relative 'klass'
module Ssource
module Source
class Extension < Klass
def initialize(json)
super
if superklass
@protocols << superklass
@superklass = nil
end
end
end
end
end
| 15.6875 | 34 | 0.581673 |
261a3ec6a9aebfcc50f042f22fc48d8631e0decd | 3,096 | java | Java | 20190902_v1_1/src/pos/app/src/main/java/com/bx/erp/bo/RetailTradeCouponSQLiteBO.java | Boxin-ChinaGD/BXERP | 4273910059086ab9b76bd547c679d852a1129a0c | [
"Apache-2.0"
] | 4 | 2021-11-11T08:57:32.000Z | 2022-03-21T02:56:08.000Z | 20190902_v1_1/src/pos/app/src/main/java/com/bx/erp/bo/RetailTradeCouponSQLiteBO.java | Boxin-ChinaGD/BXERP | 4273910059086ab9b76bd547c679d852a1129a0c | [
"Apache-2.0"
] | null | null | null | 20190902_v1_1/src/pos/app/src/main/java/com/bx/erp/bo/RetailTradeCouponSQLiteBO.java | Boxin-ChinaGD/BXERP | 4273910059086ab9b76bd547c679d852a1129a0c | [
"Apache-2.0"
] | 2 | 2021-12-20T08:34:31.000Z | 2022-02-09T06:52:41.000Z | package com.bx.erp.bo;
import android.content.Context;
import com.bx.erp.common.GlobalController;
import com.bx.erp.event.BaseHttpEvent;
import com.bx.erp.event.UI.BaseSQLiteEvent;
import com.bx.erp.model.BaseModel;
import com.bx.erp.model.ErrorInfo;
import com.bx.erp.model.RetailTradeCoupon;
import org.apache.log4j.Logger;
import java.util.List;
public class RetailTradeCouponSQLiteBO extends BaseSQLiteBO{
private Logger log = Logger.getLogger(this.getClass());
public RetailTradeCouponSQLiteBO(Context ctx, BaseSQLiteEvent sEvent, BaseHttpEvent hEvent) {
context = ctx;
sqLiteEvent = sEvent;
httpEvent = hEvent;
}
@Override
public BaseModel createSync(int iUseCaseID, final BaseModel bm) {
log.info("正在执行RetailTradeCouponSQLiteBO的createSync,bm=" + bm);
if(bm != null){
RetailTradeCoupon rtc = (RetailTradeCoupon) bm;
String checkMsg = rtc.checkCreate(iUseCaseID);
if (!"".equals(checkMsg)) {
sqLiteEvent.setLastErrorCode(ErrorInfo.EnumErrorCode.EC_WrongFormatForInputField);
sqLiteEvent.setLastErrorMessage(checkMsg);
return null;
}
switch (iUseCaseID) {
case CASE_RetailTradeCoupon_CreateSync:
RetailTradeCoupon retailTradeCoupon = (RetailTradeCoupon) GlobalController.getInstance().getRetailTradeCouponPresenter().createObjectSync(iUseCaseID, bm);
if (retailTradeCoupon != null) {
return retailTradeCoupon;
} else {
log.info("创建临时零售单优惠券使用表失败");
}
break;
default:
log.info("未定义的事件!");
throw new RuntimeException("未定义的事件!");
}
}
return null;
}
@Override
public boolean createAsync(int iUseCaseID, BaseModel bm) {
return false;
}
@Override
protected boolean applyServerDataListAsync(List<BaseModel> bmList) {
return false;
}
@Override
protected boolean applyServerDataAsync(BaseModel bmNew) {
return false;
}
@Override
public boolean updateAsync(int iUseCaseID, BaseModel bm) {
return false;
}
@Override
protected boolean applyServerDataUpdateAsync(BaseModel bmNew) {
return false;
}
@Override
protected boolean applyServerDataUpdateAsyncN(List<?> bmList) {
return false;
}
@Override
protected boolean applyServerDataDeleteAsync(BaseModel bmDelete) {
return false;
}
@Override
protected boolean applyServerListDataAsync(List<BaseModel> bmList) {
return false;
}
@Override
protected boolean applyServerListDataAsyncC(List<BaseModel> bmList) {
return false;
}
@Override
public boolean deleteAsync(int iUseCaseID, BaseModel bm) {
return false;
}
@Override
public List<?> retrieveNSync(int iUseCaseID, BaseModel bm) {
return null;
}
}
| 27.891892 | 174 | 0.634044 |
60418fe02dd43897d6bc5ed3b9ae42241a91bfaa | 1,471 | asm | Assembly | gfx/tilesets/pokecenter_palette_map.asm | AtmaBuster/pokeplat-gen2 | fa83b2e75575949b8f72cb2c48f7a1042e97f70f | [
"blessing"
] | 6 | 2021-06-19T06:41:19.000Z | 2022-02-15T17:12:33.000Z | gfx/tilesets/pokecenter_palette_map.asm | AtmaBuster/pokeplat-gen2-old | 01e42c55db5408d72d89133dc84a46c699d849ad | [
"blessing"
] | null | null | null | gfx/tilesets/pokecenter_palette_map.asm | AtmaBuster/pokeplat-gen2-old | 01e42c55db5408d72d89133dc84a46c699d849ad | [
"blessing"
] | 3 | 2021-01-15T18:45:40.000Z | 2021-10-16T03:35:27.000Z | tilepal 0, GRAY, RED, GRAY, WATER, WATER, WATER, ROOF, ROOF
tilepal 0, GRAY, GRAY, GRAY, GRAY, GRAY, WATER, WATER, WATER
tilepal 0, GRAY, RED, RED, WATER, WATER, WATER, WATER, WATER
tilepal 0, GRAY, GRAY, GRAY, GRAY, GRAY, GREEN, GREEN, GRAY
tilepal 0, GRAY, GRAY, RED, RED, WATER, WATER, GRAY, GRAY
tilepal 0, GRAY, GRAY, BROWN, BROWN, GRAY, GRAY, GRAY, GRAY
tilepal 0, GRAY, GRAY, RED, RED, GRAY, WATER, WATER, WATER
tilepal 0, WATER, WATER, WATER, WATER, GRAY, GRAY, WATER, GRAY
tilepal 0, GRAY, GRAY, RED, RED, RED, RED, WATER, WATER
tilepal 0, YELLOW, YELLOW, GRAY, GRAY, GRAY, RED, RED, GRAY
tilepal 0, RED, RED, RED, RED, RED, RED, GRAY, GRAY
tilepal 0, YELLOW, YELLOW, GRAY, GRAY, GRAY, GRAY, GRAY, GRAY
rept 32
db $ff
endr
tilepal 1, GRAY, RED, GRAY, WATER, WATER, WATER, ROOF, ROOF
tilepal 1, GRAY, GRAY, GRAY, GRAY, GRAY, WATER, WATER, WATER
tilepal 1, GRAY, RED, RED, WATER, WATER, WATER, WATER, WATER
tilepal 1, GRAY, GRAY, GRAY, GRAY, GRAY, GREEN, GREEN, GRAY
tilepal 1, GRAY, GRAY, RED, RED, WATER, WATER, GRAY, GRAY
tilepal 1, GRAY, GRAY, BROWN, BROWN, GRAY, GRAY, GRAY, GRAY
tilepal 1, GRAY, GRAY, RED, RED, GRAY, WATER, WATER, WATER
tilepal 1, WATER, WATER, WATER, WATER, GRAY, GRAY, WATER, GRAY
tilepal 1, GRAY, GRAY, RED, RED, RED, RED, WATER, WATER
tilepal 1, YELLOW, YELLOW, GRAY, GRAY, GRAY, RED, RED, GRAY
tilepal 1, RED, RED, RED, RED, RED, RED, GRAY, GRAY
tilepal 1, YELLOW, YELLOW, GRAY, GRAY, GRAY, GRAY, GRAY, GRAY
| 49.033333 | 63 | 0.683889 |
68f294fc199e78168ec10aa33559e1c9a622e67c | 1,068 | sql | SQL | admin/rwlsynonyms.sql | MarkkuPekkarinen/rwloadsim | 6a0be379806bde923a93208a627e750267f7eed0 | [
"UPL-1.0"
] | 27 | 2021-01-13T13:08:39.000Z | 2022-03-16T09:45:29.000Z | admin/rwlsynonyms.sql | MarkkuPekkarinen/rwloadsim | 6a0be379806bde923a93208a627e750267f7eed0 | [
"UPL-1.0"
] | 1 | 2021-01-18T09:07:18.000Z | 2021-01-18T11:16:42.000Z | admin/rwlsynonyms.sql | MarkkuPekkarinen/rwloadsim | 6a0be379806bde923a93208a627e750267f7eed0 | [
"UPL-1.0"
] | 9 | 2021-01-12T20:56:04.000Z | 2022-02-18T01:04:24.000Z | -- create synonyms to RWP*Load Simulator repository schema
--
-- Copyright (c) 2021 Oracle Corporation
-- Licensed under the Universal Permissive License v 1.0
-- as shown at https://oss.oracle.com/licenses/upl/
-- History
-- bengsig 03-dec-2020 - Add ash
-- bengsig 2017 - Creation
--
-- If you have an extra users granted access to the
-- rwloadsim repository, run this to create synonyms
-- and also run rwlviews.sql
--
create or replace synonym HISTOGRAM for rwloadsim.HISTOGRAM;
create or replace synonym PERSEC for rwloadsim.PERSEC;
create or replace synonym RUNCPU for rwloadsim.RUNCPU;
create or replace synonym RUNRES for rwloadsim.RUNRES;
create or replace synonym RWLCPU for rwloadsim.RWLCPU;
create or replace synonym RWLRUN for rwloadsim.RWLRUN;
create or replace synonym SYSRES for rwloadsim.SYSRES;
create or replace synonym rwlash for rwloadsim.rwlash;
create or replace synonym ashdata for rwloadsim.ashdata;
create or replace synonym oerstats for rwloadsim.oerstats;
create or replace synonym runnumber_seq for rwloadsim.runnumber_seq;
| 38.142857 | 68 | 0.789326 |
2f73500194aba972fbb98183bfcae14fad2c0ea8 | 12,906 | php | PHP | app/Http/Controllers/HomeController.php | harishdurga/laravel-video-chat | 4829e98dd41e09409d2fdc82efbf7eff568ba891 | [
"MIT"
] | 58 | 2020-06-15T10:47:59.000Z | 2022-03-25T20:30:06.000Z | app/Http/Controllers/HomeController.php | bhaskardas9475/laravel-video-chat | 4829e98dd41e09409d2fdc82efbf7eff568ba891 | [
"MIT"
] | 7 | 2020-07-11T00:15:56.000Z | 2022-02-27T03:21:16.000Z | app/Http/Controllers/HomeController.php | bhaskardas9475/laravel-video-chat | 4829e98dd41e09409d2fdc82efbf7eff568ba891 | [
"MIT"
] | 18 | 2020-06-15T10:48:55.000Z | 2021-12-30T12:26:20.000Z | <?php
namespace App\Http\Controllers;
use App\User;
use Pusher\Pusher;
use App\SiteSetting;
use App\UserMessage;
use App\FriendRequest;
use App\GoogleLanguage;
use Twilio\Rest\Client;
use App\Events\NewMessage;
use Twilio\Jwt\AccessToken;
use Illuminate\Http\Request;
use Twilio\Jwt\Grants\VideoGrant;
use Google\Cloud\Translate\V3\TranslationServiceClient;
class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the application dashboard.
*
* @return \Illuminate\Contracts\Support\Renderable
*/
public function index()
{
return view('home');
}
public function authenticate(Request $request)
{
$socketId = $request->socket_id;
$channelName = $request->channel_name;
$pusher = new Pusher(env('PUSHER_APP_KEY'), env('PUSHER_APP_SECRET'), env('PUSHER_APP_ID'), [
'cluster' => env('PUSHER_APP_CLUSTER'),
'encrypted' => true
]);
$presence_data = ['name' => auth()->user()->name];
$key = $pusher->presence_auth($channelName, $socketId, auth()->id(), $presence_data);
return response($key);
}
public function testTranslation($message = '', $sender_lang = "en", $recipient_lang = "en")
{
$translation = "";
if ($sender_lang == $recipient_lang) {
return $message;
}
try {
putenv('GOOGLE_APPLICATION_CREDENTIALS=' . env('GOOGLE_APPLICATION_CREDENTIALS'));
$translationClient = new TranslationServiceClient();
$content = [$message];
$targetLanguage = $recipient_lang;
$response = $translationClient->translateText(
$content,
$targetLanguage,
TranslationServiceClient::locationName(env('GOOGLE_PROJECT_ID', ''), 'global'),
[
'sourceLanguageCode' => $sender_lang
]
);
$translation = $response->getTranslations()[0]->getTranslatedText();
// foreach ($response->getTranslations() as $key => $translation) {
// echo $translation->getTranslatedText();
// }
} catch (\Throwable $th) {
\Log::error($th->getMessage());
}
return $translation;
}
public function sendNewMessage(Request $request)
{
$recipient = User::find($request->recipient_id);
$translation = $this->testTranslation($request->message, auth()->user()->preferred_language, $recipient->preferred_language);
$user_message = new UserMessage();
$user_message->sender_id = auth()->user()->id;
$user_message->recipient_id = $recipient->id;
$user_message->message = $request->message;
$user_message->translated_message = $translation;
$user_message->org_lang = auth()->user()->preferred_language;
$user_message->trans_lang = $recipient->preferred_language;
$user_message->status = 0;
try {
$user_message->save();
} catch (\Throwable $th) {
\Log::error($th->getMessage());
}
event(new NewMessage(
[
'message' => $request->message,
'sender' => auth()->user()->name,
'recipient_id' => $request->recipient_id,
'sender_id' => auth()->user()->id,
'translated_message' => $translation,
'time' => date('d-m-Y H:i:s')
]
));
return response()->json(
[
'message' => $request->message,
'sender' => auth()->user()->name,
'recipient_id' => $request->recipient_id,
'sender_id' => auth()->user()->id,
'translated_message' => $translation,
'time' => date('d-m-Y H:i:s')
]
);
}
public function getMyProfile()
{
$user = auth()->user();
$languages = GoogleLanguage::where('enabled', 1)->get();
return view('my_profile', compact('user', 'languages'));
}
public function saveMyProfile(Request $request)
{
$validatedData = $request->validate([
'name' => 'required|max:191',
'preferred_language' => 'required|max:10',
]);
$user = User::find(auth()->user()->id);
if ($user) {
$user->name = $request->name;
$user->preferred_language = $request->preferred_language;
if ($user->save()) {
flash("User information successfully updated!")->success();
} else {
flash("Unable to save the user information!")->error();
}
} else {
flash("Unable to find the user!")->error();
}
return redirect()->back();
}
public function getInitData()
{
$friendsQuery = FriendRequest::getUserFriends(auth()->user()->id);
$friends = [];
if ($friendsQuery->count()) {
foreach ($friendsQuery as $key => $value) {
if ($value->sender->id != auth()->user()->id) {
$friends[] = [
'id' => $value->sender->id,
'name' => $value->sender->name,
'is_selected' => false,
'is_online' => $value->sender->is_online,
'new_message' => false,
'unread_message_count' => UserMessage::getUnreadMessageCount($value->sender->id, auth()->user()->id)
];
} else {
$friends[] = [
'id' => $value->recipient->id,
'name' => $value->recipient->name,
'is_selected' => false,
'is_online' => $value->recipient->is_online,
'new_message' => false,
'unread_message_count' => UserMessage::getUnreadMessageCount($value->recipient->id, auth()->user()->id)
];
}
}
}
return response()->json(['friends' => $friends]);
}
public function getPreviousMessages($id)
{
$previous_messages = [];
$messagesQuery = UserMessage::where(function ($query) use ($id) {
$query->where('sender_id', auth()->user()->id);
$query->where('recipient_id', $id);
})->orWhere(function ($query) use ($id) {
$query->where('sender_id', $id);
$query->where('recipient_id', auth()->user()->id);
})->with('sender')->with('recipient')->orderBy('created_at', 'DESC')->limit(50)->get();
if ($messagesQuery->count() > 0) {
foreach ($messagesQuery as $key => $value) {
$previous_messages[] = [
'message' => $value->message,
'sender' => $value->sender->name,
'recipient_id' => $value->recipient->id,
'sender_id' => $value->sender->id,
'translated_message' => $value->translated_message,
'time' => date('d-m-Y H:i:s', strtotime($value->created_at))
];
}
}
$previous_messages = array_reverse($previous_messages);
return \response()->json(['previous_messages' => $previous_messages]);
}
public function searchUsers(Request $request)
{
$users = [];
if (!empty($request->keyword)) {
$userId = auth()->user()->id;
$usersQuery = User::select('id', 'name', 'email')->where('email', 'like', "%$request->keyword%")->where('id', '!=', $userId)->get();
$friendsQuery = FriendRequest::select('sender_id', 'recipient_id')->where(function ($query) use ($userId) {
$query->where('sender_id', $userId);
$query->orWhere('recipient_id', $userId);
})->where('accepted', 1)->get();
$friendIds = [];
foreach ($friendsQuery as $key => $value) {
if ($value->sender_id != $userId) {
$friendIds[] = $value->sender_id;
} else {
$friendIds[] = $value->recipient_id;
}
}
foreach ($usersQuery as $key => $value) {
$users[] = [
'id' => $value->id,
'name' => $value->name,
'is_friend' => in_array($value->id, $friendIds)
];
}
}
return response()->json(['users' => $users]);
}
public function addFriend(Request $request)
{
$message = "";
$status = true;
$userId = auth()->user()->id;
$recipientId = $request->user_id;
$frinedRequest = FriendRequest::where('sender_id', $userId)->where('recipient_id', $recipientId)->first();
if ($frinedRequest) {
if ($frinedRequest->accepted == 0) {
$status = false;
$message = "You have already sent a freind request! Please wait for the user to accept it";
} elseif ($frinedRequest->accepted == 1) {
$status = false;
$message = "You are already friends with the user!";
} elseif ($frinedRequest->accepted == -1) {
$status = false;
$message = "User rejected your last request!";
}
}
if ($status) {
$frinedRequest = FriendRequest::where('sender_id', $recipientId)->where('recipient_id', $userId)->first();
if ($frinedRequest) {
if ($frinedRequest->accepted == 0) {
$status = false;
$message = "User has sent you a friend request! Please check in your friend requests list!";
} elseif ($frinedRequest->accepted == 1) {
$status = false;
$message = "You are already friends with the user!";
}
}
}
if ($status) {
$frinedRequest = new FriendRequest();
$frinedRequest->sender_id = $userId;
$frinedRequest->recipient_id = $recipientId;
$frinedRequest->accepted = 0;
if ($frinedRequest->save()) {
$message = "Friend request sent to the user!";
} else {
$status = false;
$message = "Unable to send friend request to user!";
}
}
return response()->json(['status' => $status, 'message' => $message]);
}
public function friendRequests()
{
$frinedRequestsQuery = FriendRequest::where(['recipient_id' => auth()->user()->id, 'accepted' => 0])->with('sender')->get();
$frinedRequests = [];
if ($frinedRequestsQuery->count()) {
foreach ($frinedRequestsQuery as $key => $value) {
$frinedRequests[] = ['id' => $value->id, 'name' => $value->sender->name];
}
}
return response()->json(['requests' => $frinedRequests]);
}
public function acceptRejectPost(Request $request)
{
$status = false;
$message = "";
$frinedRequest = FriendRequest::where(['id' => $request->id, 'recipient_id' => auth()->user()->id])->first();
if ($frinedRequest) {
$frinedRequest->accepted = ($request->action == true) ? 1 : -1;
if ($frinedRequest->save()) {
$status = true;
$message = "Request successfully " . (($request->action == true) ? 'accepted' : 'rejected');
} else {
$message = "Unable to accept/reject the request!";
}
} else {
$message = "Unable to find the friend request!";
}
return response()->json(['status' => $status, 'message' => $message]);
}
public function getTwilioInitData()
{
$roomName = '';
$roomName = SiteSetting::where('key', 'twillio_room_name')->first();
if ($roomName) {
$roomName = $roomName->value;
} else {
$roomName = "OneToOne";
}
return response()->json([
'twilio_room_name' => $roomName
]);
}
public function markUserMessagesAsRead(Request $request)
{
$status = false;
$message = '';
try {
UserMessage::markMessagesAsRead($request->sender_id, auth()->user()->id);
$status = true;
} catch (\Throwable $th) {
$message = $th->getMessage();
\Log::critical($th->getMessage());
}
return response()->json(['status' => $status, 'message' => $message]);
}
}
| 37.847507 | 144 | 0.504572 |
3bcf02c28b2791ad25da5e5e6b6a835531025762 | 214 | h | C | Example/Test/VSViewController.h | michaelchen73092/Test | 5a37f9ebdc6a6d4d16c5832cfd0f7edd1a2d6c77 | [
"MIT"
] | null | null | null | Example/Test/VSViewController.h | michaelchen73092/Test | 5a37f9ebdc6a6d4d16c5832cfd0f7edd1a2d6c77 | [
"MIT"
] | null | null | null | Example/Test/VSViewController.h | michaelchen73092/Test | 5a37f9ebdc6a6d4d16c5832cfd0f7edd1a2d6c77 | [
"MIT"
] | null | null | null | //
// VSViewController.h
// Test
//
// Created by Wei-Chih Chen on 05/23/2018.
// Copyright (c) 2018 Wei-Chih Chen. All rights reserved.
//
@import UIKit;
@interface VSViewController : UIViewController
@end
| 15.285714 | 58 | 0.691589 |
940c5810c2f811aa9c15a67bf18eec07f9b8c902 | 654 | pks | SQL | 5.2.3/Database/Packages/AFW_12_SCENR_NOTFC_ACTIO_PKG.pks | lgcarrier/AFW | a58ef2a26cb78bb0ff9b4db725df5bd4118e4945 | [
"MIT"
] | 1 | 2017-07-06T14:53:28.000Z | 2017-07-06T14:53:28.000Z | 5.2.3/Database/Packages/AFW_12_SCENR_NOTFC_ACTIO_PKG.pks | lgcarrier/AFW | a58ef2a26cb78bb0ff9b4db725df5bd4118e4945 | [
"MIT"
] | null | null | null | 5.2.3/Database/Packages/AFW_12_SCENR_NOTFC_ACTIO_PKG.pks | lgcarrier/AFW | a58ef2a26cb78bb0ff9b4db725df5bd4118e4945 | [
"MIT"
] | null | null | null | SET DEFINE OFF;
create or replace package afw_12_scenr_notfc_actio_pkg
as
function obten_seqnc (pva_scenr_notfc_code in varchar2
,pva_actio_code in varchar2
,pnu_prodt in vd_i_afw_12_scenr_notfc.ref_prodt%type default afw_11_prodt_pkg.obten_prodt_sesn)
return vd_i_afw_12_scenr_notfc_actio.seqnc%type;
function obten_code (pnu_seqnc in vd_i_afw_12_scenr_notfc.seqnc%type
,pnu_prodt in vd_i_afw_12_scenr_notfc.ref_prodt%type default afw_11_prodt_pkg.obten_prodt_sesn)
return vd_i_afw_12_scenr_notfc.code%type;
end afw_12_scenr_notfc_actio_pkg;
/
| 43.6 | 131 | 0.737003 |
9b9cc93ad63c368a98da31f15060416a7fff3e73 | 3,124 | js | JavaScript | src/utils/audio-visualization/audio-for-pie.js | MeishanGuo/vue-todo-mvc | 114ddac51bd19a14c1a0ea7d05e382c34d996c37 | [
"MIT"
] | 2 | 2018-05-24T08:47:57.000Z | 2019-10-12T07:35:38.000Z | src/utils/audio-visualization/audio-for-pie.js | MeishanGuo/vue-todo-mvc | 114ddac51bd19a14c1a0ea7d05e382c34d996c37 | [
"MIT"
] | 5 | 2020-12-04T17:09:12.000Z | 2022-02-10T13:28:54.000Z | src/utils/audio-visualization/audio-for-pie.js | MeishanGuo/bs-charts | ebf95286811cc522496b1dade69b8b7fabfde80f | [
"MIT"
] | null | null | null |
import ThreeDScene from './index.js'
/**
* 扩展shapes,来创建几何图形
*/
let AudioVis = new ThreeDScene()
AudioVis.cubes = {};
AudioVis.shapes = function () {};
AudioVis.shapes = function() {
this.shapeList.forEach((circle, i) => {
let count = circle.count
var delte = 2 * Math.PI / count
for (var j = 0; j < count; j++) {
var shape = this.shape(circle)
shape.position.x = circle.radius * Math.cos(delte * j)
shape.position.y = circle.radius * Math.sin(delte * j)
shape.rotation.z = delte * j
this.scene.add(shape);
this.cubes['cube_' + i + '_' + j] = shape
}
})
};
/**
* 图形基类
*/
AudioVis.shape = function (config) {
var geometry = new THREE.PlaneGeometry(config.width, config.height, 1, 1);
var material = new THREE.MeshBasicMaterial({
color: config.color,
transparent: true,
opacity: config.opacity !== undefined ? config.opacity : 1
});
return new THREE.Mesh(geometry, material);
}
/**
* 扩展渲染函数,实现动效
*/
AudioVis.render = function() {
// Apply spectrum.
var total = this._getShapeTotal()
this.shapeList.forEach((circle, i) => {
let count = circle.count
var delte = 2 * Math.PI / count
for (var j = 0; j < count; j++) {
var range = this.equalizer.getSpectrumByPercentage(j / total) * circle.range || 1
var shape = this.cubes['cube_' + i + '_' + j]
shape.scale.x = range
shape.position.x = (circle.radius + circle.width * shape.scale.x / 2) * Math.cos(delte * j)
shape.position.y = (circle.radius + circle.width * shape.scale.x / 2) * Math.sin(delte * j)
}
})
// Render scene.
this.renderer.render(this.scene, this.camera);
// Request new frame.
requestAnimationFrame(this.render.bind(this));
}
/**
* 获得节点总数量
*/
AudioVis._getShapeTotal = function () {
var _total = 0
this.shapeList.forEach(circle => {
_total += circle.count
})
return _total
}
/**
* 音响效果配置
*/
function getAudioAniConfig () {
return {
width: 239,
height: 239,
shapeList: [
{
count: 100,
radius: 110,
range: 0.02,
type: 'plane',
color: '#fff',
opacity: 0.3,
width: 2,
height: 2
},
{
count: 100,
radius: 105,
range: 0.01,
type: 'plane',
color: '#fff',
opacity: 0.3,
width: 1,
height: 1
},
{
count: 100,
radius: 102,
range: 0.02,
type: 'plane',
color: '#fff',
opacity: 0.3,
width: 1,
height: 1
},
{
count: 100,
radius: 98,
range: 0.01,
type: 'plane',
color: '#fff',
opacity: 0.3,
width: 1.4,
height: 1.4
}
]
}
}
export default function createAudioForPie (config) {
var _container = config.container || document.body
var _audioUrl = config.audioUrl
var audioAniConfig = getAudioAniConfig()
AudioVis.shapeList = audioAniConfig.shapeList || []
AudioVis.init(_container, audioAniConfig)
AudioVis.equalizer.play(_audioUrl, function () {})
}
| 22.156028 | 97 | 0.56306 |
4010f4c156cc298232cb7a64e839715db36b91ff | 225 | py | Python | GUI/ErrorDialog.py | ishtjot/susereumutep | 56e20c1777e0c938ac42bd8056f84af9e0b76e46 | [
"Apache-2.0"
] | 2 | 2018-11-07T20:52:53.000Z | 2019-10-20T15:57:01.000Z | GUI/ErrorDialog.py | ishtjot/susereumutep | 56e20c1777e0c938ac42bd8056f84af9e0b76e46 | [
"Apache-2.0"
] | 3 | 2021-12-14T20:57:54.000Z | 2022-01-21T23:50:36.000Z | GUI/ErrorDialog.py | ishtjot/susereumutep | 56e20c1777e0c938ac42bd8056f84af9e0b76e46 | [
"Apache-2.0"
] | 2 | 2018-11-16T04:20:06.000Z | 2019-03-28T23:49:13.000Z | import gi; gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
def ErrorDialog(self, message):
d = Gtk.MessageDialog(self, 0, Gtk.MessageType.WARNING, Gtk.ButtonsType.OK, message)
d.run()
d.destroy()
| 25 | 88 | 0.702222 |
0ce9ddf8982fdd13b64038e356850186f884758e | 4,462 | py | Python | go/apps/http_api/tests/test_views.py | lynnUg/vumi-go | 852f906c46d5d26940bd6699f11488b73bbc3742 | [
"BSD-3-Clause"
] | null | null | null | go/apps/http_api/tests/test_views.py | lynnUg/vumi-go | 852f906c46d5d26940bd6699f11488b73bbc3742 | [
"BSD-3-Clause"
] | null | null | null | go/apps/http_api/tests/test_views.py | lynnUg/vumi-go | 852f906c46d5d26940bd6699f11488b73bbc3742 | [
"BSD-3-Clause"
] | null | null | null | from go.apps.tests.view_helpers import AppViewsHelper
from go.base.tests.helpers import GoDjangoTestCase
class TestHttpApiViews(GoDjangoTestCase):
def setUp(self):
self.app_helper = self.add_helper(AppViewsHelper(u'http_api'))
self.client = self.app_helper.get_client()
def test_show_stopped(self):
"""
Test showing the conversation
"""
conv_helper = self.app_helper.create_conversation_helper(
name=u"myconv")
response = self.client.get(conv_helper.get_view_url('show'))
self.assertContains(response, u"<h1>myconv</h1>")
def test_show_running(self):
"""
Test showing the conversation
"""
conv_helper = self.app_helper.create_conversation_helper(
name=u"myconv", started=True)
response = self.client.get(conv_helper.get_view_url('show'))
self.assertContains(response, u"<h1>myconv</h1>")
def test_edit_view(self):
conv_helper = self.app_helper.create_conversation_helper()
conversation = conv_helper.get_conversation()
self.assertEqual(conversation.config, {})
response = self.client.post(conv_helper.get_view_url('edit'), {
'http_api-api_tokens': 'token',
'http_api-push_message_url': 'http://messages/',
'http_api-push_event_url': 'http://events/',
'http_api-metric_store': 'foo_metric_store',
}, follow=True)
self.assertRedirects(response, conv_helper.get_view_url('show'))
reloaded_conv = conv_helper.get_conversation()
self.assertEqual(reloaded_conv.config, {
'http_api': {
'push_event_url': 'http://events/',
'push_message_url': 'http://messages/',
'api_tokens': ['token'],
'metric_store': 'foo_metric_store',
'ignore_events': False,
'ignore_messages': False,
}
})
def test_edit_view_no_event_url(self):
conv_helper = self.app_helper.create_conversation_helper()
conversation = conv_helper.get_conversation()
self.assertEqual(conversation.config, {})
response = self.client.post(conv_helper.get_view_url('edit'), {
'http_api-api_tokens': 'token',
'http_api-push_message_url': 'http://messages/',
'http_api-push_event_url': '',
'http_api-metric_store': 'foo_metric_store',
})
self.assertRedirects(response, conv_helper.get_view_url('show'))
reloaded_conv = conv_helper.get_conversation()
self.assertEqual(reloaded_conv.config, {
'http_api': {
'push_event_url': None,
'push_message_url': 'http://messages/',
'api_tokens': ['token'],
'metric_store': 'foo_metric_store',
'ignore_events': False,
'ignore_messages': False,
}
})
self.assertEqual(conversation.config, {})
response = self.client.get(conv_helper.get_view_url('edit'))
self.assertContains(response, 'http://messages/')
self.assertContains(response, 'foo_metric_store')
self.assertEqual(response.status_code, 200)
def test_edit_view_no_push_urls(self):
conv_helper = self.app_helper.create_conversation_helper()
conversation = conv_helper.get_conversation()
self.assertEqual(conversation.config, {})
response = self.client.post(conv_helper.get_view_url('edit'), {
'http_api-api_tokens': 'token',
'http_api-push_message_url': '',
'http_api-push_event_url': '',
'http_api-metric_store': 'foo_metric_store',
})
self.assertRedirects(response, conv_helper.get_view_url('show'))
reloaded_conv = conv_helper.get_conversation()
self.assertEqual(reloaded_conv.config, {
'http_api': {
'push_event_url': None,
'push_message_url': None,
'api_tokens': ['token'],
'metric_store': 'foo_metric_store',
'ignore_events': False,
'ignore_messages': False,
}
})
self.assertEqual(conversation.config, {})
response = self.client.get(conv_helper.get_view_url('edit'))
self.assertContains(response, 'foo_metric_store')
self.assertEqual(response.status_code, 200)
| 40.93578 | 72 | 0.61385 |
cc03a9e42db7d2b0e00d7c5a64d4e2e6286d98ab | 2,690 | sql | SQL | solarnet-db-setup/postgres/updates/NET-112-jsonb-generic-datum-x-functions.sql | Tsvetelin98/Solar | 350341d4f6a32d53efd48778ee7a8ba89a591978 | [
"Apache-2.0"
] | null | null | null | solarnet-db-setup/postgres/updates/NET-112-jsonb-generic-datum-x-functions.sql | Tsvetelin98/Solar | 350341d4f6a32d53efd48778ee7a8ba89a591978 | [
"Apache-2.0"
] | null | null | null | solarnet-db-setup/postgres/updates/NET-112-jsonb-generic-datum-x-functions.sql | Tsvetelin98/Solar | 350341d4f6a32d53efd48778ee7a8ba89a591978 | [
"Apache-2.0"
] | null | null | null | DROP FUNCTION solardatum.find_most_recent(bigint, text[]);
CREATE OR REPLACE FUNCTION solardatum.find_most_recent(
node bigint,
sources text[] DEFAULT NULL)
RETURNS SETOF solardatum.da_datum_data AS
$BODY$
SELECT dd.* FROM solardatum.da_datum_data dd
INNER JOIN (
-- to speed up query for sources (which can be very slow when queried directly on da_datum),
-- we find the most recent hour time slot in agg_datum_hourly, and then join to da_datum with that narrow time range
SELECT max(d.ts) as ts, d.source_id FROM solardatum.da_datum d
INNER JOIN (SELECT node_id, ts_start, source_id FROM solaragg.find_most_recent_hourly(node, sources)) AS days
ON days.node_id = d.node_id
AND days.ts_start <= d.ts
AND days.ts_start + interval '1 hour' > d.ts
AND days.source_id = d.source_id
GROUP BY d.source_id
) AS r ON r.ts = dd.ts AND r.source_id = dd.source_id AND dd.node_id = node
ORDER BY dd.source_id ASC;
$BODY$
LANGUAGE sql STABLE
ROWS 20;
DROP FUNCTION solardatum.find_most_recent(bigint[]);
CREATE OR REPLACE FUNCTION solardatum.find_most_recent(nodes bigint[])
RETURNS SETOF solardatum.da_datum_data AS
$BODY$
SELECT r.*
FROM (SELECT unnest(nodes) AS node_id) AS n,
LATERAL (SELECT * FROM solardatum.find_most_recent(n.node_id)) AS r
ORDER BY r.node_id, r.source_id;
$BODY$
LANGUAGE sql STABLE;
DROP FUNCTION solardatum.store_datum(timestamp with time zone, bigint, text, timestamp with time zone, text);
CREATE OR REPLACE FUNCTION solardatum.store_datum(
cdate timestamp with time zone,
node bigint,
src text,
pdate timestamp with time zone,
jdata text)
RETURNS void LANGUAGE plpgsql VOLATILE AS
$BODY$
DECLARE
ts_crea timestamp with time zone := COALESCE(cdate, now());
ts_post timestamp with time zone := COALESCE(pdate, now());
jdata_json jsonb := jdata::jsonb;
jdata_prop_count integer := solardatum.datum_prop_count(jdata_json);
ts_post_hour timestamp with time zone := date_trunc('hour', ts_post);
BEGIN
INSERT INTO solardatum.da_datum(ts, node_id, source_id, posted, jdata_i, jdata_a, jdata_s, jdata_t)
VALUES (ts_crea, node, src, ts_post, jdata_json->'i', jdata_json->'a', jdata_json->'s', solarcommon.json_array_to_text_array(jdata_json->'t'))
ON CONFLICT (node_id, ts, source_id) DO UPDATE
SET jdata_i = EXCLUDED.jdata_i,
jdata_a = EXCLUDED.jdata_a,
jdata_s = EXCLUDED.jdata_s,
jdata_t = EXCLUDED.jdata_t,
posted = EXCLUDED.posted;
INSERT INTO solaragg.aud_datum_hourly (
ts_start, node_id, source_id, prop_count)
VALUES (ts_post_hour, node, src, jdata_prop_count)
ON CONFLICT (node_id, ts_start, source_id) DO UPDATE
SET prop_count = aud_datum_hourly.prop_count + EXCLUDED.prop_count;
END;
$BODY$;
| 40.149254 | 143 | 0.763941 |
b2d171ee084b4ded299d8d9b2d8e8e0fa604218a | 213 | py | Python | src/about.py | jukeboxroundtable/JukeboxRoundtable | 06670d2e8511848829b68fddac5bc77806606f98 | [
"MIT"
] | 1 | 2019-02-15T17:33:51.000Z | 2019-02-15T17:33:51.000Z | src/about.py | jukeboxroundtable/JukeboxRoundtable | 06670d2e8511848829b68fddac5bc77806606f98 | [
"MIT"
] | 37 | 2019-01-30T18:32:43.000Z | 2019-06-11T18:00:11.000Z | src/about.py | jukeboxroundtable/JukeboxRoundtable | 06670d2e8511848829b68fddac5bc77806606f98 | [
"MIT"
] | null | null | null | from flask import Blueprint, render_template
about_blueprint = Blueprint('about', __name__)
@about_blueprint.route('/about')
def about():
"""Show the about page."""
return render_template('about.html')
| 21.3 | 46 | 0.7277 |
1b14694d4cf2270aee12fed9ab4327fe80f9f961 | 5,943 | swift | Swift | src/testrunner/Sources/TestRunner/TestParsers.swift | desi-belokonska/swift-test-runner | 7a336d24d7ea9cacf0c2f2c41f520747b204f0b9 | [
"MIT"
] | null | null | null | src/testrunner/Sources/TestRunner/TestParsers.swift | desi-belokonska/swift-test-runner | 7a336d24d7ea9cacf0c2f2c41f520747b204f0b9 | [
"MIT"
] | null | null | null | src/testrunner/Sources/TestRunner/TestParsers.swift | desi-belokonska/swift-test-runner | 7a336d24d7ea9cacf0c2f2c41f520747b204f0b9 | [
"MIT"
] | null | null | null | //
// TestParsers.swift
//
//
// Created by William Neumann on 5/13/20.
//
import Foundation
// MARK: - Test Case Parsing
let suiteAndCase = zip(
with: { (suite: String($0), case: String($1)) },
Parser.keep(prefix(until: { $0.isWhitespace }), discard: Parser.whitespace),
prefix(until: { $0 == "]" })
)
let caseNameParser = zip(
with: { (open: $0, suiteAndCase: $1, close: $2) },
Parser.choose(Parser.string("'-["), Parser.string("'")),
suiteAndCase,
Parser.choose(Parser.string("]' "), Parser.string("' "))
)
let testNameParser: Parser<(open: String, name: String, close: String)> =
Parser.choose(Parser.string("'-["), Parser.string("'")).flatMap { openDelim in
zip(
with: { name, closeDelim, _, _ in (open: openDelim, name: String(name), close: closeDelim) },
prefix(until: openDelim == "'" ? { $0 == "'" } : { $0 == "]" }),
openDelim == "'" ? Parser.string("'") : Parser.string("]'"),
prefix(until: { $0 == "\n" }),
Parser.literal("\n")
)
}
//Parser.discard(Parser.choose(Parser.literal("'-["), Parser.literal("'")), keep: Parser.keep(suiteAndCase, discard: Parser.choose(Parser.literal("]' "), Parser.literal("' "))))
let caseStartParser = Parser.discard(Parser.literal("Test Case "), keep: testNameParser)
let caseMessageParser = Parser.keep(
Parser.star(
Parser.discard(not(Parser.literal("Test Case")), keep: prefix(until: { $0 == "\n" })),
separatedBy: Parser.literal("\n")), discard: Parser.star(Parser.literal("\n")))
let caseParser: Parser<(String, [String], Either<String, Void>)> = caseStartParser.flatMap {
caseNames in
let caseFinishParser = Parser.discard(
Parser.literal("Test Case \(caseNames.open)\(caseNames.name)\(caseNames.close) "),
keep: Parser.keep(
Parser.choice([Parser.string("passed"), Parser.string("failed"), Parser.string("skipped")]),
discard: drop(while: { $0 != "\n" })))
let caseEndParser = Parser.either(
caseFinishParser, Parser.discard(Parser.star(Parser.whitespace), keep: Parser.end))
let messageFinishParser = zip(caseMessageParser, caseEndParser).map { result in
(caseNames.name, result.0.map { String($0) }, result.1)
}
return messageFinishParser
}
let testCaseParser = Parser.star(caseParser.map(TestCase.init), separatedBy: Parser.literal("\n"))
// MARK: - Test Suite Parsing
let suiteNameParser = Parser.keep(
Parser.discard(Parser.literal("'"), keep: prefix(until: { $0 == "'" })),
discard: Parser.literal("'"))
let suiteLineParser =
Parser.discard(Parser.literal("Test Suite "), keep: suiteNameParser)
let suiteStartParser = Parser.keep(
Parser.discard(Parser.literal(" started at "), keep: prefix(until: { $0 == "\n" })),
discard: Parser.literal("\n"))
let openSuiteParser = zip(
with: { name, startTime in
(String(name), startTimeFormatter.date(from: String(startTime)) ?? Date())
},
suiteLineParser,
suiteStartParser)
let suiteParser = openSuiteParser.flatMap { (nameAndDate) -> Parser<TestSuite> in
let closeParser =
Parser.discard(
Parser.literal("Test Suite '\(nameAndDate.0)' "),
keep: Parser.choose(Parser.string("passed"), Parser.string("failed")).map { str in
String(str.prefix(4))
}
)
let skipLine = zip(prefix(until: { $0 == "\n" }), Parser.choose(Parser.literal("\n"), Parser.end))
let endSuite = Parser.choose(
Parser.keep(closeParser, discard: skipLine), Parser.end.flatMap { Parser.always("error") })
return Parser.keep(zip(testCaseParser.eatNewline(), endSuite), discard: skipLine).map {
(casesAndStatus) -> TestSuite in
let status = TestStatus(rawValue: casesAndStatus.1) ?? .error
return TestSuite(
name: nameAndDate.0, startTime: nameAndDate.1, status: status, cases: casesAndStatus.0)
}
}
// MARK: - Package Suite Parser
let packageSuiteParser = openSuiteParser.flatMap { (nameAndDate) -> Parser<PackageSuite> in
let closeParser =
Parser.discard(
Parser.literal("Test Suite '\(nameAndDate.0)' "),
keep: Parser.choose(Parser.string("passed"), Parser.string("failed")).map { str in
String(str.prefix(4))
}
)
let skipLine = zip(prefix(until: { $0 == "\n" }), Parser.choose(Parser.literal("\n"), Parser.end))
let endSuite = Parser.choose(
Parser.keep(closeParser, discard: skipLine), Parser.end.flatMap { Parser.always("error") })
return Parser.keep(zip(Parser.plus(suiteParser), endSuite), discard: skipLine).map {
(suitesAndStatus) -> PackageSuite in
let status = TestStatus(rawValue: suitesAndStatus.1) ?? .error
return PackageSuite(
name: nameAndDate.0, startTime: nameAndDate.1, status: status, testSuites: suitesAndStatus.0)
}
}
// MARK: - All Tests Parser
let allTestsParser = openSuiteParser.flatMap { (nameAndDate) -> Parser<TestResult> in
let closeParser =
Parser.discard(
Parser.literal("Test Suite '\(nameAndDate.0)' "),
keep: Parser.choose(Parser.string("passed"), Parser.string("failed")).map { str in
String(str.prefix(4))
}
)
let skipLine = zip(prefix(until: { $0 == "\n" }), Parser.choose(Parser.literal("\n"), Parser.end))
// let endSuite = Parser.keep(closeParser, discard: skipLine)
let endSuite = Parser.choose(
Parser.keep(closeParser, discard: skipLine), Parser.end.flatMap { Parser.always("error") })
return Parser.keep(zip(Parser.plus(packageSuiteParser), endSuite), discard: skipLine).map {
(packages) -> TestResult in
let status = TestStatus(rawValue: packages.1) ?? .error //== "passed" ? TestStatus.passed : .failed
return TestResult(
startTime: nameAndDate.1, status: status, testSuites: packages.0, message: nil)
}
}
let stepLineParser = zip(
Parser.literal("["),
Parser.int,
Parser.literal("/"),
Parser.int,
Parser.literal("]"),
chomp(until: { $0 == "\n" }),
Parser.literal("\n")
)
let stepFreeParser = Parser.discard(Parser.star(stepLineParser), keep: Parser.rest.map(String.init))
| 40.986207 | 177 | 0.66633 |
f30969f2f38ecec9d56dd34627ea342a0674b713 | 547 | swift | Swift | YooKassaPayments/Private/Atomic Design/Molecules/ItemViews/SwitchItemView/SwitchItemViewIO.swift | instasergio/yookassa-payments-swift | 31c4e52c2c1b0fd87c239d7ece70a05b74641ac3 | [
"MIT"
] | 14 | 2020-12-17T14:38:16.000Z | 2022-02-18T11:01:50.000Z | YooKassaPayments/Private/Atomic Design/Molecules/ItemViews/SwitchItemView/SwitchItemViewIO.swift | instasergio/yookassa-payments-swift | 31c4e52c2c1b0fd87c239d7ece70a05b74641ac3 | [
"MIT"
] | 54 | 2020-12-09T14:52:15.000Z | 2022-03-30T08:16:36.000Z | YooKassaPayments/Private/Atomic Design/Molecules/ItemViews/SwitchItemView/SwitchItemViewIO.swift | instasergio/yookassa-payments-swift | 31c4e52c2c1b0fd87c239d7ece70a05b74641ac3 | [
"MIT"
] | 16 | 2021-01-26T09:28:31.000Z | 2022-01-25T01:08:48.000Z | /// SwitchItemView input protocol
protocol SwitchItemViewInput: AnyObject {
/// Textual content
var title: String { get set }
/// Switch state
var state: Bool { get set }
}
/// SwitchItemView output protocol
protocol SwitchItemViewOutput: AnyObject {
/// Tells output that switch state is changed
///
/// - Parameter itemView: An item view object informing the output
/// - state: New switch state
func switchItemView(_ itemView: SwitchItemViewInput,
didChangeState state: Bool)
}
| 26.047619 | 70 | 0.667276 |
7dcc1743fbe8744d784302fe57d519a7fda04d00 | 716 | kt | Kotlin | src/test/kotlin/io/frontierrobotics/gps/PositionSpecs.kt | andycondon/gis-service | 8aa9e73b160e10eca5f57236f9b0abeadb5dcbc4 | [
"MIT"
] | 2 | 2016-03-10T03:40:20.000Z | 2016-03-14T02:10:37.000Z | src/test/kotlin/io/frontierrobotics/gps/PositionSpecs.kt | andycondon/gis-service | 8aa9e73b160e10eca5f57236f9b0abeadb5dcbc4 | [
"MIT"
] | 1 | 2017-12-24T10:36:30.000Z | 2017-12-25T17:49:25.000Z | src/test/kotlin/io/frontierrobotics/gps/PositionSpecs.kt | andycondon/gis-service | 8aa9e73b160e10eca5f57236f9b0abeadb5dcbc4 | [
"MIT"
] | null | null | null | package io.frontierrobotics.gps
import io.frontierrobotics.gps.Direction.NORTH
import io.frontierrobotics.gps.Direction.WEST
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.it
import org.jetbrains.spek.api.dsl.on
import kotlin.test.assertEquals
class PositionSpecs : Spek({
describe("a position")
{
val position = Position(Angle(NORTH, 41, 10.1833), Angle(WEST, 104, 49.5843))
on("calling toGmaps")
{
val gmaps = position.toGmaps()
it("should return the correct result")
{
assertEquals("41.16972166670693,-104.826404999627", gmaps)
}
}
}
}) | 27.538462 | 85 | 0.660615 |
7f8297dde48b77ef004e479f3f65dc806c32a6a6 | 1,296 | rs | Rust | src/structure/locator_kind.rs | frehberg/rtps-rs | cafb408a90be6d2323183b6f227dd8a685520483 | [
"Apache-2.0"
] | 3 | 2019-04-24T16:48:37.000Z | 2020-08-03T05:47:02.000Z | src/structure/locator_kind.rs | frehberg/rtps-rs | cafb408a90be6d2323183b6f227dd8a685520483 | [
"Apache-2.0"
] | null | null | null | src/structure/locator_kind.rs | frehberg/rtps-rs | cafb408a90be6d2323183b6f227dd8a685520483 | [
"Apache-2.0"
] | null | null | null | #[derive(Clone, Debug, Eq, PartialEq, Readable, Writable)]
pub struct LocatorKind_t {
value: i32,
}
impl LocatorKind_t {
pub const LOCATOR_KIND_INVALID: LocatorKind_t = LocatorKind_t { value: -1 };
pub const LOCATOR_KIND_RESERVED: LocatorKind_t = LocatorKind_t { value: 0 };
pub const LOCATOR_KIND_UDPv4: LocatorKind_t = LocatorKind_t { value: 1 };
pub const LOCATOR_KIND_UDPv6: LocatorKind_t = LocatorKind_t { value: 2 };
}
#[cfg(test)]
mod tests {
use super::*;
serialization_test!( type = LocatorKind_t,
{
locator_kind_invalid,
LocatorKind_t::LOCATOR_KIND_INVALID,
le = [0xFF, 0xFF, 0xFF, 0xFF],
be = [0xFF, 0xFF, 0xFF, 0xFF]
},
{
locator_kind_reserved,
LocatorKind_t::LOCATOR_KIND_RESERVED,
le = [0x00, 0x00, 0x00, 0x00],
be = [0x00, 0x00, 0x00, 0x00]
},
{
locator_kind_udpv4,
LocatorKind_t::LOCATOR_KIND_UDPv4,
le = [0x01, 0x00, 0x00, 0x00],
be = [0x00, 0x00, 0x00, 0x01]
},
{
locator_kind_udpv6,
LocatorKind_t::LOCATOR_KIND_UDPv6,
le = [0x02, 0x00, 0x00, 0x00],
be = [0x00, 0x00, 0x00, 0x02]
}
);
}
| 29.454545 | 80 | 0.56713 |
cb0c5bfee8532be0e0062dee3e8db14ba9f5759e | 764 | sql | SQL | init/procedures/Ignore/CreateException.sql | devnw/aegis | 61a1ad3018e3df4e1fb872285236647aa496c287 | [
"Apache-2.0"
] | null | null | null | init/procedures/Ignore/CreateException.sql | devnw/aegis | 61a1ad3018e3df4e1fb872285236647aa496c287 | [
"Apache-2.0"
] | null | null | null | init/procedures/Ignore/CreateException.sql | devnw/aegis | 61a1ad3018e3df4e1fb872285236647aa496c287 | [
"Apache-2.0"
] | null | null | null | DROP PROCEDURE IF EXISTS `CreateException`;
CREATE PROCEDURE `CreateException` (inSourceID VARCHAR(36), inOrganizationID VARCHAR(36), inTypeID INT, inVulnerabilityID NVARCHAR(120), inDeviceID VARCHAR(36), inDueDate DATETIME, inApproval NVARCHAR(120), inActive BIT, inPort NVARCHAR(15), inCreatedBy NVARCHAR(255))
#BEGIN#
INSERT INTO `Ignore` (SourceId, OrganizationId, TypeId, VulnerabilityId, DeviceId, DueDate, Approval, Active, Port, CreatedBy, DBCreatedDate)
VALUE (inSourceID, inOrganizationID, inTypeID, inVulnerabilityID, inDeviceID, inDueDate, inApproval, inActive, inPort, inCreatedBy, NOW())
ON DUPLICATE KEY UPDATE TypeId = inTypeID, DueDate = inDueDate, Approval = inApproval, Active = inActive, UpdatedBy = inCreatedBy,DBUpdatedDate = NOW(); | 95.5 | 268 | 0.791885 |
b419048df43155e4e2bf1b5845f7d5343d4885ed | 575 | sql | SQL | presto-native-execution/src/test/resources/tpch/queries/q16.sql | shrinidhijoshi/presto | 34437ceaed40f32d50c90cfff320f5286ce8cfa2 | [
"Apache-2.0"
] | 1 | 2021-12-13T18:44:43.000Z | 2021-12-13T18:44:43.000Z | presto-native-execution/src/test/resources/tpch/queries/q16.sql | shrinidhijoshi/presto | 34437ceaed40f32d50c90cfff320f5286ce8cfa2 | [
"Apache-2.0"
] | null | null | null | presto-native-execution/src/test/resources/tpch/queries/q16.sql | shrinidhijoshi/presto | 34437ceaed40f32d50c90cfff320f5286ce8cfa2 | [
"Apache-2.0"
] | null | null | null | -- TPC-H/TPC-R Parts/Supplier Relationship Query (Q16)
-- Functional Query Definition
-- Approved February 1998
select
p.brand,
p.type,
p.size,
count(distinct ps.suppkey) as supplier_cnt
from
partsupp as ps,
part as p
where
p.partkey = ps.partkey
and p.brand <> 'Brand#45'
and p.type not like 'MEDIUM POLISHED%'
and p.size in (49, 14, 23, 45, 19, 3, 36, 9)
and ps.suppkey not in (
select
suppkey
from
supplier
where
comment like '%Customer%Complaints%'
)
group by
p.brand,
p.type,
p.size
order by
supplier_cnt desc,
p.brand,
p.type,
p.size;
| 16.911765 | 54 | 0.688696 |
95c6ae4921c248c1a102b848c9000410c2232038 | 1,463 | html | HTML | application/admin/view/news/photos.html | 201506dongzehao/thinkph-wx | a44ba1d76976e34615725ddc29788dd354111314 | [
"Apache-2.0"
] | null | null | null | application/admin/view/news/photos.html | 201506dongzehao/thinkph-wx | a44ba1d76976e34615725ddc29788dd354111314 | [
"Apache-2.0"
] | null | null | null | application/admin/view/news/photos.html | 201506dongzehao/thinkph-wx | a44ba1d76976e34615725ddc29788dd354111314 | [
"Apache-2.0"
] | null | null | null |
<div class="crumb-wrap">
<div class="crumb-list"><i class="icon-font"></i>
<a href="index.html">首页</a>
<span class="crumb-step">>
</span><a class="crumb-name" href="http://dzhao.wywwwxm.com/thinkphp/public/index.php//admin/news/material">素材管理</a><span class="crumb-step">>
</span><span>图片</span></div>
</div>
<div class="result-wrap">
<div class="result-content" >
<form action="http://dzhao.wywwwxm.com/thinkphp/public/index.php/admin/news/uploadi" method="post" id="myform" name="myform" enctype="multipart/form-data" style="height: 600px;">
<table width="100%">
<tr>
<input type="file" name="image" /> <br>
<input type="submit" name="submit" value="本地上传">
</tr>
<tr>
<hr>
</tr>
<!--</tbody>-->
</table>
<div style="width: 900px; height: 140px;">
{volist name="image" id="vo" mod="4"}
<div style="width:25%;height:100%;float:left;margin-bottom:50px"><img src="http://dzhao.wywwwxm.com/thinkphp/public/{$vo.image}" alt="" height="140px" width="140px"></div>
<!--<i class="icon-font"></i><a href="">删除</a>-->
{eq name="mod" value="3"}{/eq}
{/volist}
</div>
</form>
</div>
</div>
| 45.71875 | 188 | 0.488722 |
2a2611155cba30717e570814d6b53bac008adf46 | 4,278 | java | Java | JavaEE/Code/FileUploadTools/src/main/java/com/ztiany/servlet/FileUploadServlet.java | hiloWang/notes | 64a637a86f734e4e80975f4aa93ab47e8d7e8b64 | [
"Apache-2.0"
] | 2 | 2020-10-08T13:22:08.000Z | 2021-07-28T14:45:41.000Z | JavaEE/FileUploadTools/src/main/java/com/ztiany/servlet/FileUploadServlet.java | flyfire/Programming-Notes-Code | 4b1bdd74c1ba0c007c504834e4508ec39f01cd94 | [
"Apache-2.0"
] | null | null | null | JavaEE/FileUploadTools/src/main/java/com/ztiany/servlet/FileUploadServlet.java | flyfire/Programming-Notes-Code | 4b1bdd74c1ba0c007c504834e4508ec39f01cd94 | [
"Apache-2.0"
] | 6 | 2020-08-20T07:19:17.000Z | 2022-03-02T08:16:21.000Z | package com.ztiany.servlet;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.UUID;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author Ztiany
* Email ztiany3@gmail.com
* Date 17.7.7 22:24
*/
public class FileUploadServlet extends HttpServlet {
private static final long serialVersionUID = 2944809556494489970L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
Utils.setUTF8Encode(request, response);
try {
boolean isMultipartContent = ServletFileUpload.isMultipartContent(request);
if (!isMultipartContent) {
response.getWriter().write("你的表单的enctype必须是multipart/form-data");
return;
}
//创建DiskFileItemFactory对象:设置一些上传环境
DiskFileItemFactory factory = new DiskFileItemFactory();
//factory.setRepository(new File("D:\\dev_file"));//改变临时文件的存放目录
factory.setSizeThreshold(4 * 1024);//缓存大小
ServletFileUpload sfu = new ServletFileUpload(factory);
sfu.setFileSizeMax(10 * 1024 * 1024);//限制单个文件的大小
sfu.setSizeMax(100 * 1024 * 1024);//限制总文件的大小
@SuppressWarnings("unchecked")
List<FileItem> items = sfu.parseRequest(request);
for (FileItem item : items) {
if (item.isFormField()) {
//如果是普通表单字段
processFormFiled(item);
} else {
//处理文件
processUploadFile(item, request);
}
}
response.getWriter().write("文件上传成功");
} catch (FileUploadBase.FileSizeLimitExceededException e) {
response.getWriter().write("upload file can not over 10M");
} catch (FileUploadBase.SizeLimitExceededException e) {
response.getWriter().write("all upload file can not over 100M");
} catch (Exception e) {
e.printStackTrace();
}
}
private void processUploadFile(FileItem item, @SuppressWarnings("unused") HttpServletRequest request) throws Exception {
//设置上传文件的存储目录 放在WEB-INF目录下安全
String directory = getServletContext().getRealPath("WEB-INF/files");
File file = new File(directory);
if (!file.exists()) {
boolean mkdirs = file.mkdirs();//创建目录
System.out.println("mkdirs:" + mkdirs);
}
String filedName = item.getName();//获取表单字段名 c:/a.txt a.txt 根据浏览器不同而不同
//为了保证上传文件不被以后上传文件 因为同名而被覆盖 应该给文件名前面加上唯一的UUID
if (filedName != null) {
filedName = UUID.randomUUID().toString() + "_" + FilenameUtils.getName(filedName);
//同一个文件夹 里不能存储太多文件,否者不好管理
int hashCode = filedName.hashCode();
int dir1 = hashCode & 0XF;//一级目录,取最低四位,0~15共16个
int dir2 = (hashCode & 0XF0) >> 4;//二级目录,取5-8位,0~15共16个
File dir = new File(file, dir1 + "/" + dir2);
if (!dir.exists()) {
boolean mkdirs = dir.mkdirs();
System.out.println("mkdirs:" + mkdirs);
}
//打印一下文件的类型
String type = item.getContentType(); //IE会根据文件内容来判断文件类型
System.out.println(type);
//jpg后缀名的文本 得到的文件类型 还是文本类型 其他浏览器不一定
//使用item.write方法,会自动删除临时文件
item.write(new File(dir, filedName));
}
}
private void processFormFiled(FileItem item) throws UnsupportedEncodingException {
String filedName = item.getFieldName();
String filedValue = item.getString("UTF-8");//Tomcat6/7默认使用IOS-8869-1查码表,这里设置位UTF-8
System.out.println(filedName + ":" + filedValue);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
doPost(request, response);
}
}
| 36.87931 | 124 | 0.631837 |
0694b555555af51919aaf8336b58ff9a3d702887 | 365 | asm | Assembly | Palmtree.Math.Core.Sint/vs_build/x64_Release/pmc_clone.asm | rougemeilland/Palmtree.Math.Core.Sint | 0895fd4988b146f01ec705e091ef3fd79a721b40 | [
"MIT"
] | null | null | null | Palmtree.Math.Core.Sint/vs_build/x64_Release/pmc_clone.asm | rougemeilland/Palmtree.Math.Core.Sint | 0895fd4988b146f01ec705e091ef3fd79a721b40 | [
"MIT"
] | null | null | null | Palmtree.Math.Core.Sint/vs_build/x64_Release/pmc_clone.asm | rougemeilland/Palmtree.Math.Core.Sint | 0895fd4988b146f01ec705e091ef3fd79a721b40 | [
"MIT"
] | null | null | null | ; Listing generated by Microsoft (R) Optimizing Compiler Version 19.16.27026.1
include listing.inc
INCLUDELIB OLDNAMES
PUBLIC PMC_Clone_X
; COMDAT pdata
pdata SEGMENT
$pdata$PMC_Clone_X DD imagerel $LN17@PMC_Clone_
DD imagerel $LN17@PMC_Clone_+112
DD imagerel $unwind$PMC_Clone_X
; COMDAT xdata
xdata SEGMENT
$unwind$PMC_Clone_X DD 020601H
DD 030023206H
END
| 20.277778 | 79 | 0.810959 |
d2b58c3db9b8c64b6a1fe5c1cefeeb2ba720c290 | 2,348 | php | PHP | app/Http/Controllers/PelangganController.php | ashern11/laundryweb | 982b94dcdbbed361f0d2663b29c8b077813ef276 | [
"MIT"
] | null | null | null | app/Http/Controllers/PelangganController.php | ashern11/laundryweb | 982b94dcdbbed361f0d2663b29c8b077813ef276 | [
"MIT"
] | null | null | null | app/Http/Controllers/PelangganController.php | ashern11/laundryweb | 982b94dcdbbed361f0d2663b29c8b077813ef276 | [
"MIT"
] | null | null | null | <?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Yajra\Datatables\Datatables;
use Illuminate\Support\Facades\Validator;
use App\Pelanggan;
use App\Http\Requests;
class PelangganController extends Controller
{
public function index()
{
return view('Pelanggan');
}
public function dataPelanggan(){
$datapelanggan = Pelanggan::select('id_pelanggan', 'nama', 'alamat', 'telp')->get();
return Datatables::of($datapelanggan)
->addColumn('action',function ($datapelanggan) {
return '<button type="button" id="edit_modal" value="'.$datapelanggan->id_pelanggan.'" class="btn btn-primary waves-effect"><i class="glyphicon glyphicon-edit"></i> Edit</button>';
})
->make(true);
}
protected function validator(array $data){
$rules = [
'nama' => 'required|string|max:255',
'alamat' => 'required|min:3|max:255',
'telp' => 'required|string|max:13'
];
$messages = [
'required' => ':attribute wajib di isi',
'max' => ':attribute terlalu panjang',
];
return Validator::make($data, $rules, $messages);
}
public function insert(Request $request)
{
$validator = $this->validator($request->all());
if ($validator->fails()) {
return response()->json(['error' => $validator->errors()->all()]);
}else{
$Pelanggan = Pelanggan::create($request->all());
return Response()->json(['success'=>'Berhasil Ditambahkan']);
};
}
public function edit($id)
{
$Pelanggan = Pelanggan::find($id);
return Response()->json($Pelanggan);
}
public function update(Request $request, $id)
{
$validator = $this->validator($request->all());
if ($validator->fails()) {
return response()->json(['error' => $validator->errors()->all()]);
}else{
$Pelanggan = Pelanggan::find($id);
$Pelanggan->nama = $request->nama;
$Pelanggan->alamat = $request->alamat;
$Pelanggan->telp = $request->telp;
$Pelanggan->save();
return Response()->json(['success'=>'Berhasil Diedit']);
};
}
}
| 31.72973 | 196 | 0.5477 |
2db849cadaefe6fbf58028f7d43e79823b484a58 | 2,207 | html | HTML | index.html | bpalowski/Beep-Boop | dd290c7bbcbf8b022b95973c9ffd7d1d8d2d0545 | [
"MIT"
] | null | null | null | index.html | bpalowski/Beep-Boop | dd290c7bbcbf8b022b95973c9ffd7d1d8d2d0545 | [
"MIT"
] | null | null | null | index.html | bpalowski/Beep-Boop | dd290c7bbcbf8b022b95973c9ffd7d1d8d2d0545 | [
"MIT"
] | null | null | null | <!DOCTYPE html>
<html>
<head>
<link href="css/bootstrap.css" rel="stylesheet" type="text/css">
<link href="css/styles.css" rel="stylesheet" type="text/css">
<script src="js/jquery-3.3.1.js"></script>
<script src="js/scripts.js"></script>
<meta charset="utf-8">
<title>Beep Boop</title>
</head>
<body>
<div id="show">
<div class="container">
<style>
body{
background-image: url("Robot.png");
}
</style>
<div class="jumbotron">
<h2><strong>Beep Boop</strong></h2>
</div>
<form id="formOne">
<div class="col-ld-4">
<label id="info" for="beep-boop">Enter a Number</lable>
<input id="beep-boop" class="form-control" type="text">
<button id="submit" type="submit" name="button">Beep or Boop</button>
</div>
</form>
</div>
<!-- Heading to Questions -->
<div class="row">
<ul id="show_Output">
</ul>
</div>
<div id="Questions">
<div class="row">
<div class="col-md-4">
<select id="Question_1" class="custom-select" type="text">
<option selected>Open this select menu</option>
<option value="3">Yes</option>
<option value="1">No</option>
</select>
</div>
<div class="col-md-4">
<select id="Question_2" class="custom-select" type="text">
<option selected>Open this select menu</option>
<option value="3">Yes</option>
<option value="1">No</option>
</select>
</div>
<div class="col-md-4">
<select id="Question_3" class="custom-select" type="text">
<option selected>Open this select menu</option>
<option value="4">Yes</option>
<option value="1">No</option>
</select>
</div>
</div>
<div>
<button type="submit" class="btn btn-success">Submit</button>
</div>
</div>
</div>
</div>
<div id="off">
<h2>Suprise</h2>
</div>
<div id="Num1">
<h2>you</h2>
<ul >
</ul>
</div>
<div id="Num2">
<h2>no</h2>
<ul>
</ul>
</div>
<div id="Num3">
<h2>sdfsdf</h2>
<ul >
</ul>
</div>
</div>
</body>
</html>
| 22.752577 | 79 | 0.524241 |
3d5747df77154fd69d22e074627c654c7c25921b | 2,027 | rs | Rust | src/materialiconstwotone/social/icon_sledding.rs | andoriyu/material-design-icons-rs | a258e7ff9380fca49cb65ab0ea10d8fb8c8c79b3 | [
"Apache-2.0"
] | null | null | null | src/materialiconstwotone/social/icon_sledding.rs | andoriyu/material-design-icons-rs | a258e7ff9380fca49cb65ab0ea10d8fb8c8c79b3 | [
"Apache-2.0"
] | null | null | null | src/materialiconstwotone/social/icon_sledding.rs | andoriyu/material-design-icons-rs | a258e7ff9380fca49cb65ab0ea10d8fb8c8c79b3 | [
"Apache-2.0"
] | null | null | null |
pub struct IconSledding {
props: crate::Props,
}
impl yew::Component for IconSledding {
type Properties = crate::Props;
type Message = ();
fn create(props: Self::Properties, _: yew::prelude::ComponentLink<Self>) -> Self
{
Self { props }
}
fn update(&mut self, _: Self::Message) -> yew::prelude::ShouldRender
{
true
}
fn change(&mut self, _: Self::Properties) -> yew::prelude::ShouldRender
{
false
}
fn view(&self) -> yew::prelude::Html
{
yew::prelude::html! {
<svg
class=self.props.class.unwrap_or("")
width=self.props.size.unwrap_or(24).to_string()
height=self.props.size.unwrap_or(24).to_string()
viewBox="0 0 24 24"
fill=self.props.fill.unwrap_or("none")
stroke=self.props.color.unwrap_or("currentColor")
stroke-width=self.props.stroke_width.unwrap_or(2).to_string()
stroke-linecap=self.props.stroke_linecap.unwrap_or("round")
stroke-linejoin=self.props.stroke_linejoin.unwrap_or("round")
>
<svg xmlns="http://www.w3.org/2000/svg" enable-background="new 0 0 24 24" height="24" viewBox="0 0 24 24" width="24"><rect fill="none" height="24" width="24"/><path d="M14,4.5c0,1.1-0.9,2-2,2s-2-0.9-2-2s0.9-2,2-2S14,3.4,14,4.5z M22.8,20.24c-0.68,2.1-2.94,3.25-5.04,2.57h0L1,17.36 l0.46-1.43l3.93,1.28l0.46-1.43L1.93,14.5l0.46-1.43L4,13.6V9.5l5.47-2.35c0.39-0.17,0.84-0.21,1.28-0.07 c0.95,0.31,1.46,1.32,1.16,2.27l-1.05,3.24L13,12.25c0.89-0.15,1.76,0.32,2.14,1.14l2.08,4.51l1.93,0.63l-0.46,1.43l-3.32-1.08 L14.9,20.3l3.32,1.08l0,0c1.31,0.43,2.72-0.29,3.15-1.61c0.43-1.31-0.29-2.72-1.61-3.15l0.46-1.43 C22.33,15.88,23.49,18.14,22.8,20.24z M6,14.25l1.01,0.33c-0.22-0.42-0.28-0.92-0.12-1.4L7.92,10L6,10.82V14.25z M13.94,18.41 l-6.66-2.16l-0.46,1.43l6.66,2.16L13.94,18.41z M14.63,17.05l-1.18-2.56l-3.97,0.89L14.63,17.05z"/></svg>
</svg>
}
}
}
| 44.065217 | 836 | 0.596448 |
73c0d8f8591e8bc51d784a45febddfa4037cfa49 | 5,826 | lua | Lua | BGAnimations/ScreenEvaluationSummary overlay/stageStats.lua | Roujo/Simply-Love-SM5-Vertical | b32f4caed4a4e6efbcf9b5e47cb45b54d11950d0 | [
"MIT"
] | null | null | null | BGAnimations/ScreenEvaluationSummary overlay/stageStats.lua | Roujo/Simply-Love-SM5-Vertical | b32f4caed4a4e6efbcf9b5e47cb45b54d11950d0 | [
"MIT"
] | null | null | null | BGAnimations/ScreenEvaluationSummary overlay/stageStats.lua | Roujo/Simply-Love-SM5-Vertical | b32f4caed4a4e6efbcf9b5e47cb45b54d11950d0 | [
"MIT"
] | null | null | null | local position_on_screen = ...
local Players = GAMESTATE:GetHumanPlayers()
local song, StageNum, LetterGradesAF
local bannerZoom = 0.27
local quadWidth = _screen.w-40
local quadHeight = 75
local bannerXOffset = -quadWidth/4+10
local path = "/"..THEME:GetCurrentThemeDirectory().."Graphics/_FallbackBanners/"..ThemePrefs.Get("VisualTheme")
local banner_directory = FILEMAN:DoesFileExist(path) and path or THEME:GetPathG("","_FallbackBanners/Arrows")
local t = Def.ActorFrame{
OnCommand=function(self)
LetterGradesAF = self:GetParent():GetChild("LetterGradesAF")
end,
DrawPageCommand=function(self, params)
self:sleep(position_on_screen*0.05):linear(0.15):diffusealpha(0)
StageNum = ((params.Page-1)*params.SongsPerPage) + position_on_screen
local stage = SL.Global.Stages.Stats[StageNum]
song = stage ~= nil and stage.song or nil
self:queuecommand("DrawStage")
end,
DrawStageCommand=function(self)
if song == nil then
self:visible(false)
else
self:queuecommand("Show"):visible(true)
end
end,
-- black quad
Def.Quad{
InitCommand=function(self) self:zoomto( quadWidth, quadHeight ):diffuse(0,0,0,0.5):y(-6) end
},
--fallback banner
LoadActor(banner_directory.."/banner"..SL.Global.ActiveColorIndex.." (doubleres).png")..{
InitCommand=function(self) self:xy(bannerXOffset, -4):zoom(bannerZoom) end,
DrawStageCommand=function(self) self:visible(song ~= nil and not song:HasBanner()) end
},
-- the banner, if there is one
Def.Banner{
Name="Banner",
InitCommand=function(self) self:xy(bannerXOffset, -4) end,
DrawStageCommand=function(self)
if song then
if GAMESTATE:IsCourseMode() then
self:LoadFromCourse(song)
else
self:LoadFromSong(song)
end
self:setsize(418,164):zoom(bannerZoom)
end
end
},
-- the title of the song
LoadFont("Common Normal")..{
InitCommand=function(self) self:zoom(0.58):xy(bannerXOffset, -quadHeight/2 + 3):maxwidth(200) end,
DrawStageCommand=function(self)
if song then self:settext(song:GetDisplayFullTitle()) end
end
},
-- the BPM(s) of the song
LoadFont("Common Normal")..{
InitCommand=function(self) self:zoom(0.45):xy(bannerXOffset, quadHeight/3):maxwidth(200) end,
DrawStageCommand=function(self)
if song then
local text = ""
local BPMs
if GAMESTATE:IsCourseMode() then
-- I'm unable to find a way to figure out which songs were played in a randomly
-- generated course (for example, the "Most Played" courses that ship with SM5),
-- so GetCourseModeBPMs() will return nil in those cases.
BPMs = GetCourseModeBPMs(song)
else
BPMs = song:GetDisplayBpms()
end
local MusicRate = SL.Global.Stages.Stats[StageNum].MusicRate
if BPMs then
if BPMs[1] == BPMs[2] then
text = text .. round(BPMs[1] * MusicRate) .. " bpm"
else
text = text .. round(BPMs[1] * MusicRate) .. " - " .. round(BPMs[2] * MusicRate) .. " bpm"
end
end
if MusicRate ~= 1 then
text = text .. " (" .. tostring(MusicRate).."x Music Rate)"
end
self:settext(text)
end
end
}
}
for player in ivalues(Players) do
local playerStats, difficultyMeter, difficulty, stepartist, grade, score
local TNSTypes = { 'W1', 'W2', 'W3', 'W4', 'W5', 'Miss' }
-- variables for positioning and horizalign
local col1x, col2x, align1, align2
col1x = quadWidth/2 - 10
col2x = 20
align1 = right
align2 = left
local PlayerStatsAF = Def.ActorFrame{
DrawStageCommand=function(self)
playerStats = SL[ToEnumShortString(player)].Stages.Stats[StageNum]
if playerStats then
difficultyMeter = playerStats.difficultyMeter
difficulty = playerStats.difficulty
stepartist = playerStats.stepartist
grade = playerStats.grade
score = playerStats.score
end
end
}
--percent score
PlayerStatsAF[#PlayerStatsAF+1] = LoadFont("_wendy small")..{
InitCommand=function(self) self:zoom(0.4):horizalign(align1):x(col1x):y(-quadHeight/2+19) end,
DrawStageCommand=function(self)
if playerStats and score then
-- trim off the % symbol
local score = string.sub(FormatPercentScore(score),1,-2)
-- If the score is < 10.00% there will be leading whitespace, like " 9.45"
-- trim that too, so PLAYER_2's scores align properly.
score = score:gsub(" ", "")
self:settext(score):diffuse(Color.White)
if grade and grade == "Grade_Failed" then
self:diffuse(Color.Red)
end
else
self:settext("")
end
end
}
-- difficulty meter
PlayerStatsAF[#PlayerStatsAF+1] = LoadFont("_wendy small")..{
InitCommand=function(self) self:zoom(0.3):horizalign(align1):x(col1x):y(quadHeight/2-35) end,
DrawStageCommand=function(self)
if playerStats and difficultyMeter then
self:diffuse(DifficultyColor(difficulty)):settext(difficultyMeter)
else
self:settext("")
end
end
}
-- stepartist
PlayerStatsAF[#PlayerStatsAF+1] = LoadFont("Common Normal")..{
InitCommand=function(self) self:zoom(0.55):horizalign(align1):x(col1x):y(quadHeight/2-20):maxwidth(130) end,
DrawStageCommand=function(self)
if playerStats and stepartist then
self:settext(stepartist)
else
self:settext("")
end
end
}
-- numbers
for i=1,#TNSTypes do
PlayerStatsAF[#PlayerStatsAF+1] = LoadFont("_wendy small")..{
InitCommand=function(self)
self:zoom(0.2):horizalign(align2):x(col2x):y(i*11-45)
:diffuse( SL.JudgmentColors[SL.Global.GameMode][i] )
end,
DrawStageCommand=function(self)
if playerStats and playerStats.judgments then
local val = playerStats.judgments[TNSTypes[i]]
if val then self:settext(val) end
local worst = SL.Global.Stages.Stats[StageNum].WorstTimingWindow
self:visible( i <= worst or i==#TNSTypes )
else
self:settext("")
end
end
}
end
t[#t+1] = PlayerStatsAF
end
return t
| 28.281553 | 111 | 0.697219 |
7d8346ef599b6a8b568c8a65e4bf15e344fcb62a | 5,922 | html | HTML | static/index.html | SPSquonK/PropHtml | a6206eb0e5cf66ab4e85cd1021b5717bd72eceb3 | [
"MIT"
] | null | null | null | static/index.html | SPSquonK/PropHtml | a6206eb0e5cf66ab4e85cd1021b5717bd72eceb3 | [
"MIT"
] | 3 | 2021-06-15T07:23:00.000Z | 2021-06-19T00:00:38.000Z | static/index.html | SPSquonK/PropHtml | a6206eb0e5cf66ab4e85cd1021b5717bd72eceb3 | [
"MIT"
] | null | null | null | <!DOCTYPE html>
<html>
<head>
<title>Express Prop Html</title>
<!-- <link href="itemlist.css" rel="stylesheet" /> -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.9.2/css/bulma.min.css" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
.hidden { display: none; }
.table.itemlist td,
.table.itemlist tr {
vertical-align: middle;
}
</style>
</head>
<body>
<section class="section">
<h1 class="title has-text-centered is-link">Express Prop Html</h1>
<div id="loading"></div>
<div id="app" class="hidden">
<div class="block">
<nav class="navbar is-link has-shadow" role="navigation" aria-label="main navigation">
<div class="navbar-brand">
<span class="navbar-item" style="font-weight: bold;">Categories</span>
</div>
<div class="navbar-menu">
<div class="navbar-start">
<a
v-for="(oneCategory, index) in categories"
v-bind:href="'javascript:requestIk3(' + index + ')'"
v-bind:class="'navbar-item' + (oneCategory === category ? ' is-active' : '')"
>
{{ oneCategory }}
</a>
</div>
</div>
</nav>
</div>
<div class="block box" v-if="editable">
<p>
<label for="editMode" class="checkbox">
<input type="checkbox" name="editMode" v-model="editMode" />
Switch to edit mode
</label>
</p>
<div v-if="editMode" class="box">
<h2 class="title is-3">Pending changes</h2>
<ul style="height: 7.7em; overflow-y: scroll;">
<li v-for="item in pending">
<em>{{ item.name }}</em>:
<span v-html="strInLine(item.originalBonus)" style="text-decoration: line-through"></span>
->
<span v-html="strInLine(item.bonus)"></span>
</li>
</ul>
<article class="message is-danger message-body" v-if="errorMessage">
{{ errorMessage }}
<br />
<em>
If you think your input was correct, submit an issue here:
<a href="https://github.com/SPSquonK/PropHtml/issues">
https://github.com/SPSquonK/PropHtml/issues
</a>
</em>
</article>
<article class="message is-success message-body" v-if="commitMessage">{{ commitMessage }}</article>
<div class="field is-grouped">
<p class="control">
<input type="submit" value="Submit" v-on:click="submit()" class="button is-primary" />
</p>
<p class="control">
<input type="Reset" value="Reset" v-on:click="reset()" class="button is-light" />
</p>
</div>
</div>
</div>
<div class="block box">
<h2 class="title is-3">{{ category }}</h2>
<table
class="table is-hoverable is-striped is-bordered is-fullwidth itemlist has-text-centered"
v-if="categoryType === 'Single Item'"
>
<thead>
<tr>
<th style="width: 64px;">Icon</th>
<th style="width: 30em;">Name</th>
<th style="width: 10em;">Job</th>
<th style="width: 5em;">Level</th>
<th class="has-text-left">Bonus</th>
</tr>
</thead>
<tbody>
<template>
<item-row
v-for="item in items"
v-bind:item="item"
v-bind:dstlist="dstList"
v-bind:editmode="editMode"
v-on:modifieditem="modifyPending($event)"
v-bind:key="item.id"
>
</item-row>
</template>
</tbody>
</table>
<article
class="message is-danger message-body"
v-if="categoryType === 'Item Set' && editMode"
>
Edit mode is not yet supported for item sets
</article>
<table
class="table is-hoverable is-striped is-bordered is-fullwidth itemlist has-text-centered"
v-if="categoryType === 'Item Set'"
>
<thead>
<tr>
<th style="width: 30em;">Item set</th>
<th style="width: 10em;">Requirements</th>
<th class="has-text-left">Bonus</th>
</tr>
</thead>
<tbody>
<template>
<item-set-row
v-for="itemset in itemsets"
v-bind:itemset="itemset"
v-bind:dstlist="dstList"
v-bind:key="itemset.id"
>
</item-set-row>
</template>
</tbody>
</table>
<article
class="message is-danger message-body"
v-if="categoryType && categoryType.startsWith('Unsupported ')"
>
{{ categoryType }}
</article>
</div>
<footer class="has-text-right">
<strong><a href="https://github.com/SPSquonK/PropHtml">Express Prop Html</a></strong>
by <a href="https://squonk.fr">SquonK</a>, 2021.
</footer>
</div>
</section>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<script
src="https://code.jquery.com/jquery-3.6.0.min.js"
integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
crossorigin="anonymous"></script>
<script src="main.js"></script>
</body>
</html> | 33.647727 | 111 | 0.474333 |
043df088c2211ff5e57ed334b7c0e194c244bbae | 3,565 | java | Java | imageio/imageio-core/src/test/java/com/twelvemonkeys/imageio/util/IndexedImageTypeSpecifierTest.java | seafraf/TwelveMonkeys | b43faf2fae8e2c944145f738735f544f559886f8 | [
"BSD-3-Clause"
] | 1 | 2018-07-04T02:29:53.000Z | 2018-07-04T02:29:53.000Z | imageio/imageio-core/src/test/java/com/twelvemonkeys/imageio/util/IndexedImageTypeSpecifierTest.java | seafraf/TwelveMonkeys | b43faf2fae8e2c944145f738735f544f559886f8 | [
"BSD-3-Clause"
] | null | null | null | imageio/imageio-core/src/test/java/com/twelvemonkeys/imageio/util/IndexedImageTypeSpecifierTest.java | seafraf/TwelveMonkeys | b43faf2fae8e2c944145f738735f544f559886f8 | [
"BSD-3-Clause"
] | null | null | null | package com.twelvemonkeys.imageio.util;
import org.junit.Test;
import javax.imageio.ImageTypeSpecifier;
import java.awt.image.BufferedImage;
import java.awt.image.DataBuffer;
import java.awt.image.IndexColorModel;
import static org.junit.Assert.*;
/**
* IndexedImageTypeSpecifierTestCase
*
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
* @author last modified by $Author: haraldk$
* @version $Id: IndexedImageTypeSpecifierTestCase.java,v 1.0 Jun 9, 2008 2:42:03 PM haraldk Exp$
*/
public class IndexedImageTypeSpecifierTest {
@Test
public void testEquals() {
IndexColorModel cm = new IndexColorModel(1, 2, new int[]{0xffffff, 0x00}, 0, false, -1, DataBuffer.TYPE_BYTE);
ImageTypeSpecifier spec = IndexedImageTypeSpecifier.createFromIndexColorModel(cm);
ImageTypeSpecifier other = IndexedImageTypeSpecifier.createFromIndexColorModel(cm);
ImageTypeSpecifier different = IndexedImageTypeSpecifier.createFromIndexColorModel(new IndexColorModel(2, 2, new int[]{0xff00ff, 0x00, 0xff00ff, 0x00}, 0, false, -1, DataBuffer.TYPE_BYTE));
assertEquals(spec, other);
assertEquals(other, spec);
assertEquals(spec.hashCode(), other.hashCode());
assertTrue(spec.equals(other));
assertTrue(other.equals(spec));
// TODO: There is still a problem that IndexColorModel does not override equals,
// so any model with the same number of bits, transparency, and transfer type will be treated as equal
assertFalse(other.equals(different));
}
@Test
public void testHashCode() {
IndexColorModel cm = new IndexColorModel(1, 2, new int[]{0xffffff, 0x00}, 0, false, -1, DataBuffer.TYPE_BYTE);
ImageTypeSpecifier spec = IndexedImageTypeSpecifier.createFromIndexColorModel(cm);
ImageTypeSpecifier other = IndexedImageTypeSpecifier.createFromIndexColorModel(cm);
ImageTypeSpecifier different = IndexedImageTypeSpecifier.createFromIndexColorModel(new IndexColorModel(2, 2, new int[]{0xff00ff, 0x00, 0xff00ff, 0x00}, 0, false, -1, DataBuffer.TYPE_BYTE));
// TODO: There is still a problem that IndexColorModel does not override hashCode,
// so any model with the same number of bits, transparency, and transfer type will have same hash
assertEquals(spec.hashCode(), other.hashCode());
assertFalse(spec.hashCode() == different.hashCode());
}
@Test(expected = IllegalArgumentException.class)
public void testCreateNull() {
IndexedImageTypeSpecifier.createFromIndexColorModel(null);
}
@Test
public void testCreateBufferedImageBinary() {
IndexColorModel cm = new IndexColorModel(1, 2, new int[]{0xffffff, 0x00}, 0, false, -1, DataBuffer.TYPE_BYTE);
ImageTypeSpecifier spec = IndexedImageTypeSpecifier.createFromIndexColorModel(cm);
BufferedImage image = spec.createBufferedImage(2, 2);
assertNotNull(image);
assertEquals(BufferedImage.TYPE_BYTE_BINARY, image.getType());
assertEquals(cm, image.getColorModel());
}
@Test
public void testCreateBufferedImageIndexed() {
IndexColorModel cm = new IndexColorModel(8, 256, new int[256], 0, false, -1, DataBuffer.TYPE_BYTE);
ImageTypeSpecifier spec = IndexedImageTypeSpecifier.createFromIndexColorModel(cm);
BufferedImage image = spec.createBufferedImage(2, 2);
assertNotNull(image);
assertEquals(BufferedImage.TYPE_BYTE_INDEXED, image.getType());
assertEquals(cm, image.getColorModel());
}
}
| 42.440476 | 197 | 0.721739 |
c7c3e3ae6feff628206648eebcbb8b0ae35f5f27 | 1,838 | py | Python | django_rotate_secret_key/management/commands/rotatesecretkey.py | securedirective/django-rotate-secret-key | 89e08f986eabec0ac7ed2126f3d3265bd6920191 | [
"MIT"
] | null | null | null | django_rotate_secret_key/management/commands/rotatesecretkey.py | securedirective/django-rotate-secret-key | 89e08f986eabec0ac7ed2126f3d3265bd6920191 | [
"MIT"
] | null | null | null | django_rotate_secret_key/management/commands/rotatesecretkey.py | securedirective/django-rotate-secret-key | 89e08f986eabec0ac7ed2126f3d3265bd6920191 | [
"MIT"
] | null | null | null | import os
import string
import random
from django.core.management.base import BaseCommand
from django.utils import six
from django.utils.six.moves import input
from django.conf import settings
class Command(BaseCommand):
help = "Generate/regenerate a random 50-character secret key stored in a file specified by the `SECRET_KEY_FILE` setting."
def add_arguments(self, parser):
parser.add_argument(
'--force',
action='store_true',
dest='force',
default=False,
help='Replace the existing key without prompting'
)
def handle(self, *args, **options):
# Find the key file (this setting must exist)
try:
key_file = settings.SECRET_KEY_FILE
except:
self.stderr.write('SECRET_KEY_FILE not configured!')
exit(2)
# If the file exists and already has contents, then only replace if --force argument was given
existing_key = ''
try:
existing_key = open(key_file).read().strip()
except:
pass # No key file found, so we're safe to create a new one without prompting
else:
if existing_key:
self.stdout.write("EXISTING SECRET KEY: {}".format(existing_key))
if not options.get('force'):
if input("Replace this with a new key? [y/N] ").lower() != 'y': return
self.stdout.write('')
# Generate new key
char_list = string.ascii_letters + string.digits + string.punctuation
generated_key = ''.join([random.SystemRandom().choice(char_list) for _ in range(50)])
self.stdout.write("NEW SECRET KEY: {}".format(generated_key))
# Create directory if it doesn't already exist
key_dir = os.path.dirname(key_file)
if six.PY2:
if not os.path.isdir(key_dir):
os.makedirs(key_dir)
else:
os.makedirs(key_dir, exist_ok=True)
# Write new key to file
with open(key_file, 'w') as f:
f.write(generated_key)
self.stdout.write("Written to {}".format(key_file))
| 30.633333 | 123 | 0.712731 |
8139f0f4493bac43994b7d87436543724704f062 | 1,435 | sql | SQL | unittests/test_dorm_sqlserver.sql | raelb/delphi-orm | 73e0caede84f2753550492deeaad35bf4191be30 | [
"Apache-2.0"
] | 156 | 2015-05-28T19:14:20.000Z | 2022-03-18T05:34:41.000Z | unittests/test_dorm_sqlserver.sql | raelb/delphi-orm | 73e0caede84f2753550492deeaad35bf4191be30 | [
"Apache-2.0"
] | 10 | 2015-05-31T09:19:41.000Z | 2021-09-27T14:34:31.000Z | unittests/test_dorm_sqlserver.sql | raelb/delphi-orm | 73e0caede84f2753550492deeaad35bf4191be30 | [
"Apache-2.0"
] | 70 | 2015-06-20T17:34:17.000Z | 2022-03-03T10:05:31.000Z | CREATE TABLE CARS (
ID INT IDENTITY(1,1) PRIMARY KEY,
BRAND VARCHAR(30),
MODEL VARCHAR(30),
ID_PERSON INT,
OBJVERSION INT
);
CREATE TABLE COUNTRIES (
ID INTEGER IDENTITY(1,1) PRIMARY KEY,
DESCRIPTION VARCHAR(50) NOT NULL,
OBJVERSION INT
);
CREATE TABLE EMAILS (
ID INT IDENTITY(1,1) PRIMARY KEY,
ADDRESS VARCHAR(100),
ID_PERSON INT,
OBJVERSION INT
);
CREATE TABLE PEOPLE (
ID INT IDENTITY(1,1) PRIMARY KEY,
FIRST_NAME VARCHAR(50),
LAST_NAME VARCHAR(50),
AGE INT,
BORN_DATE DATE,
BORN_DATE_TIME DATETIME,
PHOTO VARBINARY(MAX),
IS_MALE INT NOT NULL,
OBJVERSION INT
);
CREATE TABLE PEOPLE_COUNTRIES (
ID INTEGER IDENTITY(1,1) PRIMARY KEY,
ID_PEOPLE INTEGER NOT NULL,
ID_COUNTRY INTEGER NOT NULL,
OBJVERSION INT
);
CREATE TABLE PHONES (
ID INT IDENTITY(1,1) PRIMARY KEY,
NUMBER VARCHAR(50),
MODEL VARCHAR(50),
ID_PERSON INT,
OBJVERSION INT
);
CREATE TABLE TODOS (
ID INTEGER IDENTITY(1,1) PRIMARY KEY,
DESCRIPTION VARCHAR(200) NOT NULL,
DUE_DATE DATE NOT NULL,
DUE_TIME TIME NOT NULL,
DONE INT NOT NULL,
OBJVERSION INTEGER NOT NULL
);
| 22.777778 | 52 | 0.55331 |
77621674bf883e95d37964b7cb8fcc0bceb9a322 | 97 | html | HTML | pa1-skeleton/pa1-data/2/glast-isoc.slac.stanford.edu_pages_photo_Gallery_Ken_Fouts_farewell_target10.html | yzhong94/cs276-spring-2019 | a4780a9f88b8c535146040fe11bb513c91c5693b | [
"MIT"
] | null | null | null | pa1-skeleton/pa1-data/2/glast-isoc.slac.stanford.edu_pages_photo_Gallery_Ken_Fouts_farewell_target10.html | yzhong94/cs276-spring-2019 | a4780a9f88b8c535146040fe11bb513c91c5693b | [
"MIT"
] | null | null | null | pa1-skeleton/pa1-data/2/glast-isoc.slac.stanford.edu_pages_photo_Gallery_Ken_Fouts_farewell_target10.html | yzhong94/cs276-spring-2019 | a4780a9f88b8c535146040fe11bb513c91c5693b | [
"MIT"
] | null | null | null | dsc_0018 jpg ken_fouts_farewell dsc_0018 jpg first previous picture next picture last thumbnails
| 48.5 | 96 | 0.876289 |
6512ccce127a82c68b221b5453c2086be0c2bb8b | 3,165 | py | Python | 00-basic/04_01_data_structures_lists.py | TranXuanHoang/Python | 6e62282540a7f1e2b2d0dff99b1803715bf6c4b0 | [
"CNRI-Python"
] | null | null | null | 00-basic/04_01_data_structures_lists.py | TranXuanHoang/Python | 6e62282540a7f1e2b2d0dff99b1803715bf6c4b0 | [
"CNRI-Python"
] | null | null | null | 00-basic/04_01_data_structures_lists.py | TranXuanHoang/Python | 6e62282540a7f1e2b2d0dff99b1803715bf6c4b0 | [
"CNRI-Python"
] | null | null | null | # Lists
# Basics
foods = ['rice', 'Meat', 'vegetables', 'Eggs']
print(foods)
# Same as foods[len(foods):] = ['butter']
foods.append('butter')
print(foods)
# Same as foods[len(foods):] = ['tomatoes', 'chili sauce']
foods.extend(['tomatoes', 'Chili sauce'])
print(foods)
# Reverse order of elements in the list
foods.reverse()
print(foods)
# Copy the list
copy_of_foods = foods.copy()
print(copy_of_foods)
# Sort in ascending order
foods.sort()
print(foods)
# Sort in descending order without considering lower or upper case
copy_of_foods.sort(key=str.lower, reverse=True)
print(copy_of_foods)
# Using Lists as Stacks
stack_normal = ['+', 4, '*', 7, '-', 3, 6]
stack_error = ['+', 4, '?', 7, '-', 3, 6]
def evaluate(stack):
expression = ''
round = 0
while len(stack) >= 3:
first_operand = stack.pop()
second_operand = stack.pop()
operator = stack.pop()
subexpression = str(first_operand) + ' ' + operator + \
' ' + str(second_operand)
if round == 0:
expression = '(' + subexpression + ')'
else:
expression = '(' + expression + ' ' + operator + \
' ' + str(second_operand) + ')'
round += 1
if operator == '+':
stack.append(first_operand + second_operand)
elif operator == '-':
stack.append(first_operand - second_operand)
elif operator == '*':
stack.append(first_operand * second_operand)
elif operator == '/':
stack.append(first_operand / second_operand)
else:
stack.append('Error [Invalid Operator]: ' + subexpression)
break
result = str(stack.pop())
if 'Error' in result:
return result
else:
return expression + ' = ' + result
print(evaluate(stack_normal))
print(evaluate(stack_error))
# Using List as Queues
from collections import deque
queue = deque(["(", "c", "+", "d", ")"])
print(queue)
queue.append('/')
queue.append('d')
print(queue)
queue.appendleft('*')
queue.appendleft('a')
print(queue)
# List Comprehensions
drinks = [' Beer ', ' Tea', 'Coca Cola ', ' Pepsi', 'Water']
trimmed_drinks = [drink.strip()
for drink in drinks] # trim all trailing spaces
print(drinks)
print(trimmed_drinks)
# filter drinks whose name length is longer that or equal to 5
print([drink for drink in trimmed_drinks if len(drink) >= 5])
foods = ['rice', 'Meat', 'vegetables', 'Eggs']
menus = [(food.upper(), drink.lower())
for food in foods for drink in trimmed_drinks]
print(menus)
vector = [
[1, 2, 3],
['Monday', 'Tuesday', 'Wednesday'],
['Morning', 'Afternoon', 'Night']
]
# [1, 2, 3, 'Monday', 'Tuesday', 'Wednesday', 'Morning', 'Afternoon', 'Night']
flatten_vector = [el for row in vector for el in row]
print(flatten_vector)
# [
# [1, 'Monday', 'Morning'],
# [2, 'Tuesday', 'Afternoon'],
# [3, 'Wednesday', 'Night']
# ]
transposed_vector = [[row[i] for row in vector] for i in range(3)]
print(transposed_vector)
| 25.524194 | 79 | 0.581043 |
fd9330714dc1eea3c47bd0c20034eba8bd05403c | 643 | c | C | c/clock/src/clock.c | vlzware/exercism_c | 08d363cf7f0a9855b21f6588edb5702046145fdf | [
"MIT"
] | 1 | 2018-04-06T02:11:55.000Z | 2018-04-06T02:11:55.000Z | c/clock/src/clock.c | vlzware/exercism_c | 08d363cf7f0a9855b21f6588edb5702046145fdf | [
"MIT"
] | null | null | null | c/clock/src/clock.c | vlzware/exercism_c | 08d363cf7f0a9855b21f6588edb5702046145fdf | [
"MIT"
] | null | null | null | #include "clock.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void clock(time_text_t time_text, int hour, int minute)
{
if (time_text == NULL)
return;
int ch = 0, cm = 0;
cm += minute % 60;
if (cm < 0) {
ch--;
cm += 60;
}
ch += (hour + minute/60) % 24;
if (ch < 0) {
ch += 24;
}
sprintf(time_text, "%2.2i:%2.2i", ch, cm);
}
void clock_add(time_text_t time_text, int minute_offset)
{
if (time_text == NULL)
return;
char buf[3] = {0};
strncpy(buf, time_text, 2);
int hour = atoi(buf);
strncpy(buf, (time_text + 3), 2);
int minute = atoi(buf);
clock(time_text, hour, minute + minute_offset);
}
| 15.309524 | 56 | 0.603421 |
d2b71586871efd8c0b5bf236953230e382370347 | 5,936 | dart | Dart | ants_clock/lib/widgets/snow_flakes.dart | StuartApp/Flutter-clock-challenge | 27850d5c96b1f1f39da70cb1d110ba06078889c6 | [
"MIT"
] | 37 | 2020-01-31T21:13:23.000Z | 2022-01-17T07:58:06.000Z | ants_clock/lib/widgets/snow_flakes.dart | StuartApp/Flutter-clock-challenge | 27850d5c96b1f1f39da70cb1d110ba06078889c6 | [
"MIT"
] | null | null | null | ants_clock/lib/widgets/snow_flakes.dart | StuartApp/Flutter-clock-challenge | 27850d5c96b1f1f39da70cb1d110ba06078889c6 | [
"MIT"
] | 5 | 2020-02-26T08:50:08.000Z | 2021-08-16T03:48:53.000Z | // Copyright 2020 Stuart Delivery Limited. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'package:ants_clock/math_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter_clock_helper/model.dart';
class SnowFlakes extends StatefulWidget {
final WeatherCondition weatherCondition;
final bool isDarkMode;
const SnowFlakes({
Key key,
@required this.weatherCondition,
@required this.isDarkMode,
}) : super(key: key);
@override
_SnowFlakesState createState() => _SnowFlakesState();
}
class _SnowFlakesState extends State<SnowFlakes> {
static const _snowFlakesInterval = 400;
static const _snowFlakesPerInterval = 2;
final List<_SnowFlakePosition> _snowFlakePositions = [];
Timer _timer;
double _width;
double _height;
@override
void initState() {
super.initState();
}
@override
void dispose() {
_timer?.cancel();
super.dispose();
}
@override
void didUpdateWidget(SnowFlakes oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.weatherCondition != oldWidget.weatherCondition ||
widget.isDarkMode != oldWidget.isDarkMode) {
_timer?.cancel();
_width = null;
_height = null;
}
}
@override
Widget build(BuildContext context) {
if (widget.weatherCondition == WeatherCondition.snowy &&
!widget.isDarkMode) {
return LayoutBuilder(
builder: (context, constraints) {
_initTimer(constraints);
return Stack(
children: _buildSnowFlakes(),
);
},
);
} else {
return Container();
}
}
void _initTimer(BoxConstraints constraints) {
if (_width == constraints.maxWidth && _height == constraints.maxHeight) {
return;
}
_width = constraints.maxWidth;
_height = constraints.maxHeight;
_snowFlakePositions.clear();
_timer?.cancel();
_timer =
Timer.periodic(Duration(milliseconds: _snowFlakesInterval), (timer) {
setState(() {
_snowFlakePositions.removeWhere((position) {
return position.snowFlakeKey.currentState?.isCompleted ?? true;
});
for (var i = 0; i < _snowFlakesPerInterval; ++i) {
final snowFlakeKey = GlobalKey<_SnowFlakeState>();
final _SnowFlakePosition snowFlakePosition = _SnowFlakePosition(
randomDouble(0.0, _width - _SnowFlakeState.snowFlakeSize),
randomDouble(0.0, _height - _SnowFlakeState.snowFlakeSize),
_SnowFlake(key: snowFlakeKey),
snowFlakeKey,
);
_snowFlakePositions.add(snowFlakePosition);
}
});
});
}
List<Widget> _buildSnowFlakes() {
return _snowFlakePositions.map<Widget>((snowFlakePosition) {
return Positioned(
child: snowFlakePosition.snowFlake,
left: snowFlakePosition.left,
top: snowFlakePosition.top,
);
}).toList();
}
}
class _SnowFlakePosition {
final double left;
final double top;
final _SnowFlake snowFlake;
final GlobalKey<_SnowFlakeState> snowFlakeKey;
_SnowFlakePosition(this.left, this.top, this.snowFlake, this.snowFlakeKey);
}
class _SnowFlake extends StatefulWidget {
const _SnowFlake({Key key}) : super(key: key);
@override
_SnowFlakeState createState() => _SnowFlakeState();
}
class _SnowFlakeState extends State<_SnowFlake>
with SingleTickerProviderStateMixin {
static const snowFlakeSize = 35.0;
AnimationController _controller;
bool get isCompleted => _controller.status == AnimationStatus.completed;
@override
void initState() {
super.initState();
_controller = AnimationController(
vsync: this,
duration: Duration(milliseconds: 5000),
);
_controller.forward();
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return AnimatedBuilder(
animation: _controller,
builder: (context, child) {
return CustomPaint(
painter: _CustomPainter(_controller.value),
size: Size(snowFlakeSize, snowFlakeSize),
);
},
);
}
}
class _CustomPainter extends CustomPainter {
static const Color _color = Colors.white;
final double t;
final Paint _paintFill = Paint()
..color = _color.withOpacity(0.5)
..style = PaintingStyle.fill;
_CustomPainter(this.t);
@override
void paint(Canvas canvas, Size size) {
final center = size.center(Offset.zero);
_drawSnowFlakeFalling(
canvas,
0.0,
0.25,
5.0,
2.5,
center,
Offset(size.width / 2.0, -2.5),
Offset(-size.width / 2.0, 0.0),
);
_drawSnowFlakeFalling(
canvas,
0.25,
0.6,
2.5,
1.0,
center,
Offset(-size.width / 2.0, 0.0),
Offset(size.width / 4.0, 1.5),
);
_drawSnowFlakeFalling(
canvas,
0.6,
1.0,
1.5,
0.0,
center,
Offset(size.width / 4.0, 1.5),
Offset(0.0, 2.5),
);
}
void _drawSnowFlakeFalling(
Canvas canvas,
double intervalBegin,
double intervalEnd,
double beginRadius,
double endRadius,
Offset center,
Offset beginOffset,
Offset endOffset,
) {
if (t >= intervalBegin && t <= intervalEnd) {
final interval = CurveTween(curve: Interval(intervalBegin, intervalEnd));
final radius = Tween(begin: beginRadius, end: endRadius).chain(interval);
final offset = Tween(begin: center + beginOffset, end: center + endOffset)
.chain(CurveTween(curve: Curves.easeInOut))
.chain(interval);
canvas.drawCircle(offset.transform(t), radius.transform(t), _paintFill);
}
}
@override
bool shouldRepaint(CustomPainter oldDelegate) {
return (oldDelegate as _CustomPainter).t != t;
}
}
| 23.555556 | 80 | 0.648416 |
414748f2b58dc7fb0f8187727bdb71fed5e38415 | 2,792 | c | C | win32/err.c | sjmulder/netwake | e44d67b41d4d318f7c49caf1f1a359929986f63d | [
"BSD-2-Clause"
] | 47 | 2020-10-23T20:04:14.000Z | 2022-02-16T18:55:41.000Z | win32/err.c | sjmulder/netwake | e44d67b41d4d318f7c49caf1f1a359929986f63d | [
"BSD-2-Clause"
] | 1 | 2020-11-14T22:08:11.000Z | 2020-11-14T22:38:29.000Z | win32/err.c | sjmulder/netwake | e44d67b41d4d318f7c49caf1f1a359929986f63d | [
"BSD-2-Clause"
] | 2 | 2021-02-02T11:03:40.000Z | 2021-12-17T17:35:21.000Z | #define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include "err.h"
#include "resource.h"
static HINSTANCE sInstance;
static const char *sAppTitle;
static const HWND *sWndPtr;
static void
strAppend(char *dst, size_t *len, size_t sz, char *src)
{
size_t i;
for (i = 0; src[i] && *len < sz-1; i++)
dst[(*len)++] = src[i];
dst[*len] = '\0';
}
static void
strAppendInt(char *dst, size_t *len, size_t sz, int num)
{
char numStr[16];
size_t numLen=0, i;
for (; num && numLen < sizeof(numStr); num /= 10)
numStr[numLen++] = '0' + (num % 10);
for (i = numLen; i && *len < sz-1; i--)
dst[(*len)++] = numStr[i-1];
}
void
Info(int msgRes)
{
char msg[1024];
if (!LoadString(sInstance, msgRes, msg, sizeof(msg))) {
WarnWin(IDS_ERESMISS);
return;
}
MessageBox(*sWndPtr, msg, sAppTitle, MB_OK | MB_ICONINFORMATION);
}
void
InitErr(HINSTANCE instance, const char *appTitle, const HWND *wndPtr)
{
sInstance = instance;
sAppTitle = appTitle;
sWndPtr = wndPtr;
}
void
Warn(int msgRes)
{
char msg[1024];
DWORD err;
size_t len;
if (!LoadString(sInstance, msgRes, msg, sizeof(msg))) {
err = GetLastError();
strAppend(msg, &len, sizeof(msg), "An error occured, but the "
"description no. ");
strAppendInt(msg, &len, sizeof(msg), msgRes);
strAppend(msg, &len, sizeof(msg), " could not be loaded:"
"\r\n\r\n");
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, err, 0,
&msg[len], sizeof(msg) - len, NULL);
MessageBox(*sWndPtr, msg, sAppTitle, MB_OK |
MB_ICONEXCLAMATION);
return;
}
MessageBox(*sWndPtr, msg, sAppTitle, MB_OK | MB_ICONEXCLAMATION);
}
void
WarnWin(int prefixRes)
{
char msg[1024];
DWORD err, err2;
size_t len;
err = GetLastError();
if (!(len = LoadString(sInstance, prefixRes, msg, sizeof(msg)))) {
err2 = GetLastError();
strAppend(msg, &len, sizeof(msg), "An error occured, but the "
"description no. ");
strAppendInt(msg, &len, sizeof(msg), prefixRes);
strAppend(msg, &len, sizeof(msg), " could not be loaded:"
"\r\n\r\n");
len += FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, err2, 0,
&msg[len], sizeof(msg) - len, NULL);
strAppend(msg, &len, sizeof(msg), "\r\nThe original error was:"
"\r\n\r\n");
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, err, 0,
&msg[len], sizeof(msg) - len, NULL);
MessageBox(*sWndPtr, msg, sAppTitle, MB_OK |
MB_ICONEXCLAMATION);
return;
}
strAppend(msg, &len, sizeof(msg), "\r\n\r\n");
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, err, 0,
&msg[len], sizeof(msg) - len, NULL);
MessageBox(*sWndPtr, msg, sAppTitle, MB_OK | MB_ICONEXCLAMATION);
}
void __declspec(noreturn)
Err(int msgRes)
{
Warn(msgRes);
ExitProcess(1);
}
void __declspec(noreturn)
ErrWin(int msgRes)
{
WarnWin(msgRes);
ExitProcess(1);
}
| 21.151515 | 69 | 0.655802 |
e670d6709c655e188d13e1c02083df36fcec71dc | 3,800 | ps1 | PowerShell | Public/get-winEventsLoopedIDs.ps1 | tostka/verb-logging | 7e52b14922018501b6b7fcd15a7d6a85aa141215 | [
"MIT"
] | null | null | null | Public/get-winEventsLoopedIDs.ps1 | tostka/verb-logging | 7e52b14922018501b6b7fcd15a7d6a85aa141215 | [
"MIT"
] | null | null | null | Public/get-winEventsLoopedIDs.ps1 | tostka/verb-logging | 7e52b14922018501b6b7fcd15a7d6a85aa141215 | [
"MIT"
] | null | null | null | #*------v get-winEventsLoopedIDs.ps1 v------
function get-winEventsLoopedIDs {
<#
.SYNOPSIS
get-lastevent - return the last 7 wake events on the local pc
.NOTES
Version : 1.0.11.0
Author : Todd Kadrie
Website : https://www.toddomation.com
Twitter : @tostka
CreatedDate : 2/18/2020
FileName : get-lastevent.ps1
License : MIT
Copyright : (c) 2/18/2020 Todd Kadrie
Github : https://github.com/tostka
AddedCredit : REFERENCE
AddedWebsite: REFERENCEURL
AddedTwitter: @HANDLE / http://twitter.com/HANDLE
REVISIONS
* 8:11 AM 3/9/2020 added verbose support & verbose echo'ing of hash values
* 4:00 PM 3/7/2020 ran vsc expalias
* 1:11 PM 3/6/2020 init
.DESCRIPTION
get-winevents -filterhashtable supports an array in the ID field, but I want MaxEvents _per event_ filtered,
not overall (total most recent 7 drawn from most recent 14 of each type, sorted by date)
This function pulls the ID array off and loops & aggregate the events,
sorts on time, and returns the most recent x
.PARAMETER MaxEvents
Maximum # of events to poll for each event specified -MaxEvents 14]
.PARAMETER FinalEvents
Final # of sorted events of all types to return [-FinalEvents 7]
.PARAMETER Filter
get-WinEvents -FilterHashtable hash obj to be queried to return matching events[-filter `$hashobj]
A typical hash of this type, could look like: @{logname='System';id=6009 ;ProviderName='EventLog';Level=4;}
Corresponding to a search of the System log, EventLog source, for ID 6009, of Informational type (Level 4).
.EXAMPLE
[array]$evts = @() ;
$hlastShutdown=@{logname = 'System'; ProviderName = $null ; ID = '13','6008','13','6008','6006' ; Level = 4 ; } ;
$evts += get-winEventsLoopedIDs -filter $hlastShutdown -MaxEvents ;
The above runs a collection pass for each of the ID's specified above (which are associated with shutdowns),
returns the 14 most recent of each type, sorts the aggregate matched events on timestamp, and returns the most
recent 7 events of any of the matched types.
.LINK
https://github.com/tostka/verb-logging
#>
[CmdletBinding()]
PARAM(
[Parameter(HelpMessage = "Maximum # of events to poll for each event specified[-MaxEvents 14]")]
[int] $MaxEvents = 14,
[Parameter(HelpMessage = "Final # of sorted events of all types to return [-FinalEvents 7]")]
[int] $FinalEvents = 7,
[Parameter(Position=0,Mandatory=$True,HelpMessage="get-WinEvents -FilterHashtable hash obj to be queried to return matching events[-filter `$hashobj]")]
$Filter
) ;
[CmdletBinding()]
$verbose = ($VerbosePreference -eq "Continue") ;
$EventProperties ="timecreated","id","leveldisplayname","message" ;
$tIDs = $filter.ID ;
$filter.remove('Verbose') ;
$pltWinEvt=@{
FilterHashtable=$null;
MaxEvents=$MaxEvents ;
Verbose=$($VerbosePreference -eq 'Continue') ;
erroraction=0 ;
} ;
foreach($ID in $tIDs){
$filter.ID = $id ;
# purge empty values (throws up on ProviderName:$null)
$filter | ForEach-Object {$p = $_ ;@($p.GetEnumerator()) | Where-Object{ ($_.Value | Out-String).length -eq 0 } | Foreach-Object {$p.Remove($_.Key)} ;} ;
$pltWinEvt.FilterHashtable = $filter ;
write-verbose -verbose:$verbose "$((get-date).ToString('HH:mm:ss')):get-winevent w`n$(($pltWinEvt|out-string).trim())`n`n`Expanded -filterhashtable:$(($filter|out-string).trim())" ;
$evts += get-winevent @pltWinEvt | Select-Object $EventProperties ;
} ;
$evts = $evts | Sort-Object TimeCreated -desc ;
$evts | write-output ;
}
#*------^ get-winEventsLoopedIDs.ps1 ^------ | 48.717949 | 191 | 0.656842 |
8d8512e9d66278ac356e4083b75d8c414e754831 | 2,544 | swift | Swift | AnimationDemo/VC/NavigationDemo.swift | z30262226/TransitioningDemo | 4a1d76a3e2fac1e65cab0c91e44a76d983bbe6b3 | [
"MIT"
] | null | null | null | AnimationDemo/VC/NavigationDemo.swift | z30262226/TransitioningDemo | 4a1d76a3e2fac1e65cab0c91e44a76d983bbe6b3 | [
"MIT"
] | null | null | null | AnimationDemo/VC/NavigationDemo.swift | z30262226/TransitioningDemo | 4a1d76a3e2fac1e65cab0c91e44a76d983bbe6b3 | [
"MIT"
] | null | null | null | //
// NavigationDemo.swift
// AnimationDemo
//
// Created by ohlulu on 2018/12/23.
// Copyright © 2018 ohlulu. All rights reserved.
//
import UIKit
class NavigationDemo: UIViewController , UIViewControllerTransitioningDelegate, UINavigationControllerDelegate {
let animation = OHTableCellToTop()
fileprivate lazy var table: UITableView = {
let table = UITableView()
table.register(CellImage.self, forCellReuseIdentifier: "cell1")
table.delegate = self
table.dataSource = self
return table
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
navigationController?.delegate = self
view.addSubview(table)
table.translatesAutoresizingMaskIntoConstraints = false
table.translatesAutoresizingMaskIntoConstraints = false
table.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
table.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
table.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
table.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
}
func navigationController(_ navigationController: UINavigationController,
animationControllerFor operation: UINavigationController.Operation,
from fromVC: UIViewController,
to toVC: UIViewController)
-> UIViewControllerAnimatedTransitioning? {
animation.popStyle = (operation == .pop)
return animation
}
}
// MARK: - UITableViewDelegate
extension NavigationDemo: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let vc = NavigaitonNextViewController()
navigationController?.pushViewController(vc, animated: true)
}
}
// MARK: - UITableViewDataSource
extension NavigationDemo: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: CellImage = tableView.dequeueReusableCell(withIdentifier: "cell1", for: indexPath) as! CellImage
return cell
}
}
| 34.849315 | 114 | 0.683962 |
587b18c7a42cc233cd54d4d4af425aac6f77ef8c | 2,310 | rs | Rust | client/metaservice_mgr/src/meta_upload_segs_thread_pool.rs | duanjh7/yigfs | 36d8f641af3ad942aa46aeb2f2f48472c3ac535e | [
"Apache-2.0"
] | null | null | null | client/metaservice_mgr/src/meta_upload_segs_thread_pool.rs | duanjh7/yigfs | 36d8f641af3ad942aa46aeb2f2f48472c3ac535e | [
"Apache-2.0"
] | null | null | null | client/metaservice_mgr/src/meta_upload_segs_thread_pool.rs | duanjh7/yigfs | 36d8f641af3ad942aa46aeb2f2f48472c3ac535e | [
"Apache-2.0"
] | null | null | null | use crate::{
meta_op::MetaBatchOp, meta_upload_segs_thread::MetaUploadSegsThread, mgr::MetaServiceMgr,
};
use common::numbers::NumberOp;
use crossbeam_channel::Sender;
use hash_ring::HashRing;
use std::sync::Arc;
pub struct MetaUploadSegsThreadPool {
pool: Vec<MetaUploadSegsThread>,
thread_selector: HashRing<usize>,
}
impl MetaUploadSegsThreadPool {
pub fn new(
num: u32,
prefix: &String,
mgr: Arc<dyn MetaServiceMgr>,
batch_upload_segs_num: u64,
) -> (Self, Vec<Sender<MetaBatchOp>>) {
let mut senders: Vec<Sender<MetaBatchOp>> = Vec::new();
let mut thr_pool: Vec<MetaUploadSegsThread> = Vec::new();
let mut thr_vec: Vec<usize> = Vec::new();
for i in 0..num {
let name = format!("{}_{}", prefix, i);
let (upload_segs_thread, sender) =
MetaUploadSegsThread::new(&name, mgr.clone(), batch_upload_segs_num);
thr_pool.push(upload_segs_thread);
thr_vec.push(i as usize);
senders.push(sender);
}
return (
MetaUploadSegsThreadPool {
pool: thr_pool,
thread_selector: HashRing::new(thr_vec, 3),
},
senders,
);
}
pub fn stop(&mut self) {
for t in &mut self.pool {
t.stop();
}
}
pub fn num(&self) -> u32 {
self.pool.len() as u32
}
pub fn get_meta_thread_for_seg(&self, id0: u64, id1: u64) -> &MetaUploadSegsThread {
let idx: usize;
let id = NumberOp::to_u128(id0, id1);
let ret = self.thread_selector.get_node(id.to_string());
if let Some(id) = ret {
idx = *id;
} else {
let size = self.num();
idx = (id % size as u128) as usize;
}
return &self.pool[idx];
}
pub fn get_meta_thread_for_ino(&self, ino: u64, generation: u64) -> &MetaUploadSegsThread {
let id = NumberOp::to_u128(ino, generation);
let idx: usize;
let ret = self.thread_selector.get_node(id.to_string());
if let Some(id) = ret {
idx = *id;
} else {
let size = self.num();
idx = (id % size as u128) as usize;
}
return &self.pool[idx];
}
}
| 28.875 | 95 | 0.55368 |
db72bf76551f2d844c352707d02196b3d31b7d70 | 3,258 | ps1 | PowerShell | Get-VPNStatus.ps1 | gildas/posh-anyconnect | f2ce34f50829badaf0ebd47ec84b71e3492ece62 | [
"MIT"
] | 11 | 2016-01-08T16:07:59.000Z | 2022-03-01T15:33:07.000Z | Get-VPNStatus.ps1 | gildas/posh-anyconnect | f2ce34f50829badaf0ebd47ec84b71e3492ece62 | [
"MIT"
] | 4 | 2016-10-06T19:48:01.000Z | 2020-08-07T07:40:04.000Z | Get-VPNStatus.ps1 | gildas/posh-anyconnect | f2ce34f50829badaf0ebd47ec84b71e3492ece62 | [
"MIT"
] | 2 | 2019-12-17T10:59:29.000Z | 2020-08-06T18:40:10.000Z | function Get-AnyConnectStatus() # {{{
{
[CmdletBinding()]
[OutputType([string])]
Param(
[Parameter(Mandatory=$false)]
[PSCustomObject] $VPNSession
)
Write-Verbose "Starting the AnyConnect cli"
$vpncli = New-Object System.Diagnostics.Process
$vpncli.StartInfo = New-Object System.Diagnostics.ProcessStartInfo(Get-AnyConnect)
$vpncli.StartInfo.Arguments = "state"
$vpncli.StartInfo.CreateNoWindow = $false
$vpncli.StartInfo.UseShellExecute = $false
$vpncli.StartInfo.RedirectStandardOutput = $true
$vpncli.StartInfo.RedirectStandardError = $true
$vpncli.Start() | Out-Null
$status = 'Unknown'
Write-Verbose "Reading its output"
for ($output = $vpncli.StandardOutput.ReadLine(); $output -ne $null; $output = $vpncli.StandardOutput.ReadLine())
{
Write-Debug $output
if ($output -match ' >> note: (.*)')
{
Write-Warning $matches[1]
$status = 'Note'
}
if ($output -match ' >> state: (.*)')
{
$status = $matches[1]
Write-Verbose $status
}
}
for ($output = $vpncli.StandardError.ReadLine(); $output -ne $null; $output = $vpncli.StandardError.ReadLine())
{
Write-Warning $output
}
return $status
} #}}}
<#
.SYNOPSIS
Gets the current status of a VPN Session or a Provider.
.DESCRIPTION
Gets the current status of a VPN Session or a Provider.
.NOTES
Only Cisco AnyConnect VPNs are supported as of now.
.PARAMETER Provider
The VPN Provider to use.
One of: AnyConnect
.PARAMETER VPNSession
The VPN session object returned by Connect-VPN.
.OUTPUTS
System.String
The current status of the VPN Session of the Provider.
With AnyConnect, the values are typically: Connected, Disconnected, Unknown.
.LINK
https://github.com/gildas/posh-vpn
.EXAMPLE
$session = Connect-VPN -Provider AnyConnect -ComputerName vpn.acme.com -Credentials (Get-Credential ACME\gildas)
Get-VPNStatus $session
Connected
Description
-----------
Gets the connection of a session
.EXAMPLE
Get-VPNStatus -Provider AnyConnect
Disconnected
Description
-----------
Gets the status of Cisco AnyConnect VPN
#>
function Get-VPNStatus() # {{{
{
[CmdletBinding(DefaultParameterSetName='Session')]
[OutputType([string])]
Param(
[Parameter(Position=1, ParameterSetName='Session', Mandatory=$true)]
[PSCustomObject] $VPNSession,
[Parameter(Position=1, ParameterSetName='Provider', Mandatory=$true)]
[ValidateSet('AnyConnect')]
[string] $Provider
)
switch($PSCmdlet.ParameterSetName)
{
'Session'
{
switch($VPNSession.Provider)
{
'AnyConnect' { Get-AnyConnectStatus @PSBoundParameters }
$null { Throw [System.ArgumentException] "VPNSession misses a Provider"; }
default { Throw "Unsupported VPN Provider: $VPNSession.Provider" }
}
}
'Provider'
{
$PSBoundParameters.Remove('Provider') | Out-Null
switch($Provider)
{
'AnyConnect' { Get-AnyConnectStatus @PSBoundParameters }
default { Throw "Unsupported VPN Provider: $VPNSession.Provider" }
}
}
}
} # }}}
| 27.610169 | 116 | 0.644874 |
bcdb4136277e7591140f76c2a1819e8430f2b381 | 918 | ps1 | PowerShell | scipts/setup.ps1 | beric7/YOLOv4_infrastructure | d5c7ec0296dbe3db656ab6a0259bc709162539d4 | [
"Apache-2.0"
] | null | null | null | scipts/setup.ps1 | beric7/YOLOv4_infrastructure | d5c7ec0296dbe3db656ab6a0259bc709162539d4 | [
"Apache-2.0"
] | null | null | null | scipts/setup.ps1 | beric7/YOLOv4_infrastructure | d5c7ec0296dbe3db656ab6a0259bc709162539d4 | [
"Apache-2.0"
] | null | null | null | ## enable or disable installed components
$install_cuda=$true
###########################
# Download and install Chocolatey
Set-ExecutionPolicy unrestricted
Invoke-Expression ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))
choco.exe install -y cmake ninja powershell git vscode
choco-exe install -y visualstudio2019buildtools --package-parameters "--add Microsoft.VisualStudio.Component.VC.CoreBuildTools --includeRecommended --includeOptional --passive --locale en-US --lang en-US"
if ($install_cuda) {
choco-exe install -y cuda
$features = "full"
}
else {
$features = "opencv-base,weights,weights-train"
}
Remove-Item -r $temp_folder
Set-Location ..
Set-Location $vcpkg_folder\
git.exe clone https://github.com/microsoft/vcpkg
Set-Location vcpkg
.\bootstrap-vcpkg.bat -disableMetrics
.\vcpkg.exe install darknet[${features}]:x64-windows
| 32.785714 | 205 | 0.733115 |
06e8a346348d3dd22c1f04d3dcf078026fcade91 | 619 | swift | Swift | ReSwiftRouter/NavigationActions.swift | egorvoronov/ReSwift-Router | 804c8cbb390a31bd777dc06f8f5b356160608662 | [
"MIT"
] | 38 | 2016-01-20T13:45:08.000Z | 2021-01-06T00:15:39.000Z | ReSwiftRouter/NavigationActions.swift | anshkhanna/ReSwift-Router | 5231c3e645317c32977b8514aeee6f6f8e3aa16e | [
"MIT"
] | 10 | 2016-01-22T20:55:45.000Z | 2020-04-03T02:19:10.000Z | ReSwiftRouter/NavigationActions.swift | anshkhanna/ReSwift-Router | 5231c3e645317c32977b8514aeee6f6f8e3aa16e | [
"MIT"
] | 26 | 2016-02-04T16:51:20.000Z | 2021-01-06T00:15:37.000Z | //
// NavigationAction.swift
// Meet
//
// Created by Benjamin Encz on 11/27/15.
// Copyright © 2015 DigiTales. All rights reserved.
//
import ReSwift
public struct SetRouteAction: Action {
let route: Route
let animated: Bool
public static let type = "RE_SWIFT_ROUTER_SET_ROUTE"
public init (_ route: Route, animated: Bool = true) {
self.route = route
self.animated = animated
}
}
public struct SetRouteSpecificData: Action {
let route: Route
let data: Any
public init(route: Route, data: Any) {
self.route = route
self.data = data
}
}
| 18.757576 | 57 | 0.638126 |
cf1838c61c7a74fce28c232f21ed7242e5195090 | 105 | css | CSS | css/mystyles.css | Bm2mhc/Slotshaven-bet | dccbe779b66fb51735826e073d22a11a0a6931f5 | [
"MIT"
] | null | null | null | css/mystyles.css | Bm2mhc/Slotshaven-bet | dccbe779b66fb51735826e073d22a11a0a6931f5 | [
"MIT"
] | null | null | null | css/mystyles.css | Bm2mhc/Slotshaven-bet | dccbe779b66fb51735826e073d22a11a0a6931f5 | [
"MIT"
] | null | null | null | .activity{
padding:15px;
border-radius:4px;
border: 1px solid grey;
margin-bottom:6px;
}
| 15 | 27 | 0.638095 |
e757a0e6ffaef675eefcb46c998695c63c85bdd0 | 48 | js | JavaScript | src/components/knob/index.js | tsucaet/quasar | 874da3b749aba563731969b1d4e60a96f9f547e0 | [
"MIT"
] | 1 | 2020-09-14T09:34:32.000Z | 2020-09-14T09:34:32.000Z | src/components/knob/index.js | AreaDeno/quasar | 0cfeafded36461487ec1ce6b63705f87e2b65333 | [
"MIT"
] | 1 | 2018-02-26T07:24:32.000Z | 2018-02-26T07:24:32.000Z | src/components/knob/index.js | AreaDeno/quasar | 0cfeafded36461487ec1ce6b63705f87e2b65333 | [
"MIT"
] | null | null | null | import QKnob from './QKnob'
export {
QKnob
}
| 8 | 27 | 0.645833 |
072a7af9bc9cf9b66fdddba54f65355c008d0be9 | 803 | dart | Dart | lib/module_user/manager/user/user_manager.dart | Mohammed0Shnan/reposito | 14584a1b293ffabc0168a52fc2dcf3b364101cef | [
"MIT"
] | null | null | null | lib/module_user/manager/user/user_manager.dart | Mohammed0Shnan/reposito | 14584a1b293ffabc0168a52fc2dcf3b364101cef | [
"MIT"
] | null | null | null | lib/module_user/manager/user/user_manager.dart | Mohammed0Shnan/reposito | 14584a1b293ffabc0168a52fc2dcf3b364101cef | [
"MIT"
] | null | null | null | import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter_boilerplate/module_user/model/user/user_model.dart';
import 'package:flutter_boilerplate/module_user/repository/user/user_repository.dart';
import 'package:flutter_boilerplate/module_user/request/user_edit_request/user_edit_equest.dart';
import 'package:inject/inject.dart';
@provide
class UserManager {
final UserRepository _userRepository =UserRepository();
UserManager();
Future<List> getUsers()async {
return await _userRepository.requestUsers();
}
Future<Map<String ,dynamic>> editProfile(EditProfileRequest request,token)async {
return await _userRepository.editProfile(request,token);
}
Future<Map> createUser(UserModel user) async{
return await _userRepository.createUser(user);
}
}
| 30.884615 | 97 | 0.799502 |
7d841096b014f651cb9db3e2ded432c174bc0ea4 | 1,234 | html | HTML | QaA/ask/templates/ask/unanswered.html | jedrzejkozal/QuestionsAndAnswers | 24e8915295af08f1904cfe7c1ac2b1719586d7d7 | [
"MIT"
] | null | null | null | QaA/ask/templates/ask/unanswered.html | jedrzejkozal/QuestionsAndAnswers | 24e8915295af08f1904cfe7c1ac2b1719586d7d7 | [
"MIT"
] | null | null | null | QaA/ask/templates/ask/unanswered.html | jedrzejkozal/QuestionsAndAnswers | 24e8915295af08f1904cfe7c1ac2b1719586d7d7 | [
"MIT"
] | null | null | null | {% extends "ask/navigation_bar.html" %}
{% load static %}
{%block styles %}
<link rel="stylesheet" type="text/css" href="{% static 'ask/navigation_bar.css' %}">
<link rel="stylesheet" type="text/css" href="{% static 'ask/questions.css' %}">
<link rel="stylesheet" type="text/css" href="{% static 'ask/unanswered.css' %}">
{% endblock styles %}
{% block content %}
<div class="questions">
{% if unanswered_questions %}
{% for question in unanswered_questions %}
<div class="question_block">
<a class="asked_by">Asked by: {{ question.asked_by.username }}</a>
<a class="asked_date"> {{ question.date }} </a>
<p class="question">{{ question.content }}</p>
<form method="POST" action="{% url 'ask:unanswered' %}">
{% csrf_token %}
<input type="text" class="answer_textbox" name="answer_content" required>
<input type="hidden" name="question_id" value={{question.id}} required>
<input type="submit" class="answer_submit" value="Answer">
</form>
</div>
{% endfor %}
{% else %}
<div class="question_block">
<p class="no_unanswered">No unanswered questions</p>
</div>
{% endif %}
</div>
{% endblock content %} | 38.5625 | 85 | 0.604538 |
043a72eb323e48e476566b145b5e78a85cd99875 | 2,116 | java | Java | Greedy Algorithms/activity-selection.java | MaunilN/DSA-for-SDE-interview | 026cf3f53b3a252c33ed5cec95f71dd914f62ad5 | [
"MIT"
] | 15 | 2020-06-22T08:37:01.000Z | 2022-02-13T19:27:54.000Z | Greedy Algorithms/activity-selection.java | MaunilN/DSA-for-SDE-interview | 026cf3f53b3a252c33ed5cec95f71dd914f62ad5 | [
"MIT"
] | 3 | 2020-09-30T18:45:43.000Z | 2020-09-30T18:59:08.000Z | Greedy Algorithms/activity-selection.java | MaunilN/DSA-for-SDE-interview | 026cf3f53b3a252c33ed5cec95f71dd914f62ad5 | [
"MIT"
] | 16 | 2020-08-27T06:59:46.000Z | 2022-01-06T17:40:30.000Z | /*
Activity Selection
Given N activities with their start and finish times. Select the maximum number of activities that can
be performed by a single person, assuming that a person can only work on a single activity at a time.
Note : The start time and end time of two activities may coincide.
Input:
The first line contains T denoting the number of testcases. Then follows description of testcases. First line
is N number of activities then second line contains N numbers which are starting time of activies.Third line
contains N finishing time of activities.
Output:
For each test case, output a single number denoting maximum activites which can be performed in new line.
Constraints:
1<=T<=50
1<=N<=1000
1<=A[i]<=100 */
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG {
static class pair{
int start;
int finish;
}
static class CustomSort implements Comparator<pair>
{
public int compare(pair p1,pair p2)
{
if(p1.finish>p2.finish) return 1;
return -1;
}
}
public static void main (String[] args) {
//code
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-- >0)
{
int n = sc.nextInt();
int start[] = new int[n];
int finish[] = new int[n];
for(int i=0;i<n;i++)
start[i] = sc.nextInt();
for(int i=0;i<n;i++)
finish[i] = sc.nextInt();
System.out.println(activity(start,finish,n));
}
}
static int activity(int s[],int f[],int n)
{
ArrayList<pair>al = new ArrayList<>();
for(int i=0;i<n;i++)
{
pair p = new pair();
p.start = s[i];
p.finish = f[i];
al.add(p);
}
Collections.sort(al,new CustomSort());
int end = Integer.MIN_VALUE;
int count =0;
for(int i=0;i<al.size();i++)
{
pair p = al.get(i);
if(p.start >= end)
{
count++;
end = p.finish;
}
}
return(count);
}
} | 23.775281 | 110 | 0.566635 |
d540922f44688f67d44a7565def5e319de27acf8 | 354 | sql | SQL | src/main/resources/dbmigrate/hsql/group/V0_0_0_4__group_relation.sql | GEDS1990/szyoa | b646384c1cd995e8812455885228b4347bffe5b9 | [
"Apache-2.0"
] | null | null | null | src/main/resources/dbmigrate/hsql/group/V0_0_0_4__group_relation.sql | GEDS1990/szyoa | b646384c1cd995e8812455885228b4347bffe5b9 | [
"Apache-2.0"
] | null | null | null | src/main/resources/dbmigrate/hsql/group/V0_0_0_4__group_relation.sql | GEDS1990/szyoa | b646384c1cd995e8812455885228b4347bffe5b9 | [
"Apache-2.0"
] | null | null | null |
CREATE TABLE GROUP_RELATION(
ID BIGINT NOT NULL,
PARENT_ID BIGINT,
CHILD_ID BIGINT,
TENANT_ID VARCHAR(64),
CONSTRAINT PK_GROUP_RELATION PRIMARY KEY(ID),
CONSTRAINT FK_GROUP_RELATION_PARENT FOREIGN KEY(PARENT_ID) REFERENCES GROUP_INFO(ID),
CONSTRAINT FK_GROUP_RELATION_CHILD FOREIGN KEY(CHILD_ID) REFERENCES GROUP_INFO(ID)
);
| 32.181818 | 93 | 0.774011 |
8f80887d887144807200c3018b78840fe1f5bd95 | 1,569 | sql | SQL | egov/egov-collection/src/main/resources/db/migration/main/V20160208171251__collection_workflow_challan.sql | cscl-git/digit-bpa | bcf2a4f0dadcee3d636357c51350db96071b40c6 | [
"MIT"
] | null | null | null | egov/egov-collection/src/main/resources/db/migration/main/V20160208171251__collection_workflow_challan.sql | cscl-git/digit-bpa | bcf2a4f0dadcee3d636357c51350db96071b40c6 | [
"MIT"
] | null | null | null | egov/egov-collection/src/main/resources/db/migration/main/V20160208171251__collection_workflow_challan.sql | cscl-git/digit-bpa | bcf2a4f0dadcee3d636357c51350db96071b40c6 | [
"MIT"
] | null | null | null | delete from eg_roleaction where roleid in (select id from eg_role where name = 'ULB Operator') and actionid in (select id from eg_action where name in('CreateChallan','AjaxChallanApproverDesignation','AjaxChallanApproverPosition'));
INSERT INTO eg_role (id, name, description, createddate, createdby, lastmodifiedby, lastmodifieddate, version)
VALUES (nextval('SEQ_EG_ROLE'), 'Challan Creator', 'Challan Creator', now(), 1, 1, now(), 0);
INSERT INTO EG_USERROLE(ROLEID,USERID)(SELECT (SELECT id FROM eg_role WHERE name = 'Challan Creator'),u.id
FROM view_egeis_employee v ,eg_user u WHERE u.username = v.username
AND v.designation in (SELECT id from eg_designation where name in ('Junior Assistant'))
and v.department in (select id from eg_department where upper(name) in ('REVENUE','ACCOUNTS','ADMINISTRATION')));
Insert into eg_roleaction (roleid, actionid) (select (select id from eg_role where name = 'Challan Creator') as roleid , id from eg_action where name in('CreateChallan','AjaxChallanApproverDesignation','AjaxChallanApproverPosition','SaveChallan'));
INSERT INTO eg_appconfig ( ID, KEY_NAME, DESCRIPTION, VERSION, MODULE ) VALUES (nextval('SEQ_EG_APPCONFIG'), 'COLLECTIONDESIGCHALLANWORKFLOW','Collection Challan Validator Designation',0, (select id from eg_module where name='Collection'));
INSERT INTO eg_appconfig_values ( ID, KEY_ID, EFFECTIVE_FROM, VALUE, VERSION ) VALUES (nextval('SEQ_EG_APPCONFIG_VALUES'),(SELECT id FROM EG_APPCONFIG WHERE KEY_NAME='COLLECTIONDESIGCHALLANWORKFLOW'),current_date, 'Senior Assistant',0);
| 104.6 | 250 | 0.779477 |
7f3084032e09cca22c18b347643be917712b7025 | 1,580 | go | Go | src/mongo/gotools/common/db/tlsgo/rootcerts_darwin.go | wiredtiger/mongo-wiredtiger-evg | 5c97edfba301beb31bd8dcabc81c43f1097d2467 | [
"Apache-2.0"
] | null | null | null | src/mongo/gotools/common/db/tlsgo/rootcerts_darwin.go | wiredtiger/mongo-wiredtiger-evg | 5c97edfba301beb31bd8dcabc81c43f1097d2467 | [
"Apache-2.0"
] | null | null | null | src/mongo/gotools/common/db/tlsgo/rootcerts_darwin.go | wiredtiger/mongo-wiredtiger-evg | 5c97edfba301beb31bd8dcabc81c43f1097d2467 | [
"Apache-2.0"
] | null | null | null | // Copyright (C) MongoDB, Inc. 2018-present.
//
// 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
//
// Based on https://github.com/hashicorp/go-rootcerts by HashiCorp
// See THIRD-PARTY-NOTICES for original license terms.
// +build ssl,openssl_pre_1.0
package tlsgo
import (
"crypto/x509"
"os/exec"
"os/user"
"path"
)
// loadSystemCAs has special behavior on Darwin systems to work around
// bugs loading certs from keychains. See this GitHub issues query:
// https://github.com/golang/go/issues?utf8=%E2%9C%93&q=is%3Aissue+darwin+keychain
func loadSystemCAs() (*x509.CertPool, error) {
pool := x509.NewCertPool()
for _, keychain := range certKeychains() {
err := addCertsFromKeychain(pool, keychain)
if err != nil {
return nil, err
}
}
return pool, nil
}
func addCertsFromKeychain(pool *x509.CertPool, keychain string) error {
cmd := exec.Command("/usr/bin/security", "find-certificate", "-a", "-p", keychain)
data, err := cmd.Output()
if err != nil {
return err
}
pool.AppendCertsFromPEM(data)
return nil
}
func certKeychains() []string {
keychains := []string{
"/System/Library/Keychains/SystemRootCertificates.keychain",
"/Library/Keychains/System.keychain",
}
user, err := user.Current()
if err == nil {
loginKeychain := path.Join(user.HomeDir, "Library", "Keychains", "login.keychain")
keychains = append(keychains, loginKeychain)
}
return keychains
}
| 25.901639 | 84 | 0.708228 |
40c4f53fbbf17d23229fe528f106c87b9a4b0bcb | 342 | py | Python | python_skeleton_project/tools/hello_world.py | aagnone3/python-skeleton | 5f8f334ec36388ea51f4aed9074c8222d4c2b0b6 | [
"Apache-2.0"
] | 1 | 2020-04-01T05:17:44.000Z | 2020-04-01T05:17:44.000Z | python_skeleton_project/tools/hello_world.py | aagnone3/python-skeleton | 5f8f334ec36388ea51f4aed9074c8222d4c2b0b6 | [
"Apache-2.0"
] | 2 | 2018-11-23T02:32:09.000Z | 2021-12-20T14:36:53.000Z | python_skeleton_project/tools/hello_world.py | aagnone3/python-skeleton | 5f8f334ec36388ea51f4aed9074c8222d4c2b0b6 | [
"Apache-2.0"
] | 4 | 2019-03-21T17:15:51.000Z | 2021-07-22T13:59:36.000Z | import sys
from argparse import ArgumentParser
from python_skeleton_project import greet_world
def get_clargs():
parser = ArgumentParser()
parser.add_argument("-d", "--descriptor", help="Descriptor of world to greet.")
return parser.parse_args()
def main():
args = get_clargs()
sys.exit(greet_world(args.descriptor))
| 21.375 | 83 | 0.730994 |
04d0328da9fa4b6230dd9663e7c2f19eafa50ebf | 5,001 | java | Java | src/main/java/gyro/aws/ec2/EbsSnapshotFinder.java | perfectsense/gyro-aws-provider | d7bbb01e4c6c860241436a46e32dd325a18e62bd | [
"Apache-2.0"
] | 9 | 2019-10-07T19:40:46.000Z | 2021-08-09T17:58:41.000Z | src/main/java/gyro/aws/ec2/EbsSnapshotFinder.java | perfectsense/gyro-aws-provider | d7bbb01e4c6c860241436a46e32dd325a18e62bd | [
"Apache-2.0"
] | 194 | 2019-10-09T20:07:25.000Z | 2022-03-02T20:59:09.000Z | src/main/java/gyro/aws/ec2/EbsSnapshotFinder.java | perfectsense/gyro-aws-provider | d7bbb01e4c6c860241436a46e32dd325a18e62bd | [
"Apache-2.0"
] | 1 | 2019-12-08T07:57:03.000Z | 2019-12-08T07:57:03.000Z | /*
* Copyright 2019, Perfect Sense, 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 gyro.aws.ec2;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import gyro.core.Type;
import software.amazon.awssdk.services.ec2.Ec2Client;
import software.amazon.awssdk.services.ec2.model.Snapshot;
/**
* Query ebs snapshot.
*
* Example
* -------
*
* .. code-block:: gyro
*
* ebs-snapshot: $(external-query aws::ebs-snapshot { owner-alias: 'amazon'})
*/
@Type("ebs-snapshot")
public class EbsSnapshotFinder extends Ec2TaggableAwsFinder<Ec2Client, Snapshot, EbsSnapshotResource> {
private String description;
private String encrypted;
private String ownerAlias;
private String ownerId;
private String progress;
private String snapshotId;
private String startTime;
private String status;
private Map<String, String> tag;
private String tagKey;
private String volumeId;
private String volumeSize;
/**
* A description of the snapshot.
*/
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
/**
* Indicates whether the snapshot is encrypted . Valid values are ``true`` or ``false``
*/
public String getEncrypted() {
return encrypted;
}
public void setEncrypted(String encrypted) {
this.encrypted = encrypted;
}
/**
* Value from an Amazon-maintained list . Valid values are ``amazon`` or ``self`` or ``all`` or ``aws-marketplace`` or ``microsoft``.
*/
public String getOwnerAlias() {
return ownerAlias;
}
public void setOwnerAlias(String ownerAlias) {
this.ownerAlias = ownerAlias;
}
/**
* The ID of the AWS account that owns the snapshot.
*/
public String getOwnerId() {
return ownerId;
}
public void setOwnerId(String ownerId) {
this.ownerId = ownerId;
}
/**
* The progress of the snapshot, as a percentage (for example, 80%).
*/
public String getProgress() {
return progress;
}
public void setProgress(String progress) {
this.progress = progress;
}
/**
* The snapshot ID.
*/
public String getSnapshotId() {
return snapshotId;
}
public void setSnapshotId(String snapshotId) {
this.snapshotId = snapshotId;
}
/**
* The time stamp when the snapshot was initiated.
*/
public String getStartTime() {
return startTime;
}
public void setStartTime(String startTime) {
this.startTime = startTime;
}
/**
* The status of the snapshot . Valid values are ``pending`` or ``completed`` or ``error``.
*/
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
/**
* The key/value combination of a tag assigned to the resource.
*/
public Map<String, String> getTag() {
if (tag == null) {
tag = new HashMap<>();
}
return tag;
}
public void setTag(Map<String, String> tag) {
this.tag = tag;
}
/**
* The key of a tag assigned to the resource. Use this filter to find all resources assigned a tag with a specific key, regardless of the tag value.
*/
public String getTagKey() {
return tagKey;
}
public void setTagKey(String tagKey) {
this.tagKey = tagKey;
}
/**
* The ID of the volume the snapshot is for.
*/
public String getVolumeId() {
return volumeId;
}
public void setVolumeId(String volumeId) {
this.volumeId = volumeId;
}
/**
* The size of the volume, in GiB.
*/
public String getVolumeSize() {
return volumeSize;
}
public void setVolumeSize(String volumeSize) {
this.volumeSize = volumeSize;
}
@Override
protected List<Snapshot> findAllAws(Ec2Client client) {
return client.describeSnapshotsPaginator().snapshots().stream().collect(Collectors.toList());
}
@Override
protected List<Snapshot> findAws(Ec2Client client, Map<String, String> filters) {
return client.describeSnapshotsPaginator(r -> r.filters(createFilters(filters)))
.snapshots().stream().collect(Collectors.toList());
}
}
| 24.880597 | 152 | 0.634673 |
fb950b0d958788d317102dad0e6275db0a24779f | 2,190 | java | Java | src/main/java/com/example/mothertochild/mapper/CategoryMapper.java | QiRang/mother-to-child-online-shopping | 274a6ea279baba2693c250e8a4f451a5665fb2b4 | [
"MIT"
] | null | null | null | src/main/java/com/example/mothertochild/mapper/CategoryMapper.java | QiRang/mother-to-child-online-shopping | 274a6ea279baba2693c250e8a4f451a5665fb2b4 | [
"MIT"
] | null | null | null | src/main/java/com/example/mothertochild/mapper/CategoryMapper.java | QiRang/mother-to-child-online-shopping | 274a6ea279baba2693c250e8a4f451a5665fb2b4 | [
"MIT"
] | null | null | null | package com.example.mothertochild.mapper;
import com.example.mothertochild.entity.Category;
import com.github.pagehelper.Page;
import org.apache.ibatis.annotations.*;
import java.util.List;
@Mapper
public interface CategoryMapper {
//查询所有,不包括产品
@Select("select * from category")
// @Results({
// @Result(id=true,column="categoryId",property="categoryId"),
// @Result(property = "products", column = "categoryId",
// many = @Many(select = "com.example.mothertochild.mapper.ProductMapper.findProductByCategoryId"))
// })
List<Category> categoryList();
// 查询所有,包括产品
@Select("select * from category")
@Results({
@Result(id=true,column="categoryId",property="categoryId"),
@Result(property = "products", column = "categoryId",
many = @Many(select = "com.example.mothertochild.mapper.ProductMapper.findProductByCategoryId"))
})
List<Category> categoryAndProductList();
//按页查询
@Select("select * from category order by categoryId desc")
Page<Category> categoryListWithPage();
@Select("SELECT * from category WHERE categoryName LIKE CONCAT('%',#{categoryName},'%') order by categoryId desc")
List<Category> searchCategoryList(String categoryName);
//查询单条记录
@Select("select * from category where categoryName = #{categoryName}")
Category getCategory(String categoryName);
//查询单条记录
@Select("select * from category where categoryId = #{categoryId}")
Category getCategoryById(String categoryId);
//插入一条记录
@Options(useGeneratedKeys = true,keyProperty = "categoryId")
@Insert("insert into category(categoryName,categoryIcon,createDate) values (#{categoryName},#{categoryIcon},#{createDate})")
int insertCategory(Category category);
//删除一条记录
@Delete("delete from category where categoryId = #{categoryId}")
int deleteCategory(int categoryId);
//更改
@Options(useGeneratedKeys = true,keyProperty = "categoryId")
@Update("update category set categoryName= #{categoryName},categoryIcon = #{categoryIcon} where categoryId = #{categoryId}")
public int updateCategory(Category category);
}
| 36.5 | 128 | 0.691324 |
6baf1b8d5864707ebf3a73896e13618596f1e512 | 15,944 | swift | Swift | Division2FanApp/Logic/DpsCalculator.swift | ChristianDeckert/Division2FanApp | 46ef705cd95525cd9749b4793300bbf49206a105 | [
"MIT"
] | 4 | 2019-03-15T22:19:10.000Z | 2019-03-26T13:55:00.000Z | Division2FanApp/Logic/DpsCalculator.swift | ChristianDeckert/Division2FanApp | 46ef705cd95525cd9749b4793300bbf49206a105 | [
"MIT"
] | 1 | 2019-03-18T13:34:53.000Z | 2019-03-18T13:34:53.000Z | Division2FanApp/Logic/DpsCalculator.swift | ChristianDeckert/Division2FanApp | 46ef705cd95525cd9749b4793300bbf49206a105 | [
"MIT"
] | null | null | null | //
// DpsCalculator.swift
// Division2FanApp
//
// Created by Christian on 15.03.19.
// Copyright © 2019 Christian Deckert. All rights reserved.
//
import Foundation
import CommonCrypto
enum Attribute {
case weaponDamage
case criticalHitChance
case criticalHitDamage
case headshotDamage
case outOfCoverDamage
case enemyArmorDamage
case healthDamage
case damageToElites
case rpm
var description: String {
switch self {
case .weaponDamage: return "calculator-controller.weapon-damage.title".localized
case .criticalHitChance: return "calculator-controller.crit-chance.title".localized
case .criticalHitDamage: return "calculator-controller.crit-damage.title".localized
case .headshotDamage: return "calculator-controller.headshot-damage.title".localized
case .outOfCoverDamage: return "calculator-controller.out-of-cover-damage.title".localized
case .enemyArmorDamage: return "calculator-controller.enemy-armor-damage.title".localized
case .healthDamage: return "calculator-controller.health-damage.title".localized
case .damageToElites: return "calculator-controller.damage-to-elites.title".localized
case .rpm: return "calculator-controller.rpm.title".localized
}
}
}
enum Category {
case bodyshot
case headshot
case critBodyShot
case critHeadShot
case dps
}
final class DpsCalculator {
static let defaultWeaponDamage: Double = 5000
struct InputAttribute {
let attribute: Attribute
let value: Double
}
var inputAttributes: Set<InputAttribute>
var isValid: Bool {
return value(of: .weaponDamage) > 0
}
init(inputAttributes: Set<InputAttribute> = []) {
self.inputAttributes = inputAttributes
if !has(attribute: .weaponDamage) {
add(attribute: .weaponDamage, value: DpsCalculator.defaultWeaponDamage)
}
}
private func has(attribute: Attribute) -> Bool {
return inputAttributes.first(where: { $0.attribute == attribute }) != nil
}
private func value(of attribute: Attribute) -> Double {
return inputAttributes.first(where: { $0.attribute == attribute })?.value ?? 0
}
func add(attribute: Attribute, value: Double) {
if let existing = inputAttributes.firstIndex(where: { $0.attribute == attribute }) {
inputAttributes.remove(at: existing)
}
inputAttributes.insert(DpsCalculator.InputAttribute(
attribute: attribute,
value: value
)
)
}
func calulate(stat: StatsCollectionViewController.Stat, category: Category) -> Double {
let weaponDamageValue = value(of: .weaponDamage)
guard weaponDamageValue > 0 else { return 0 }
let headshotRate: Double = 100
var result: Double = 0
switch stat {
case .npcInCoverHealth:
let healthDamageValue = value(of: .healthDamage)
switch category {
case .bodyshot:
result = weaponDamageValue * (1 + healthDamageValue / 100)
case .headshot:
let headshotDamage = value(of: .headshotDamage)
result = weaponDamageValue * (1 + healthDamageValue / 100) * (1 + headshotDamage / 100)
case .critBodyShot:
let criticalHitDamage = value(of: .criticalHitDamage)
result = weaponDamageValue * (1 + healthDamageValue / 100) * (1 + criticalHitDamage / 100)
case .critHeadShot:
let criticalHitDamage = value(of: .criticalHitDamage)
let headshotDamage = value(of: .headshotDamage)
result = weaponDamageValue * (1 + healthDamageValue / 100) * (1 + criticalHitDamage / 100 + headshotDamage / 100)
case .dps:
let criticalHitDamage = value(of: .criticalHitDamage)
let criticalHitChance = value(of: .criticalHitChance)
let headshotDamage = value(of: .headshotDamage)
let rpm = value(of: .rpm)
result = weaponDamageValue * (1 + criticalHitDamage/100 * criticalHitChance/100)
* (1 + (headshotDamage/100) * (headshotRate/100))
* (rpm/60)
* (1 + healthDamageValue/100)
}
case .eliteNpcInCoverHealth:
let healthDamageValue = value(of: .healthDamage)
let damageToElites = value(of: .damageToElites)
switch category {
case .bodyshot:
result = weaponDamageValue * (1 + healthDamageValue / 100) * (1 + damageToElites / 100)
case .headshot:
let headshotDamage = value(of: .headshotDamage)
result = weaponDamageValue * (1 + healthDamageValue / 100) * (1 + headshotDamage / 100) * (1 + damageToElites / 100)
case .critBodyShot:
let criticalHitDamage = value(of: .criticalHitDamage)
result = weaponDamageValue * (1 + healthDamageValue / 100) * (1 + criticalHitDamage / 100) * (1 + damageToElites / 100)
case .critHeadShot:
let criticalHitDamage = value(of: .criticalHitDamage)
let headshotDamage = value(of: .headshotDamage)
result = weaponDamageValue * (1 + healthDamageValue / 100) * (1 + criticalHitDamage / 100 + headshotDamage / 100) * (1 + damageToElites / 100)
case .dps:
let criticalHitDamage = value(of: .criticalHitDamage)
let criticalHitChance = value(of: .criticalHitChance)
let headshotDamage = value(of: .headshotDamage)
let rpm = value(of: .rpm)
result = weaponDamageValue * (1 + criticalHitDamage/100 * criticalHitChance/100)
* (1 + (headshotDamage/100) * (headshotRate/100))
* (rpm/60)
* (1 + healthDamageValue/100)
* (1 + damageToElites/100)
}
case .npcOutOfCoverHealth:
let outOfCoverDamage = value(of: .outOfCoverDamage)
let healthDamageValue = value(of: .healthDamage)
switch category {
case .bodyshot:
result = weaponDamageValue * (1 + healthDamageValue / 100) * (1 + outOfCoverDamage / 100)
case .headshot:
let headshotDamage = value(of: .headshotDamage)
result = weaponDamageValue * (1 + healthDamageValue / 100) * (1 + headshotDamage / 100) * (1 + outOfCoverDamage / 100)
case .critBodyShot:
let criticalHitDamage = value(of: .criticalHitDamage)
result = weaponDamageValue * (1 + healthDamageValue / 100) * (1 + criticalHitDamage / 100) * (1 + outOfCoverDamage / 100)
case .critHeadShot:
let criticalHitDamage = value(of: .criticalHitDamage)
let headshotDamage = value(of: .headshotDamage)
result = weaponDamageValue * (1 + healthDamageValue / 100) * (1 + criticalHitDamage / 100 + headshotDamage / 100) * (1 + outOfCoverDamage / 100)
case .dps:
let criticalHitDamage = value(of: .criticalHitDamage)
let criticalHitChance = value(of: .criticalHitChance)
let headshotDamage = value(of: .headshotDamage)
let rpm = value(of: .rpm)
result = weaponDamageValue * (1 + criticalHitDamage/100 * criticalHitChance/100)
* (1 + (headshotDamage/100) * (headshotRate/100))
* (rpm/60)
* (1 + healthDamageValue/100)
* (1 + outOfCoverDamage/100)
}
case .eliteNpcOutOfCoverHealth:
let outOfCoverDamage = value(of: .outOfCoverDamage)
let damageToElites = value(of: .damageToElites)
let healthDamageValue = value(of: .healthDamage)
switch category {
case .bodyshot:
result = weaponDamageValue * (1 + healthDamageValue / 100) * (1 + outOfCoverDamage / 100) * (1 + damageToElites / 100)
case .headshot:
let headshotDamage = value(of: .headshotDamage)
result = weaponDamageValue * (1 + healthDamageValue / 100) * (1 + headshotDamage / 100) * (1 + outOfCoverDamage / 100) * (1 + damageToElites / 100)
case .critBodyShot:
let healthDamageValue = value(of: .healthDamage)
let criticalHitDamage = value(of: .criticalHitDamage)
result = weaponDamageValue * (1 + healthDamageValue / 100) * (1 + criticalHitDamage / 100) * (1 + outOfCoverDamage / 100) * (1 + damageToElites / 100)
case .critHeadShot:
let healthDamageValue = value(of: .healthDamage)
let criticalHitDamage = value(of: .criticalHitDamage)
let headshotDamage = value(of: .headshotDamage)
result = weaponDamageValue * (1 + healthDamageValue / 100) * (1 + criticalHitDamage / 100 + headshotDamage / 100) * (1 + outOfCoverDamage / 100) * (1 + damageToElites / 100)
case .dps:
let criticalHitDamage = value(of: .criticalHitDamage)
let criticalHitChance = value(of: .criticalHitChance)
let headshotDamage = value(of: .headshotDamage)
let rpm = value(of: .rpm)
result = weaponDamageValue * (1 + criticalHitDamage/100 * criticalHitChance/100)
* (1 + (headshotDamage/100) * (headshotRate/100))
* (rpm/60)
* (1 + healthDamageValue/100)
* (1 + outOfCoverDamage/100)
* (1 + damageToElites/100)
}
case .npcInCoverArmor:
let armorDamageValue = value(of: .enemyArmorDamage)
switch category {
case .bodyshot:
result = weaponDamageValue * (1 + armorDamageValue / 100)
case .headshot:
let headshotDamage = value(of: .headshotDamage)
result = weaponDamageValue * (1 + armorDamageValue / 100) * (1 + headshotDamage / 100)
case .critBodyShot:
let criticalHitDamage = value(of: .criticalHitDamage)
result = weaponDamageValue * (1 + armorDamageValue / 100) * (1 + criticalHitDamage / 100)
case .critHeadShot:
let criticalHitDamage = value(of: .criticalHitDamage)
let headshotDamage = value(of: .headshotDamage)
result = weaponDamageValue * (1 + armorDamageValue / 100) * (1 + criticalHitDamage / 100 + headshotDamage / 100)
case .dps:
let criticalHitDamage = value(of: .criticalHitDamage)
let criticalHitChance = value(of: .criticalHitChance)
let headshotDamage = value(of: .headshotDamage)
let rpm = value(of: .rpm)
result = weaponDamageValue * (1 + criticalHitDamage/100 * criticalHitChance/100)
* (1 + (headshotDamage/100) * (headshotRate/100))
* (rpm/60)
* (1 + armorDamageValue/100)
}
case .eliteNpcInCoverArmor:
let armorDamageValue = value(of: .enemyArmorDamage)
let damageToElites = value(of: .damageToElites)
switch category {
case .bodyshot:
result = weaponDamageValue * (1 + armorDamageValue / 100) * (1 + damageToElites / 100)
case .headshot:
let headshotDamage = value(of: .headshotDamage)
result = weaponDamageValue * (1 + armorDamageValue / 100) * (1 + headshotDamage / 100) * (1 + damageToElites / 100)
case .critBodyShot:
let criticalHitDamage = value(of: .criticalHitDamage)
result = weaponDamageValue * (1 + armorDamageValue / 100) * (1 + criticalHitDamage / 100) * (1 + damageToElites / 100)
case .critHeadShot:
let criticalHitDamage = value(of: .criticalHitDamage)
let headshotDamage = value(of: .headshotDamage)
result = weaponDamageValue * (1 + armorDamageValue / 100) * (1 + criticalHitDamage / 100 + headshotDamage / 100) * (1 + damageToElites / 100)
case .dps:
let criticalHitDamage = value(of: .criticalHitDamage)
let criticalHitChance = value(of: .criticalHitChance)
let headshotDamage = value(of: .headshotDamage)
let rpm = value(of: .rpm)
result = weaponDamageValue * (1 + criticalHitDamage/100 * criticalHitChance/100)
* (1 + (headshotDamage/100) * (headshotRate/100))
* (rpm/60)
* (1 + armorDamageValue/100)
* (1 + damageToElites/100)
}
case .npcOutOfCoverArmor:
let outOfCoverDamage = value(of: .outOfCoverDamage)
let armorDamageValue = value(of: .enemyArmorDamage)
switch category {
case .bodyshot:
result = weaponDamageValue * (1 + armorDamageValue / 100) * (1 + outOfCoverDamage / 100)
case .headshot:
let headshotDamage = value(of: .headshotDamage)
result = weaponDamageValue * (1 + armorDamageValue / 100) * (1 + headshotDamage / 100) * (1 + outOfCoverDamage / 100)
case .critBodyShot:
let criticalHitDamage = value(of: .criticalHitDamage)
result = weaponDamageValue * (1 + armorDamageValue / 100) * (1 + criticalHitDamage / 100) * (1 + outOfCoverDamage / 100)
case .critHeadShot:
let criticalHitDamage = value(of: .criticalHitDamage)
let headshotDamage = value(of: .headshotDamage)
result = weaponDamageValue * (1 + armorDamageValue / 100) * (1 + criticalHitDamage / 100 + headshotDamage / 100) * (1 + outOfCoverDamage / 100)
case .dps:
let criticalHitDamage = value(of: .criticalHitDamage)
let criticalHitChance = value(of: .criticalHitChance)
let headshotDamage = value(of: .headshotDamage)
let rpm = value(of: .rpm)
result = weaponDamageValue * (1 + criticalHitDamage/100 * criticalHitChance/100)
* (1 + (headshotDamage/100) * (headshotRate/100))
* (rpm/60)
* (1 + armorDamageValue/100)
* (1 + outOfCoverDamage/100)
}
case .eliteNpcOutOfCoverArmor:
let outOfCoverDamage = value(of: .outOfCoverDamage)
let damageToElites = value(of: .damageToElites)
let armorDamageValue = value(of: .enemyArmorDamage)
switch category {
case .bodyshot:
result = weaponDamageValue * (1 + armorDamageValue / 100) * (1 + outOfCoverDamage / 100) * (1 + damageToElites / 100)
case .headshot:
let headshotDamage = value(of: .headshotDamage)
result = weaponDamageValue * (1 + armorDamageValue / 100) * (1 + headshotDamage / 100) * (1 + outOfCoverDamage / 100) * (1 + damageToElites / 100)
case .critBodyShot:
let criticalHitDamage = value(of: .criticalHitDamage)
result = weaponDamageValue * (1 + armorDamageValue / 100) * (1 + criticalHitDamage / 100) * (1 + outOfCoverDamage / 100) * (1 + damageToElites / 100)
case .critHeadShot:
let criticalHitDamage = value(of: .criticalHitDamage)
let headshotDamage = value(of: .headshotDamage)
result = weaponDamageValue * (1 + armorDamageValue / 100) * (1 + criticalHitDamage / 100 + headshotDamage / 100) * (1 + outOfCoverDamage / 100) * (1 + damageToElites / 100)
case .dps:
let criticalHitDamage = value(of: .criticalHitDamage)
let criticalHitChance = value(of: .criticalHitChance)
let headshotDamage = value(of: .headshotDamage)
let rpm = value(of: .rpm)
result = weaponDamageValue * (1 + criticalHitDamage/100 * criticalHitChance/100)
* (1 + (headshotDamage/100) * (headshotRate/100))
* (rpm/60)
* (1 + armorDamageValue/100)
* (1 + outOfCoverDamage/100)
* (1 + damageToElites/100)
}
}
return result
}
}
extension DpsCalculator.InputAttribute: Hashable {
var hash: String {
var hasher = Hasher()
hasher.combine(attribute.description)
return String(describing: hasher.finalize())
// return sha256()
}
func sha256() -> String {
guard let data = attribute.description.data(using: .utf8) else { return "" }
/// #define CC_SHA256_DIGEST_LENGTH 32
/// Creates an array of unsigned 8 bit integers that contains 32 zeros
var digest = [UInt8](repeating: 0, count:Int(CC_SHA256_DIGEST_LENGTH))
/// CC_SHA256 performs digest calculation and places the result in the caller-supplied buffer for digest (md)
/// Takes the strData referenced value (const unsigned char *d) and hashes it into a reference to the digest parameter.
_ = data.withUnsafeBytes {
CC_SHA256($0.baseAddress, UInt32(data.count), &digest)
}
var sha256String = ""
/// Unpack each byte in the digest array and add them to the sha256String
for byte in digest {
sha256String += String(format:"%02x", UInt8(byte))
}
return sha256String
}
}
| 44.044199 | 181 | 0.655733 |
c73888c34628e7e86a7286f3eece1206e8592b5e | 728 | sql | SQL | dotnet/src/TheEight.Database/Tables/TEAM_MEMBERS.sql | the-eight/WebApp | 87df559ce1777a5d09cb6003d5af2748b9528d96 | [
"MIT"
] | null | null | null | dotnet/src/TheEight.Database/Tables/TEAM_MEMBERS.sql | the-eight/WebApp | 87df559ce1777a5d09cb6003d5af2748b9528d96 | [
"MIT"
] | 20 | 2016-09-03T20:14:57.000Z | 2016-11-29T00:14:22.000Z | dotnet/src/TheEight.Database/Tables/TEAM_MEMBERS.sql | the-eight/WebApp | 87df559ce1777a5d09cb6003d5af2748b9528d96 | [
"MIT"
] | 1 | 2016-09-03T08:47:22.000Z | 2016-09-03T08:47:22.000Z | CREATE TABLE [dbo].[TEAM_MEMBERS]
(
[TeamMemberId] UNIQUEIDENTIFIER NOT NULL,
[ClubMemberId] UNIQUEIDENTIFIER NOT NULL,
[TeamId] UNIQUEIDENTIFIER NOT NULL,
[PreferredBoatPositionId] TINYINT NOT NULL,
CONSTRAINT [PK__TEAM_MEMBERS] PRIMARY KEY ([TeamMemberId]),
CONSTRAINT [FK__TEAM_MEMBERS__CLUB_MEMBERS] FOREIGN KEY ([ClubMemberId])
REFERENCES [CLUB_MEMBERS]([ClubMemberId]),
CONSTRAINT [FK__TEAM_MEMBERS__TEAMS] FOREIGN KEY ([TeamId]) REFERENCES [TEAMS]([TeamId]),
CONSTRAINT [FK__TEAM_MEMBERS__BOAT_POSITIONS] FOREIGN KEY ([PreferredBoatPositionId])
REFERENCES [BOAT_POSITIONS]([BoatPositionId]),
CONSTRAINT [AK__TEAM_MEMBERS__ClubMemberId__TeamId] UNIQUE ([ClubMemberId], [TeamId])
)
| 48.533333 | 91 | 0.770604 |
95c50af5e66733e5fcbe30a20ff122fb6d1b6ab9 | 1,762 | dart | Dart | lib/widgets/quill_editor.dart | varadgauthankar/my_journal | 017e26480b64c2d8b4d69ed1fb33891cdaf79add | [
"MIT"
] | null | null | null | lib/widgets/quill_editor.dart | varadgauthankar/my_journal | 017e26480b64c2d8b4d69ed1fb33891cdaf79add | [
"MIT"
] | null | null | null | lib/widgets/quill_editor.dart | varadgauthankar/my_journal | 017e26480b64c2d8b4d69ed1fb33891cdaf79add | [
"MIT"
] | null | null | null | import 'package:flutter/material.dart';
import 'package:flutter_quill/flutter_quill.dart';
class MyQuillEditor {
static Widget editor({
bool autoFocus = false,
required QuillController controller,
String? placeholder,
}) {
return QuillEditor(
autoFocus: autoFocus,
controller: controller,
readOnly: false,
scrollable: true,
focusNode: FocusNode(),
expands: false,
padding: EdgeInsets.zero,
keyboardAppearance: Brightness.light,
scrollController: ScrollController(),
placeholder: placeholder,
scrollPhysics: const BouncingScrollPhysics(),
maxHeight: 300,
);
}
static toolbar(
BuildContext context, {
required QuillController controller,
}) {
return QuillToolbar.basic(
multiRowsDisplay: false,
controller: controller,
iconTheme: QuillIconTheme(
iconSelectedFillColor: Theme.of(context).colorScheme.primaryContainer,
iconSelectedColor: Theme.of(context).colorScheme.onPrimaryContainer,
),
showRedo: false,
showUndo: false,
showCodeBlock: false,
showColorButton: false,
showIndent: false,
showImageButton: false,
showVideoButton: false,
showInlineCode: false,
showJustifyAlignment: false,
showAlignmentButtons: false,
showLink: false,
showListCheck: false,
showListBullets: false,
showListNumbers: false,
showQuote: false,
showDividers: false,
showDirection: false,
showLeftAlignment: false,
showRightAlignment: false,
showSmallButton: false,
showCenterAlignment: false,
showCameraButton: false,
showClearFormat: true,
showBackgroundColorButton: true,
);
}
}
| 27.53125 | 78 | 0.675369 |
4170930a57cda29ef68823a3c9fcee504c028dda | 230 | ps1 | PowerShell | StartPoshGit.ps1 | mattblackham/GitScripts | d64f5b6fa12295ed24b7234645abc6dc9d0331c9 | [
"Apache-2.0"
] | null | null | null | StartPoshGit.ps1 | mattblackham/GitScripts | d64f5b6fa12295ed24b7234645abc6dc9d0331c9 | [
"Apache-2.0"
] | null | null | null | StartPoshGit.ps1 | mattblackham/GitScripts | d64f5b6fa12295ed24b7234645abc6dc9d0331c9 | [
"Apache-2.0"
] | null | null | null | #See https://github.com/dahlbyk/posh-git
#posh-git is a PowerShell module that integrates Git and PowerShell by providing Git status summary information that can be displayed in the PowerShell prompt, e.g.:
Import-Module posh-git | 57.5 | 165 | 0.804348 |
2633003844197ce1eff17bbe8b69fff9b3cf7f35 | 2,893 | java | Java | src/main/java/coneforest/psylla/engine/PsyllaScriptEngineFactory.java | urbic/psyche | 1c114bd30ae6c1449fd4797e16ee716382c7c0fa | [
"Zlib"
] | 1 | 2020-02-09T02:34:37.000Z | 2020-02-09T02:34:37.000Z | src/main/java/coneforest/psylla/engine/PsyllaScriptEngineFactory.java | urbic/psyche | 1c114bd30ae6c1449fd4797e16ee716382c7c0fa | [
"Zlib"
] | null | null | null | src/main/java/coneforest/psylla/engine/PsyllaScriptEngineFactory.java | urbic/psyche | 1c114bd30ae6c1449fd4797e16ee716382c7c0fa | [
"Zlib"
] | null | null | null | package coneforest.psylla.engine;
/**
* The Psylla language scripting engine factory.
*/
public class PsyllaScriptEngineFactory
implements javax.script.ScriptEngineFactory
{
/**
* @return a string {@code "Psylla"}.
*/
@Override
public String getEngineName()
{
return "Psylla";
}
/**
* Returns an engine.
*
* @return an engine.
*/
@Override
public javax.script.ScriptEngine getScriptEngine()
{
return new PsyllaScriptEngine(this);
}
/**
* @return a list consisting of single string {@code "psylla"}.
*/
@Override
public java.util.List<String> getNames()
{
return java.util.Collections.unmodifiableList(java.util.Arrays.asList("psylla"));
}
@Override
public String getProgram(final String... statements)
{
final var sb=new StringBuilder();
for(final var statement: statements)
{
sb.append(statement);
sb.append('\n');
}
return sb.toString();
}
@Override
public String getOutputStatement(final String toDisplay)
throws UnsupportedOperationException
{
throw new UnsupportedOperationException(getClass().getName()+".getOutputStatement not supported");
}
@Override
public String getMethodCallSyntax(final String obj, final String m, final String... args)
{
throw new UnsupportedOperationException(getClass().getName()+".getMethodCalSyntax not supported");
}
@Override
public String getParameter(final String key)
{
if(key.equals(javax.script.ScriptEngine.ENGINE))
return getEngineName();
if(key.equals(javax.script.ScriptEngine.ENGINE_VERSION))
return getEngineVersion();
if(key.equals(javax.script.ScriptEngine.NAME))
return getEngineName();
if(key.equals(javax.script.ScriptEngine.LANGUAGE))
return getLanguageName();
if(key.equals(javax.script.ScriptEngine.LANGUAGE_VERSION))
return getLanguageVersion();
if(key.equals("THREADING"))
return "MULTITHREADED"; // TODO
return null;
}
@Override
public String getLanguageVersion()
{
return coneforest.psylla.Version.getVersion();
}
@Override
public String getEngineVersion()
{
return coneforest.psylla.Version.getVersion();
}
/**
* Returns a name of a language.
*
* @return the string {@code "Psylla"}.
*/
@Override
public String getLanguageName()
{
return "Psylla";
}
/**
* @return a list consisting of single string {@code "application/x-psylla"}.
*/
@Override
public java.util.List<String> getMimeTypes()
{
if(mimeTypes==null)
mimeTypes=java.util.Collections.unmodifiableList(java.util.Arrays.asList("application/x-psylla"));
return mimeTypes;
}
/**
* @return a list consisting of single string {@code "psy"}.
*/
@Override
public java.util.List<String> getExtensions()
{
if(extensions==null)
extensions=java.util.Collections.unmodifiableList(java.util.Arrays.asList("psy"));
return extensions;
}
private java.util.List<String> mimeTypes;
private java.util.List<String> extensions;
}
| 22.426357 | 101 | 0.72589 |
d3358be2c6f85eae523fb4652ac84cd3f7277574 | 1,128 | dart | Dart | test/core/validator_extensions/must_extension_test.dart | ErkinKurt/fluent_validator | accb51f1cb381b4a70cecf372f689024c898d2c5 | [
"MIT"
] | 1 | 2021-09-15T09:42:08.000Z | 2021-09-15T09:42:08.000Z | test/core/validator_extensions/must_extension_test.dart | ErkinKurt/fluent_validator | accb51f1cb381b4a70cecf372f689024c898d2c5 | [
"MIT"
] | null | null | null | test/core/validator_extensions/must_extension_test.dart | ErkinKurt/fluent_validator | accb51f1cb381b4a70cecf372f689024c898d2c5 | [
"MIT"
] | null | null | null | import 'package:fluent_validator/core/validator.dart';
import 'package:flutter_test/flutter_test.dart';
class TestClass {
const TestClass(this.prop1);
final int? prop1;
}
class TestValidator extends Validator<TestClass> {
TestValidator() {
rulesFor('Prop1', (TestClass testClass) => testClass.prop1).must<int?>((value) => value! < 5);
}
}
void main() {
group('ValidatorBuilderExtensions', () {
late TestValidator testValidator;
group('Must', () {
testValidator = TestValidator();
test(
'should return invalid validation result'
' when value does not meet predicate criteria',
() {
const testClass = TestClass(9);
final validationResult = testValidator.validate(testClass);
expect(false, validationResult.isValid);
},
);
test(
'should return valid validation result'
' when value meets predicate criteria', () {
const testClass = TestClass(3);
final validationResult = testValidator.validate(testClass);
expect(true, validationResult.isValid);
});
});
});
}
| 26.232558 | 98 | 0.639184 |
28231afda62089a2c2494615fa64e03f7eaa7358 | 29 | go | Go | components/argo/argo.go | wanglei4687/Infrastructure | 337f7ee582327e82ba40bb9ec3f09d690f731567 | [
"MIT"
] | null | null | null | components/argo/argo.go | wanglei4687/Infrastructure | 337f7ee582327e82ba40bb9ec3f09d690f731567 | [
"MIT"
] | null | null | null | components/argo/argo.go | wanglei4687/Infrastructure | 337f7ee582327e82ba40bb9ec3f09d690f731567 | [
"MIT"
] | null | null | null | package argo
func init() {}
| 7.25 | 14 | 0.655172 |
178d9d7a25a883a60ee7ab36f611fea0ee285c68 | 6,313 | asm | Assembly | Transynther/x86/_processed/NONE/_xt_/i3-7100_9_0x84_notsx.log_21829_1270.asm | ljhsiun2/medusa | 67d769b8a2fb42c538f10287abaf0e6dbb463f0c | [
"MIT"
] | 9 | 2020-08-13T19:41:58.000Z | 2022-03-30T12:22:51.000Z | Transynther/x86/_processed/NONE/_xt_/i3-7100_9_0x84_notsx.log_21829_1270.asm | ljhsiun2/medusa | 67d769b8a2fb42c538f10287abaf0e6dbb463f0c | [
"MIT"
] | 1 | 2021-04-29T06:29:35.000Z | 2021-05-13T21:02:30.000Z | Transynther/x86/_processed/NONE/_xt_/i3-7100_9_0x84_notsx.log_21829_1270.asm | ljhsiun2/medusa | 67d769b8a2fb42c538f10287abaf0e6dbb463f0c | [
"MIT"
] | 3 | 2020-07-14T17:07:07.000Z | 2022-03-21T01:12:22.000Z | .global s_prepare_buffers
s_prepare_buffers:
push %r13
push %r15
push %r8
push %r9
push %rcx
push %rdi
push %rsi
lea addresses_UC_ht+0xb7fa, %rsi
lea addresses_UC_ht+0x1287a, %rdi
nop
nop
nop
nop
inc %r15
mov $5, %rcx
rep movsw
nop
nop
nop
nop
nop
xor $6290, %r9
lea addresses_WT_ht+0x6f3e, %r13
nop
nop
nop
nop
nop
add $31656, %r8
movb $0x61, (%r13)
nop
xor $10267, %r9
lea addresses_normal_ht+0xa3fa, %r9
inc %r8
movl $0x61626364, (%r9)
nop
and $16739, %r8
lea addresses_normal_ht+0x9d1a, %rsi
nop
nop
nop
sub %r8, %r8
vmovups (%rsi), %ymm2
vextracti128 $0, %ymm2, %xmm2
vpextrq $1, %xmm2, %r15
add %r9, %r9
lea addresses_WT_ht+0x23a, %rsi
sub %r13, %r13
mov $0x6162636465666768, %r9
movq %r9, (%rsi)
nop
nop
dec %r9
pop %rsi
pop %rdi
pop %rcx
pop %r9
pop %r8
pop %r15
pop %r13
ret
.global s_faulty_load
s_faulty_load:
push %r13
push %r15
push %r8
push %rbp
push %rbx
push %rcx
push %rdi
// Store
mov $0x6fa, %rdi
nop
dec %r8
mov $0x5152535455565758, %rcx
movq %rcx, %xmm0
vmovups %ymm0, (%rdi)
nop
and $46084, %r15
// Store
lea addresses_US+0x17e3a, %rdi
clflush (%rdi)
nop
dec %rbx
movw $0x5152, (%rdi)
nop
nop
sub $39304, %r15
// Store
lea addresses_D+0x1c18a, %rcx
nop
nop
nop
nop
cmp $45741, %rbp
movb $0x51, (%rcx)
inc %rbx
// Store
lea addresses_PSE+0x11c7a, %rdi
nop
xor %r15, %r15
movb $0x51, (%rdi)
nop
nop
nop
xor $19132, %rcx
// Store
lea addresses_UC+0x1b3fa, %rcx
nop
sub %rbx, %rbx
mov $0x5152535455565758, %rbp
movq %rbp, %xmm7
movaps %xmm7, (%rcx)
dec %r8
// Faulty Load
lea addresses_D+0x17bfa, %rdi
nop
nop
nop
nop
nop
sub %rbp, %rbp
mov (%rdi), %r13d
lea oracles, %rbx
and $0xff, %r13
shlq $12, %r13
mov (%rbx,%r13,1), %r13
pop %rdi
pop %rcx
pop %rbx
pop %rbp
pop %r8
pop %r15
pop %r13
ret
/*
<gen_faulty_load>
[REF]
{'src': {'type': 'addresses_D', 'same': False, 'size': 32, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
{'dst': {'type': 'addresses_P', 'same': False, 'size': 32, 'congruent': 8, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
{'dst': {'type': 'addresses_US', 'same': False, 'size': 2, 'congruent': 6, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
{'dst': {'type': 'addresses_D', 'same': False, 'size': 1, 'congruent': 4, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
{'dst': {'type': 'addresses_PSE', 'same': False, 'size': 1, 'congruent': 7, 'NT': True, 'AVXalign': False}, 'OP': 'STOR'}
{'dst': {'type': 'addresses_UC', 'same': False, 'size': 16, 'congruent': 7, 'NT': False, 'AVXalign': True}, 'OP': 'STOR'}
[Faulty Load]
{'src': {'type': 'addresses_D', 'same': True, 'size': 4, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'src': {'type': 'addresses_UC_ht', 'congruent': 6, 'same': False}, 'dst': {'type': 'addresses_UC_ht', 'congruent': 7, 'same': False}, 'OP': 'REPM'}
{'dst': {'type': 'addresses_WT_ht', 'same': False, 'size': 1, 'congruent': 1, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
{'dst': {'type': 'addresses_normal_ht', 'same': False, 'size': 4, 'congruent': 11, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
{'src': {'type': 'addresses_normal_ht', 'same': False, 'size': 32, 'congruent': 1, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
{'dst': {'type': 'addresses_WT_ht', 'same': False, 'size': 8, 'congruent': 4, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
{'36': 21829}
36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36
*/
| 38.03012 | 2,999 | 0.653255 |
34828d5fc2910279dce01a07ba2956855a561ed5 | 456 | sql | SQL | sql/docker_blogs.sql | tantai1123/aiviet-docker | b353856aea3df2f87c7804dd041dd3868e61f24a | [
"MIT"
] | null | null | null | sql/docker_blogs.sql | tantai1123/aiviet-docker | b353856aea3df2f87c7804dd041dd3868e61f24a | [
"MIT"
] | null | null | null | sql/docker_blogs.sql | tantai1123/aiviet-docker | b353856aea3df2f87c7804dd041dd3868e61f24a | [
"MIT"
] | 1 | 2021-01-04T12:21:36.000Z | 2021-01-04T12:21:36.000Z | create table blogs
(
id int unsigned auto_increment
primary key,
category varchar(255) not null,
title varchar(255) not null,
content text not null,
slug varchar(255) not null,
image varchar(255) null,
created_at timestamp null,
updated_at timestamp null,
constraint blogs_slug_unique
unique (slug),
constraint blogs_title_unique
unique (title)
);
| 25.333333 | 42 | 0.614035 |
fd81cbcb76f61e2526157e98f5ff7477e75cbfd2 | 6,549 | h | C | include/main/hurricane/base/Values.h | lihuaweishiyigehaoren/hurricane | 71118616dd08b7b2b46ecacd34b8bb642ac4ea9e | [
"Apache-2.0"
] | 3 | 2019-07-26T10:46:30.000Z | 2021-07-10T07:38:00.000Z | include/main/hurricane/base/Values.h | lihuaweishiyigehaoren/hurricane | 71118616dd08b7b2b46ecacd34b8bb642ac4ea9e | [
"Apache-2.0"
] | null | null | null | include/main/hurricane/base/Values.h | lihuaweishiyigehaoren/hurricane | 71118616dd08b7b2b46ecacd34b8bb642ac4ea9e | [
"Apache-2.0"
] | 1 | 2019-04-29T12:53:54.000Z | 2019-04-29T12:53:54.000Z | /**
* 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.
*/
#pragma once
#include <string>
#include <exception>
#include <cstdint>
#include <vector>
#include <initializer_list>
#include <iostream>
#ifdef WIN32
#define NOEXCEPT
#else
#define NOEXCEPT noexcept
#endif // NOEXCEPT
namespace hurricane {
namespace base {
class Variant;
// 标准异常类型
class TypeMismatchException : std::exception {
public:
TypeMismatchException(const std::string& message) :
_message(message) {}
// 重载的父类的虚函数,系统用这个函数获取异常的文本消息.我们将构造函数的消息直接返回
// noexcept 表示该函数不会抛出异常,这样有利于编译器进行函数调用优化
// override 表示该函数是覆盖了一个父类的虚函数,如果不是覆盖了一个函数就会报错
const char* what() const NOEXCEPT override{
return _message.c_str();
}
private:
std::string _message;// 异常消息
};
// 该类型表示一个可以存储任意类型的值
class Value {
public:
// 枚举类,C++新加入特性,和传统的枚举相比,枚举类会使用枚举类类型名称来做命名空间越约束
// 比如我们想要引用Type中名为Boolean的值,需要使用Value::Type::Boolean,而不能使用Value::Type
// 枚举类不能和整数值之间进行任何类型转换,这样可以确保代码更加规范
enum class Type {
Invalid,
Boolean,
Character,
Int8,
Int16,
Int32,
Int64,
Float,
Double,
String
};
// 联合体
// 联合体的优点在于所有的值公用一片存储空间,因此不会引起额外的空间存储消耗
// 概念:联合是一种变量,他可以在不同时间内维持不同类型和不同长度的对象,它提供了在单个存储区域中操作不同类型数据的方法,
// 而无需在程序中存放与机器有关的信息
// 联合是一种形式特殊的结构变量. 和结构一样,对联合施加的操作只能是存取成员和取其地址,不能把联合联合作为参数传递给函数,也不能由函数返回联合
union InnerValue {
bool booleanValue;
char characterValue;
int8_t int8Value;
int16_t int16Value;
int32_t int32Value;
int64_t int64Value;
float floatValue;
double doubleValue;
};
// 以下函数都是用来:从一个普通的值转换成Value,这里我们支持前文体积的所有类型
Value() : _type(Type::Invalid) {
}
Value(bool value) : _type(Type::Boolean) {
_value.booleanValue = value;
}
Value(char value) : _type(Type::Character) {
_value.characterValue = value;
}
Value(int8_t value) : _type(Type::Int8) {
_value.int8Value = value;
}
Value(int16_t value) : _type(Type::Int16) {
_value.int16Value = value;
}
Value(int32_t value) : _type(Type::Int32) {
_value.int32Value = value;
}
Value(int64_t value) : _type(Type::Int64) {
_value.int64Value = value;
}
Value(float value) : _type(Type::Float) {
_value.floatValue = value;
}
Value(double value) : _type(Type::Double) {
_value.doubleValue = value;
}
Value(const std::string& value) : _type(Type::String) {
_stringValue = value;
}
Value(const char* value) : Value(std::string(value)) {
}
// 转换函数,可以将Value的值转换为实际的值,如果值的类型不匹配,则直接抛出TypeMismatchException
bool ToBoolean() const {
if ( _type != Type::Boolean ) {
throw TypeMismatchException("The type of value is not boolean");
}
}
int8_t ToInt8() const {
if ( _type != Type::Int8 ) {
throw TypeMismatchException("The type of value is not int8");
}
return _value.int8Value;
}
int16_t ToInt16() const {
if ( _type != Type::Int16 ) {
throw TypeMismatchException("The type of value is not int16");
}
return _value.int16Value;
}
int32_t ToInt32() const {
if ( _type != Type::Int32 ) {
throw TypeMismatchException("The type of value is not int32");
}
return _value.int32Value;
}
int64_t ToInt64() const {
if ( _type != Type::Int64 ) {
throw TypeMismatchException("The type of value is not int64");
}
return _value.int64Value;
}
char ToCharacter() const {
if ( _type != Type::Character ) {
throw TypeMismatchException("The type of value is not character");
}
return _value.characterValue;
}
const std::string& ToString() const {
if ( _type != Type::String ) {
throw TypeMismatchException("The type of value is not string");
}
return _stringValue;
}
Variant ToVariant() const;
static Value FromVariant(const Variant& variant);
private:
Type _type;
InnerValue _value;
std::string _stringValue;// 将字符串类型分离出来的原因-并不是所有的编译器都支持讲一个复杂的POD对象放在联合体中,这样更有利于可移植性
};
// 该类型的接口应该支持任意基础类型和值类型之间的转换,因此这方面的接口略为复杂,而元祖就是一个由值组成的有序序列.定义如下
class Values : public std::vector<Value> {
public:
Values() = default;
Values(std::initializer_list<Value> values) : std::vector<Value>(values) {
}
// 索引操作符,和普通向量一模一样
Value& operator[](size_t index) {
return std::vector<Value>::operator[](index);
}
const Value& operator[](size_t index) const {
return std::vector<Value>::operator[](index);
}
};
}
}
| 30.179724 | 94 | 0.536418 |
bbdc7c4c02b82197fa0b01f9d9fdae7c6cc93f37 | 2,288 | swift | Swift | EmibraRA/ChatViewController.swift | Davidsonts/emibra | 9431d466e33a7c53c07db064a7c4279eb4e9d797 | [
"MIT"
] | null | null | null | EmibraRA/ChatViewController.swift | Davidsonts/emibra | 9431d466e33a7c53c07db064a7c4279eb4e9d797 | [
"MIT"
] | null | null | null | EmibraRA/ChatViewController.swift | Davidsonts/emibra | 9431d466e33a7c53c07db064a7c4279eb4e9d797 | [
"MIT"
] | null | null | null | //
// ChatViewController.swift
// EmibraRA
//
// Created by Davidson Santos on 18/01/21.
// Copyright © 2021 Apple. All rights reserved.
//
import UIKit
import WebKit
class ChatViewController: UIViewController, WKUIDelegate {
@IBOutlet weak var mWKWebView: WKWebView!
override func loadView() {
let webConfiguration = WKWebViewConfiguration()
mWKWebView = WKWebView(frame: .zero, configuration: webConfiguration)
mWKWebView.uiDelegate = self
view = mWKWebView
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let myURL = URL(string:"https://tawk.to/emibra")
let myRequest = URLRequest(url: myURL!)
mWKWebView.load(myRequest)
}
/// CHECK INTERNET
func Alert (Message: String){
let alert = UIAlertController(title: "Alert", message: Message, preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "ok", style: UIAlertAction.Style.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
/// CHECK INTERNET
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// if (ARConfiguration.isSupported) {
//
// // Great! let have experience of ARKIT
// } else {
// // Sorry! you don't have ARKIT support in your device
//
// }
if CheckInternet.Connection(){
// self.Alert(Message: "Connected")
}
else{
self.Alert(Message: "Seu dispositivo não está conectado à internet")
}
// Prevent the screen from being dimmed to avoid interuppting the AR experience.
UIApplication.shared.isIdleTimerDisabled = true
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
| 27.902439 | 118 | 0.610577 |
b9cdab79ca40e3e717c7522531b7f70f652c5afa | 352 | h | C | GDTest/Header/GDUtils/GDColorUtil.h | guodong10518/GDTest | 2e4171ade9cd5de12722ab6cae1c36b0361ecacd | [
"MIT"
] | null | null | null | GDTest/Header/GDUtils/GDColorUtil.h | guodong10518/GDTest | 2e4171ade9cd5de12722ab6cae1c36b0361ecacd | [
"MIT"
] | null | null | null | GDTest/Header/GDUtils/GDColorUtil.h | guodong10518/GDTest | 2e4171ade9cd5de12722ab6cae1c36b0361ecacd | [
"MIT"
] | null | null | null | //
// GDColorUtil.h
// BSDLOA
//
// Created by wangguodong on 15/5/19.
// Copyright (c) 2015年 隔壁老王. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@interface GDColorUtil : NSObject
/**
16进制转RGB
@param hexColor 16进制字符串
@return UIColor
*/
+ (UIColor *)getColorWithHexStr:(NSString *)hexColor;
@end
| 16.761905 | 53 | 0.676136 |
4f1a234e0cfd3bc4bc2939347bb4e7f4ec6554ce | 1,824 | swift | Swift | concentration-game/concentration-game/Model/CardModel.swift | GiovanniMoratto/stanford-concentration-game_app | 2e7616d210699ef5b5433327425c6665a3663af9 | [
"MIT"
] | null | null | null | concentration-game/concentration-game/Model/CardModel.swift | GiovanniMoratto/stanford-concentration-game_app | 2e7616d210699ef5b5433327425c6665a3663af9 | [
"MIT"
] | null | null | null | concentration-game/concentration-game/Model/CardModel.swift | GiovanniMoratto/stanford-concentration-game_app | 2e7616d210699ef5b5433327425c6665a3663af9 | [
"MIT"
] | null | null | null | //
// Card.swift
// concentration-game
//
// Created by Giovanni Vicentin Moratto on 17/09/21.
//
import Foundation
struct CardModel: Hashable {
// Representa a model de um card no game
// MARK: - Attributes
var isFaceUp: Bool = false
var isMatched: Bool = false
var twoCardsFaceUp: Bool = false
var flipCount = 0
private var identifier: Int
// Variável com um valor de Int que representa um identificador no game.
/*
Cada par de card terá um identificador único.
*/
// MARK: - Static Attributes
private static var identifierFactory: Int = 0
// Variável com um valor de Int que representa um identificador no game.
/*
Inicializada com valor 0. É responsável por criar os identificadores, aumentando seu valor a cada chamada do método getUniqueIdentifier().
*/
// MARK: - Static Methods
/// Método para retornar um ID usado como um identificador de cartão
private static func getUniqueIdentifier() -> Int {
identifierFactory += 1
return identifierFactory
}
/// Método hashValue
func hash(into hasher: inout Hasher) {
// var hashValue: Int { return identifier } - Deprecated
hasher.combine(identifier)
hasher.combine(identifier)
}
/// protocols stubs
static func ==(lhs: CardModel, rhs: CardModel) -> Bool {
return lhs.identifier == rhs.identifier
}
// MARK: - Initializers (Constructors)
init() {
/*
Cria um card com o ID gerado. Sempre que instanciar um card, o atributo identifier será atualizado para um novo valor.
*/
self.identifier = CardModel.getUniqueIdentifier()
// self == this no java
}
}
| 25.690141 | 143 | 0.616228 |
0dc152a2ca8dcd179f384f606a00ec0d5ed0a04c | 685 | sql | SQL | Database/KH/Procedures/GET_NOTIFICATION_DETAIL.sql | lemalcs/Khernet | 7a33684ad9843be528a721bcb0255bf8a318bb6c | [
"MIT"
] | 1 | 2021-11-25T08:55:27.000Z | 2021-11-25T08:55:27.000Z | Database/KH/Procedures/GET_NOTIFICATION_DETAIL.sql | lemalcs/Khernet | 7a33684ad9843be528a721bcb0255bf8a318bb6c | [
"MIT"
] | null | null | null | Database/KH/Procedures/GET_NOTIFICATION_DETAIL.sql | lemalcs/Khernet | 7a33684ad9843be528a721bcb0255bf8a318bb6c | [
"MIT"
] | null | null | null | /* Definition for the GET_NOTIFICATION_DETAIL procedure : */
------------------------------------------------------------------------------
-- Create date: 2020-02-15
-- Autor: Luis Lema
--
-- Description:
-- Get the details of specified notification.
--
-- Parameters:
-- ID - The id of notification.
--
-- Returns:
-- The metadata of notification.
------------------------------------------------------------------------------
CREATE OR ALTER PROCEDURE GET_NOTIFICATION_DETAIL
(
ID TYPE OF COLUMN NOTIFICATION.ID
)
RETURNS
(
CONTENT TYPE OF COLUMN NOTIFICATION.CONTENT
)
AS
BEGIN
FOR SELECT CONTENT FROM NOTIFICATION
WHERE
ID=:ID
INTO :CONTENT
DO SUSPEND;
END | 21.40625 | 78 | 0.551825 |
2f7634b6a57827ddceda5c8f8efaae19e65c7fe8 | 255 | php | PHP | patches/premium_ecommerce_filter_products.php | jtylek/EpesiWarehouse | ec3f1e2c9da8575a9be00801c17d9cd3536456ad | [
"MIT"
] | 3 | 2020-11-28T00:22:35.000Z | 2021-10-16T12:28:45.000Z | patches/premium_ecommerce_filter_products.php | jtylek/EpesiWarehouse | ec3f1e2c9da8575a9be00801c17d9cd3536456ad | [
"MIT"
] | null | null | null | patches/premium_ecommerce_filter_products.php | jtylek/EpesiWarehouse | ec3f1e2c9da8575a9be00801c17d9cd3536456ad | [
"MIT"
] | null | null | null | <?php
defined("_VALID_ACCESS") || die('Direct access forbidden');
if (ModuleManager::is_installed('Premium_Warehouse_eCommerce')>=0) {
DB::Execute('UPDATE premium_ecommerce_products_field SET filter=1 WHERE field="Item Name" OR type="checkbox"');
}
?> | 42.5 | 115 | 0.74902 |
75a0c02abe03140ee5f4c996b8130e573cd1912b | 195 | sql | SQL | de.kleiber.demos.plsql.testing.unit.parent/src/login.sql | tkleiber/de.kleiber.demos.plsql.testing.unit | ee4fb81d636797840cc231e0f3096be509c231a0 | [
"MIT"
] | null | null | null | de.kleiber.demos.plsql.testing.unit.parent/src/login.sql | tkleiber/de.kleiber.demos.plsql.testing.unit | ee4fb81d636797840cc231e0f3096be509c231a0 | [
"MIT"
] | 2 | 2022-03-11T21:38:46.000Z | 2022-03-17T21:17:07.000Z | de.kleiber.demos.plsql.testing.unit.parent/src/login.sql | tkleiber/de.kleiber.demos.plsql.testing.unit | ee4fb81d636797840cc231e0f3096be509c231a0 | [
"MIT"
] | null | null | null | -- whenever sqlerror exit sql.sqlcode
whenever sqlerror exit failure rollback
whenever oserror exit failure rollback
set serveroutput on size unlimited
PROMPT init via login script
set timing on | 32.5 | 39 | 0.841026 |
2409e32a57735ebffa0fd304244cd64ac88b46df | 1,479 | kt | Kotlin | swing-ui/src/main/kotlin/ru/aleshi/scoreboards/view/MessagesFrame.kt | AlexanderShirokih/KarateScoreboard | 7f827bbfad8c9e46c0349a53f52662e72e69996a | [
"MIT"
] | null | null | null | swing-ui/src/main/kotlin/ru/aleshi/scoreboards/view/MessagesFrame.kt | AlexanderShirokih/KarateScoreboard | 7f827bbfad8c9e46c0349a53f52662e72e69996a | [
"MIT"
] | null | null | null | swing-ui/src/main/kotlin/ru/aleshi/scoreboards/view/MessagesFrame.kt | AlexanderShirokih/KarateScoreboard | 7f827bbfad8c9e46c0349a53f52662e72e69996a | [
"MIT"
] | 1 | 2020-08-07T16:01:23.000Z | 2020-08-07T16:01:23.000Z | package ru.aleshi.scoreboards.view
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.launch
import ru.aleshi.scoreboards.core.IEventsController
import java.awt.Dimension
import javax.swing.*
class MessagesFrame(private val eventsController: IEventsController) : JFrame() {
private val scope = MainScope()
private val content = JPanel().apply { layout = BoxLayout(this, BoxLayout.Y_AXIS) }
private val scrollPane = JScrollPane(
content, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED
).apply { alignmentY = -1f }
init {
add(scrollPane)
size = Dimension(285, 480)
scope.launch {
eventsController.messagesChannel.consumeAsFlow().collect { list ->
setMessages(list)
}
}
}
private fun setMessages(messages: List<String>) {
content.removeAll()
messages
.map { JLabel(it) }
.forEach { content.add(it) }
this.revalidate()
this.repaint()
SwingUtilities.invokeLater {
val vertical = scrollPane.verticalScrollBar
vertical.value = vertical.maximum
}
}
/**
* Detaches subscriptions of ru.aleshi.scoreboards.view-model events.
*/
fun clearSubscriptions() {
scope.cancel()
}
} | 26.410714 | 101 | 0.663286 |
f09526dcd50abd939ecced47712bab3aac595f44 | 1,202 | lua | Lua | src/StarterPlayerScripts/Clock.client.lua | Fumohouse/Fumofas | f7314e2aec059e83d0bdec39de2c48c63c10622b | [
"Unlicense",
"MIT"
] | null | null | null | src/StarterPlayerScripts/Clock.client.lua | Fumohouse/Fumofas | f7314e2aec059e83d0bdec39de2c48c63c10622b | [
"Unlicense",
"MIT"
] | null | null | null | src/StarterPlayerScripts/Clock.client.lua | Fumohouse/Fumofas | f7314e2aec059e83d0bdec39de2c48c63c10622b | [
"Unlicense",
"MIT"
] | null | null | null | ---
-- Clock.client.lua - Clientside tracking of time
--
local RunService = game:GetService("RunService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Lighting = game:GetService("Lighting")
local kStartSeconds = 420 -- 7AM
local localOffset = 0
local offset = ReplicatedStorage.UIRemotes.GetServerTime:InvokeServer() - tick() -- timezones
local serverStartTime = ReplicatedStorage.UIRemotes.GetServerStartTime:InvokeServer()
local advanceTime = true
-- get the current server time
local function getTime()
return tick() - serverStartTime + offset + kStartSeconds
end
local function updateTime()
Lighting:SetMinutesAfterMidnight(getTime() + localOffset)
end
RunService.Stepped:Connect(function()
if advanceTime then
updateTime()
end
end)
local events = ReplicatedStorage.UIEvents.Clock
events.SetTime.Event:Connect(function(t)
if t < 0 then
localOffset = 0
advanceTime = true
return
end
localOffset = t - getTime()
updateTime()
end)
events.SetTimeFrozen.Event:Connect(function(frozen)
if frozen == nil then
frozen = advanceTime
end
advanceTime = not frozen
if not advanceTime then
localOffset = Lighting.ClockTime * 60 - getTime()
end
end)
| 21.087719 | 93 | 0.766223 |
7015ec571d045a7aa9d45ee2cb7cb990cb3fbee8 | 282 | kt | Kotlin | rvhelper/src/main/kotlin/com/ansgar/rvhelper/adapters/SingleTypeAdapter.kt | kirilamenski/RvHelper | 0815970b889a14f2dbc08fd5adff7c746dfe79a8 | [
"Apache-2.0"
] | 1 | 2021-06-16T11:41:09.000Z | 2021-06-16T11:41:09.000Z | rvhelper/src/main/kotlin/com/ansgar/rvhelper/adapters/SingleTypeAdapter.kt | kirilamenski/RvHelper | 0815970b889a14f2dbc08fd5adff7c746dfe79a8 | [
"Apache-2.0"
] | null | null | null | rvhelper/src/main/kotlin/com/ansgar/rvhelper/adapters/SingleTypeAdapter.kt | kirilamenski/RvHelper | 0815970b889a14f2dbc08fd5adff7c746dfe79a8 | [
"Apache-2.0"
] | null | null | null | package com.ansgar.rvhelper.adapters
import com.ansgar.rvhelper.utils.ViewHoldersUtil
class SingleTypeAdapter<VM>(viewHoldersUtil: ViewHoldersUtil) : BaseAdapter<VM>(viewHoldersUtil) {
override fun getItemViewType(position: Int): Int = viewHoldersUtil.vhCallbacks.keyAt(0)
} | 31.333333 | 98 | 0.812057 |
c11e56aaa1d328eea289623ed97f1445e896e8bc | 1,055 | lua | Lua | src/lua/LazarusMod/Modules/Alien/Gorge/Tunnels/Post/AlienCommander.lua | adsfgg/LazarusMod | 47525094eaf175fe1f11c624c1536581ded8cfa8 | [
"MIT"
] | null | null | null | src/lua/LazarusMod/Modules/Alien/Gorge/Tunnels/Post/AlienCommander.lua | adsfgg/LazarusMod | 47525094eaf175fe1f11c624c1536581ded8cfa8 | [
"MIT"
] | null | null | null | src/lua/LazarusMod/Modules/Alien/Gorge/Tunnels/Post/AlienCommander.lua | adsfgg/LazarusMod | 47525094eaf175fe1f11c624c1536581ded8cfa8 | [
"MIT"
] | null | null | null | local gAlienMenuButtons =
{
[kTechId.BuildMenu] = { kTechId.Cyst, kTechId.Harvester, kTechId.DrifterEgg, kTechId.Hive,
kTechId.ThreatMarker, kTechId.NeedHealingMarker, kTechId.ExpandingMarker, kTechId.None --[[ kTechId.BuildTunnelMenu ]] },
[kTechId.AdvancedMenu] = { kTechId.Crag, kTechId.Shade, kTechId.Shift, kTechId.Whip,
kTechId.Shell, kTechId.Veil, kTechId.Spur, kTechId.None },
[kTechId.AssistMenu] = { kTechId.HealWave, kTechId.ShadeInk, kTechId.SelectShift, kTechId.SelectDrifter,
kTechId.NutrientMist, kTechId.Rupture, kTechId.BoneWall, kTechId.Contamination }
}
local gAlienMenuIds = {}
do
for menuId, _ in pairs(gAlienMenuButtons) do
gAlienMenuIds[#gAlienMenuIds+1] = menuId
end
end
function AlienCommander:GetButtonTable()
return gAlienMenuButtons
end
function AlienCommander:GetMenuIds()
return gAlienMenuIds
end
debug.setupvaluex(AlienCommander.GetQuickMenuTechButtons, "gAlienMenuButtons", gAlienMenuButtons)
| 36.37931 | 149 | 0.712796 |
d2c0e731016248ac486fb2b047374cafc07682da | 1,896 | php | PHP | app/Http/Controllers/LandloardController.php | alnurarif/patabd | eeef12b139c6a092716836acd4ff01d1ab3123b2 | [
"MIT"
] | null | null | null | app/Http/Controllers/LandloardController.php | alnurarif/patabd | eeef12b139c6a092716836acd4ff01d1ab3123b2 | [
"MIT"
] | null | null | null | app/Http/Controllers/LandloardController.php | alnurarif/patabd | eeef12b139c6a092716836acd4ff01d1ab3123b2 | [
"MIT"
] | null | null | null | <?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Landloard;
use Carbon\Carbon;
use Session;
class LandloardController extends Controller
{
public function register(){
return view('website.landloard.register');
}
public function create(Request $request){
$this->validate($request,[
'f_name'=>'required',
'l_name'=>'required',
'email'=>'required',
'password'=>'required|string|min:6|confirmed',
],[
'f_name.required'=> 'Please enter your first name',
'l_name.required'=> 'Please enter your last name',
'email.required'=> 'Please enter your email',
'password.confirmed'=> 'Password did not match',
]);
$data=[];
$data['l_name'] = $request->l_name;
$data['f_name'] = $request->f_name;
$data['email'] = $request->email;
$data['password'] = md5($_POST['password']);
$data['image'] = 'default.jpg';
$data['created_at'] = Carbon::now()->toDateTimeString();
$insert=Landloard:: insert($data);
if ($insert) {
return back();
}else {
return back();
}
}
public function login_form(){
return view('website.landloard.login');
}
public function login(Request $request){
$this->validate($request,[
'email'=> ['required','string','email','max:255'],
'password'=> ['required','string','min:6'],
]);
$email=$request->email;
$password= md5($request->password);
$Landloard=Landloard:: where('email',$email)->where('password',$password)->first();
if ($Landloard) {
Session::put('id',$Landloard->id);
return redirect('/');
}else{
return redirect('/');
}
}
public function logout(){
Session:: flush('id');
return redirect('/landloard/login_form');
}
}
| 25.28 | 89 | 0.567511 |
2f32bcdc2805b55e73438d2bbfa4691b01199a12 | 435 | php | PHP | src/cargar_datos.php | pcandrews/mapa_abonados | 4cda12a64d7aec8c1cdd6d7d6be3dcf71e4b8344 | [
"Apache-2.0"
] | null | null | null | src/cargar_datos.php | pcandrews/mapa_abonados | 4cda12a64d7aec8c1cdd6d7d6be3dcf71e4b8344 | [
"Apache-2.0"
] | 1 | 2022-03-24T17:11:30.000Z | 2022-03-24T17:11:30.000Z | src/cargar_datos.php | pcandrews/mapa_abonados | 4cda12a64d7aec8c1cdd6d7d6be3dcf71e4b8344 | [
"Apache-2.0"
] | null | null | null | <?php
header('Content-Type: text/html; charset=UTF-8');
ini_set("display_errors", "On");
ini_set('display_startup_errors', 1);
error_reporting(E_ALL | E_STRICT);
header("Content-Type: text/html; charset=UTF-8");
date_default_timezone_set('America/Argentina/Tucuman');
setlocale(LC_ALL, 'es-AR');
// Esta ruta tiene que ser estatica
require_once("cfg/config.php");
indexar_datos(DIR_UHFAPP);
tiempo_de_ejecucion();
?> | 25.588235 | 56 | 0.726437 |
2a123ff1c4b70f32a798b627b4e0305fa5608ff5 | 854 | java | Java | tests/features/fixtures/mazerunner/src/main/java/com/bugsnag/android/mazerunner/scenarios/CXXJavaUserInfoNativeCrashScenario.java | ivansnag/bugsnag-android | b71d5ffb957c0d9dced90ad5c2e579f2d36e7c8b | [
"MIT"
] | null | null | null | tests/features/fixtures/mazerunner/src/main/java/com/bugsnag/android/mazerunner/scenarios/CXXJavaUserInfoNativeCrashScenario.java | ivansnag/bugsnag-android | b71d5ffb957c0d9dced90ad5c2e579f2d36e7c8b | [
"MIT"
] | null | null | null | tests/features/fixtures/mazerunner/src/main/java/com/bugsnag/android/mazerunner/scenarios/CXXJavaUserInfoNativeCrashScenario.java | ivansnag/bugsnag-android | b71d5ffb957c0d9dced90ad5c2e579f2d36e7c8b | [
"MIT"
] | null | null | null | package com.bugsnag.android.mazerunner.scenarios;
import android.content.Context;
import com.bugsnag.android.Bugsnag;
import com.bugsnag.android.Configuration;
import androidx.annotation.NonNull;
public class CXXJavaUserInfoNativeCrashScenario extends Scenario {
static {
System.loadLibrary("bugsnag-ndk");
System.loadLibrary("monochrome");
System.loadLibrary("entrypoint");
}
public native void crash();
public CXXJavaUserInfoNativeCrashScenario(@NonNull Configuration config, @NonNull Context context) {
super(config, context);
}
@Override
public void run() {
super.run();
Bugsnag.setUser("9816734", "j@example.com", "Strulyegha Ghaumon Rabelban Snefkal Angengtai Samperris Dreperwar Raygariss Haytther Ackworkin Turdrakin Clardon");
crash();
}
}
| 28.466667 | 178 | 0.710773 |
bb1a9f15cb63c5a586198b9d52dde9a9410f97f1 | 1,826 | swift | Swift | Sources/AppStoreConnectCLI/Commands/TestFlight/BetaGroups/ModifyBetaGroupCommand.swift | csjones/appstoreconnect-cli | e3dfede3653c717aa82884afcfaa0092a7828451 | [
"MIT"
] | 1 | 2020-10-09T07:41:41.000Z | 2020-10-09T07:41:41.000Z | Sources/AppStoreConnectCLI/Commands/TestFlight/BetaGroups/ModifyBetaGroupCommand.swift | ptmt/appstoreconnect-cli | 418db470be8c3a91915306fe213e6ec20823b627 | [
"MIT"
] | null | null | null | Sources/AppStoreConnectCLI/Commands/TestFlight/BetaGroups/ModifyBetaGroupCommand.swift | ptmt/appstoreconnect-cli | 418db470be8c3a91915306fe213e6ec20823b627 | [
"MIT"
] | null | null | null | // Copyright 2020 Itty Bitty Apps Pty Ltd
import ArgumentParser
import Foundation
struct ModifyBetaGroupCommand: CommonParsableCommand {
static var configuration = CommandConfiguration(
commandName: "modify",
abstract: "Modify a beta group, only the specified options are modified"
)
@OptionGroup()
var common: CommonOptions
@Argument(
help: """
The reverse-DNS bundle ID of the app which the group should be associated with. \
Must be unique. (eg. com.example.app)
"""
) var appBundleId: String
@Argument(
help: ArgumentHelp(
"The current name of the beta group to be modified",
discussion: """
This name will be used to search for a unique beta group matching the specified \
app bundle id
""",
valueName: "beta-group-name"
)
) var currentGroupName: String
@Option(
name: .customLong("name"),
help: "Modifies the name of the beta group"
) var newGroupName: String?
@Option(help: "Enables or disables the public link")
var publicLinkEnabled: Bool?
@Option(help: "Adjusts the public link limit")
var publicLinkLimit: Int?
@Option(help: "Enables or disables whether to use a public link limit")
var publicLinkLimitEnabled: Bool?
func run() throws {
let service = try makeService()
let betaGroup = try service.modifyBetaGroup(
appBundleId: appBundleId,
currentGroupName: currentGroupName,
newGroupName: newGroupName,
publicLinkEnabled: publicLinkEnabled,
publicLinkLimit: publicLinkLimit,
publicLinkLimitEnabled: publicLinkLimitEnabled
)
betaGroup.render(format: common.outputFormat)
}
}
| 29.451613 | 93 | 0.63965 |
3c4d7863a1e9b7f37339e65ae5868eeb01820089 | 565 | sql | SQL | kata-files/lesson2/postgresql/expected/MYLARGESCHEMA/function/func374.sql | goldmansachs/obevo-kata | 5596ff44ad560d89d183ac0941b727db1a2a7346 | [
"Apache-2.0"
] | 22 | 2017-09-28T21:35:04.000Z | 2022-02-12T06:24:28.000Z | kata-files/lesson2/postgresql/expected/MYLARGESCHEMA/function/func374.sql | goldmansachs/obevo-kata | 5596ff44ad560d89d183ac0941b727db1a2a7346 | [
"Apache-2.0"
] | 6 | 2017-07-01T13:52:34.000Z | 2018-09-13T15:43:47.000Z | kata-files/lesson2/postgresql/expected/MYLARGESCHEMA/function/func374.sql | goldmansachs/obevo-kata | 5596ff44ad560d89d183ac0941b727db1a2a7346 | [
"Apache-2.0"
] | 11 | 2017-04-30T18:39:09.000Z | 2021-08-22T16:21:11.000Z | CREATE FUNCTION func374() RETURNS integer
LANGUAGE plpgsql
AS $$ DECLARE val INTEGER; BEGIN val:=(SELECT COUNT(*)INTO MYCOUNT FROM MYLARGESCHEMA.TABLE478);val:=(SELECT COUNT(*)INTO MYCOUNT FROM MYLARGESCHEMA.TABLE407);val:=(SELECT COUNT(*)INTO MYCOUNT FROM MYLARGESCHEMA.TABLE153);val:=(SELECT COUNT(*)INTO MYCOUNT FROM MYLARGESCHEMA.VIEW13);val:=(SELECT COUNT(*)INTO MYCOUNT FROM MYLARGESCHEMA.VIEW72);val:=(SELECT COUNT(*)INTO MYCOUNT FROM MYLARGESCHEMA.VIEW43);CALL FUNC922(MYVAR);CALL FUNC481(MYVAR);CALL FUNC588(MYVAR);CALL FUNC634(MYVAR);END $$;
GO | 80.714286 | 496 | 0.773451 |
9f2d7887bb283d9b9360c3fd773d3e1259624876 | 901 | asm | Assembly | oeis/167/A167322.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 11 | 2021-08-22T19:44:55.000Z | 2022-03-20T16:47:57.000Z | oeis/167/A167322.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 9 | 2021-08-29T13:15:54.000Z | 2022-03-09T19:52:31.000Z | oeis/167/A167322.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 3 | 2021-08-22T20:56:47.000Z | 2021-09-29T06:26:12.000Z | ; A167322: Totally multiplicative sequence with a(p) = 3*(p+3) for prime p.
; Submitted by Jon Maiga
; 1,15,18,225,24,270,30,3375,324,360,42,4050,48,450,432,50625,60,4860,66,5400,540,630,78,60750,576,720,5832,6750,96,6480,102,759375,756,900,720,72900,120,990,864,81000,132,8100,138,9450,7776,1170,150,911250,900,8640,1080,10800,168,87480,1008,101250,1188,1440,186,97200,192,1530,9720,11390625,1152,11340,210,13500,1404,10800,222,1093500,228,1800,10368,14850,1260,12960,246,1215000,104976,1980,258,121500,1440,2070,1728,141750,276,116640,1440,17550,1836,2250,1584,13668750,300,13500,13608,129600
add $0,1
mov $1,1
lpb $0
mov $3,$0
lpb $3
mov $4,$0
cmp $6,0
add $2,$6
mod $4,$2
add $2,1
cmp $4,0
cmp $4,0
max $4,$6
sub $3,$4
mov $6,12
lpe
lpb $0
dif $0,$2
mul $1,3
mov $5,$2
sub $2,1
lpe
add $2,1
add $5,3
mul $1,$5
lpe
mov $0,$1
| 28.15625 | 493 | 0.657048 |
0134af2eb28300636d33158fc60d465095faa2c1 | 1,263 | dart | Dart | Demo/lib/pages/home.dart | kuaifengle/Flutter-WeChat | b06b10f505b518e9e9446e5e1f3ad129ca7838c7 | [
"MIT"
] | 172 | 2018-12-25T06:43:22.000Z | 2020-05-15T11:33:48.000Z | Demo/lib/pages/home.dart | kuaifengle/flutter-wechat | b06b10f505b518e9e9446e5e1f3ad129ca7838c7 | [
"MIT"
] | 1 | 2021-06-05T14:29:05.000Z | 2021-07-08T09:19:03.000Z | Demo/lib/pages/home.dart | kuaifengle/Flutter-WeChat | b06b10f505b518e9e9446e5e1f3ad129ca7838c7 | [
"MIT"
] | 37 | 2018-12-27T15:13:27.000Z | 2020-04-30T18:01:12.000Z | import 'package:flutter/material.dart';
import 'package:flutter_vector_icons/flutter_vector_icons.dart';
import 'package:flutter_inner_drawer/inner_drawer.dart';
import 'package:flutter_translate/flutter_translate.dart';
import './contacts/contactsList.dart';
import './drawer/rightDrawer.dart';
import '../components/appbar.dart';
class Home extends StatefulWidget {
Home({Key key, this.innerDrawerKey}) : super(key: key);
final GlobalKey<InnerDrawerState> innerDrawerKey;
HomeState createState() => HomeState();
}
class HomeState extends State<Home> {
final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey();
Widget build(BuildContext context) {
return Scaffold(
key: _scaffoldKey,
appBar: setCustomAppBar(context, translate('title.wechat'),
actions: <Widget>[
IconButton(
icon: Icon(Feather.plus),
onPressed: () {
_scaffoldKey.currentState.openEndDrawer();
},
)
],
leading: IconButton(
icon: Icon(Feather.list),
onPressed: () {
widget.innerDrawerKey.currentState.toggle();
},
)),
endDrawer: IndexRightDrawer(),
body: Contacts(),
);
}
}
| 28.704545 | 65 | 0.638955 |
265d4889e99126c1b75b1946b6a36dd132659be5 | 2,399 | java | Java | FlappyBird/LabTest/core/src/com/mygdx/game/MyGame.java | ricardoshimoda/gbc_game2014 | 7997e50cd3fb790129379980c1a08c408a3703f1 | [
"MIT"
] | null | null | null | FlappyBird/LabTest/core/src/com/mygdx/game/MyGame.java | ricardoshimoda/gbc_game2014 | 7997e50cd3fb790129379980c1a08c408a3703f1 | [
"MIT"
] | null | null | null | FlappyBird/LabTest/core/src/com/mygdx/game/MyGame.java | ricardoshimoda/gbc_game2014 | 7997e50cd3fb790129379980c1a08c408a3703f1 | [
"MIT"
] | null | null | null | package com.mygdx.game;
import com.badlogic.gdx.Gdx;
import com.mygdx.game.base.GameBeta;
import com.mygdx.game.scenes.LevelOne;
import com.mygdx.game.scenes.Play;
import com.mygdx.game.scenes.Score;
import com.mygdx.game.scenes.Title;
/**
* Created by markapptist on 2018-09-26.
* Modified by Ricardo Shimoda Nakasako - 101128885 - 2018-10-05
*/
public class MyGame extends GameBeta {
/*
* Scenes
*/
Title titleScene;
Play playScene;
Score scoreScene;
LevelOne levelOne;
String activeScreen;
@Override
public void create() {
super.create();
titleScene = new Title();
playScene = new Play();
scoreScene = new Score();
/*
-- Testing scenes
-- Score
setScreen(scoreScene);
activeScreen = "Score";
-- Title
setScreen(titleScene);
activeScreen = "Title";
-- Play
setScreen(playScene);
activeScreen = "Play";
*/
setScreen(titleScene);
activeScreen = "Title";
}
private void resetScreen(String finalScreen)
{
titleScene.transitionTo="";
playScene.transitionTo="";
scoreScene.transitionTo="";
activeScreen = finalScreen;
}
@Override
public void render()
{
//clearWhite();
if (activeScreen == "Title")
{
if (titleScene.transitionTo == "Play")
{
resetScreen("Play");
playScene.initialize();
setActiveScreen(playScene);
}
if (titleScene.transitionTo == "Score")
{
Gdx.app.log("Debug","Changing to Score");
resetScreen("Score");
setActiveScreen(scoreScene);
}
}
if (activeScreen == "Score")
{
if (scoreScene.transitionTo == "Title")
{
Gdx.app.log("Debug","Changing to Title");
resetScreen("Title");
setActiveScreen(titleScene);
}
}
if (activeScreen == "Play")
{
if (playScene.transitionTo == "Title")
{
Gdx.app.log("Debug","Changing to Title");
resetScreen("Title");
setActiveScreen(titleScene);
}
}
super.render();
}
}
| 23.519608 | 64 | 0.52105 |
90ba5b1c9de4853fa6bc6ffb22325c40c64cbb6c | 1,010 | swift | Swift | Weibo_DemoTest/Weibo_DemoTest/StatusNormalCell.swift | iXieYi/Weibo_DemoTest | 5cf3f30d93e1bcb217874324fc1e5df6db3586ff | [
"MIT"
] | null | null | null | Weibo_DemoTest/Weibo_DemoTest/StatusNormalCell.swift | iXieYi/Weibo_DemoTest | 5cf3f30d93e1bcb217874324fc1e5df6db3586ff | [
"MIT"
] | null | null | null | Weibo_DemoTest/Weibo_DemoTest/StatusNormalCell.swift | iXieYi/Weibo_DemoTest | 5cf3f30d93e1bcb217874324fc1e5df6db3586ff | [
"MIT"
] | null | null | null | //
// StatusNormalCell.swift
// Weibo_DemoTest
//
// Created by 谢毅 on 16/12/27.
// Copyright © 2016年 xieyi. All rights reserved.
//
import UIKit
//原创微博
class StatusNormalCell: StatusCell {
//微博视图模型
override var viewModel:StatusViewModel?{
didSet{
pictureView.snp_updateConstraints { (make) -> Void in
//根据配图数量,决定配图视图的顶部间距
let offset = viewModel?.thumbnailUrls?.count > 0 ?StatusCellMargin :0
make.top.equalTo(contentLabel.snp_bottom).offset(offset)
}
}
}
override func setupUI() {
//若没有下面这句话,会提示没有办法安装约束,!!!
//本质原因是没有创建控件,所导致的
super.setupUI()
//配图
pictureView.snp_makeConstraints { (make) -> Void in
make.top.equalTo(contentLabel.snp_bottom).offset(StatusCellMargin)
make.left.equalTo(contentLabel.snp_left)
make.width.equalTo(300)
make.height.equalTo(90)
}
}
}
| 21.489362 | 86 | 0.576238 |
53fde52a905df283b36df03b747b0cc069e69c1b | 8,456 | sql | SQL | sql/quartz.sql | liheyang/vue-oracle-base | 479177f039b500067d3676412aa8da84b272048a | [
"MIT"
] | 1 | 2021-06-21T08:48:50.000Z | 2021-06-21T08:48:50.000Z | sql/quartz.sql | liheyang/vue-oracle-base | 479177f039b500067d3676412aa8da84b272048a | [
"MIT"
] | null | null | null | sql/quartz.sql | liheyang/vue-oracle-base | 479177f039b500067d3676412aa8da84b272048a | [
"MIT"
] | null | null | null | -- ----------------------------
-- 1、存储每一个已配置的 jobDetail 的详细信息
-- ----------------------------
create table qrtz_job_details
(
sched_name varchar2(120) not null,
job_name varchar2(200) not null,
job_group varchar2(200) not null,
description varchar2(250) null,
job_class_name varchar2(250) not null,
is_durable varchar2(1) not null,
is_nonconcurrent varchar2(1) not null,
is_update_data varchar2(1) not null,
requests_recovery varchar2(1) not null,
job_data blob null,
constraint qrtz_job_details_pk primary key (sched_name, job_name, job_group)
);
-- ----------------------------
-- 2、 存储已配置的 Trigger 的信息
-- ----------------------------
create table qrtz_triggers
(
sched_name varchar2(120) not null,
trigger_name varchar2(200) not null,
trigger_group varchar2(200) not null,
job_name varchar2(200) not null,
job_group varchar2(200) not null,
description varchar2(250) null,
next_fire_time number(13) null,
prev_fire_time number(13) null,
priority number(13) null,
trigger_state varchar2(16) not null,
trigger_type varchar2(8) not null,
start_time number(13) not null,
end_time number(13) null,
calendar_name varchar2(200) null,
misfire_instr number(2) null,
job_data blob null,
constraint qrtz_triggers_pk primary key (sched_name, trigger_name, trigger_group),
constraint qrtz_trigger_to_jobs_fk foreign key (sched_name, job_name, job_group)
references qrtz_job_details (sched_name, job_name, job_group)
);
-- ----------------------------
-- 3、 存储简单的 Trigger,包括重复次数,间隔,以及已触发的次数
-- ----------------------------
create table qrtz_simple_triggers
(
sched_name varchar2(120) not null,
trigger_name varchar2(200) not null,
trigger_group varchar2(200) not null,
repeat_count number(7) not null,
repeat_interval number(12) not null,
times_triggered number(10) not null,
constraint qrtz_simple_trig_pk primary key (sched_name, trigger_name, trigger_group),
constraint qrtz_simple_trig_to_trig_fk foreign key (sched_name, trigger_name, trigger_group)
references qrtz_triggers (sched_name, trigger_name, trigger_group)
);
-- ----------------------------
-- 4、 存储 Cron Trigger,包括 Cron 表达式和时区信息
-- ----------------------------
create table qrtz_cron_triggers
(
sched_name varchar2(120) not null,
trigger_name varchar2(200) not null,
trigger_group varchar2(200) not null,
cron_expression varchar2(120) not null,
time_zone_id varchar2(80),
constraint qrtz_cron_trig_pk primary key (sched_name, trigger_name, trigger_group),
constraint qrtz_cron_trig_to_trig_fk foreign key (sched_name, trigger_name, trigger_group)
references qrtz_triggers (sched_name, trigger_name, trigger_group)
);
-- ----------------------------
-- 5、 Trigger 作为 Blob 类型存储(用于 Quartz 用户用 JDBC 创建他们自己定制的 Trigger 类型,JobStore 并不知道如何存储实例的时候)
-- ----------------------------
create table qrtz_blob_triggers
(
sched_name varchar2(120) not null,
trigger_name varchar2(200) not null,
trigger_group varchar2(200) not null,
blob_data blob null,
constraint qrtz_blob_trig_pk primary key (sched_name, trigger_name, trigger_group),
constraint qrtz_blob_trig_to_trig_fk foreign key (sched_name, trigger_name, trigger_group)
references qrtz_triggers (sched_name, trigger_name, trigger_group)
);
-- ----------------------------
-- 6、 以 Blob 类型存储存放日历信息, quartz可配置一个日历来指定一个时间范围
-- ----------------------------
create table qrtz_calendars
(
sched_name varchar2(120) not null,
calendar_name varchar2(200) not null,
calendar blob not null,
constraint qrtz_calendars_pk primary key (sched_name, calendar_name)
);
-- ----------------------------
-- 7、 存储已暂停的 Trigger 组的信息
-- ----------------------------
create table qrtz_paused_trigger_grps
(
sched_name varchar2(120) not null,
trigger_group varchar2(200) not null,
constraint qrtz_paused_trig_grps_pk primary key (sched_name, trigger_group)
);
-- ----------------------------
-- 8、 存储与已触发的 Trigger 相关的状态信息,以及相联 Job 的执行信息
-- ----------------------------
create table qrtz_fired_triggers
(
sched_name varchar2(120) not null,
entry_id varchar2(95) not null,
trigger_name varchar2(200) not null,
trigger_group varchar2(200) not null,
instance_name varchar2(200) not null,
fired_time number(13) not null,
sched_time number(13) not null,
priority number(13) not null,
state varchar2(16) not null,
job_name varchar2(200) null,
job_group varchar2(200) null,
is_nonconcurrent varchar2(1) null,
requests_recovery varchar2(1) null,
constraint qrtz_fired_trigger_pk primary key (sched_name, entry_id)
);
-- ----------------------------
-- 9、 存储少量的有关 Scheduler 的状态信息,假如是用于集群中,可以看到其他的 Scheduler 实例
-- ----------------------------
create table qrtz_scheduler_state
(
sched_name varchar2(120) not null,
instance_name varchar2(200) not null,
last_checkin_time number(13) not null,
checkin_interval number(13) not null,
constraint qrtz_scheduler_state_pk primary key (sched_name, instance_name)
);
-- ----------------------------
-- 10、 存储程序的悲观锁的信息(假如使用了悲观锁)
-- ----------------------------
create table qrtz_locks
(
sched_name varchar2(120) not null,
lock_name varchar2(40) not null,
constraint qrtz_locks_pk primary key (sched_name, lock_name)
);
create table qrtz_simprop_triggers
(
sched_name varchar2(120) not null,
trigger_name varchar2(200) not null,
trigger_group varchar2(200) not null,
str_prop_1 varchar2(512) null,
str_prop_2 varchar2(512) null,
str_prop_3 varchar2(512) null,
int_prop_1 number(10) null,
int_prop_2 number(10) null,
long_prop_1 number(13) null,
long_prop_2 number(13) null,
dec_prop_1 numeric(13, 4) null,
dec_prop_2 numeric(13, 4) null,
bool_prop_1 varchar2(1) null,
bool_prop_2 varchar2(1) null,
constraint qrtz_simprop_trig_pk primary key (sched_name, trigger_name, trigger_group),
constraint qrtz_simprop_trig_to_trig_fk foreign key (sched_name, trigger_name, trigger_group)
references qrtz_triggers (sched_name, trigger_name, trigger_group)
);
create index idx_qrtz_j_req_recovery on qrtz_job_details (sched_name, requests_recovery);
create index idx_qrtz_j_grp on qrtz_job_details (sched_name, job_group);
create index idx_qrtz_t_j on qrtz_triggers (sched_name, job_name, job_group);
create index idx_qrtz_t_jg on qrtz_triggers (sched_name, job_group);
create index idx_qrtz_t_c on qrtz_triggers (sched_name, calendar_name);
create index idx_qrtz_t_g on qrtz_triggers (sched_name, trigger_group);
create index idx_qrtz_t_state on qrtz_triggers (sched_name, trigger_state);
create index idx_qrtz_t_n_state on qrtz_triggers (sched_name, trigger_name, trigger_group, trigger_state);
create index idx_qrtz_t_n_g_state on qrtz_triggers (sched_name, trigger_group, trigger_state);
create index idx_qrtz_t_next_fire_time on qrtz_triggers (sched_name, next_fire_time);
create index idx_qrtz_t_nft_st on qrtz_triggers (sched_name, trigger_state, next_fire_time);
create index idx_qrtz_t_nft_misfire on qrtz_triggers (sched_name, misfire_instr, next_fire_time);
create index idx_qrtz_t_nft_st_misfire on qrtz_triggers (sched_name, misfire_instr, next_fire_time, trigger_state);
create index idx_qrtz_t_nft_st_misfire_grp on qrtz_triggers (sched_name, misfire_instr, next_fire_time, trigger_group,
trigger_state);
create index idx_qrtz_ft_trig_inst_name on qrtz_fired_triggers (sched_name, instance_name);
create index idx_qrtz_ft_inst_job_req_rcvry on qrtz_fired_triggers (sched_name, instance_name, requests_recovery);
create index idx_qrtz_ft_j_g on qrtz_fired_triggers (sched_name, job_name, job_group);
create index idx_qrtz_ft_jg on qrtz_fired_triggers (sched_name, job_group);
create index idx_qrtz_ft_t_g on qrtz_fired_triggers (sched_name, trigger_name, trigger_group);
create index idx_qrtz_ft_tg on qrtz_fired_triggers (sched_name, trigger_group);
commit;
| 42.069652 | 118 | 0.678926 |
ab65c100a7301e7ab6021581b39eff7503b44469 | 909 | swift | Swift | BinarySearch.playground/Pages/String.xcplaygroundpage/Contents.swift | Yar177/DS-Algs | 499633a9973ed05bc5529714ac5f85c2c81fcc54 | [
"Apache-2.0"
] | null | null | null | BinarySearch.playground/Pages/String.xcplaygroundpage/Contents.swift | Yar177/DS-Algs | 499633a9973ed05bc5529714ac5f85c2c81fcc54 | [
"Apache-2.0"
] | null | null | null | BinarySearch.playground/Pages/String.xcplaygroundpage/Contents.swift | Yar177/DS-Algs | 499633a9973ed05bc5529714ac5f85c2c81fcc54 | [
"Apache-2.0"
] | null | null | null | //: [Previous](@previous)
import Foundation
var str = "abssscded"
str.count
for (n, c) in "Swift".enumerated() {
print("\(n): '\(c)'")
}
class Solution {
func lengthOfLongestSubstring(_ s: String) -> Int {
var maxLength = 0
for (i, c) in s.enumerated() {
print("\(i): '\(c)'")
var count = 0
for cr in (i+1)...s.count{
print(count += 1)
}
}
return maxLength
}
}
let index = String.Index(encodedOffset: 0)
print(str[index])
for i in 1...100{
if i % 15 == 0 {
print("FizzBuzz")
}else if i % 3 == 0{
print("Fizz")
}else if i % 5 == 0{
print("Buzz")
}else {
print(i)
}
}
var fullName: String = "First Last"
let fullNameArr = fullName.components(separatedBy: "")
//for i in 0...5{
// // print(str[i])
//}
//: [Next](@next)
| 14.428571 | 55 | 0.482948 |
1b6a1f48707ec377f17b2fc412f37e5524481f8a | 61 | sql | SQL | core/src/main/resources/schema/sqlserver/sqlserver-drop-schema-legacy.sql | innFactory/akka-persistence-jdbc | e2e08a2f5186b20c376cb26c1754ffb869a9e6c1 | [
"Apache-2.0"
] | 62 | 2019-11-29T14:35:30.000Z | 2022-03-22T14:27:47.000Z | core/src/main/resources/schema/sqlserver/sqlserver-drop-schema-legacy.sql | innFactory/akka-persistence-jdbc | e2e08a2f5186b20c376cb26c1754ffb869a9e6c1 | [
"Apache-2.0"
] | 181 | 2019-11-29T07:44:42.000Z | 2022-03-29T15:28:29.000Z | core/src/main/resources/schema/sqlserver/sqlserver-drop-schema-legacy.sql | innFactory/akka-persistence-jdbc | e2e08a2f5186b20c376cb26c1754ffb869a9e6c1 | [
"Apache-2.0"
] | 33 | 2019-12-04T12:17:26.000Z | 2022-03-28T17:07:01.000Z | DROP TABLE IF EXISTS journal;
DROP TABLE IF EXISTS snapshot;
| 20.333333 | 30 | 0.803279 |
40efa27e5e9ea791d32928e30fbc429ff78f8ba9 | 1,707 | py | Python | run_scenarios_and_save_results.py | mgilleran/REopt_BTMS_API | eb5d837897a69f1225e1aae8e0035b5445d59b1f | [
"BSD-3-Clause"
] | null | null | null | run_scenarios_and_save_results.py | mgilleran/REopt_BTMS_API | eb5d837897a69f1225e1aae8e0035b5445d59b1f | [
"BSD-3-Clause"
] | null | null | null | run_scenarios_and_save_results.py | mgilleran/REopt_BTMS_API | eb5d837897a69f1225e1aae8e0035b5445d59b1f | [
"BSD-3-Clause"
] | null | null | null | import os
from src.multi_site_inputs_parser import multi_site_csv_parser
from src.parse_api_responses_to_csv import parse_responses_to_csv_with_template
from src.post_and_poll import get_api_results
from src.parse_api_responses_to_excel import parse_api_responses_to_excel
"""
Change these values
"""
##############################################################################################################
API_KEY = 'my_API_KEY' # REPLACE WITH YOUR API KEY
inputs_path = os.path.join('inputs')
outputs_path = os.path.join('outputs')
output_template = os.path.join(outputs_path, 'results_template.csv')
output_file = os.path.join(outputs_path, 'results_summary.csv')
##############################################################################################################
server = 'https://developer.nrel.gov/api/reopt/v1'
path_to_inputs = os.path.join(inputs_path, 'scenarios.csv')
list_of_posts = multi_site_csv_parser(path_to_inputs, api_url=server, API_KEY=API_KEY)
responses = []
for post in list_of_posts:
responses.append(get_api_results(
post, results_file=os.path.join(outputs_path, post['Scenario']['description'] + '.json'),
api_url=server, API_KEY=API_KEY)
)
"""
Two options for making a summary of scenarios:
1. Write to a csv using a template with column headers for desired summary keys (scalar values only)
2. Write all inputs, outputs, and dispatch to an Excel spreadsheet
"""
parse_responses_to_csv_with_template(csv_template=output_template, responses=responses, output_csv=output_file, input_csv=path_to_inputs,
n_custom_columns=2)
parse_api_responses_to_excel(responses, spreadsheet='results_summary.xlsx') | 43.769231 | 137 | 0.680141 |
e5e23180d02dcff4b61c949cb8dc3c938e5bb2f6 | 41,822 | sql | SQL | data/sql/create.sql | nesp-tsr3-1/tsx | 9fc221be448bc666b6eab7207a9fb343212c9a53 | [
"MIT"
] | 3 | 2019-01-27T12:03:46.000Z | 2022-01-29T02:06:33.000Z | data/sql/create.sql | nesp-tsr3-1/tsx | 9fc221be448bc666b6eab7207a9fb343212c9a53 | [
"MIT"
] | 27 | 2019-02-25T22:49:14.000Z | 2022-02-02T04:07:52.000Z | data/sql/create.sql | nesp-tsr3-1/tsx | 9fc221be448bc666b6eab7207a9fb343212c9a53 | [
"MIT"
] | 1 | 2019-02-28T04:24:43.000Z | 2019-02-28T04:24:43.000Z | -- MySQL Script generated by MySQL Workbench
-- Mon Nov 15 13:29:58 2021
-- Model: New Model Version: 1.0
-- MySQL Workbench Forward Engineering
SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION';
-- -----------------------------------------------------
-- Schema nesp
-- -----------------------------------------------------
-- -----------------------------------------------------
-- Table `unit`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `unit` ;
CREATE TABLE IF NOT EXISTS `unit` (
`id` INT NOT NULL AUTO_INCREMENT,
`description` VARCHAR(255) NOT NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `search_type`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `search_type` ;
CREATE TABLE IF NOT EXISTS `search_type` (
`id` INT NOT NULL AUTO_INCREMENT,
`description` VARCHAR(255) NOT NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `source_type`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `source_type` ;
CREATE TABLE IF NOT EXISTS `source_type` (
`id` INT NOT NULL AUTO_INCREMENT,
`description` VARCHAR(255) NOT NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `monitoring_program`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `monitoring_program` ;
CREATE TABLE IF NOT EXISTS `monitoring_program` (
`id` INT NOT NULL AUTO_INCREMENT,
`description` VARCHAR(255) NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `source`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `source` ;
CREATE TABLE IF NOT EXISTS `source` (
`id` INT NOT NULL AUTO_INCREMENT,
`source_type_id` INT NULL,
`provider` TEXT NULL,
`description` TEXT NULL,
`notes` TEXT NULL,
`authors` TEXT NULL,
`contact_name` TEXT NULL,
`contact_institution` TEXT NULL,
`contact_position` TEXT NULL,
`contact_email` TEXT NULL,
`contact_phone` TEXT NULL,
`monitoring_program_id` INT NULL,
`time_created` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
`last_modified` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
INDEX `fk_Source_SourceType_idx` (`source_type_id` ASC) VISIBLE,
INDEX `fk_source_monitoring_program1_idx` (`monitoring_program_id` ASC) VISIBLE,
CONSTRAINT `fk_Source_SourceType`
FOREIGN KEY (`source_type_id`)
REFERENCES `source_type` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_source_monitoring_program1`
FOREIGN KEY (`monitoring_program_id`)
REFERENCES `monitoring_program` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `intensive_management`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `intensive_management` ;
CREATE TABLE IF NOT EXISTS `intensive_management` (
`id` INT NOT NULL AUTO_INCREMENT,
`description` VARCHAR(255) NULL,
`grouping` VARCHAR(255) NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `data_import_status`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `data_import_status` ;
CREATE TABLE IF NOT EXISTS `data_import_status` (
`id` INT NOT NULL AUTO_INCREMENT,
`description` VARCHAR(255) NULL,
`code` VARCHAR(255) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE INDEX `code_UNIQUE` (`code` ASC) VISIBLE)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `user`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `user` ;
CREATE TABLE IF NOT EXISTS `user` (
`id` INT NOT NULL AUTO_INCREMENT,
`email` VARCHAR(255) NULL COMMENT ' ',
`password_hash` TEXT NULL,
`first_name` TEXT NULL,
`last_name` TEXT NULL,
`phone_number` VARCHAR(32) NULL,
`password_reset_code` VARCHAR(32) NULL,
PRIMARY KEY (`id`),
UNIQUE INDEX `email_UNIQUE` (`email` ASC) VISIBLE)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `data_import`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `data_import` ;
CREATE TABLE IF NOT EXISTS `data_import` (
`id` INT NOT NULL AUTO_INCREMENT,
`source_id` INT NULL,
`status_id` INT NULL,
`upload_uuid` VARCHAR(36) NULL,
`filename` TEXT NULL,
`error_count` INT NULL,
`warning_count` INT NULL,
`data_type` INT NOT NULL,
`user_id` INT NULL,
`time_created` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
`last_modified` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
INDEX `fk_data_import_source1_idx` (`source_id` ASC) VISIBLE,
INDEX `fk_data_import_data_import_status1_idx` (`status_id` ASC) VISIBLE,
INDEX `fk_data_import_user1_idx` (`user_id` ASC) VISIBLE,
CONSTRAINT `fk_data_import_source1`
FOREIGN KEY (`source_id`)
REFERENCES `source` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_data_import_data_import_status1`
FOREIGN KEY (`status_id`)
REFERENCES `data_import_status` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_data_import_user1`
FOREIGN KEY (`user_id`)
REFERENCES `user` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `t1_site`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `t1_site` ;
CREATE TABLE IF NOT EXISTS `t1_site` (
`id` INT NOT NULL AUTO_INCREMENT,
`source_id` INT NOT NULL,
`data_import_id` INT NULL,
`name` VARCHAR(255) NULL,
`search_type_id` INT NOT NULL,
`notes` TEXT NULL,
`intensive_management_id` INT NULL,
PRIMARY KEY (`id`),
INDEX `fk_T1Site_Source1_idx` (`source_id` ASC) VISIBLE,
INDEX `fk_T1Site_SearchType1_idx` (`search_type_id` ASC) VISIBLE,
INDEX `fk_t1_site_intensive_management1_idx` (`intensive_management_id` ASC) VISIBLE,
INDEX `fk_t1_site_data_import1_idx` (`data_import_id` ASC) VISIBLE,
CONSTRAINT `fk_T1Site_Source1`
FOREIGN KEY (`source_id`)
REFERENCES `source` (`id`)
ON DELETE CASCADE
ON UPDATE NO ACTION,
CONSTRAINT `fk_T1Site_SearchType1`
FOREIGN KEY (`search_type_id`)
REFERENCES `search_type` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_t1_site_intensive_management1`
FOREIGN KEY (`intensive_management_id`)
REFERENCES `intensive_management` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_t1_site_data_import1`
FOREIGN KEY (`data_import_id`)
REFERENCES `data_import` (`id`)
ON DELETE CASCADE
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `t1_survey`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `t1_survey` ;
CREATE TABLE IF NOT EXISTS `t1_survey` (
`id` INT NOT NULL AUTO_INCREMENT,
`site_id` INT NOT NULL,
`source_id` INT NOT NULL,
`data_import_id` INT NULL,
`source_primary_key` VARCHAR(255) NOT NULL,
`start_date_d` SMALLINT NULL,
`start_date_m` SMALLINT NULL,
`start_date_y` SMALLINT NOT NULL,
`finish_date_d` SMALLINT NULL,
`finish_date_m` SMALLINT NULL,
`finish_date_y` SMALLINT NULL,
`start_time` TIME NULL,
`finish_time` TIME NULL,
`duration_in_minutes` INT NULL,
`area_in_m2` DOUBLE NULL,
`length_in_km` DOUBLE NULL,
`number_of_traps_per_day` INT NULL,
`coords` POINT NOT NULL,
`location` TEXT NULL,
`positional_accuracy_in_m` DOUBLE NULL,
`comments` TEXT NULL,
PRIMARY KEY (`id`),
INDEX `fk_T1Survey_T1Site1_idx` (`site_id` ASC) VISIBLE,
INDEX `fk_T1Survey_Source1_idx` (`source_id` ASC) VISIBLE,
UNIQUE INDEX `source_primary_key_UNIQUE` (`source_primary_key` ASC) VISIBLE,
INDEX `fk_t1_survey_data_import1_idx` (`data_import_id` ASC) VISIBLE,
CONSTRAINT `fk_T1Survey_T1Site1`
FOREIGN KEY (`site_id`)
REFERENCES `t1_site` (`id`)
ON DELETE CASCADE
ON UPDATE NO ACTION,
CONSTRAINT `fk_T1Survey_Source1`
FOREIGN KEY (`source_id`)
REFERENCES `source` (`id`)
ON DELETE CASCADE
ON UPDATE NO ACTION,
CONSTRAINT `fk_t1_survey_data_import1`
FOREIGN KEY (`data_import_id`)
REFERENCES `data_import` (`id`)
ON DELETE CASCADE
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `taxon_level`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `taxon_level` ;
CREATE TABLE IF NOT EXISTS `taxon_level` (
`id` INT NOT NULL AUTO_INCREMENT,
`description` VARCHAR(255) NOT NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `taxon_status`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `taxon_status` ;
CREATE TABLE IF NOT EXISTS `taxon_status` (
`id` INT NOT NULL,
`description` VARCHAR(255) NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `taxon`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `taxon` ;
CREATE TABLE IF NOT EXISTS `taxon` (
`id` CHAR(8) NOT NULL,
`ultrataxon` TINYINT(1) NOT NULL,
`taxon_level_id` INT NULL,
`spno` SMALLINT NULL,
`common_name` VARCHAR(255) NULL,
`scientific_name` VARCHAR(255) NOT NULL,
`family_common_name` VARCHAR(255) NULL,
`family_scientific_name` VARCHAR(255) NULL,
`order` VARCHAR(255) NULL,
`population` VARCHAR(255) NULL,
`epbc_status_id` INT NULL,
`iucn_status_id` INT NULL,
`state_status_id` INT NULL,
`max_status_id` INT GENERATED ALWAYS AS (NULLIF(GREATEST(COALESCE(taxon.epbc_status_id, 0), COALESCE(taxon.iucn_status_id, 0)), 0)),
`national_priority` TINYINT(1) NOT NULL DEFAULT 0,
`taxonomic_group` VARCHAR(255) NOT NULL,
`suppress_spatial_representativeness` TINYINT(1) NOT NULL DEFAULT 0,
PRIMARY KEY (`id`),
INDEX `fk_Taxon_TaxonLevel1_idx` (`taxon_level_id` ASC) VISIBLE,
INDEX `fk_taxon_taxon_status2_idx` (`epbc_status_id` ASC) VISIBLE,
INDEX `fk_taxon_taxon_status3_idx` (`iucn_status_id` ASC) VISIBLE,
INDEX `fk_taxon_taxon_status4_idx` (`state_status_id` ASC) VISIBLE,
CONSTRAINT `fk_Taxon_TaxonLevel1`
FOREIGN KEY (`taxon_level_id`)
REFERENCES `taxon_level` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_taxon_taxon_status2`
FOREIGN KEY (`epbc_status_id`)
REFERENCES `taxon_status` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_taxon_taxon_status3`
FOREIGN KEY (`iucn_status_id`)
REFERENCES `taxon_status` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_taxon_taxon_status4`
FOREIGN KEY (`state_status_id`)
REFERENCES `taxon_status` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `taxon_hybrid`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `taxon_hybrid` ;
CREATE TABLE IF NOT EXISTS `taxon_hybrid` (
`id` CHAR(12) NOT NULL COMMENT 'e.g. u123a.b.c',
`taxon_id` CHAR(8) NULL,
PRIMARY KEY (`id`),
INDEX `fk_TaxonHybrid_Taxon1_idx` (`taxon_id` ASC) VISIBLE,
CONSTRAINT `fk_TaxonHybrid_Taxon1`
FOREIGN KEY (`taxon_id`)
REFERENCES `taxon` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `t1_sighting`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `t1_sighting` ;
CREATE TABLE IF NOT EXISTS `t1_sighting` (
`id` INT NOT NULL AUTO_INCREMENT,
`survey_id` INT NOT NULL,
`taxon_id` CHAR(8) NOT NULL,
`count` DOUBLE NOT NULL,
`unit_id` INT NOT NULL,
`breeding` TINYINT(1) NULL,
PRIMARY KEY (`id`),
INDEX `fk_T1Sighting_T1Survey1_idx` (`survey_id` ASC) VISIBLE,
INDEX `fk_T1Sighting_Taxon1_idx` (`taxon_id` ASC) VISIBLE,
INDEX `fk_T1Sighting_Unit1_idx` (`unit_id` ASC) VISIBLE,
CONSTRAINT `fk_T1Sighting_T1Survey1`
FOREIGN KEY (`survey_id`)
REFERENCES `t1_survey` (`id`)
ON DELETE CASCADE
ON UPDATE NO ACTION,
CONSTRAINT `fk_T1Sighting_Taxon1`
FOREIGN KEY (`taxon_id`)
REFERENCES `taxon` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_T1Sighting_Unit1`
FOREIGN KEY (`unit_id`)
REFERENCES `unit` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `incidental_sighting`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `incidental_sighting` ;
CREATE TABLE IF NOT EXISTS `incidental_sighting` (
`taxon_id` CHAR(8) NOT NULL,
`coords` POINT NULL,
`date` DATE NULL,
INDEX `fk_incidental_sighting_taxon1_idx` (`taxon_id` ASC) VISIBLE,
CONSTRAINT `fk_incidental_sighting_taxon1`
FOREIGN KEY (`taxon_id`)
REFERENCES `taxon` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `t2_site`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `t2_site` ;
CREATE TABLE IF NOT EXISTS `t2_site` (
`id` INT NOT NULL AUTO_INCREMENT,
`source_id` INT NULL,
`data_import_id` INT NULL,
`name` VARCHAR(255) NULL,
`search_type_id` INT NOT NULL,
`geometry` MULTIPOLYGON NULL,
PRIMARY KEY (`id`),
INDEX `fk_t2_site_search_type1_idx` (`search_type_id` ASC) VISIBLE,
INDEX `fk_t2_site_source1_idx` (`source_id` ASC) VISIBLE,
INDEX `source_name` (`source_id` ASC, `name` ASC) VISIBLE,
INDEX `fk_t2_site_data_import1_idx` (`data_import_id` ASC) VISIBLE,
CONSTRAINT `fk_t2_site_search_type1`
FOREIGN KEY (`search_type_id`)
REFERENCES `search_type` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_t2_site_source1`
FOREIGN KEY (`source_id`)
REFERENCES `source` (`id`)
ON DELETE CASCADE
ON UPDATE NO ACTION,
CONSTRAINT `fk_t2_site_data_import1`
FOREIGN KEY (`data_import_id`)
REFERENCES `data_import` (`id`)
ON DELETE CASCADE
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `t2_survey`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `t2_survey` ;
CREATE TABLE IF NOT EXISTS `t2_survey` (
`id` INT NOT NULL AUTO_INCREMENT,
`site_id` INT NULL,
`source_id` INT NOT NULL,
`data_import_id` INT NULL,
`start_date_d` SMALLINT NULL,
`start_date_m` SMALLINT NULL,
`start_date_y` SMALLINT NOT NULL,
`finish_date_d` SMALLINT NULL,
`finish_date_m` SMALLINT NULL,
`finish_date_y` SMALLINT NULL,
`start_time` TIME NULL,
`finish_time` TIME NULL,
`duration_in_minutes` INT NULL,
`area_in_m2` DOUBLE NULL,
`length_in_km` DOUBLE NULL,
`coords` POINT NOT NULL,
`location` TEXT NULL,
`positional_accuracy_in_m` DOUBLE NULL,
`comments` TEXT NULL,
`search_type_id` INT NOT NULL,
`source_primary_key` VARCHAR(255) NOT NULL,
`secondary_source_id` VARCHAR(255) NULL,
PRIMARY KEY (`id`),
INDEX `fk_T1Survey_Source1_idx` (`source_id` ASC) VISIBLE,
INDEX `fk_T2Survey_SearchType1_idx` (`search_type_id` ASC) VISIBLE,
UNIQUE INDEX `source_primary_key_UNIQUE` (`source_primary_key` ASC) VISIBLE,
INDEX `fk_t2_survey_t2_site1_idx` (`site_id` ASC) VISIBLE,
INDEX `fk_t2_survey_data_import1_idx` (`data_import_id` ASC) VISIBLE,
CONSTRAINT `fk_T1Survey_Source10`
FOREIGN KEY (`source_id`)
REFERENCES `source` (`id`)
ON DELETE CASCADE
ON UPDATE NO ACTION,
CONSTRAINT `fk_T2Survey_SearchType1`
FOREIGN KEY (`search_type_id`)
REFERENCES `search_type` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_t2_survey_t2_site1`
FOREIGN KEY (`site_id`)
REFERENCES `t2_site` (`id`)
ON DELETE CASCADE
ON UPDATE NO ACTION,
CONSTRAINT `fk_t2_survey_data_import1`
FOREIGN KEY (`data_import_id`)
REFERENCES `data_import` (`id`)
ON DELETE CASCADE
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `t2_survey_site`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `t2_survey_site` ;
CREATE TABLE IF NOT EXISTS `t2_survey_site` (
`survey_id` INT NOT NULL,
`site_id` INT NOT NULL,
INDEX `fk_T2SurveySite_T2Site1_idx` (`site_id` ASC) VISIBLE,
PRIMARY KEY (`survey_id`, `site_id`),
CONSTRAINT `fk_T2SurveySite_T2Survey1`
FOREIGN KEY (`survey_id`)
REFERENCES `t2_survey` (`id`)
ON DELETE CASCADE
ON UPDATE NO ACTION,
CONSTRAINT `fk_T2SurveySite_T2Site1`
FOREIGN KEY (`site_id`)
REFERENCES `t2_site` (`id`)
ON DELETE CASCADE
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `t2_sighting`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `t2_sighting` ;
CREATE TABLE IF NOT EXISTS `t2_sighting` (
`id` INT NOT NULL AUTO_INCREMENT,
`survey_id` INT NOT NULL,
`taxon_id` CHAR(8) NOT NULL,
`count` DOUBLE NULL,
`unit_id` INT NULL,
`breeding` TINYINT(1) NULL,
PRIMARY KEY (`id`),
INDEX `fk_T2Sighting_T2Survey1_idx` (`survey_id` ASC) VISIBLE,
INDEX `fk_T2Sighting_Unit1_idx` (`unit_id` ASC) VISIBLE,
INDEX `fk_T2Sighting_Taxon1_idx` (`taxon_id` ASC) VISIBLE,
CONSTRAINT `fk_T2Sighting_T2Survey1`
FOREIGN KEY (`survey_id`)
REFERENCES `t2_survey` (`id`)
ON DELETE CASCADE
ON UPDATE NO ACTION,
CONSTRAINT `fk_T2Sighting_Unit1`
FOREIGN KEY (`unit_id`)
REFERENCES `unit` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_T2Sighting_Taxon1`
FOREIGN KEY (`taxon_id`)
REFERENCES `taxon` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `range`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `range` ;
CREATE TABLE IF NOT EXISTS `range` (
`id` INT NOT NULL AUTO_INCREMENT,
`description` VARCHAR(255) NOT NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `t2_ultrataxon_sighting`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `t2_ultrataxon_sighting` ;
CREATE TABLE IF NOT EXISTS `t2_ultrataxon_sighting` (
`sighting_id` INT NOT NULL,
`taxon_id` CHAR(8) NOT NULL,
`range_id` INT NOT NULL,
`generated_subspecies` TINYINT(1) NOT NULL,
INDEX `fk_T2SightingRangeType_RangeType1_idx` (`range_id` ASC) VISIBLE,
PRIMARY KEY (`sighting_id`, `taxon_id`),
INDEX `fk_T2ProcessedSighting_Taxon1_idx` (`taxon_id` ASC) VISIBLE,
CONSTRAINT `fk_T2SightingRangeType_RangeType1`
FOREIGN KEY (`range_id`)
REFERENCES `range` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_T2ProcessedSighting_T2Sighting1`
FOREIGN KEY (`sighting_id`)
REFERENCES `t2_sighting` (`id`)
ON DELETE CASCADE
ON UPDATE NO ACTION,
CONSTRAINT `fk_T2ProcessedSighting_Taxon1`
FOREIGN KEY (`taxon_id`)
REFERENCES `taxon` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `taxon_presence_alpha_hull`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `taxon_presence_alpha_hull` ;
CREATE TABLE IF NOT EXISTS `taxon_presence_alpha_hull` (
`taxon_id` CHAR(8) NOT NULL,
`range_id` INT NOT NULL,
`breeding_range_id` INT NULL,
`geometry` GEOMETRY NOT NULL,
INDEX `fk_taxon_presence_alpha_hull_range1_idx` (`range_id` ASC) VISIBLE,
CONSTRAINT `fk_taxon_presence_alpha_hull_taxon1`
FOREIGN KEY (`taxon_id`)
REFERENCES `taxon` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_taxon_presence_alpha_hull_range1`
FOREIGN KEY (`range_id`)
REFERENCES `range` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `grid_cell`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `grid_cell` ;
CREATE TABLE IF NOT EXISTS `grid_cell` (
`id` INT NOT NULL AUTO_INCREMENT,
`geometry` POLYGON NOT NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `t2_processed_survey`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `t2_processed_survey` ;
CREATE TABLE IF NOT EXISTS `t2_processed_survey` (
`id` INT NOT NULL AUTO_INCREMENT,
`raw_survey_id` INT NOT NULL,
`site_id` INT NULL,
`grid_cell_id` INT NULL,
`search_type_id` INT NOT NULL,
`start_date_y` SMALLINT NOT NULL,
`start_date_m` SMALLINT NULL,
`source_id` INT NOT NULL,
`experimental_design_type_id` INT NULL,
PRIMARY KEY (`id`),
INDEX `fk_t2_processed_survey_t2_survey1_idx` (`raw_survey_id` ASC) VISIBLE,
INDEX `fk_t2_processed_survey_t2_site1_idx` (`site_id` ASC) VISIBLE,
INDEX `fk_t2_processed_survey_grid_cell1_idx` (`grid_cell_id` ASC) VISIBLE,
INDEX `fk_t2_processed_survey_source1_idx` (`source_id` ASC) VISIBLE,
CONSTRAINT `fk_t2_processed_survey_t2_survey1`
FOREIGN KEY (`raw_survey_id`)
REFERENCES `t2_survey` (`id`)
ON DELETE CASCADE
ON UPDATE NO ACTION,
CONSTRAINT `fk_t2_processed_survey_t2_site1`
FOREIGN KEY (`site_id`)
REFERENCES `t2_site` (`id`)
ON DELETE CASCADE
ON UPDATE NO ACTION,
CONSTRAINT `fk_t2_processed_survey_grid_cell1`
FOREIGN KEY (`grid_cell_id`)
REFERENCES `grid_cell` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_t2_processed_survey_source1`
FOREIGN KEY (`source_id`)
REFERENCES `source` (`id`)
ON DELETE CASCADE
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `response_variable_type`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `response_variable_type` ;
CREATE TABLE IF NOT EXISTS `response_variable_type` (
`id` INT NOT NULL,
`description` VARCHAR(255) NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `state`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `state` ;
CREATE TABLE IF NOT EXISTS `state` (
`id` INT NOT NULL AUTO_INCREMENT,
`name` VARCHAR(255) NULL,
`geometry` MULTIPOLYGON NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `region`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `region` ;
CREATE TABLE IF NOT EXISTS `region` (
`id` INT NOT NULL,
`name` VARCHAR(255) NULL,
`geometry` MULTIPOLYGON NOT NULL,
`state` VARCHAR(255) NULL,
`positional_accuracy_in_m` INT NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `taxon_range`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `taxon_range` ;
CREATE TABLE IF NOT EXISTS `taxon_range` (
`taxon_id` CHAR(8) NOT NULL,
`range_id` INT NOT NULL,
`breeding_range_id` INT NULL,
`geometry` MULTIPOLYGON NOT NULL,
INDEX `fk_taxon_range_range1_idx` (`range_id` ASC) VISIBLE,
INDEX `fk_taxon_range_range2_idx` (`breeding_range_id` ASC) VISIBLE,
INDEX `fk_taxon_range_taxon1_idx` (`taxon_id` ASC) VISIBLE,
CONSTRAINT `fk_taxon_range_range1`
FOREIGN KEY (`range_id`)
REFERENCES `range` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_taxon_range_range2`
FOREIGN KEY (`breeding_range_id`)
REFERENCES `range` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_taxon_range_taxon1`
FOREIGN KEY (`taxon_id`)
REFERENCES `taxon` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `taxon_range_subdiv`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `taxon_range_subdiv` ;
CREATE TABLE IF NOT EXISTS `taxon_range_subdiv` (
`taxon_id` CHAR(8) NOT NULL,
`range_id` INT NOT NULL,
`breeding_range_id` INT NULL,
`geometry` MULTIPOLYGON NOT NULL,
INDEX `fk_taxon_range_range1_idx` (`range_id` ASC) VISIBLE,
INDEX `fk_taxon_range_range2_idx` (`breeding_range_id` ASC) VISIBLE,
INDEX `fk_taxon_range_taxon1_idx` (`taxon_id` ASC) VISIBLE,
CONSTRAINT `fk_taxon_range_range10`
FOREIGN KEY (`range_id`)
REFERENCES `range` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_taxon_range_range20`
FOREIGN KEY (`breeding_range_id`)
REFERENCES `range` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_taxon_range_taxon10`
FOREIGN KEY (`taxon_id`)
REFERENCES `taxon` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `taxon_presence_alpha_hull_subdiv`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `taxon_presence_alpha_hull_subdiv` ;
CREATE TABLE IF NOT EXISTS `taxon_presence_alpha_hull_subdiv` (
`taxon_id` CHAR(8) NOT NULL,
`range_id` INT NOT NULL,
`breeding_range_id` INT NULL,
`geometry` GEOMETRY NOT NULL,
INDEX `fk_taxon_presence_alpha_hull_range1_idx` (`range_id` ASC) VISIBLE,
CONSTRAINT `fk_taxon_presence_alpha_hull_taxon10`
FOREIGN KEY (`taxon_id`)
REFERENCES `taxon` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_taxon_presence_alpha_hull_range10`
FOREIGN KEY (`range_id`)
REFERENCES `range` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `t2_processed_sighting`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `t2_processed_sighting` ;
CREATE TABLE IF NOT EXISTS `t2_processed_sighting` (
`id` INT NOT NULL AUTO_INCREMENT,
`survey_id` INT NOT NULL,
`taxon_id` CHAR(8) NOT NULL,
`count` DOUBLE NOT NULL,
`unit_id` INT NOT NULL,
`pseudo_absence` TINYINT(1) NOT NULL,
PRIMARY KEY (`id`),
INDEX `survey_id_taxon_id` (`survey_id` ASC, `taxon_id` ASC) VISIBLE,
INDEX `fk_t2_processed_sighting_unit1_idx` (`unit_id` ASC) VISIBLE,
INDEX `fk_t2_processed_sighting_taxon1_idx` (`taxon_id` ASC) VISIBLE,
CONSTRAINT `fk_t2_processed_sighting_unit1`
FOREIGN KEY (`unit_id`)
REFERENCES `unit` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_t2_processed_sighting_t2_processed_survey1`
FOREIGN KEY (`survey_id`)
REFERENCES `t2_processed_survey` (`id`)
ON DELETE CASCADE
ON UPDATE NO ACTION,
CONSTRAINT `fk_t2_processed_sighting_taxon1`
FOREIGN KEY (`taxon_id`)
REFERENCES `taxon` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `experimental_design_type`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `experimental_design_type` ;
CREATE TABLE IF NOT EXISTS `experimental_design_type` (
`id` INT NOT NULL,
`description` VARCHAR(255) NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `aggregated_by_month`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `aggregated_by_month` ;
CREATE TABLE IF NOT EXISTS `aggregated_by_month` (
`start_date_y` SMALLINT NOT NULL,
`start_date_m` SMALLINT NULL,
`site_id` INT NULL,
`grid_cell_id` INT NULL,
`search_type_id` INT NULL,
`taxon_id` CHAR(8) NOT NULL,
`experimental_design_type_id` INT NOT NULL,
`response_variable_type_id` INT NOT NULL,
`value` DOUBLE NOT NULL,
`data_type` INT NOT NULL,
`source_id` INT NOT NULL,
`region_id` INT NULL,
`unit_id` INT NOT NULL,
`positional_accuracy_in_m` DOUBLE NULL,
`centroid_coords` POINT NOT NULL,
`survey_count` INT NOT NULL,
`time_series_id` VARCHAR(32) GENERATED ALWAYS AS (CONCAT(source_id, '_', unit_id, '_', COALESCE(search_type_id, '0'), '_', COALESCE(site_id, CONCAT('g', grid_cell_id)), '_', taxon_id)),
INDEX `fk_aggregated_by_month_grid_cell1_idx` (`grid_cell_id` ASC) VISIBLE,
INDEX `fk_aggregated_by_month_search_type1_idx` (`search_type_id` ASC) VISIBLE,
INDEX `fk_aggregated_by_month_taxon1_idx` (`taxon_id` ASC) VISIBLE,
INDEX `fk_aggregated_by_month_source1_idx` (`source_id` ASC) VISIBLE,
INDEX `fk_aggregated_by_month_experimental_design_type1_idx` (`experimental_design_type_id` ASC) VISIBLE,
INDEX `fk_aggregated_by_month_response_variable_type1_idx` (`response_variable_type_id` ASC) VISIBLE,
INDEX `fk_aggregated_by_month_unit1_idx` (`unit_id` ASC) VISIBLE,
INDEX `fk_aggregated_by_month_region1_idx` (`region_id` ASC) VISIBLE,
CONSTRAINT `fk_aggregated_by_month_grid_cell1`
FOREIGN KEY (`grid_cell_id`)
REFERENCES `grid_cell` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_aggregated_by_month_search_type1`
FOREIGN KEY (`search_type_id`)
REFERENCES `search_type` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_aggregated_by_month_taxon1`
FOREIGN KEY (`taxon_id`)
REFERENCES `taxon` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_aggregated_by_month_source1`
FOREIGN KEY (`source_id`)
REFERENCES `source` (`id`)
ON DELETE CASCADE
ON UPDATE NO ACTION,
CONSTRAINT `fk_aggregated_by_month_experimental_design_type1`
FOREIGN KEY (`experimental_design_type_id`)
REFERENCES `experimental_design_type` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_aggregated_by_month_response_variable_type1`
FOREIGN KEY (`response_variable_type_id`)
REFERENCES `response_variable_type` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_aggregated_by_month_unit1`
FOREIGN KEY (`unit_id`)
REFERENCES `unit` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_aggregated_by_month_region1`
FOREIGN KEY (`region_id`)
REFERENCES `region` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `aggregated_by_year`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `aggregated_by_year` ;
CREATE TABLE IF NOT EXISTS `aggregated_by_year` (
`start_date_y` SMALLINT NOT NULL,
`site_id` INT NULL,
`grid_cell_id` INT NULL,
`search_type_id` INT NULL,
`taxon_id` CHAR(8) NOT NULL,
`experimental_design_type_id` INT NOT NULL,
`response_variable_type_id` INT NOT NULL,
`value` DOUBLE NOT NULL,
`data_type` INT NOT NULL,
`source_id` INT NOT NULL,
`region_id` INT NULL,
`unit_id` INT NOT NULL,
`positional_accuracy_in_m` DOUBLE NULL,
`centroid_coords` POINT NOT NULL,
`survey_count` INT NOT NULL,
`time_series_id` VARCHAR(32) GENERATED ALWAYS AS (CONCAT(source_id, '_', unit_id, '_', COALESCE(search_type_id, '0'), '_', COALESCE(site_id, CONCAT('g', grid_cell_id)), '_', taxon_id)),
`include_in_analysis` TINYINT(1) NOT NULL DEFAULT 0,
INDEX `fk_aggregated_by_year_grid_cell1_idx` (`grid_cell_id` ASC) VISIBLE,
INDEX `fk_aggregated_by_year_search_type1_idx` (`search_type_id` ASC) VISIBLE,
INDEX `fk_aggregated_by_year_taxon1_idx` (`taxon_id` ASC) VISIBLE,
INDEX `fk_aggregated_by_year_source1_idx` (`source_id` ASC) VISIBLE,
INDEX `fk_aggregated_by_year_experimental_design_type1_idx` (`experimental_design_type_id` ASC) VISIBLE,
INDEX `fk_aggregated_by_year_response_variable_type1_idx` (`response_variable_type_id` ASC) VISIBLE,
INDEX `fk_aggregated_by_year_unit1_idx` (`unit_id` ASC) VISIBLE,
INDEX `fk_aggregated_by_year_region1_idx` (`region_id` ASC) VISIBLE,
CONSTRAINT `fk_aggregated_by_year_grid_cell1`
FOREIGN KEY (`grid_cell_id`)
REFERENCES `grid_cell` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_aggregated_by_year_search_type1`
FOREIGN KEY (`search_type_id`)
REFERENCES `search_type` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_aggregated_by_year_taxon1`
FOREIGN KEY (`taxon_id`)
REFERENCES `taxon` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_aggregated_by_year_source1`
FOREIGN KEY (`source_id`)
REFERENCES `source` (`id`)
ON DELETE CASCADE
ON UPDATE NO ACTION,
CONSTRAINT `fk_aggregated_by_year_experimental_design_type1`
FOREIGN KEY (`experimental_design_type_id`)
REFERENCES `experimental_design_type` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_aggregated_by_year_response_variable_type1`
FOREIGN KEY (`response_variable_type_id`)
REFERENCES `response_variable_type` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_aggregated_by_year_unit1`
FOREIGN KEY (`unit_id`)
REFERENCES `unit` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_aggregated_by_year_region1`
FOREIGN KEY (`region_id`)
REFERENCES `region` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `region_subdiv`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `region_subdiv` ;
CREATE TABLE IF NOT EXISTS `region_subdiv` (
`id` INT NOT NULL,
`name` VARCHAR(255) NULL,
`geometry` MULTIPOLYGON NOT NULL)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `processing_method`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `processing_method` ;
CREATE TABLE IF NOT EXISTS `processing_method` (
`taxon_id` CHAR(8) NOT NULL,
`unit_id` INT NULL,
`source_id` INT NOT NULL,
`search_type_id` INT NULL,
`data_type` INT NOT NULL,
`response_variable_type_id` INT NOT NULL,
`experimental_design_type_id` INT NOT NULL,
`positional_accuracy_threshold_in_m` DOUBLE NULL,
INDEX `fk_processing_method_unit1_idx` (`unit_id` ASC) VISIBLE,
INDEX `fk_processing_method_source1_idx` (`source_id` ASC) VISIBLE,
INDEX `fk_processing_method_search_type1_idx` (`search_type_id` ASC) VISIBLE,
UNIQUE INDEX `uniq` (`taxon_id` ASC, `unit_id` ASC, `source_id` ASC, `search_type_id` ASC, `data_type` ASC) VISIBLE,
CONSTRAINT `fk_processing_method_taxon1`
FOREIGN KEY (`taxon_id`)
REFERENCES `taxon` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_processing_method_unit1`
FOREIGN KEY (`unit_id`)
REFERENCES `unit` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_processing_method_source1`
FOREIGN KEY (`source_id`)
REFERENCES `source` (`id`)
ON DELETE CASCADE
ON UPDATE NO ACTION,
CONSTRAINT `fk_processing_method_search_type1`
FOREIGN KEY (`search_type_id`)
REFERENCES `search_type` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `taxon_source_alpha_hull`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `taxon_source_alpha_hull` ;
CREATE TABLE IF NOT EXISTS `taxon_source_alpha_hull` (
`taxon_id` CHAR(8) NOT NULL,
`source_id` INT NOT NULL,
`data_type` VARCHAR(255) NOT NULL,
`geometry` MULTIPOLYGON NULL,
`core_range_area_in_m2` DOUBLE NOT NULL,
`alpha_hull_area_in_m2` DOUBLE NULL,
PRIMARY KEY (`taxon_id`, `source_id`, `data_type`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `data_source`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `data_source` ;
CREATE TABLE IF NOT EXISTS `data_source` (
`source_id` INT NOT NULL,
`taxon_id` CHAR(8) NOT NULL,
`data_agreement_id` INT NULL,
`objective_of_monitoring_id` INT NULL,
`absences_recorded` TINYINT(1) NULL,
`standardisation_of_method_effort_id` INT NULL,
`consistency_of_monitoring_id` INT NULL,
`exclude_from_analysis` TINYINT(1) NOT NULL,
`start_year` INT(4) NULL,
`end_year` INT(4) NULL,
`suppress_aggregated_data` TINYINT(1) NOT NULL,
PRIMARY KEY (`source_id`, `taxon_id`),
INDEX `fk_data_source_taxon1_idx` (`taxon_id` ASC) VISIBLE,
CONSTRAINT `fk_data_source_source1`
FOREIGN KEY (`source_id`)
REFERENCES `source` (`id`)
ON DELETE CASCADE
ON UPDATE NO ACTION,
CONSTRAINT `fk_data_source_taxon1`
FOREIGN KEY (`taxon_id`)
REFERENCES `taxon` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `projection_name`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `projection_name` ;
CREATE TABLE IF NOT EXISTS `projection_name` (
`name` VARCHAR(64) NOT NULL,
`epsg_srid` INT NOT NULL,
PRIMARY KEY (`name`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `taxon_group`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `taxon_group` ;
CREATE TABLE IF NOT EXISTS `taxon_group` (
`id` INT NOT NULL AUTO_INCREMENT,
`taxon_id` CHAR(8) NOT NULL,
`group_name` VARCHAR(255) NOT NULL,
`subgroup_name` VARCHAR(255) NULL,
INDEX `fk_taxon_group_taxon1_idx` (`taxon_id` ASC) VISIBLE,
UNIQUE INDEX `taxon_group_subgroup` (`taxon_id` ASC, `group_name` ASC, `subgroup_name` ASC) VISIBLE,
PRIMARY KEY (`id`),
CONSTRAINT `fk_taxon_group_taxon1`
FOREIGN KEY (`taxon_id`)
REFERENCES `taxon` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `role`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `role` ;
CREATE TABLE IF NOT EXISTS `role` (
`id` INT NOT NULL AUTO_INCREMENT,
`description` VARCHAR(255) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE INDEX `name_UNIQUE` (`description` ASC) VISIBLE)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `user_role`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `user_role` ;
CREATE TABLE IF NOT EXISTS `user_role` (
`user_id` INT NOT NULL,
`role_id` INT NOT NULL,
PRIMARY KEY (`user_id`, `role_id`),
INDEX `fk_user_role_role1_idx` (`role_id` ASC) VISIBLE,
CONSTRAINT `fk_user_role_user1`
FOREIGN KEY (`user_id`)
REFERENCES `user` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_user_role_role1`
FOREIGN KEY (`role_id`)
REFERENCES `role` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `user_source`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `user_source` ;
CREATE TABLE IF NOT EXISTS `user_source` (
`user_id` INT NOT NULL,
`source_id` INT NOT NULL,
PRIMARY KEY (`user_id`, `source_id`),
INDEX `fk_user_source_source1_idx` (`source_id` ASC) VISIBLE,
CONSTRAINT `fk_user_source_user1`
FOREIGN KEY (`user_id`)
REFERENCES `user` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_user_source_source1`
FOREIGN KEY (`source_id`)
REFERENCES `source` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `data_processing_notes`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `data_processing_notes` ;
CREATE TABLE IF NOT EXISTS `data_processing_notes` (
`id` INT NOT NULL AUTO_INCREMENT,
`user_id` INT NOT NULL,
`source_id` INT NOT NULL,
`time_created` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
`notes` TEXT NOT NULL,
PRIMARY KEY (`id`),
INDEX `fk_data_processing_notes_user1_idx` (`user_id` ASC) VISIBLE,
INDEX `fk_data_processing_notes_source1_idx` (`source_id` ASC) VISIBLE,
CONSTRAINT `fk_data_processing_notes_user1`
FOREIGN KEY (`user_id`)
REFERENCES `user` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_data_processing_notes_source1`
FOREIGN KEY (`source_id`)
REFERENCES `source` (`id`)
ON DELETE CASCADE
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `user_program_manager`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `user_program_manager` ;
CREATE TABLE IF NOT EXISTS `user_program_manager` (
`user_id` INT NOT NULL,
`monitoring_program_id` INT NOT NULL,
PRIMARY KEY (`user_id`, `monitoring_program_id`),
INDEX `fk_user_program_manager_user1_idx` (`user_id` ASC) VISIBLE,
INDEX `fk_user_program_manager_monitoring_program1_idx` (`monitoring_program_id` ASC) VISIBLE,
CONSTRAINT `fk_user_program_manager_user1`
FOREIGN KEY (`user_id`)
REFERENCES `user` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_user_program_manager_monitoring_program1`
FOREIGN KEY (`monitoring_program_id`)
REFERENCES `monitoring_program` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
| 33.297771 | 187 | 0.632108 |
9bf83716d1ebb00e7ad0e09e0b7970ac802f9bf1 | 8,509 | js | JavaScript | mysql-dst/mysql-cluster/ndb/mcc/frontend/dojo/dojox/mobile/View.js | SJTU-IPADS/dst | 897b929a692642cbf295c105d9d6e64090abb673 | [
"Apache-2.0"
] | 9 | 2020-12-17T01:59:13.000Z | 2022-03-30T16:25:08.000Z | mysql-dst/mysql-cluster/ndb/mcc/frontend/dojo/dojox/mobile/View.js | SJTU-IPADS/dst | 897b929a692642cbf295c105d9d6e64090abb673 | [
"Apache-2.0"
] | 1 | 2021-07-30T12:06:33.000Z | 2021-07-31T10:16:09.000Z | mysql-dst/mysql-cluster/ndb/mcc/frontend/dojo/dojox/mobile/View.js | SJTU-IPADS/dst | 897b929a692642cbf295c105d9d6e64090abb673 | [
"Apache-2.0"
] | 1 | 2021-08-01T13:47:07.000Z | 2021-08-01T13:47:07.000Z | //>>built
define("dojox/mobile/View",["dojo/_base/kernel","dojo/_base/array","dojo/_base/config","dojo/_base/connect","dojo/_base/declare","dojo/_base/lang","dojo/_base/sniff","dojo/_base/window","dojo/_base/Deferred","dojo/dom","dojo/dom-class","dojo/dom-geometry","dojo/dom-style","dijit/registry","dijit/_Contained","dijit/_Container","dijit/_WidgetBase","./ViewController","./transition"],function(_1,_2,_3,_4,_5,_6,_7,_8,_9,_a,_b,_c,_d,_e,_f,_10,_11,_12,_13){
var dm=_6.getObject("dojox.mobile",true);
return _5("dojox.mobile.View",[_11,_10,_f],{selected:false,keepScrollPos:true,constructor:function(_14,_15){
if(_15){
_a.byId(_15).style.visibility="hidden";
}
this._aw=_7("android")>=2.2&&_7("android")<3;
},buildRendering:function(){
this.domNode=this.containerNode=this.srcNodeRef||_8.doc.createElement("DIV");
this.domNode.className="mblView";
this.connect(this.domNode,"webkitAnimationEnd","onAnimationEnd");
this.connect(this.domNode,"webkitAnimationStart","onAnimationStart");
if(!_3["mblCSS3Transition"]){
this.connect(this.domNode,"webkitTransitionEnd","onAnimationEnd");
}
var id=location.href.match(/#(\w+)([^\w=]|$)/)?RegExp.$1:null;
this._visible=this.selected&&!id||this.id==id;
if(this.selected){
dm._defaultView=this;
}
},startup:function(){
if(this._started){
return;
}
var _16=[];
var _17=this.domNode.parentNode.childNodes;
var _18=false;
for(var i=0;i<_17.length;i++){
var c=_17[i];
if(c.nodeType===1&&_b.contains(c,"mblView")){
_16.push(c);
_18=_18||_e.byNode(c)._visible;
}
}
var _19=this._visible;
if(_16.length===1||(!_18&&_16[0]===this.domNode)){
_19=true;
}
var _1a=this;
setTimeout(function(){
if(!_19){
_1a.domNode.style.display="none";
}else{
dm.currentView=_1a;
_1a.onStartView();
_4.publish("/dojox/mobile/startView",[_1a]);
}
if(_1a.domNode.style.visibility!="visible"){
_1a.domNode.style.visibility="visible";
}
var _1b=_1a.getParent&&_1a.getParent();
if(!_1b||!_1b.resize){
_1a.resize();
}
},_7("ie")?100:0);
this.inherited(arguments);
},resize:function(){
_2.forEach(this.getChildren(),function(_1c){
if(_1c.resize){
_1c.resize();
}
});
},onStartView:function(){
},onBeforeTransitionIn:function(_1d,dir,_1e,_1f,_20){
},onAfterTransitionIn:function(_21,dir,_22,_23,_24){
},onBeforeTransitionOut:function(_25,dir,_26,_27,_28){
},onAfterTransitionOut:function(_29,dir,_2a,_2b,_2c){
},_saveState:function(_2d,dir,_2e,_2f,_30){
this._context=_2f;
this._method=_30;
if(_2e=="none"){
_2e=null;
}
this._moveTo=_2d;
this._dir=dir;
this._transition=_2e;
this._arguments=_6._toArray(arguments);
this._args=[];
if(_2f||_30){
for(var i=5;i<arguments.length;i++){
this._args.push(arguments[i]);
}
}
},_fixViewState:function(_31){
var _32=this.domNode.parentNode.childNodes;
for(var i=0;i<_32.length;i++){
var n=_32[i];
if(n.nodeType===1&&_b.contains(n,"mblView")){
n.className="mblView";
}
}
_31.className="mblView";
},convertToId:function(_33){
if(typeof (_33)=="string"){
_33.match(/^#?([^&?]+)/);
return RegExp.$1;
}
return _33;
},performTransition:function(_34,dir,_35,_36,_37){
if(_34==="#"){
return;
}
if(_1.hash){
if(typeof (_34)=="string"&&_34.charAt(0)=="#"&&!dm._params){
dm._params=[];
for(var i=0;i<arguments.length;i++){
dm._params.push(arguments[i]);
}
_1.hash(_34);
return;
}
}
this._saveState.apply(this,arguments);
var _38;
if(_34){
_38=this.convertToId(_34);
}else{
if(!this._dummyNode){
this._dummyNode=_8.doc.createElement("DIV");
_8.body().appendChild(this._dummyNode);
}
_38=this._dummyNode;
}
var _39=this.domNode;
var _3a=_39.offsetTop;
_38=this.toNode=_a.byId(_38);
if(!_38){
return;
}
_38.style.visibility=this._aw?"visible":"hidden";
_38.style.display="";
this._fixViewState(_38);
var _3b=_e.byNode(_38);
if(_3b){
if(_3["mblAlwaysResizeOnTransition"]||!_3b._resized){
dm.resizeAll(null,_3b);
_3b._resized=true;
}
if(_35&&_35!="none"){
_3b.containerNode.style.paddingTop=_3a+"px";
}
_3b.movedFrom=_39.id;
}
this.onBeforeTransitionOut.apply(this,arguments);
_4.publish("/dojox/mobile/beforeTransitionOut",[this].concat(_6._toArray(arguments)));
if(_3b){
if(this.keepScrollPos&&!this.getParent()){
var _3c=_8.body().scrollTop||_8.doc.documentElement.scrollTop||_8.global.pageYOffset||0;
_39._scrollTop=_3c;
var _3d=(dir==1)?0:(_38._scrollTop||0);
_38.style.top="0px";
if(_3c>1||_3d!==0){
_39.style.top=_3d-_3c+"px";
if(_3["mblHideAddressBar"]!==false){
setTimeout(function(){
_8.global.scrollTo(0,(_3d||1));
},0);
}
}
}else{
_38.style.top="0px";
}
_3b.onBeforeTransitionIn.apply(_3b,arguments);
_4.publish("/dojox/mobile/beforeTransitionIn",[_3b].concat(_6._toArray(arguments)));
}
if(!this._aw){
_38.style.display="none";
_38.style.visibility="visible";
}
if(dm._iw&&dm.scrollable){
var ss=dm.getScreenSize();
_8.body().appendChild(dm._iwBgCover);
_d.set(dm._iwBgCover,{position:"absolute",top:"0px",left:"0px",height:(ss.h+1)+"px",width:ss.w+"px",backgroundColor:_d.get(_8.body(),"background-color"),zIndex:-10000,display:""});
_d.set(_38,{position:"absolute",zIndex:-10001,visibility:"visible",display:""});
setTimeout(_6.hitch(this,function(){
this._doTransition(_39,_38,_35,dir);
}),80);
}else{
this._doTransition(_39,_38,_35,dir);
}
},_toCls:function(s){
return "mbl"+s.charAt(0).toUpperCase()+s.substring(1);
},_doTransition:function(_3e,_3f,_40,dir){
var rev=(dir==-1)?" mblReverse":"";
if(dm._iw&&dm.scrollable){
_d.set(_3f,{position:"",zIndex:""});
_8.body().removeChild(dm._iwBgCover);
}else{
if(!this._aw){
_3f.style.display="";
}
}
if(!_40||_40=="none"){
this.domNode.style.display="none";
this.invokeCallback();
}else{
if(_3["mblCSS3Transition"]){
_9.when(_13,_6.hitch(this,function(_41){
var _42=_d.get(_3f,"position");
_d.set(_3f,"position","absolute");
_9.when(_41(_3e,_3f,{transition:_40,reverse:(dir===-1)?true:false}),_6.hitch(this,function(){
_d.set(_3f,"position",_42);
this.invokeCallback();
}));
}));
}else{
var s=this._toCls(_40);
_b.add(_3e,s+" mblOut"+rev);
_b.add(_3f,s+" mblIn"+rev);
setTimeout(function(){
_b.add(_3e,"mblTransition");
_b.add(_3f,"mblTransition");
},100);
var _43="50% 50%";
var _44="50% 50%";
var _45,_46,_47;
if(_40.indexOf("swirl")!=-1||_40.indexOf("zoom")!=-1){
if(this.keepScrollPos&&!this.getParent()){
_45=_8.body().scrollTop||_8.doc.documentElement.scrollTop||_8.global.pageYOffset||0;
}else{
_45=-_c.position(_3e,true).y;
}
_47=_8.global.innerHeight/2+_45;
_43="50% "+_47+"px";
_44="50% "+_47+"px";
}else{
if(_40.indexOf("scale")!=-1){
var _48=_c.position(_3e,true);
_46=((this.clickedPosX!==undefined)?this.clickedPosX:_8.global.innerWidth/2)-_48.x;
if(this.keepScrollPos&&!this.getParent()){
_45=_8.body().scrollTop||_8.doc.documentElement.scrollTop||_8.global.pageYOffset||0;
}else{
_45=-_48.y;
}
_47=((this.clickedPosY!==undefined)?this.clickedPosY:_8.global.innerHeight/2)+_45;
_43=_46+"px "+_47+"px";
_44=_46+"px "+_47+"px";
}
}
_d.set(_3e,{webkitTransformOrigin:_43});
_d.set(_3f,{webkitTransformOrigin:_44});
}
}
dm.currentView=_e.byNode(_3f);
},onAnimationStart:function(e){
},onAnimationEnd:function(e){
var _49=e.animationName||e.target.className;
if(_49.indexOf("Out")===-1&&_49.indexOf("In")===-1&&_49.indexOf("Shrink")===-1){
return;
}
var _4a=false;
if(_b.contains(this.domNode,"mblOut")){
_4a=true;
this.domNode.style.display="none";
_b.remove(this.domNode,[this._toCls(this._transition),"mblIn","mblOut","mblReverse"]);
}else{
this.containerNode.style.paddingTop="";
}
_d.set(this.domNode,{webkitTransformOrigin:""});
if(_49.indexOf("Shrink")!==-1){
var li=e.target;
li.style.display="none";
_b.remove(li,"mblCloseContent");
}
if(_4a){
this.invokeCallback();
}
this.domNode&&(this.domNode.className="mblView");
this.clickedPosX=this.clickedPosY=undefined;
},invokeCallback:function(){
this.onAfterTransitionOut.apply(this,this._arguments);
_4.publish("/dojox/mobile/afterTransitionOut",[this].concat(this._arguments));
var _4b=_e.byNode(this.toNode);
if(_4b){
_4b.onAfterTransitionIn.apply(_4b,this._arguments);
_4.publish("/dojox/mobile/afterTransitionIn",[_4b].concat(this._arguments));
_4b.movedFrom=undefined;
}
var c=this._context,m=this._method;
if(!c&&!m){
return;
}
if(!m){
m=c;
c=null;
}
c=c||_8.global;
if(typeof (m)=="string"){
c[m].apply(c,this._args);
}else{
m.apply(c,this._args);
}
},getShowingView:function(){
var _4c=this.domNode.parentNode.childNodes;
for(var i=0;i<_4c.length;i++){
var n=_4c[i];
if(n.nodeType===1&&_b.contains(n,"mblView")&&_d.get(n,"display")!=="none"){
return _e.byNode(n);
}
}
return null;
},show:function(){
var _4d=this.getShowingView();
if(_4d){
_4d.domNode.style.display="none";
}
this.domNode.style.display="";
dm.currentView=this;
}});
});
| 27.272436 | 454 | 0.712305 |
7fe20002500b17fbb210bdb232ed9e7cfeb1adef | 466 | asm | Assembly | oeis/072/A072371.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 11 | 2021-08-22T19:44:55.000Z | 2022-03-20T16:47:57.000Z | oeis/072/A072371.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 9 | 2021-08-29T13:15:54.000Z | 2022-03-09T19:52:31.000Z | oeis/072/A072371.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 3 | 2021-08-22T20:56:47.000Z | 2021-09-29T06:26:12.000Z | ; A072371: a(0) = 0, a(1) = 1, a(n+1) = 2*a(n) + (2*n-1)^2*a(n-1).
; Submitted by Christian Krause
; 1,2,5,28,181,1734,18129,246072,3555945,62478090,1152624285,24859839060,558026987805,14266908838350,377300685054825,11155177913266800,339620231957641425,11399366438564677650,392645165479000867125,14749514218199731855500,567030259977151650805125
mov $1,-1
mov $2,-1
mov $3,1
lpb $0
sub $0,1
mul $1,-1
add $2,2
mul $3,$2
add $3,$1
mul $1,$2
lpe
mov $0,$3
| 27.411765 | 245 | 0.712446 |
4a4f79d2cc95b8f1f02f967dd2d19ebb44290e0c | 4,372 | js | JavaScript | src/js/timepicker/selectbox.js | IvanWei/tui.time-picker | 133306278e79f9712a51f2743a130809a41fe43f | [
"MIT"
] | null | null | null | src/js/timepicker/selectbox.js | IvanWei/tui.time-picker | 133306278e79f9712a51f2743a130809a41fe43f | [
"MIT"
] | null | null | null | src/js/timepicker/selectbox.js | IvanWei/tui.time-picker | 133306278e79f9712a51f2743a130809a41fe43f | [
"MIT"
] | null | null | null | /**
* @fileoverview Selectbox (in TimePicker)
* @author NHN Ent. FE Development Lab <dl_javascript@nhnent.com>
*/
'use strict';
var $ = require('jquery');
var snippet = require('@ivanwei/tui-code-snippet');
var tmpl = require('./../../template/timepicker/selectbox.hbs');
/**
* @class
* @ignore
* @param {jQuery|string|Element} container - Container element
* @param {object} options - Options
* @param {Array.<number>} options.items - Items
* @param {number} options.initialValue - Initial value
*/
var Selectbox = snippet.defineClass(/** @lends Selectbox.prototype */ {
init: function(container, options) {
options = snippet.extend({
items: []
}, options);
/**
* Container element
* @type {jQuery}
* @private
*/
this._$container = $(container);
/**
* Selectbox items
* @type {Array.<number>}
* @private
*/
this._items = options.items || [];
/**
* Selectbox disabled items info
* @type {Array.<number>}
* @private
*/
this._disabledItems = options.disabledItems || [];
/**
* Selected index
* @type {number}
* @private
*/
this._selectedIndex = Math.max(0, snippet.inArray(options.initialValue, this._items));
/**
* Time format for output
* @type {string}
* @private
*/
this._format = options.format;
/**
* Element
* @type {jQuery}
* @private
*/
this._$element = $();
this._render();
this._setEvents();
},
/**
* Render selectbox
* @private
*/
_render: function() {
var context;
this._changeEnabledIndex();
context = {
items: this._items,
initialValue: this.getValue(),
format: this._format,
disabledItems: snippet.map(this._disabledItems, function(item) {
if (item) {
return 'disabled';
}
return '';
})
};
this._$element.remove();
this._$element = $(tmpl(context));
this._$element.appendTo(this._$container);
},
/**
* Change the index of the enabled item
* @private
*/
_changeEnabledIndex: function() {
if (this._disabledItems[this._items.indexOf(this.getValue())]) {
this._selectedIndex = snippet.inArray(false, this._disabledItems);
}
},
/**
* Set disabledItems
* @param {object} disabledItems - disabled status of items
* @private
*/
setDisabledItems: function(disabledItems) {
this._disabledItems = disabledItems;
this._render();
},
/**
* Set events
* @private
*/
_setEvents: function() {
this._$container.on('change.selectbox', 'select', $.proxy(this._onChange, this));
this.on('changeItems', function(items) {
this._items = items;
this._render();
}, this);
},
/**
* Change event handler
* @param {jQuery.Event} ev - Event object
* @private
*/
_onChange: function(ev) {
var newValue = Number(ev.target.value);
this._selectedIndex = snippet.inArray(newValue, this._items);
this.fire('change', {
value: newValue
});
},
/**
* Returns current value
* @returns {number}
*/
getValue: function() {
return this._items[this._selectedIndex];
},
/**
* Set value
* @param {number} value - New value
*/
setValue: function(value) {
var newIndex = snippet.inArray(value, this._items);
if (newIndex > -1 && newIndex !== this._selectedIndex) {
this._selectedIndex = newIndex;
this._$element.val(value).change();
}
},
/**
* Destory
*/
destroy: function() {
this.off();
this._$container.off('.selectbox');
this._$element.remove();
this._$container
= this._items
= this._selectedIndex
= this._$element
= this._$element
= null;
}
});
snippet.CustomEvents.mixin(Selectbox);
module.exports = Selectbox;
| 23.632432 | 94 | 0.5215 |
26a4fb4f41fc1f49de275f70341ac39651f28bb5 | 265 | java | Java | src/test/java/org/github/arkinator/jaur/BasicJsonParserTest.java | Arkinator/jaur | 1740b3221f3430a46df2e4c395a2d56cfca0e342 | [
"MIT"
] | null | null | null | src/test/java/org/github/arkinator/jaur/BasicJsonParserTest.java | Arkinator/jaur | 1740b3221f3430a46df2e4c395a2d56cfca0e342 | [
"MIT"
] | null | null | null | src/test/java/org/github/arkinator/jaur/BasicJsonParserTest.java | Arkinator/jaur | 1740b3221f3430a46df2e4c395a2d56cfca0e342 | [
"MIT"
] | null | null | null | package org.github.arkinator.jaur;
import org.junit.Test;
public class BasicJsonParserTest {
private Jaur jaur = Jaur.builder().build();
@Test
public void basicJson_shouldParseWithoutError() {
jaur.parseJson("{\"field\":\"value\"}");
}
}
| 20.384615 | 53 | 0.671698 |
4049f186e8837e67735883bc7b4c1de801d48153 | 20,852 | swift | Swift | CodeReady Containers/DaemonCommander/Handlers.swift | anjannath/tray-macos | aa731f16ad580a192a4e693c826a30fb20b98051 | [
"Apache-2.0"
] | null | null | null | CodeReady Containers/DaemonCommander/Handlers.swift | anjannath/tray-macos | aa731f16ad580a192a4e693c826a30fb20b98051 | [
"Apache-2.0"
] | null | null | null | CodeReady Containers/DaemonCommander/Handlers.swift | anjannath/tray-macos | aa731f16ad580a192a4e693c826a30fb20b98051 | [
"Apache-2.0"
] | null | null | null | //
// Handlers.swift
// CodeReady Containers
//
// Created by Anjan Nath on 22/11/19.
// Copyright © 2019 Red Hat. All rights reserved.
//
import Cocoa
struct StopResult: Decodable {
let Name: String
let Success: Bool
let State: Int
let Error: String
}
struct StartResult: Decodable {
let Name: String
let Status: String
let Error: String
let ClusterConfig: ClusterConfigType
let KubeletStarted: Bool
}
struct DeleteResult: Decodable {
let Name: String
let Success: Bool
let Error: String
}
struct ProxyConfigType: Decodable {
let HTTPProxy: String
let HTTPSProxy: String
let ProxyCACert: String
}
struct ClusterConfigType: Decodable {
let ClusterCACert: String
let KubeConfig: String
let KubeAdminPass: String
let WebConsoleURL: String
let ClusterAPI: String
let ProxyConfig: ProxyConfigType?
}
struct Request: Encodable {
let command: String
let args: Dictionary<String, String>?
}
struct ConfigGetRequest: Encodable {
let command: String
let args: PropertiesArray
}
struct PropertiesArray: Encodable {
let properties: [String]
}
struct ConfigGetResult: Decodable {
let Error: String
let Configs: Dictionary<String, String>
}
struct WebConsoleResult: Decodable {
let ClusterConfig: ClusterConfigType
let Success: Bool
let Error: String
}
struct VersionResult: Decodable {
let CrcVersion: String
let CommitSha: String
let OpenshiftVersion: String
let Success: Bool
}
struct GetconfigResult: Decodable {
let Error: String
let Configs: CrcConfigs
}
struct CrcConfigs: Codable {
var bundle: String?
var cpus: Int?
var disableUpdateCheck: Bool?
var enableExperimentalFeatures: Bool?
var httpProxy: String?
var httpsProxy: String?
var memory: Int?
var diskSize: Int?
var nameserver: String?
var noProxy: String?
var proxyCaFile: String?
var pullSecretFile: String?
var networkMode: String?
var consentTelemetry: String?
var autostartTray: Bool?
var skipCheckBundleExtracted: Bool?
var skipCheckHostsFilePermissions: Bool?
var skipCheckHyperkitDriver: Bool?
var skipCheckHyperkitInstalled: Bool?
var skipCheckPodmanCached: Bool?
var skipCheckRam: Bool?
var skipCheckResolverFilePermissions: Bool?
var skipCheckRootUser: Bool?
var skipCheckOcCached: Bool?
var skipCheckGoodhostsCached: Bool?
enum CodingKeys: String, CodingKey {
case bundle
case cpus
case memory
case nameserver
case disableUpdateCheck = "disable-update-check"
case enableExperimentalFeatures = "enable-experimental-features"
case httpProxy = "http-proxy"
case httpsProxy = "https-proxy"
case noProxy = "no-proxy"
case proxyCaFile = "proxy-ca-file"
case pullSecretFile = "pull-secret-file"
case diskSize = "disk-size"
case networkMode = "network-mode"
case consentTelemetry = "consent-telemetry"
case autostartTray = "autostart-tray"
case skipCheckBundleExtracted = "skip-check-bundle-extracted"
case skipCheckHostsFilePermissions = "skip-check-hosts-file-permissions"
case skipCheckHyperkitDriver = "skip-check-hyperkit-driver"
case skipCheckHyperkitInstalled = "skip-check-hyperkit-installed"
case skipCheckPodmanCached = "skip-check-podman-cached"
case skipCheckRam = "skip-check-ram"
case skipCheckResolverFilePermissions = "skip-check-resolver-file-permissions"
case skipCheckRootUser = "skip-check-root-user"
case skipCheckOcCached = "skip-check-oc-cached"
case skipCheckGoodhostsCached = "skip-check-goodhosts-cached"
}
}
enum DaemonError: Error {
case noResponse
case badResponse
case undefined
}
func HandleStop() {
let r = SendCommandToDaemon(command: Request(command: "stop", args: nil))
guard let data = r else { return }
if String(bytes: data, encoding: .utf8) == "Failed" {
DispatchQueue.main.async {
let appDelegate = NSApplication.shared.delegate as? AppDelegate
appDelegate?.updateMenuStates(state: MenuStates(startMenuEnabled: true,
stopMenuEnabled: false,
deleteMenuEnabled: true,
webconsoleMenuEnabled: true,
ocLoginForDeveloperEnabled: true,
ocLoginForAdminEnabled: true,
copyOcLoginCommand: true)
)
showAlertFailedAndCheckLogs(message: "Failed deleting the CRC cluster", informativeMsg: "Make sure the CRC daemon is running, or check the logs to get more information")
}
return
}
do {
let stopResult = try JSONDecoder().decode(StopResult.self, from: r!)
if stopResult.Success {
DispatchQueue.main.async {
let appDelegate = NSApplication.shared.delegate as? AppDelegate
appDelegate?.updateMenuStates(state: MenuStates(startMenuEnabled: true,
stopMenuEnabled: false,
deleteMenuEnabled: true,
webconsoleMenuEnabled: false,
ocLoginForDeveloperEnabled: false,
ocLoginForAdminEnabled: false,
copyOcLoginCommand: false)
)
appDelegate?.updateStatusMenuItem(status: "Stopped")
displayNotification(title: "Successfully Stopped Cluster", body: "The CRC Cluster was successfully stopped")
}
}
if stopResult.Error != "" {
DispatchQueue.main.async {
showAlertFailedAndCheckLogs(message: "Failed to stop OpenShift cluster", informativeMsg: "\(stopResult.Error)")
let appDelegate = NSApplication.shared.delegate as? AppDelegate
appDelegate?.showClusterStatusUnknownOnStatusMenuItem()
appDelegate?.updateMenuStates(state: MenuStates(startMenuEnabled: false,
stopMenuEnabled: true,
deleteMenuEnabled: true,
webconsoleMenuEnabled: true,
ocLoginForDeveloperEnabled: true,
ocLoginForAdminEnabled: true,
copyOcLoginCommand: true)
)
}
}
} catch let jsonErr {
print(jsonErr.localizedDescription)
}
}
func HandleStart(pullSecretPath: String) {
DispatchQueue.main.async {
let appDelegate = NSApplication.shared.delegate as? AppDelegate
appDelegate?.showClusterStartingMessageOnStatusMenuItem()
}
let response: Data?
if pullSecretPath == "" {
response = SendCommandToDaemon(command: Request(command: "start", args: nil))
} else {
response = SendCommandToDaemon(command: Request(command: "start", args: ["pullSecretFile":pullSecretPath]))
}
guard let data = response else { return }
if String(bytes: data, encoding: .utf8) == "Failed" {
// show notification about the failure
// Adjust the menus
DispatchQueue.main.async {
let appDelegate = NSApplication.shared.delegate as? AppDelegate
appDelegate?.updateMenuStates(state: MenuStates(startMenuEnabled: true,
stopMenuEnabled: false,
deleteMenuEnabled: true,
webconsoleMenuEnabled: false,
ocLoginForDeveloperEnabled: false,
ocLoginForAdminEnabled: false,
copyOcLoginCommand: false))
showAlertFailedAndCheckLogs(message: "Failed to start OpenShift cluster", informativeMsg: "CodeReady Containers failed to start the OpenShift cluster, ensure the CRC daemon is running or check the logs to find more information")
appDelegate?.showClusterStatusUnknownOnStatusMenuItem()
}
} else {
displayNotification(title: "CodeReady Containers", body: "Starting OpenShift Cluster, this could take a few minutes..")
}
do {
let startResult = try JSONDecoder().decode(StartResult.self, from: data)
if startResult.Status == "Running" {
DispatchQueue.main.async {
let appDelegate = NSApplication.shared.delegate as? AppDelegate
appDelegate?.showClusterStartingMessageOnStatusMenuItem()
appDelegate?.updateMenuStates(state: MenuStates(startMenuEnabled: false, stopMenuEnabled: true, deleteMenuEnabled: true, webconsoleMenuEnabled: false, ocLoginForDeveloperEnabled: false, ocLoginForAdminEnabled: false, copyOcLoginCommand: false))
}
// if vm is running but kubelet not yet started
if !startResult.KubeletStarted {
DispatchQueue.main.async {
let appDelegate = NSApplication.shared.delegate as? AppDelegate
appDelegate?.showClusterStatusUnknownOnStatusMenuItem()
displayNotification(title: "CodeReady Containers", body: "CodeReady Containers OpenShift Cluster is taking longer to start")
}
} else {
DispatchQueue.main.async {
let appDelegate = NSApplication.shared.delegate as? AppDelegate
appDelegate?.updateStatusMenuItem(status: startResult.Status)
appDelegate?.updateMenuStates(state: MenuStates(startMenuEnabled: false, stopMenuEnabled: true, deleteMenuEnabled: true, webconsoleMenuEnabled: true, ocLoginForDeveloperEnabled: true, ocLoginForAdminEnabled: true, copyOcLoginCommand: true))
displayNotification(title: "CodeReady Containers", body: "OpenShift Cluster is running")
}
}
}
if startResult.Error != "" {
DispatchQueue.main.async {
let errMsg = startResult.Error.split(separator: "\n")
showAlertFailedAndCheckLogs(message: "Failed to start OpenShift cluster", informativeMsg: "\(errMsg[0])")
let appDelegate = NSApplication.shared.delegate as? AppDelegate
appDelegate?.showClusterStatusUnknownOnStatusMenuItem()
appDelegate?.updateMenuStates(state: MenuStates(startMenuEnabled: true,
stopMenuEnabled: false,
deleteMenuEnabled: true,
webconsoleMenuEnabled: false,
ocLoginForDeveloperEnabled: false,
ocLoginForAdminEnabled: false,
copyOcLoginCommand: false)
)
}
}
} catch let jsonErr {
print(jsonErr.localizedDescription)
}
}
func HandleDelete() {
// prompt for confirmation and bail if No
var yes: Bool = false
DispatchQueue.main.sync {
yes = promptYesOrNo(message: "Deleting CodeReady Containers Cluster", informativeMsg: "Are you sure you want to delete the crc instance")
}
if !yes {
return
}
let r = SendCommandToDaemon(command: Request(command: "delete", args: nil))
guard let data = r else { return }
if String(bytes: data, encoding: .utf8) == "Failed" {
// handle failure to delete
// send alert that delete failed
// rearrange menu states
DispatchQueue.main.async {
let appDelegate = NSApplication.shared.delegate as? AppDelegate
appDelegate?.updateMenuStates(state: MenuStates(startMenuEnabled: true, stopMenuEnabled: false, deleteMenuEnabled: true, webconsoleMenuEnabled: false, ocLoginForDeveloperEnabled: false, ocLoginForAdminEnabled: false, copyOcLoginCommand: false))
showAlertFailedAndCheckLogs(message: "Failed to delete cluster", informativeMsg: "CRC failed to delete the OCP cluster, make sure the CRC daemom is running or check the logs to find more information")
}
}
do {
let deleteResult = try JSONDecoder().decode(DeleteResult.self, from: data)
if deleteResult.Success {
// send notification that delete succeeded
// rearrage menus
DispatchQueue.main.async {
let appDelegate = NSApplication.shared.delegate as? AppDelegate
appDelegate?.updateMenuStates(state: MenuStates(startMenuEnabled: true, stopMenuEnabled: false, deleteMenuEnabled: false, webconsoleMenuEnabled: false, ocLoginForDeveloperEnabled: false, ocLoginForAdminEnabled: false, copyOcLoginCommand: false))
appDelegate?.showClusterStatusUnknownOnStatusMenuItem()
displayNotification(title: "Cluster Deleted", body: "The CRC Cluster is successfully deleted")
}
}
if deleteResult.Error != "" {
DispatchQueue.main.async {
showAlertFailedAndCheckLogs(message: "Failed to delete OpenShift cluster", informativeMsg: "\(deleteResult.Error)")
let appDelegate = NSApplication.shared.delegate as? AppDelegate
appDelegate?.showClusterStatusUnknownOnStatusMenuItem()
}
}
} catch let jsonErr {
print(jsonErr.localizedDescription)
}
}
func HandleWebConsoleURL() {
let r = SendCommandToDaemon(command: Request(command: "webconsoleurl", args: nil))
guard let data = r else { return }
if String(bytes: data, encoding: .utf8) == "Failed" {
// Alert show error
DispatchQueue.main.async {
showAlertFailedAndCheckLogs(message: "Failed to launch web console", informativeMsg: "Ensure the CRC daemon is running and a CRC cluster is running, for more information please check the logs")
}
}
do {
let webConsoleResult = try JSONDecoder().decode(WebConsoleResult.self, from: data)
if webConsoleResult.Success {
// open the webconsoleURL
NSWorkspace.shared.open(URL(string: webConsoleResult.ClusterConfig.WebConsoleURL)!)
}
} catch let jsonErr {
print(jsonErr)
}
}
func HandleLoginCommandForKubeadmin() {
let r = SendCommandToDaemon(command: Request(command: "webconsoleurl", args: nil))
guard let data = r else { return }
if String(bytes: data, encoding: .utf8) == "Failed" {
// Alert show error
DispatchQueue.main.async {
showAlertFailedAndCheckLogs(message: "Failed to get login command", informativeMsg: "Ensure the CRC daemon is running and a CRC cluster is running, for more information please check the logs")
}
}
do {
let webConsoleResult = try JSONDecoder().decode(WebConsoleResult.self, from: data)
if webConsoleResult.Success {
// form the login command, put in clipboard and show notification
let apiURL = webConsoleResult.ClusterConfig.ClusterAPI
let kubeadminPass = webConsoleResult.ClusterConfig.KubeAdminPass
let loginCommand = "oc login -u kubeadmin -p \(kubeadminPass) \(apiURL)"
let pasteboard = NSPasteboard.general
pasteboard.declareTypes([NSPasteboard.PasteboardType.string], owner: nil)
pasteboard.setString(loginCommand, forType: NSPasteboard.PasteboardType.string)
// show notification on main thread
DispatchQueue.main.async {
displayNotification(title: "OC Login with kubeadmin", body: "OC Login command copied to clipboard, go ahead and login to your cluster")
}
}
} catch let jsonErr {
print(jsonErr.localizedDescription)
}
}
func HandleLoginCommandForDeveloper() {
let r = SendCommandToDaemon(command: Request(command: "webconsoleurl", args: nil))
guard let data = r else { return }
if String(bytes: data, encoding: .utf8) == "Failed" {
// Alert show error
DispatchQueue.main.async {
showAlertFailedAndCheckLogs(message: "Failed to get login command", informativeMsg: "Ensure the CRC daemon is running and a CRC cluster is running, for more information please check the logs")
}
}
do {
let webConsoleResult = try JSONDecoder().decode(WebConsoleResult.self, from: data)
if webConsoleResult.Success {
// form the login command, put in clipboard and show notification
let apiURL = webConsoleResult.ClusterConfig.ClusterAPI
let loginCommand = "oc login -u developer -p developer \(apiURL)"
let pasteboard = NSPasteboard.general
pasteboard.declareTypes([NSPasteboard.PasteboardType.string], owner: nil)
pasteboard.setString(loginCommand, forType: NSPasteboard.PasteboardType.string)
// show notification on main thread
DispatchQueue.main.async {
displayNotification(title: "OC Login with developer", body: "OC Login command copied to clipboard, go ahead and login to your cluster")
}
}
} catch let jsonErr {
print(jsonErr.localizedDescription)
}
}
func FetchVersionInfoFromDaemon() -> (String, String) {
let r = SendCommandToDaemon(command: Request(command: "version", args: nil))
guard let data = r else { return ("", "") }
if String(bytes: data, encoding: .utf8) == "Failed" {
// Alert show error
DispatchQueue.main.async {
showAlertFailedAndCheckLogs(message: "Failed to fetch version", informativeMsg: "Ensure the CRC daemon is running, for more information please check the logs")
}
return ("","")
}
do {
let versionResult = try JSONDecoder().decode(VersionResult.self, from: data)
if versionResult.Success {
let crcVersion = "\(versionResult.CrcVersion)+\(versionResult.CommitSha)"
return (crcVersion, versionResult.OpenshiftVersion)
}
} catch let jsonErr {
print(jsonErr)
}
return ("","")
}
func GetConfigFromDaemon(properties: [String]) -> Dictionary<String, String> {
let r = SendCommandToDaemon(command: ConfigGetRequest(command: "getconfig", args: PropertiesArray(properties: properties)))
guard let data = r else { return ["":""] }
if String(bytes: data, encoding: .utf8) == "Failed" {
// Alert show error
DispatchQueue.main.async {
showAlertFailedAndCheckLogs(message: "Failed to Check if Pull Secret is configured", informativeMsg: "Ensure the CRC daemon is running, for more information please check the logs")
}
return ["":""]
}
do {
let configGetResult = try JSONDecoder().decode(ConfigGetResult.self, from: data)
if !configGetResult.Configs.isEmpty {
return configGetResult.Configs
}
} catch let jsonErr {
print(jsonErr)
}
return ["":""]
}
func GetAllConfigFromDaemon() throws -> (CrcConfigs?) {
let crcConfig: CrcConfigs? = nil
let r = SendCommandToDaemon(command: Request(command: "getconfig", args: nil))
guard let data = r else { print("Unable to read response from daemon"); throw DaemonError.badResponse }
if String(bytes: data, encoding: .utf8) == "Failed" {
throw DaemonError.badResponse
}
let decoder = JSONDecoder()
do {
let configResult = try decoder.decode(GetconfigResult.self, from: data)
if configResult.Error == "" {
return configResult.Configs
}
} catch let jsonErr {
print(jsonErr)
}
return crcConfig
}
| 44.555556 | 261 | 0.610349 |
8469edf697240d280f2eb2b2aed5003f1d76c89c | 25,093 | asm | Assembly | enduser/netmeeting/av/codecs/intel/h263/i386/dx5aspec.asm | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | enduser/netmeeting/av/codecs/intel/h263/i386/dx5aspec.asm | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | enduser/netmeeting/av/codecs/intel/h263/i386/dx5aspec.asm | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | ;* *************************************************************************
;* INTEL Corporation Proprietary Information
;*
;* This listing is supplied under the terms of a license
;* agreement with INTEL Corporation and may not be copied
;* nor disclosed except in accordance with the terms of
;* that agreement.
;*
;* Copyright (c) 1995 Intel Corporation.
;* All Rights Reserved.
;*
;* *************************************************************************
;* -------------------------------------------------------------------------
;* PVCS Source control information:
;*
;* $Header: S:\h26x\src\dec\dx5aspec.asv 1.2 01 Sep 1995 17:12:12 DBRUCKS $
;*
;* $Log: S:\h26x\src\dec\dx5aspec.asv $
;//
;// Rev 1.2 01 Sep 1995 17:12:12 DBRUCKS
;// fix shaping
;//
;// Rev 1.1 29 Aug 1995 16:49:02 DBRUCKS
;// cleanup comment
;//
;// Rev 1.0 23 Aug 1995 12:20:32 DBRUCKS
;// Initial revision.
;*
;* NOTE:
;* The starting source for this routine came from the PVCS database
;* for the H261 decoder (aspeccor.asm version 1.1, which is a working
;* 16-bit version).
;* -------------------------------------------------------------------------
;////////////////////////////////////////////////////////////////////////////
; AspectCorrect -- This function converts the U & V data from 8 bits to 7 bits
; and moves the data into the YVU9 format the MRV color
; convertors want. Note: the Y data was already converted
; from 8 bits to 7 bits in Convert_Y_8to7_Bit.
;
; if (Input Format == YVU9)
; /* This is needed for looking glass output */
; copy U and V from src to dst
; else { /* Input Format == YVU12 */
; if (shaping) {
; copy Y from src to dst skiping every 12th line
; copy UV from src to dst subsampling and dropping one in 12 lines
; (although not every 12th).
; } else {
; copy UV from src to dst subsampling
; }
; }
;
; Notes:
; * the MRV color converters expect YVU9
; * we may need to drop every 12th line for aspect ratio correction of the
; YVU12 input.
;
; ASSUMPTIONS/LIMITATIONS:
; * IF input in YVU12, only 128x96, 176x144, & 352x288 resolutions are
; supported. YVU9 should support all sizes.
;
;-------------------------------------------------------------------------------
include decconst.inc
ifndef WIN32
.MODEL SMALL
endif
.486
ifdef WIN32
.MODEL FLAT
.DATA
else ;; WIN16
_DATA SEGMENT PUBLIC 'DATA'
endif
;; Toss lines for aspect ratio correction 12 to 9
;; 6, 19, 30, 43, 54, 67,
;; 78, 91,102,115,126,139
;; Lookup Table for 8->7 bit conversion and clamping.
;; U and V range from 16..240->8..120
gTAB_UVtbl8to7 BYTE 8, 8, 8, 8, 8, 8, 8, 8
BYTE 8, 8, 8, 8, 8, 8, 8, 8
BYTE 8, 8, 9, 9, 10, 10, 11, 11
BYTE 12, 12, 13, 13, 14, 14, 15, 15
BYTE 16, 16, 17, 17, 18, 18, 19, 19
BYTE 20, 20, 21, 21, 22, 22, 23, 23
BYTE 24, 24, 25, 25, 26, 26, 27, 27
BYTE 28, 28, 29, 29, 30, 30, 31, 31
BYTE 32, 32, 33, 33, 34, 34, 35, 35
BYTE 36, 36, 37, 37, 38, 38, 39, 39
BYTE 40, 40, 41, 41, 42, 42, 43, 43
BYTE 44, 44, 45, 45, 46, 46, 47, 47
BYTE 48, 48, 49, 49, 50, 50, 51, 51
BYTE 52, 52, 53, 53, 54, 54, 55, 55
BYTE 56, 56, 57, 57, 58, 58, 59, 59
BYTE 60, 60, 61, 61, 62, 62, 63, 63
BYTE 64, 64, 65, 65, 66, 66, 67, 67
BYTE 68, 68, 69, 69, 70, 70, 71, 71
BYTE 72, 72, 73, 73, 74, 74, 75, 75
BYTE 76, 76, 77, 77, 78, 78, 79, 79
BYTE 80, 80, 81, 81, 82, 82, 83, 83
BYTE 84, 84, 85, 85, 86, 86, 87, 87
BYTE 88, 88, 89, 89, 90, 90, 91, 91
BYTE 92, 92, 93, 93, 94, 94, 95, 95
BYTE 96, 96, 97, 97, 98, 98, 99, 99
BYTE 100,100,101,101,102,102,103,103
BYTE 104,104,105,105,106,106,107,107
BYTE 108,108,109,109,110,110,111,111
BYTE 112,112,113,113,114,114,115,115
BYTE 116,116,117,117,118,118,119,119
BYTE 120,120,120,120,120,120,120,120
BYTE 120,120,120,120,120,120,120,120
_DATA ENDS
ifdef WIN32
.CODE
assume cs : flat
assume ds : flat
assume es : flat
assume fs : flat
assume gs : flat
else
_TEXT32 SEGMENT PUBLIC READONLY USE32 'CODE'
ASSUME DS:_DATA
ASSUME CS:_TEXT32
ASSUME ES:nothing
ASSUME FS:nothing
ASSUME GS:nothing
endif
;C function prototype
;
;long AspectCorrect(
; HPBYTE pYPlaneInput, /*ptr Y plane*/
; HPBYTE pVPlaneInput, /*ptr V plane*/
; HPBYTE pUPlaneInput, /*ptr U plane*/
; DWORD YResolution, /*Y plane height*/
; DWORD XResolution, /*Y plane width*/
; WORD far * pyNewHeight, /*Pitch of Y plane in*/
; DWORD YVU9InputFlag, /*flag = YUV9 or YUV12*/
; HPBYTE pYPlaneOutput, /*pYOut*/
; HPBYTE pVPlaneOutput, /*pUOut*/
; DWORD YPitchOut, /*Pitch of Y plane out*/
; DWORD ShapingFlag /*flag = Shaping or not*/
; )
PUBLIC _AspectCorrect
ifdef WIN32
_AspectCorrect proc
else
_AspectCorrect proc far
; parmD pYPlaneIn ;ptr to Y input plane
; parmD pVPlaneIn ;ptr to V input plane
; parmD pUPlaneIn ;ptr to U input plane
; parmD YRes ;Y plane height
; parmD XRes ;Y plane width
; parmD pYNewHeight ;Pitch of Y plane input
; parmD YVU9Flag ;Flag=1 if YUV9
; parmD pYPlaneOut ;ptr to Y output plane
; parmD pVPlaneOut ;ptr to V output plane
; parmD YPitchOut ;Pitch of Y plane output
; parmD ShapingFlag ;Flag=1 if Shaping
endif
;set up equates
pYPlaneIn EQU DWORD PTR[ebp+8]
pVPlaneIn EQU DWORD PTR[ebp+12]
pUPlaneIn EQU DWORD PTR[ebp+16]
YRes EQU DWORD PTR[ebp+20]
XRes EQU DWORD PTR[ebp+24]
pYNewHeight EQU DWORD PTR[ebp+28]
YVU9Flag EQU DWORD PTR[ebp+32]
pYPlaneOut EQU DWORD PTR[ebp+36]
pVPlaneOut EQU DWORD PTR[ebp+40]
YPitchOut EQU DWORD PTR[ebp+44]
ShapingFlag EQU DWORD PTR[ebp+48]
;; stack usage
; previous ebp at ebp
; previous edi at ebp - 4
; previous esi at ebp - 8
; lXRes at ebp -12
; lYRes at ebp -16
; lYPitchOut at ebp -20
; YDiff at ebp -24
; outloopcnt at ebp -28
; uvWidth at ebp -32
; inloopcnt at ebp -36
; luvcounter at ebp -40
; uvoutloopcnt at ebp -44
; VDiff at ebp -48
; VInDiff at ebp -52
lXRes EQU DWORD PTR[ebp-12]
lYRes EQU DWORD PTR[ebp-16]
lYPitchOut EQU DWORD PTR[ebp-20]
YDiff EQU DWORD PTR[ebp-24]
outloopcnt EQU DWORD PTR[ebp-28]
uvWidth EQU DWORD PTR[ebp-32]
inloopcnt EQU DWORD PTR[ebp-36]
luvcounter EQU DWORD PTR[ebp-40]
uvoutloopcnt EQU DWORD PTR[ebp-44]
VDiff EQU DWORD PTR[ebp-48]
VInDiff EQU DWORD PTR[ebp-52]
xor ax,ax ; These two instructions give definitive proof we are
mov eax,0CCCCCCCCH ; in a 32-bit code segment. INT 3 occurs if not.
;get params
push ebp
ifdef WIN32
mov ebp, esp
else
movzx ebp, sp ;ebp now pointing to last pushed reg
endif
push edi
push esi
; zero out registers
xor edx, edx
xor esi, esi
xor edi, edi
; move stack variables to local space
mov eax, XRes
push eax ; store lXRes on stack
mov ebx, YRes
push ebx ; store lYRes on stack
mov ecx, YPitchOut
push ecx ; store lYpitchOut on stack
sub ecx, eax ; YDiff = YPitchOut - XRes
push ecx ; store YDiff on stack
; push stack with 0 6 additional times to make room for other locals
push edx ; outloopcnt
push edx ; uvWidth
push edx ; inloopcnt
push edx ; luvcounter
push edx ; uvoutloopcnt
push edx ; VDiff
push edx ; VInDiff
; test if YUV9 mode
mov edx, YVU9Flag
test edx,edx
jz YVU12; ; If the flag is false it must be YVU12
;**********************************************************************
;**********************************************************************
; know input was YVU9, Y Plane was processed in cc12to7.asm
mov esi, pYNewHeight
mov WORD PTR [esi], bx ; store YRes into address pYNewHeight
; ********************
; Copy V and U Plane from source to destination converting to 7 bit
; ********************
; Description of V & U Plane processing:
; - Double nested loop with
; Outlp1 executed YRes/4 lines
; Collp1 loops for number of columns
; - Read 1 U
; - Read 1 V
; - Convert each value from 8-bit to 7-bit
; - Store 1 U
; - Store 1 V
;
; Register usage
; eax U plane input address
; ebx source value and index into gTAB_UVtbl8to7
; ecx source value and index into gTAB_UVtbl8to7
; edx inner most loop counter
; esi V plane src address
; edi des address
; ebp stack pointer stuff
;
; if (16-bit)
; es input plane segment
; fs output plane segment
; ds table segment
; endif
;
; local variables
; outloopcnt
; lXRes
; lYRes
; uvWidth
; VDiff
;
; know input was YVU9
mov ecx, lYRes
mov ebx, lXRes
shr ebx, 2 ; uvWidth=XRes/4
mov eax, VPITCH ; get Fixed offset
shr ecx, 2 ; outloopcnt=YRes/4
mov uvWidth,ebx ; uvWidth=XRes/4
sub eax, ebx ; VPITCH - uvWidth
mov esi, pVPlaneIn ; Initialize input cursor
mov edi, pVPlaneOut ; Initialize output cursor
mov VDiff, eax ; store V difference
mov eax, pUPlaneIn ; Initialize input cursor
Row9lp2:
mov outloopcnt,ecx ; store updated outer loop count
mov edx, uvWidth ; init dx
xor ebx, ebx
xor ecx, ecx
Col9lpv1:
mov cl, BYTE PTR [eax] ; Fetch *PUtemp_IN
inc edi ; Inc des by 1, PVtemp_OUT++
mov bl, BYTE PTR [esi] ; Fetch *pVtemp_IN
inc eax ; pUtemp+=1
mov cl, gTAB_UVtbl8to7[ecx] ; cl = gTAB_UVtbl8to7[*pUtemp_IN]
inc esi ; Inc source by 1,pVtemp+=1
mov BYTE PTR [edi+167],cl ; store in PUtemp_OUT
mov bl, gTAB_UVtbl8to7[ebx] ; bl = gTAB_UVtbl8to7[*pVtemp_IN]
mov BYTE PTR [edi-1],bl ; store in PVtemp_OUT
xor ecx, ecx ; dummy op
dec edx
jg Col9lpv1
;; increment to beginning of next line
mov edx, VDiff
mov ecx, outloopcnt ; get outer loop count
add edi,edx ; Point to next output row
dec ecx
jnz Row9lp2 ; if more to do loop
jmp Cleanup
;*****************************************************************
;*****************************************************************
; know input was YVU12
;
; if (!ShapingFlag) {
; goto YVU12_NO_SHAPING;
; } else {
; switch (YRes) { // YRes = YRes * 11 / 12;
; case 96: *pyNewHeight = 88; break;
; case 144: *pyNewHeight = 132; break;
; case 288: *pyNewHeight = 264; break;
; default: error;
; }
; }
;
YVU12:
mov eax, ShapingFlag
test eax, eax
jz YVU12_NO_SHAPING
cmp lYRes, 96 ; If 96
je YRes96
cmp lYRes, 144 ; If 144
je YRes144
cmp lYRes, 288 ; If 288
je YRes288
jmp Error
;
YRes96:
mov ax, 88 ; pyNewHeight = ax = 132
mov ecx, 7 ; for YRes lines loopcounter=11
mov uvoutloopcnt, 1 ; process 1 full set of 13&11 lines
jmp Rejoin2
YRes144:
mov ax, 132 ; pyNewHeight = ax = 132
mov ecx, 11 ; for YRes lines loopcounter=11
mov uvoutloopcnt, 2 ; process 2 full sets of 13&11 lines
jmp Rejoin2
YRes288:
mov ax, 264 ; pyNewHeight = ax = 264
mov ecx, 23 ; for YRes lines loopcounter=23
mov uvoutloopcnt, 5 ; process 5 full sets of 13&11 lines
Rejoin2:
mov esi, pYNewHeight
mov [esi], ax ; store adjusted height into
; address pYNewHeight
; ********************
; Copy Y Plane from soure to dest skipping every 12th line
; ********************
; Description of YPlane processing:
;
; Triple nested loop with
; Outlp1 executed 11 or 23 times based on 144 or 288 lines respectively
; Rowlp1 is executed 11 times
; Collp1 loops for number of columns
;
; Register usage
; eax rows loop count
; ebx input and output
; ecx outer loop count
; edx column loop counter
; esi src address
; edi des address
; ebp stack pointer stuff
;
; es input plane segment
; fs output plane segment
; ds table segment
;
; local variables
; lXRes
; YDiff
; lYPitchOut
;
mov esi, pYPlaneIn ; Initialize input cursor
mov edi, pYPlaneOut ; Initialize output cursor
; No need to re-copy first 11 lines
mov eax, lYPitchOut
mov edx, YDiff
add edi, eax ; des + 1*lYPitchOut
shl eax, 1 ; lYPitchOut*2
;;; add esi, edx ; Adjust for difference in YPitchOut
; and XRes
add edi, eax ; des + 3*lYpitchOut
shl eax, 1 ; lYPirchOut*4
;;; add edi, edx ; Adjust for difference in YPitchOut
; and XRes
add esi, eax ; source + 4*lYpitchOut
shl eax, 1 ; lYPitchOut*8
add esi, eax ; source +12*lYpitchOut
add edi, eax ; des + 11*lYPitchOut
Outlp1:
mov eax, 11 ; Initialize rows loop cnter
mov edx, lXRes ; edx = number of columns
Rowlp1:
Collp1:
mov ebx, [esi+edx-4] ; Fetch source, 4 at a time
sub edx,4 ; decrement loop counter
mov [edi+edx],ebx ; Store 4 converted values
jnz Collp1 ; if not done loop
mov edx, lYPitchOut
mov ebx, YDiff
add edi, edx ; Increment to where just processed
add esi, edx
;;; add edi, ebx ; Adjust for difference in YPitchOut
;;; add esi, ebx ; and XRes
dec eax ; decrement rows loop counter
jg Rowlp1
mov eax,lYPitchOut ; Skip 12th line
add esi,eax ; Point to next input row
dec ecx ; decrement outer loop counter
jg Outlp1 ; if more to do loop
; ************************************************************
; Copy V and U Plane from source to destination converting to 7 bit
; skipping every other line and sometimes two moving only ever other
; pixel in a row.
; ********************
;
; Description of V & U Plane processing:
; - Double nested loop with
; Outlp1 executed YRes/4 lines
; Collp1 loops for number of columns
; - Read 1 U
; - Read 1 V
; - Convert each value from 8-bit to 7-bit
; - Store 1 U
; - Store 1 V
;
; Register usage
; eax U plane input address
; ebx source value and index into gTAB_UVtbl8to7
; ecx source value and index into gTAB_UVtbl8to7
; edx counter
; esi V plane src address
; edi des address, V Plane and U Plane
; ebp stack pointer stuff
;
; es input plane segment
; fs output plane segment
; ds table segment
;
; local variables
; luvcounter
; uvoutloopcnt
; inloopcnt
; lXRes
; uvWidth
; VDiff
;
mov ebx, lXRes
mov eax, VPITCH ; get Fixed offset
shr ebx, 1 ; uvWidth=XRes/2
mov uvWidth, ebx ; uvWidth=XRes/2
shr ebx, 1
sub eax, ebx ; VPITCH - uvWidth
mov VDiff, eax ; store V difference
mov luvcounter, ebx ; luvcounter = XRes/4
mov ecx, YPITCH ; Distance to the next V
add ecx, ecx
sub ecx, uvWidth
mov VInDiff, ecx ; = YPITCH + YPITCH - uvWidth
mov esi, pVPlaneIn ; Initialize input cursor
mov edi, pVPlaneOut ; Initialize output cursor
mov eax, pUPlaneIn ; Initialize input cursor
; Process 6 first lines special
mov ebx, 3 ; initialize inner loop count
Rowlp2_6:
mov edx, luvcounter ; init dx
mov inloopcnt, ebx ; store updated inloopcnt
xor ebx, ebx
xor ecx, ecx
Collpv1:
mov cl, BYTE PTR [eax] ; Fetch *PUtemp_IN
inc edi ; Inc des by 1, PVtemp_OUT++
mov bl, BYTE PTR [esi] ; Fetch *pVtemp_IN
add eax,2 ; pUtemp+=2
mov cl, gTAB_UVtbl8to7[ecx] ; cl = gTAB_UVtbl8to7[*pUtemp_IN]
add esi,2 ; Inc source by 2,pVtemp+=2
mov BYTE PTR [edi+167],cl; store in PUtemp_OUT
mov bl, gTAB_UVtbl8to7[ebx] ; bl = gTAB_UVtbl8to7[*pVtemp_IN]
mov BYTE PTR [edi-1],bl ; store in PVtemp_OUT
xor ecx, ecx ; dummy op
dec edx
jg Collpv1
; increment to beginning of next line then skip next input line
add edi,VDiff ; Point to next output row
mov edx,VInDiff ; Skip to next input row
add esi,edx ;
add eax,edx ;
; test if have processed 6 lines yet
mov ebx, inloopcnt
dec ebx
jg Rowlp2_6 ; if more to do loop
; Skipping extra line
mov edx,YPITCH ; Need same sized for add
mov ecx, uvoutloopcnt
add esi,edx ; Point to next input row
add eax,edx ; Point to next input row
; Process groups of 13 and 11 lines
Outlp2:
; Process 13 lines
mov ebx, 6 ; initialize inner loop count
mov uvoutloopcnt, ecx
Rowlp2_13:
mov edx, luvcounter ; init dx
mov inloopcnt, ebx ; store updated inloopcnt
xor ebx, ebx
xor ecx, ecx
Collpv1_13:
mov cl, BYTE PTR [eax] ; Fetch *PUtemp_IN
inc edi ; Inc des by 1, PVtemp_OUT++
mov bl, BYTE PTR [esi] ; Fetch *pVtemp_IN
add eax,2 ; pUtemp+=2
mov cl, gTAB_UVtbl8to7[ecx] ; cl = gTAB_UVtbl8to7[*pUtemp_IN]
add esi,2 ; Inc source by 2,pVtemp+=2
mov BYTE PTR [edi+167],cl; store in PUtemp_OUT
mov bl, gTAB_UVtbl8to7[ebx] ; bl = gTAB_UVtbl8to7[*pVtemp_IN]
mov BYTE PTR [edi-1],bl ; store in PVtemp_OUT
xor ecx, ecx ; dummy op
dec edx
jg Collpv1_13
; increment to beginning of next line then skip next input line
add edi,VDiff ; Point to next output row
mov edx,VInDiff ; Skip to next input row
add esi,edx ;
add eax,edx ;
; test if have processed 13 lines yet
mov ebx, inloopcnt
dec ebx
jg Rowlp2_13 ; if more to do loop
; Skipping extra line
mov edx,YPITCH ; Need same sized for add
mov ebx, 5 ; initialize inner loop count
add esi,edx ; Point to next input row
add eax,edx ; Point to next input row
; Process 11 lines
Rowlp2_11:
mov edx, luvcounter ; init dx
mov inloopcnt, ebx ; store updated inloopcnt
xor ebx, ebx
xor ecx, ecx
Collpv1_11:
mov cl, BYTE PTR [eax] ; Fetch *PUtemp_IN
inc edi ; Inc des by 1, PVtemp_OUT++
mov bl, BYTE PTR [esi] ; Fetch *pVtemp_IN
add eax,2 ; pUtemp+=2
mov cl, gTAB_UVtbl8to7[ecx] ; cl = gTAB_UVtbl8to7[*pUtemp_IN]
add esi,2 ; Inc source by 2,pVtemp+=2
mov BYTE PTR [edi+167],cl; store in PUtemp_OUT
mov bl, gTAB_UVtbl8to7[ebx] ; bl = gTAB_UVtbl8to7[*pVtemp_IN]
mov BYTE PTR [edi-1],bl ; store in PVtemp_OUT
xor ecx, ecx ; dummy op
dec edx
jg Collpv1_11
; increment to beginning of next line, then skip next input line
add edi, VDiff ; Point to next output row
mov edx,VInDiff ; Skip to next input row
add esi,edx ;
add eax,edx ;
; test if have processed 11 lines yet
mov ebx, inloopcnt
dec ebx
jg Rowlp2_11 ; if more to do loop
; Skipping extra line
mov edx,YPITCH ; Need same sized for add
mov ecx, uvoutloopcnt
add esi,edx ; Point to next input row
add eax,edx ; Point to next input row
dec ecx
jnz Outlp2 ; if more to do loop
;
; Process last set of 13
;
mov ebx, 6 ; initialize inner loop count
Rowlp2_13l:
mov edx, luvcounter ; init dx
mov inloopcnt, ebx ; store updated inloopcnt
xor ebx, ebx
xor ecx, ecx
Collpv1_13l:
mov cl, BYTE PTR [eax] ; Fetch *PUtemp_IN
inc edi ; Inc des by 1, PVtemp_OUT++
mov bl, BYTE PTR [esi] ; Fetch *pVtemp_IN
add eax,2 ; pUtemp+=2
mov cl, gTAB_UVtbl8to7[ecx] ; cl = gTAB_UVtbl8to7[*pUtemp_IN]
add esi,2 ; Inc source by 2,pVtemp+=2
mov BYTE PTR [edi+167],cl; store in PUtemp_OUT
mov bl, gTAB_UVtbl8to7[ebx] ; bl = gTAB_UVtbl8to7[*pVtemp_IN]
mov BYTE PTR [edi-1],bl ; store in PVtemp_OUT
xor ecx, ecx ; dummy op
dec edx
jg Collpv1_13l
; increment to beginning of next line then skip next input line
add edi,VDiff ; Point to next output row
mov edx,VInDiff ; Skip to next input row
add esi,edx ;
add eax,edx ;
; test if have processed 13 lines yet
mov ebx, inloopcnt
dec ebx
jg Rowlp2_13l ; if more to do loop
; Skipping extra line
mov edx,YPITCH ; Need same sized for add
mov ebx, 2 ; initialize inner loop count
add esi,edx ; Point to next input row
add eax,edx ; Point to next input row
; Process final 4 lines
Rowlp2_f:
mov edx, luvcounter ; init dx
mov inloopcnt, ebx
xor ebx, ebx
xor ecx, ecx
Collpv1_f:
mov cl, BYTE PTR [eax] ; Fetch *PUtemp_IN
inc edi ; Inc des by 1, PVtemp_OUT++
mov bl, BYTE PTR [esi] ; Fetch *pVtemp_IN
add eax,2 ; pUtemp+=2
mov cl, gTAB_UVtbl8to7[ecx] ; cl = gTAB_UVtbl8to7[*pUtemp_IN]
add esi,2 ; Inc source by 2,pVtemp+=2
mov BYTE PTR [edi+167],cl; store in PUtemp_OUT
mov bl, gTAB_UVtbl8to7[ebx] ; bl = gTAB_UVtbl8to7[*pVtemp_IN]
mov BYTE PTR [edi-1],bl ; store in PVtemp_OUT
xor ecx, ecx ; dummy op
dec edx
jg Collpv1_f
; increment to beginning of next line then skip next input line
add edi, VDiff ; Point to next output row
mov edx,VInDiff ; Skip to next input row
add esi,edx ;
add eax,edx ;
; test if have processed last lines yet
mov ebx, inloopcnt
dec ebx
jg Rowlp2_f ; if more to do loop
jmp Cleanup
; ************************************************************
; Copy V and U Plane from source to destination converting to 7 bit
; skipping every other line moving only ever other pixel in a row.
; ********************
;
; Description of V & U Plane processing:
; - Double nested loop with
; Outlp1 executed YRes/4 lines
; Collp1 loops for number of columns
; - Read 1 U
; - Read 1 V
; - Convert each value from 8-bit to 7-bit
; - Store 1 U
; - Store 1 V
;
; Register usage
; eax U plane input address
; ebx source value and index into gTAB_UVtbl8to7
; ecx source value and index into gTAB_UVtbl8to7
; edx counter
; esi V plane src address
; edi des address, V Plane and U Plane
; ebp stack pointer stuff
;
; es input plane segment
; fs output plane segment
; ds table segment
;
; local variables
; luvcounter
; inloopcnt
; lYRes
; lXRes
; uvWidth
; VDiff
; VInDiff
;
YVU12_NO_SHAPING:
cmp lYRes, 98
je YRes98_NS
cmp lYRes, 144
je YRes144_NS
cmp lYRes, 288
je YRes288_NS
jmp Error
;
YRes98_NS: ; 98 No Shaping
YRes144_NS: ; 144 No Shaping
YRes288_NS: ; 288 No Shaping
mov eax, lYRes ; pyNewHeight = ax = YRes
mov esi, pYNewHeight
mov [esi], ax ; store adjusted height into
shr eax, 2 ; inloopcnt=YRes/2
mov ebx, lXRes
shr ebx, 1 ; uvWidth=XRes/2
mov inloopcnt, eax ; initialize inner loop count
mov uvWidth, ebx ; uvWidth=XRes/2
mov ecx, VPITCH ; get output plane V pitch
shr ebx, 1
sub ecx, ebx ; VPITCH - uvWidth/2
mov luvcounter, ebx ; luvcounter = XRes/4
mov VDiff, ecx ; Store VDiff
mov ecx, YPITCH ; Distance to the next V
add ecx, ecx
sub ecx, uvWidth
mov VInDiff, ecx ; = YPITCH + YPITCH - uvWidth
mov esi, pVPlaneIn ; Initialize input cursor
mov edi, pVPlaneOut ; Initialize output cursor
mov eax, pUPlaneIn ; Initialize input cursor
mov ecx, inloopcnt
; Process all lines skipping just every other
Rowlp2_NS:
mov inloopcnt, ecx ; store update inloopcnt
xor ebx, ebx
mov edx, luvcounter ; init dx
xor ecx, ecx
Collpv1_NS:
mov cl, BYTE PTR [eax] ; Fetch *PUtemp_IN
inc edi ; Inc des by 1, PVtemp_OUT++
mov bl, BYTE PTR [esi] ; Fetch *pVtemp_IN
add eax,2 ; pUtemp+=2
mov cl, gTAB_UVtbl8to7[ecx] ; cl = gTAB_UVtbl8to7[*pUtemp_IN]
add esi,2 ; Inc source by 2,pVtemp+=2
mov BYTE PTR [edi+167],cl; store in PUtemp_OUT
mov bl, gTAB_UVtbl8to7[ebx] ; bl = gTAB_UVtbl8to7[*pVtemp_IN]
mov BYTE PTR [edi-1],bl ; store in PVtemp_OUT
xor ecx, ecx ; dummy op
dec edx
jg Collpv1_NS
; increment to beginning of next line then skip next input line
add edi, VDiff ; Point to next output row
mov edx,VInDiff ; Skip to next input row
add esi,edx ;
add eax,edx ;
mov ecx, inloopcnt ; get inloopcnt
; test if have processed all lines yet
dec ecx ; Process next line
jne Rowlp2_NS ; if more to do loop
Error:
Cleanup:
; clean out local variables on stack
pop ecx
pop ebx
pop ecx
pop ebx
pop ecx
pop ebx
pop ecx
pop ebx
pop ecx
pop ebx
pop ecx
;clear special seg registers, restore stack, pop saved registers
ifndef WIN32
xor ecx, ecx
xor ebx, ebx
mov es, cx
mov fs, bx
endif
pop esi
pop edi
pop ebp
ifdef WIN32
ret
else
db 066h
retf
endif
_AspectCorrect endp
END
| 28.776376 | 85 | 0.59674 |
258aef9b18da7bb834baec9f9d84af171149f6af | 3,877 | asm | Assembly | chap18/ex4/mul_blend_avx.asm | JamesType/optimization-manual | 61cdcebb16e0768a6ab7e85ed535e64e9d8cc31a | [
"0BSD"
] | 374 | 2021-06-08T10:42:01.000Z | 2022-03-29T14:21:45.000Z | chap18/ex4/mul_blend_avx.asm | JamesType/optimization-manual | 61cdcebb16e0768a6ab7e85ed535e64e9d8cc31a | [
"0BSD"
] | 1 | 2021-06-11T20:24:02.000Z | 2021-06-11T20:24:02.000Z | chap18/ex4/mul_blend_avx.asm | JamesType/optimization-manual | 61cdcebb16e0768a6ab7e85ed535e64e9d8cc31a | [
"0BSD"
] | 39 | 2021-06-08T11:25:29.000Z | 2022-03-05T05:14:17.000Z | ;
; Copyright (C) 2021 by Intel Corporation
;
; Permission to use, copy, modify, and/or distribute this software for any
; purpose with or without fee is hereby granted.
;
; THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
; REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
; AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
; INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
; LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
; OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
; PERFORMANCE OF THIS SOFTWARE.
;
; .globl mul_blend_avx
; # void mul_blend_avx(double *a, double *b, double *c, size_t N);
; # On entry:
; # rcx = a
; # rdx = b
; # r8 = c
; # r9 = N
.code
mul_blend_avx PROC public
push rbx
push r12
sub rsp, 168
vmovaps xmmword ptr [rsp], xmm6
vmovaps xmmword ptr [rsp+16], xmm7
vmovaps xmmword ptr [rsp+32], xmm8
vmovaps xmmword ptr [rsp+48], xmm9
vmovaps xmmword ptr [rsp+64], xmm10
vmovaps xmmword ptr [rsp+80], xmm11
vmovaps xmmword ptr [rsp+96], xmm12
vmovaps xmmword ptr [rsp+112], xmm13
vmovaps xmmword ptr [rsp+128], xmm14
vmovaps xmmword ptr [rsp+144], xmm15
mov rax, rcx ; mov rax, a
mov r11, rdx ; mov r11, b
mov r12, r9 ; mov r12, N
shr r12, 5
mov rdx, r8 ; mov rdx, c
xor r9, r9
xor r10, r10
loop1:
vmovupd ymm1, ymmword ptr [rax+r9*8]
inc r10d
vmovupd ymm6, ymmword ptr [rax+r9*8+20h]
vmovupd ymm2, ymmword ptr [r11+r9*8]
vmovupd ymm7, ymmword ptr [r11+r9*8+20h]
vmovupd ymm11, ymmword ptr [rax+r9*8+40h]
vmovupd ymm12, ymmword ptr [r11+r9*8+40h]
vcmppd ymm4, ymm0, ymm1, 1h
vcmppd ymm9, ymm0, ymm6, 1h
vcmppd ymm14, ymm0, ymm11, 1h
vandpd ymm16, ymm1, ymm4
vandpd ymm17, ymm6, ymm9
vmulpd ymm3, ymm16, ymm2
vmulpd ymm8, ymm17, ymm7
vmovupd ymm1, ymmword ptr [rax+r9*8+60h]
vmovupd ymm6, ymmword ptr [rax+r9*8+80h]
vblendvpd ymm5, ymm2, ymm3, ymm4
vblendvpd ymm10, ymm7, ymm8, ymm9
vmovupd ymm2, ymmword ptr [r11+r9*8+60h]
vmovupd ymm7, ymmword ptr [r11+r9*8+80h]
vmovupd ymmword ptr [rdx], ymm5
vmovupd ymmword ptr [rdx+20h], ymm10
vcmppd ymm4, ymm0, ymm1, 1h
vcmppd ymm9, ymm0, ymm6, 1h
vandpd ymm18, ymm11, ymm14
vandpd ymm19, ymm1, ymm4
vandpd ymm20, ymm6, ymm9
vmulpd ymm13, ymm18, ymm12
vmulpd ymm3, ymm19, ymm2
vmulpd ymm8, ymm20, ymm7
vmovupd ymm11, ymmword ptr [rax+r9*8+0a0h]
vmovupd ymm1, ymmword ptr [rax+r9*8+0c0h]
vmovupd ymm6, ymmword ptr [rax+r9*8+0e0h]
vblendvpd ymm15, ymm12, ymm13, ymm14
vblendvpd ymm5, ymm2, ymm3, ymm4
vblendvpd ymm10, ymm7, ymm8, ymm9
vmovupd ymm12, ymmword ptr [r11+r9*8+0a0h]
vmovupd ymm2, ymmword ptr [r11+r9*8+0c0h]
vmovupd ymm7, ymmword ptr [r11+r9*8+0e0h]
vmovupd ymmword ptr [rdx+40h], ymm15
vmovupd ymmword ptr [rdx+60h], ymm5
vmovupd ymmword ptr [rdx+80h], ymm10
vcmppd ymm14, ymm0, ymm11, 1h
vcmppd ymm4, ymm0, ymm1, 1h
vcmppd ymm9, ymm0, ymm6, 1h
vandpd ymm21, ymm11, ymm14
add r9, 20h
vandpd ymm22, ymm1, ymm4
vandpd ymm23, ymm6, ymm9
vmulpd ymm13, ymm21, ymm12
vmulpd ymm3, ymm22, ymm2
vmulpd ymm8, ymm23, ymm7
vblendvpd ymm15, ymm12, ymm13, ymm14
vblendvpd ymm5, ymm2, ymm3, ymm4
vblendvpd ymm10, ymm7, ymm8, ymm9
vmovupd ymmword ptr [rdx+0a0h], ymm15
vmovupd ymmword ptr [rdx+0c0h], ymm5
vmovupd ymmword ptr [rdx+0e0h], ymm10
add rdx, 100h
cmp r10d, r12d
jb loop1
vmovaps xmm6, xmmword ptr [rsp]
vmovaps xmm7, xmmword ptr [rsp+16]
vmovaps xmm8, xmmword ptr [rsp+32]
vmovaps xmm9, xmmword ptr [rsp+48]
vmovaps xmm10, xmmword ptr [rsp+64]
vmovaps xmm11, xmmword ptr [rsp+80]
vmovaps xmm12, xmmword ptr [rsp+96]
vmovaps xmm13, xmmword ptr [rsp+112]
vmovaps xmm14, xmmword ptr [rsp+128]
vmovaps xmm15, xmmword ptr [rsp+144]
add rsp, 168
pop r12
pop rbx
vzeroupper
ret
mul_blend_avx ENDP
end | 29.150376 | 79 | 0.714986 |
3d81446e732b676c9fe930d4b0184cba4b844651 | 386 | swift | Swift | Rx-CoffeeShop/CoffeeShop/Models/CartItem.swift | korelhayrullah/Swift | 0c28a2a24782da31c27533de6e7be89c913a2c1e | [
"MIT"
] | 1 | 2019-01-12T20:56:07.000Z | 2019-01-12T20:56:07.000Z | Rx-CoffeeShop/CoffeeShop/Models/CartItem.swift | korelhayrullah/Swift | 0c28a2a24782da31c27533de6e7be89c913a2c1e | [
"MIT"
] | null | null | null | Rx-CoffeeShop/CoffeeShop/Models/CartItem.swift | korelhayrullah/Swift | 0c28a2a24782da31c27533de6e7be89c913a2c1e | [
"MIT"
] | null | null | null | //
// CartItem.swift
// CoffeeShop
//
// Created by Göktuğ Gümüş on 25.09.2018.
// Copyright © 2018 Göktuğ Gümüş. All rights reserved.
//
import Foundation
struct CartItem {
let coffee: Coffee
let count: Int
let totalPrice: Float
init(coffee: Coffee, count: Int) {
self.coffee = coffee
self.count = count
self.totalPrice = Float(count) * coffee.price
}
}
| 17.545455 | 55 | 0.665803 |
7b224fba6f117a77ecf19a18b652eb142e1a1b8d | 563 | rb | Ruby | Formula/font-mada.rb | mxalbert1996/homebrew-fonts | d3a705771f29804f16ce442f920f2fa161d0bead | [
"BSD-2-Clause"
] | 17 | 2019-01-19T16:32:34.000Z | 2022-03-30T23:13:32.000Z | Formula/font-mada.rb | mxalbert1996/homebrew-fonts | d3a705771f29804f16ce442f920f2fa161d0bead | [
"BSD-2-Clause"
] | 25 | 2019-01-11T23:53:24.000Z | 2022-03-29T03:15:18.000Z | Formula/font-mada.rb | mxalbert1996/homebrew-fonts | d3a705771f29804f16ce442f920f2fa161d0bead | [
"BSD-2-Clause"
] | 11 | 2019-03-08T22:58:06.000Z | 2021-12-20T01:11:06.000Z | class FontMada < Formula
head "https://github.com/google/fonts/trunk/ofl/mada", verified: "github.com/google/fonts/", using: :svn
desc "Mada"
homepage "https://fonts.google.com/specimen/Mada"
def install
(share/"fonts").install "Mada-Black.ttf"
(share/"fonts").install "Mada-Bold.ttf"
(share/"fonts").install "Mada-ExtraLight.ttf"
(share/"fonts").install "Mada-Light.ttf"
(share/"fonts").install "Mada-Medium.ttf"
(share/"fonts").install "Mada-Regular.ttf"
(share/"fonts").install "Mada-SemiBold.ttf"
end
test do
end
end
| 33.117647 | 106 | 0.678508 |
04e91cfcf67a61574ffee62416d736039ce46363 | 2,287 | java | Java | src/main/java/com/barrett/base/thread/SyncThreadBank2.java | tanyicheng/java-base | 02b20e9f69ededaf52f529da64a769de0f3ffa3a | [
"Apache-2.0"
] | null | null | null | src/main/java/com/barrett/base/thread/SyncThreadBank2.java | tanyicheng/java-base | 02b20e9f69ededaf52f529da64a769de0f3ffa3a | [
"Apache-2.0"
] | 2 | 2022-01-10T15:15:55.000Z | 2022-01-27T13:11:38.000Z | src/main/java/com/barrett/base/thread/SyncThreadBank2.java | tanyicheng/java-base | 02b20e9f69ededaf52f529da64a769de0f3ffa3a | [
"Apache-2.0"
] | null | null | null | package com.barrett.base.thread;
/**
* 银行存取钱并发测试
*
* @author created by barrett in 2021/6/8 14:04
**/
public class SyncThreadBank2 {
public static void main(String args[]) {
Acount acount = new Acount(0);
// Bank b = new Bank(acount);
// ConsumerA c = new ConsumerA(acount);
// new Thread(b).start();
// new Thread(c).start();
ThreadPoolUtils.executor.execute(new ConsumerA(acount));
ThreadPoolUtils.executor.execute(new Bank(acount));
}
}
/**
* 银行账户
*
* @author created by barrett in 2021/6/8 13:52
**/
class Acount implements Runnable {
private int money;
public Acount(int money) {
this.money = money;
}
@Override
public void run() {
}
public synchronized void getMoney(int money) {
// 注意这个地方必须用while循环,因为即便再存入钱也有可能比取的要少
while (this.money < money) {
System.out.println("准备取款:" + money + " 余额:" + this.money + " 余额不足,正在等待存款......");
try {
wait();
} catch (Exception e) {
}
}
this.money = this.money - money;
System.out.println("取出:" + money + " 还剩余:" + this.money);
}
public synchronized void setMoney(int money) {
try {
Thread.sleep(500);
} catch (Exception e) {
}
this.money = this.money + money;
System.out.println("新存入:" + money + " 共计:" + this.money);
notify();
}
}
// 存款类
class Bank implements Runnable {
Acount Acount;
public Bank(Acount Acount) {
this.Acount = Acount;
}
@Override
public void run() {
while (true) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
int temp = 200;
// int temp = (int) (Math.random() * 1000);
Acount.setMoney(temp);
}
}
}
// 取款类
class ConsumerA implements Runnable {
Acount Acount;
public ConsumerA(Acount Acount) {
this.Acount = Acount;
}
@Override
public void run() {
while (true) {
int temp = 1000;
// int temp = (int) (Math.random() * 1000);
Acount.getMoney(temp);
}
}
}
| 20.790909 | 93 | 0.522956 |
3901e621883044d7a736c1ec86b4fe02d21551bc | 219 | sql | SQL | schema/revert/warehouse/identifier-set-use/data.sql | UWIT-IAM/uw-redcap-client | 38a1eb426fa80697446df7a466a41e0305382606 | [
"MIT"
] | 21 | 2019-04-19T22:45:22.000Z | 2022-01-28T01:32:09.000Z | schema/revert/warehouse/identifier-set-use/data.sql | UWIT-IAM/uw-redcap-client | 38a1eb426fa80697446df7a466a41e0305382606 | [
"MIT"
] | 219 | 2019-04-19T21:42:24.000Z | 2022-03-29T21:41:04.000Z | schema/revert/warehouse/identifier-set-use/data.sql | UWIT-IAM/uw-redcap-client | 38a1eb426fa80697446df7a466a41e0305382606 | [
"MIT"
] | 9 | 2020-03-11T20:07:26.000Z | 2022-03-05T00:36:11.000Z | -- Revert seattleflu/schema:warehouse/identifier-set-use/data from pg
begin;
delete from warehouse.identifier_set_use where use in (
'sample',
'collection',
'clia',
'kit',
'test-strip'
);
commit;
| 15.642857 | 69 | 0.671233 |
0beb93533de877feb49df9b3c22280088c38b5d1 | 4,786 | swift | Swift | Example/Sources/AnimatedImageViewController.swift | haifengkao/NukeUI | 21ace85dda0db8b043fcfa966b4b3a4e9a58c639 | [
"MIT"
] | null | null | null | Example/Sources/AnimatedImageViewController.swift | haifengkao/NukeUI | 21ace85dda0db8b043fcfa966b4b3a4e9a58c639 | [
"MIT"
] | null | null | null | Example/Sources/AnimatedImageViewController.swift | haifengkao/NukeUI | 21ace85dda0db8b043fcfa966b4b3a4e9a58c639 | [
"MIT"
] | null | null | null | // The MIT License (MIT)
//
// Copyright (c) 2015-2021 Alexander Grebenyuk (github.com/kean).
import UIKit
import NukePod
import Gifu
// MARK: - AnimatedImageViewController
final class AnimatedImageViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
override init(nibName nibNameOrNil: String? = nil, bundle nibBundleOrNil: Bundle? = nil) {
super.init(collectionViewLayout: UICollectionViewFlowLayout())
}
required init?(coder aDecoder: NSCoder) {
super.init(collectionViewLayout: UICollectionViewFlowLayout())
}
override func viewDidLoad() {
super.viewDidLoad()
collectionView?.register(AnimatedImageCell.self, forCellWithReuseIdentifier: imageCellReuseID)
collectionView?.backgroundColor = UIColor.systemBackground
let layout = collectionViewLayout as! UICollectionViewFlowLayout
layout.sectionInset = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8)
layout.minimumInteritemSpacing = 8
}
// MARK: Collection View
override func numberOfSections(in collectionView: UICollectionView) -> Int {
1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
switch section {
default: return imageURLs.count
}
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: imageCellReuseID, for: indexPath) as! AnimatedImageCell
cell.setImage(with: imageURLs[indexPath.row])
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let layout = collectionViewLayout as! UICollectionViewFlowLayout
let width = view.bounds.size.width - layout.sectionInset.left - layout.sectionInset.right
return CGSize(width: width, height: width)
}
}
private let imageCellReuseID = "imageCellReuseID"
// MARK: - Image URLs
private let root = "https://cloud.githubusercontent.com/assets"
private let imageURLs = [
URL(string: "\(root)/1567433/6505557/77ff05ac-c2e7-11e4-9a09-ce5b7995cad0.gif")!,
URL(string: "\(root)/1567433/6505565/8aa02c90-c2e7-11e4-8127-71df010ca06d.gif")!,
URL(string: "\(root)/1567433/6505571/a28a6e2e-c2e7-11e4-8161-9f39cc3bb8df.gif")!,
URL(string: "\(root)/1567433/6505576/b785a8ac-c2e7-11e4-831a-666e2b064b95.gif")!,
URL(string: "\(root)/1567433/6505579/c88c77ca-c2e7-11e4-88ad-d98c7360602d.gif")!,
URL(string: "\(root)/1567433/6505595/def06c06-c2e7-11e4-9cdf-d37d28618af0.gif")!,
URL(string: "\(root)/1567433/6505634/26e5dad2-c2e8-11e4-89c3-3c3a63110ac0.gif")!,
URL(string: "\(root)/1567433/6505643/42eb3ee8-c2e8-11e4-8666-ac9c8e1dc9b5.gif")!
]
// MARK: - AnimatedImageCell
private final class AnimatedImageCell: UICollectionViewCell {
private let imageView: GIFImageView
private let spinner: UIActivityIndicatorView
private var task: ImageTask?
override init(frame: CGRect) {
imageView = GIFImageView()
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
spinner = UIActivityIndicatorView(style: .medium)
super.init(frame: frame)
backgroundColor = UIColor(white: 235.0 / 255.0, alpha: 1.0)
contentView.addSubview(imageView)
contentView.addSubview(spinner)
imageView.pinToSuperview()
spinner.centerInSuperview()
}
required init?(coder aDecoder: NSCoder) {
fatalError()
}
func setImage(with url: URL) {
let pipeline = ImagePipeline.shared
let request = ImageRequest(url: url)
if let image = pipeline.cache[request] {
return display(image)
}
spinner.startAnimating()
task = pipeline.loadImage(with: request) { [weak self] result in
self?.spinner.stopAnimating()
if case let .success(response) = result {
self?.display(response.container)
self?.animateFadeIn()
}
}
}
private func display(_ container: NukePod.ImageContainer) {
if let data = container.data {
imageView.animate(withGIFData: data)
} else {
imageView.image = container.image
}
}
private func animateFadeIn() {
imageView.alpha = 0
UIView.animate(withDuration: 0.33) { self.imageView.alpha = 1 }
}
override func prepareForReuse() {
super.prepareForReuse()
task?.cancel()
spinner.stopAnimating()
imageView.prepareForReuse()
}
}
| 34.185714 | 160 | 0.686168 |
e9668ab3414a9e526a35d6e142e476f313c1e022 | 1,891 | rs | Rust | renderer/src/lib.rs | columbus-elst-connection/l-system-prototype | 4495f63158dbd4fd6b83daee57c5f3895d470703 | [
"MIT"
] | null | null | null | renderer/src/lib.rs | columbus-elst-connection/l-system-prototype | 4495f63158dbd4fd6b83daee57c5f3895d470703 | [
"MIT"
] | 1 | 2019-10-15T07:40:42.000Z | 2019-10-15T07:40:42.000Z | renderer/src/lib.rs | columbus-elst-connection/l-system-prototype | 4495f63158dbd4fd6b83daee57c5f3895d470703 | [
"MIT"
] | 2 | 2018-12-02T20:36:26.000Z | 2019-03-23T23:13:34.000Z |
use api::{LSystemRules, RendererInstruction, Renderer};
use turtle::{Turtle, Point, Angle};
pub struct Crab {
step: f64,
step_multiplier: f64,
angle: f64,
stack: Vec<State>,
turtle: Turtle,
}
struct State {
position: Point,
heading: Angle,
step: f64,
}
impl State {
fn new(position: Point, heading: Angle, step: f64) -> Self {
Self { position, heading, step }
}
}
impl Crab {
pub fn new<C>(c: C) -> Self
where
C: Into<Config>,
{
let mut turtle = Turtle::new();
turtle.set_heading(65.0);
let config = c.into();
Self {
step: config.step,
step_multiplier: config.step_multiplier,
angle: config.angle,
stack: Vec::new(),
turtle,
}
}
}
impl Renderer<char> for Crab {
fn push(&mut self) {
let position = self.turtle.position();
let heading = self.turtle.heading();
let state = State::new(position, heading, self.step);
self.stack.push(state);
self.step = self.step / self.step_multiplier;
}
fn pop(&mut self) {
if let Some(state) = self.stack.pop() {
self.step = state.step;
self.turtle.pen_up();
self.turtle.go_to(state.position);
//self.turtle.set_heading(state.heading);
self.turtle.pen_down();
}
}
fn render(&mut self, instruction: char) {
match instruction {
'F' => self.turtle.forward(self.step),
'L' => self.turtle.left(self.angle),
'R' => self.turtle.right(self.angle),
_ => println!("Ignoring inscruction: {}", instruction)
}
}
fn flush(&mut self) {
// no-op
}
}
#[derive(Debug, PartialEq)]
pub struct Config {
pub step: f64,
pub angle: f64,
pub step_multiplier: f64,
}
| 21.988372 | 66 | 0.54257 |