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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d30634da44385d9a29f632348abd9931d553d04c | 1,338 | lua | Lua | config/nvim/lua/core/mappings.lua | TheCodingLab/dotfiles | 9992b6f5e9d59bd78663d9cbf063c7fb7cc7490f | [
"MIT"
] | null | null | null | config/nvim/lua/core/mappings.lua | TheCodingLab/dotfiles | 9992b6f5e9d59bd78663d9cbf063c7fb7cc7490f | [
"MIT"
] | null | null | null | config/nvim/lua/core/mappings.lua | TheCodingLab/dotfiles | 9992b6f5e9d59bd78663d9cbf063c7fb7cc7490f | [
"MIT"
] | null | null | null | vim.g.mapleader = '\\'
vim.g.maplocalleader = '\\'
local opts = { noremap = true, silent = true }
local map = vim.api.nvim_set_keymap
map('n', '<C-n>', '<cmd>NvimTreeToggle<CR>', opts)
-- Clipboard
map('v', '<Leader>y', '"+y', opts)
map('n', '<Leader>p', '"+p', opts)
map('v', '<Leader>p', '"+p', opts)
-- Buffer navigation
map('n', '<Tab>', '<cmd>bnext<CR>', opts)
map('n', '<S-Tab>', '<cmd>bprevious<CR>', opts)
-- Telescope
map('n', '<C-f>', '<cmd>Telescope find_files<CR>', opts)
-- Lspsaga
map('n', 'gl', '<cmd>Lspsaga show_line_diagnostics<CR>', opts)
map('n', 'ca', '<cmd>Lspsaga code_action<CR>', opts)
map('n', 'K', '<cmd>Lspsaga hover_doc<CR>', opts)
map('n', 'rn', '<cmd>Lspsaga rename<CR>', opts)
map('n', 'gj', '<cmd>Lspsaga diagnostic_jump_next<CR>', opts)
map('n', 'gk', '<cmd>Lspsaga diagnostic_jump_prev<CR>', opts)
map('n', '<C-u>', '<cmd>lua require(\'lspsaga.action\').smart_scroll_with_saga(-1)<CR>', opts)
map('n', '<C-d>', '<cmd>lua require(\'lspsaga.action\').smart_scroll_with_saga(1)<CR>', opts)
-- Comment
map('n', '<leader>/', '<cmd>lua require(\'Comment.api\').toggle_current_linewise()<CR>', opts)
map('v', '<leader>/', '<esc><cmd>lua require(\'Comment.api\').toggle_linewise_op(vim.fn.visualmode())<CR>', opts)
-- Indent & stay in visual mode
map('v', '<', '<gv', opts)
map('v', '>', '>gv', opts)
| 33.45 | 113 | 0.609118 |
1fe224c33fe7f96bd12963a8675f8af443d0a6c7 | 2,320 | css | CSS | conways/src/components/Congame.css | mrockingham/Conway-s-mike-s-Game | 16af9d015dff08c26f246447bd1ec917673e7590 | [
"MIT"
] | null | null | null | conways/src/components/Congame.css | mrockingham/Conway-s-mike-s-Game | 16af9d015dff08c26f246447bd1ec917673e7590 | [
"MIT"
] | null | null | null | conways/src/components/Congame.css | mrockingham/Conway-s-mike-s-Game | 16af9d015dff08c26f246447bd1ec917673e7590 | [
"MIT"
] | null | null | null |
.app-body{
display: flex;
flex-direction: column;
justify-content: center;
margin-left: auto;
margin-right: auto;
margin-top: 3%;
align-items: center;
}
.grid-container{
padding: 3%;
border-radius: 72px;
background: #110a58;
box-shadow: inset 29px 29px 45px #090630,
inset -29px -29px 45px #190f80;
}
.app{
width: 100%;
}
.start-text{
color: rgb(58,123,192);
text-decoration: none;
font-size: 1.2rem;
}
.clear-text{
color: rgb(58,123,192);
text-decoration: none;
font-size: 1.2rem;
}
.random-text{
color: rgb(58,123,192);
text-decoration: none;
font-size: 1.2rem;
}
.fast-text{
color: rgb(58,123,192);
text-decoration: none;
font-size: 1.2rem;
}
.slow-text{
color: rgb(58,123,192);
text-decoration: none;
font-size: 1.2rem;
}
.grid-size-text{
color: rgb(58,123,192);
text-decoration: none;
font-size: 1.2rem;
}
.instructions{
color: rgb(58,123,192);
text-decoration: none;
font-size: 1.2rem;
}
.grid-buttons{
margin-bottom: 3%;
display: flex;
flex-direction: column;
justify-content: center;
padding: 2%
}
.grid-buttons > button{
margin-bottom: 30%;
}
.grid-generation{
color: rgb(58,123,192);
font-size: 1.5rem;
}
.game-lineup{
width: 100%;
display: flex;
justify-content: center;
}
@media only screen and (max-width: 1012px) {
.game-lineup{
display: flex;
flex-direction: column;
}
.grid-buttons > button{
margin-bottom: 2%;
}
.grid-buttons{
flex-direction: row;
}
.app{
column-gap: 1rem;
}
}
/* It is a zero-player game, meaning that its evolution is determined by its initial state, requiring no further input. One interacts with the Game of Life by creating an initial configuration and observing how it evolves. It is Turing complete and can simulate a universal constructor or any other Turing machine. */
/* Tetris is a tile-matching video game created by Russian software engineer Alexey Pajitnov in 1984. It has been published by several companies, most prominently during a dispute over the appropriation of the game's rights in the late 1980s. */ | 21.481481 | 319 | 0.616379 |
6b230dc3dcc5ebc264b105865b8dea34e0c23de6 | 4,574 | lua | Lua | misc/freeswitch/scripts/dialplan/ivr.lua | amooma/GS5 | acef44a7f28df0274b52a77f3a1d4c9f418d3c63 | [
"MIT"
] | 14 | 2015-01-07T10:20:22.000Z | 2020-02-19T13:35:26.000Z | misc/freeswitch/scripts/dialplan/ivr.lua | tpizzle/GS5 | acef44a7f28df0274b52a77f3a1d4c9f418d3c63 | [
"MIT"
] | 3 | 2015-07-22T04:35:10.000Z | 2021-02-20T14:07:27.000Z | misc/freeswitch/scripts/dialplan/ivr.lua | tpizzle/GS5 | acef44a7f28df0274b52a77f3a1d4c9f418d3c63 | [
"MIT"
] | 20 | 2015-04-08T07:23:21.000Z | 2021-09-11T09:05:38.000Z | -- Gemeinschaft 5 module: ivr class
-- (c) AMOOMA GmbH 2013
--
module(...,package.seeall)
Ivr = {}
-- create ivr ivr ;)
function Ivr.new(self, arg)
arg = arg or {}
ivr = arg.ivr or {}
setmetatable(ivr, self);
self.__index = self;
self.class = 'ivr';
self.log = arg.log;
self.caller = arg.caller;
self.dtmf_threshold = arg.dtmf_threshold or 500;
return ivr;
end
function Ivr.ivr_break(self)
return self.exit or not self.caller:ready();
end
function Ivr.ivr_phrase(self, phrase, keys, timeout, ivr_repeat, phrase_data)
ivr_repeat = ivr_repeat or 3;
timeout = timeout or 30;
self.digit = '';
self.exit = false;
self.break_keys = {};
local query_keys = {};
for index=1, #keys do
if type(keys[index]) == 'table' then
if tostring(keys[index].key) ~= '' then
table.insert(query_keys, keys[index].key);
end
self.break_keys[keys[index].key] = keys[index];
else
if tostring(keys[index]) ~= '' then
table.insert(query_keys, keys[index]);
end
self.break_keys[keys[index]] = true;
end
end
global_callback:callback('dtmf', 'ivr_ivr_phrase', self.ivr_phrase_dtmf, self);
local continue = true;
for index=0, ivr_repeat do
continue = self:ivr_break() or self.caller.session:sayPhrase(phrase, phrase_data or table.concat(query_keys, ':'));
continue = self:ivr_break() or self.caller:sleep(timeout * 1000);
if self:ivr_break() then
break;
end
end
global_callback:callback_unset('dtmf', 'ivr_ivr_phrase');
if type(self.break_keys[self.digit]) == 'table' then
return self.digit, self.break_keys[self.digit];
end
return self.digit;
end
function Ivr.ivr_phrase_dtmf(self, dtmf)
if self.break_keys[dtmf.digit] then
self.digit = dtmf.digit;
self.exit = true;
return false;
end
end
function Ivr.read_phrase(self, phrase, phrase_data, max_keys, min_keys, timeout, key_terminator)
self.max_keys = max_keys or 64;
self.min_keys = min_keys or 1;
self.key_terminator = key_terminator or '#';
self.digits = '';
self.exit = false;
timeout = timeout or 30;
global_callback:callback('dtmf', 'ivr_read_phrase', self.read_phrase_dtmf, self);
local continue = self:ivr_break() or self.caller.session:sayPhrase(phrase, phrase_data or key_terminator or '');
continue = self:ivr_break() or self.caller:sleep(timeout * 1000);
global_callback:callback_unset('dtmf', 'ivr_read_phrase');
return self.digits;
end
function Ivr.read_phrase_dtmf(self, dtmf)
if dtmf.duration < self.dtmf_threshold then
return nil;
end
if self.key_terminator == dtmf.digit then
self.exit = true;
return false;
end
self.digits = self.digits .. dtmf.digit;
end
function Ivr.check_pin(self, phrase_enter, phrase_incorrect, pin, pin_timeout, pin_repeat, key_terminator)
if not pin then
return nil;
end
self.exit = false;
pin_timeout = pin_timeout or 30;
pin_repeat = pin_repeat or 3;
key_terminator = key_terminator or '#';
local digits = '';
for i = 1, pin_repeat do
if digits == pin then
self.caller:send_display('PIN: OK');
break;
elseif digits ~= "" then
self.caller:send_display('PIN: wrong');
self.caller.session:sayPhrase(phrase_incorrect, '');
elseif self:ivr_break() then
break;
end
self.caller:send_display('Enter PIN');
digits = ivr:read_phrase(phrase_enter, nil, 0, pin:len() + 1, pin_timeout, key_terminator);
end
if digits ~= pin then
self.caller:send_display('PIN: wrong');
self.caller.session:sayPhrase(phrase_incorrect, '');
return false
end
self.caller:send_display('PIN: OK');
return true;
end
function Ivr.record(self, file_name, beep, phrase_record, phrase_too_short, record_length_max, record_length_min, record_repeat, silence_level, silence_lenght_abort)
local duration = nil;
for index=1, record_repeat do
if (duration and duration >= record_length_min) or not self.caller:ready() then
break;
elseif duration then
self.caller:send_display('Recording too short');
if phrase_too_short then
self.caller.session:sayPhrase(phrase_too_short);
end
end
if phrase_record then
self.caller.session:sayPhrase(phrase_record);
end
if beep then
self.caller:playback(beep);
end
self.caller:send_display('Recording...');
local result = self.caller.session:recordFile(file_name, record_length_max, silence_level, silence_lenght_abort);
duration = self.caller:to_i('record_seconds');
end
return duration or 0;
end
| 26.439306 | 165 | 0.691736 |
fd75b92d6a48ae3d56e0763c795d973d2121b99a | 57 | h | C | include/task.h | himaaaatti/himawari_server | 92da990ff991a3c6960409689afb8df7d81fc7db | [
"MIT"
] | null | null | null | include/task.h | himaaaatti/himawari_server | 92da990ff991a3c6960409689afb8df7d81fc7db | [
"MIT"
] | null | null | null | include/task.h | himaaaatti/himawari_server | 92da990ff991a3c6960409689afb8df7d81fc7db | [
"MIT"
] | null | null | null | #pragma once
#include <stdint.h>
#include <task_call.h>
| 11.4 | 22 | 0.719298 |
264f24949d386f3bc109e4cc8071940701f91baf | 13,168 | java | Java | src/main/scala/org/maltparserx/parser/guide/decision/BranchedDecisionModel.java | chrisx/processors | 98a28532d68f8c1cb643936b40d3f96c98c0940a | [
"Apache-2.0"
] | null | null | null | src/main/scala/org/maltparserx/parser/guide/decision/BranchedDecisionModel.java | chrisx/processors | 98a28532d68f8c1cb643936b40d3f96c98c0940a | [
"Apache-2.0"
] | null | null | null | src/main/scala/org/maltparserx/parser/guide/decision/BranchedDecisionModel.java | chrisx/processors | 98a28532d68f8c1cb643936b40d3f96c98c0940a | [
"Apache-2.0"
] | null | null | null | package org.maltparserx.parser.guide.decision;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import org.maltparserx.core.exception.MaltChainedException;
import org.maltparserx.core.feature.FeatureModel;
import org.maltparserx.core.feature.FeatureVector;
import org.maltparserx.core.helper.HashMap;
import org.maltparserx.core.syntaxgraph.DependencyStructure;
import org.maltparserx.parser.DependencyParserConfig;
import org.maltparserx.parser.guide.ClassifierGuide;
import org.maltparserx.parser.guide.GuideException;
import org.maltparserx.parser.guide.instance.AtomicModel;
import org.maltparserx.parser.guide.instance.FeatureDivideModel;
import org.maltparserx.parser.guide.instance.InstanceModel;
import org.maltparserx.parser.history.action.GuideDecision;
import org.maltparserx.parser.history.action.MultipleDecision;
import org.maltparserx.parser.history.action.SingleDecision;
import org.maltparserx.parser.history.container.TableContainer.RelationToNextDecision;
/**
*
* @author Johan Hall
* @since 1.1
**/
public class BranchedDecisionModel implements DecisionModel {
private ClassifierGuide guide;
private String modelName;
private FeatureModel featureModel;
private InstanceModel instanceModel;
private int decisionIndex;
private DecisionModel parentDecisionModel;
private HashMap<Integer,DecisionModel> children;
private String branchedDecisionSymbols;
public BranchedDecisionModel(ClassifierGuide guide, FeatureModel featureModel) throws MaltChainedException {
this.branchedDecisionSymbols = "";
setGuide(guide);
setFeatureModel(featureModel);
setDecisionIndex(0);
setModelName("bdm"+decisionIndex);
setParentDecisionModel(null);
}
public BranchedDecisionModel(ClassifierGuide guide, DecisionModel parentDecisionModel, String branchedDecisionSymbol) throws MaltChainedException {
if (branchedDecisionSymbol != null && branchedDecisionSymbol.length() > 0) {
this.branchedDecisionSymbols = branchedDecisionSymbol;
} else {
this.branchedDecisionSymbols = "";
}
setGuide(guide);
setParentDecisionModel(parentDecisionModel);
setDecisionIndex(parentDecisionModel.getDecisionIndex() + 1);
setFeatureModel(parentDecisionModel.getFeatureModel());
if (branchedDecisionSymbols != null && branchedDecisionSymbols.length() > 0) {
setModelName("bdm"+decisionIndex+branchedDecisionSymbols);
} else {
setModelName("bdm"+decisionIndex);
}
this.parentDecisionModel = parentDecisionModel;
}
public void updateFeatureModel() throws MaltChainedException {
featureModel.update();
}
// public void updateCardinality() throws MaltChainedException {
// featureModel.updateCardinality();
// }
public void finalizeSentence(DependencyStructure dependencyGraph) throws MaltChainedException {
if (instanceModel != null) {
instanceModel.finalizeSentence(dependencyGraph);
}
if (children != null) {
for (DecisionModel child : children.values()) {
child.finalizeSentence(dependencyGraph);
}
}
}
public void noMoreInstances() throws MaltChainedException {
if (guide.getGuideMode() == ClassifierGuide.GuideMode.CLASSIFY) {
throw new GuideException("The decision model could not create it's model. ");
}
if (instanceModel != null) {
instanceModel.noMoreInstances();
instanceModel.train();
}
if (children != null) {
for (DecisionModel child : children.values()) {
child.noMoreInstances();
}
}
}
public void terminate() throws MaltChainedException {
if (instanceModel != null) {
instanceModel.terminate();
instanceModel = null;
}
if (children != null) {
for (DecisionModel child : children.values()) {
child.terminate();
}
}
}
public void addInstance(GuideDecision decision) throws MaltChainedException {
if (decision instanceof SingleDecision) {
throw new GuideException("A branched decision model expect more than one decisions. ");
}
featureModel.update();
final SingleDecision singleDecision = ((MultipleDecision)decision).getSingleDecision(decisionIndex);
if (instanceModel == null) {
initInstanceModel(singleDecision.getTableContainer().getTableContainerName());
}
instanceModel.addInstance(singleDecision);
if (decisionIndex+1 < decision.numberOfDecisions()) {
if (singleDecision.continueWithNextDecision()) {
if (children == null) {
children = new HashMap<Integer,DecisionModel>();
}
DecisionModel child = children.get(singleDecision.getDecisionCode());
if (child == null) {
child = initChildDecisionModel(((MultipleDecision)decision).getSingleDecision(decisionIndex+1),
branchedDecisionSymbols+(branchedDecisionSymbols.length() == 0?"":"_")+singleDecision.getDecisionSymbol());
children.put(singleDecision.getDecisionCode(), child);
}
child.addInstance(decision);
}
}
}
public boolean predict(GuideDecision decision) throws MaltChainedException {
// if (decision instanceof SingleDecision) {
// throw new GuideException("A branched decision model expect more than one decisions. ");
// }
featureModel.update();
final SingleDecision singleDecision = ((MultipleDecision)decision).getSingleDecision(decisionIndex);
if (instanceModel == null) {
initInstanceModel(singleDecision.getTableContainer().getTableContainerName());
}
instanceModel.predict(singleDecision);
if (decisionIndex+1 < decision.numberOfDecisions()) {
if (singleDecision.continueWithNextDecision()) {
if (children == null) {
children = new HashMap<Integer,DecisionModel>();
}
DecisionModel child = children.get(singleDecision.getDecisionCode());
if (child == null) {
child = initChildDecisionModel(((MultipleDecision)decision).getSingleDecision(decisionIndex+1),
branchedDecisionSymbols+(branchedDecisionSymbols.length() == 0?"":"_")+singleDecision.getDecisionSymbol());
children.put(singleDecision.getDecisionCode(), child);
}
child.predict(decision);
}
}
return true;
}
public FeatureVector predictExtract(GuideDecision decision) throws MaltChainedException {
if (decision instanceof SingleDecision) {
throw new GuideException("A branched decision model expect more than one decisions. ");
}
featureModel.update();
final SingleDecision singleDecision = ((MultipleDecision)decision).getSingleDecision(decisionIndex);
if (instanceModel == null) {
initInstanceModel(singleDecision.getTableContainer().getTableContainerName());
}
FeatureVector fv = instanceModel.predictExtract(singleDecision);
if (decisionIndex+1 < decision.numberOfDecisions()) {
if (singleDecision.continueWithNextDecision()) {
if (children == null) {
children = new HashMap<Integer,DecisionModel>();
}
DecisionModel child = children.get(singleDecision.getDecisionCode());
if (child == null) {
child = initChildDecisionModel(((MultipleDecision)decision).getSingleDecision(decisionIndex+1),
branchedDecisionSymbols+(branchedDecisionSymbols.length() == 0?"":"_")+singleDecision.getDecisionSymbol());
children.put(singleDecision.getDecisionCode(), child);
}
child.predictExtract(decision);
}
}
return fv;
}
public FeatureVector extract() throws MaltChainedException {
featureModel.update();
return instanceModel.extract(); // TODO handle many feature vectors
}
public boolean predictFromKBestList(GuideDecision decision) throws MaltChainedException {
if (decision instanceof SingleDecision) {
throw new GuideException("A branched decision model expect more than one decisions. ");
}
boolean success = false;
final SingleDecision singleDecision = ((MultipleDecision)decision).getSingleDecision(decisionIndex);
if (decisionIndex+1 < decision.numberOfDecisions()) {
if (singleDecision.continueWithNextDecision()) {
if (children == null) {
children = new HashMap<Integer,DecisionModel>();
}
DecisionModel child = children.get(singleDecision.getDecisionCode());
if (child != null) {
success = child.predictFromKBestList(decision);
}
}
}
if (!success) {
success = singleDecision.updateFromKBestList();
if (decisionIndex+1 < decision.numberOfDecisions()) {
if (singleDecision.continueWithNextDecision()) {
if (children == null) {
children = new HashMap<Integer,DecisionModel>();
}
DecisionModel child = children.get(singleDecision.getDecisionCode());
if (child == null) {
child = initChildDecisionModel(((MultipleDecision)decision).getSingleDecision(decisionIndex+1),
branchedDecisionSymbols+(branchedDecisionSymbols.length() == 0?"":"_")+singleDecision.getDecisionSymbol());
children.put(singleDecision.getDecisionCode(), child);
}
child.predict(decision);
}
}
}
return success;
}
public ClassifierGuide getGuide() {
return guide;
}
public String getModelName() {
return modelName;
}
public FeatureModel getFeatureModel() {
return featureModel;
}
public int getDecisionIndex() {
return decisionIndex;
}
public DecisionModel getParentDecisionModel() {
return parentDecisionModel;
}
private void setFeatureModel(FeatureModel featureModel) {
this.featureModel = featureModel;
}
private void setDecisionIndex(int decisionIndex) {
this.decisionIndex = decisionIndex;
}
private void setParentDecisionModel(DecisionModel parentDecisionModel) {
this.parentDecisionModel = parentDecisionModel;
}
private void setModelName(String modelName) {
this.modelName = modelName;
}
private void setGuide(ClassifierGuide guide) {
this.guide = guide;
}
private DecisionModel initChildDecisionModel(SingleDecision decision, String branchedDecisionSymbol) throws MaltChainedException {
Class<?> decisionModelClass = null;
if (decision.getRelationToNextDecision() == RelationToNextDecision.SEQUANTIAL) {
decisionModelClass = org.maltparserx.parser.guide.decision.SeqDecisionModel.class;
} else if (decision.getRelationToNextDecision() == RelationToNextDecision.BRANCHED) {
decisionModelClass = org.maltparserx.parser.guide.decision.BranchedDecisionModel.class;
} else if (decision.getRelationToNextDecision() == RelationToNextDecision.NONE) {
decisionModelClass = org.maltparserx.parser.guide.decision.OneDecisionModel.class;
}
if (decisionModelClass == null) {
throw new GuideException("Could not find an appropriate decision model for the relation to the next decision");
}
try {
Class<?>[] argTypes = { org.maltparserx.parser.guide.ClassifierGuide.class, org.maltparserx.parser.guide.decision.DecisionModel.class,
java.lang.String.class };
Object[] arguments = new Object[3];
arguments[0] = getGuide();
arguments[1] = this;
arguments[2] = branchedDecisionSymbol;
Constructor<?> constructor = decisionModelClass.getConstructor(argTypes);
return (DecisionModel)constructor.newInstance(arguments);
} catch (NoSuchMethodException e) {
throw new GuideException("The decision model class '"+decisionModelClass.getName()+"' cannot be initialized. ", e);
} catch (InstantiationException e) {
throw new GuideException("The decision model class '"+decisionModelClass.getName()+"' cannot be initialized. ", e);
} catch (IllegalAccessException e) {
throw new GuideException("The decision model class '"+decisionModelClass.getName()+"' cannot be initialized. ", e);
} catch (InvocationTargetException e) {
throw new GuideException("The decision model class '"+decisionModelClass.getName()+"' cannot be initialized. ", e);
}
}
private void initInstanceModel(String subModelName) throws MaltChainedException {
FeatureVector fv = featureModel.getFeatureVector(branchedDecisionSymbols+"."+subModelName);
if (fv == null) {
fv = featureModel.getFeatureVector(subModelName);
}
if (fv == null) {
fv = featureModel.getMainFeatureVector();
}
DependencyParserConfig c = guide.getConfiguration();
// if (c.getOptionValue("guide", "tree_automatic_split_order").toString().equals("yes") ||
// (c.getOptionValue("guide", "tree_split_columns")!=null &&
// c.getOptionValue("guide", "tree_split_columns").toString().length() > 0) ||
// (c.getOptionValue("guide", "tree_split_structures")!=null &&
// c.getOptionValue("guide", "tree_split_structures").toString().length() > 0)) {
// instanceModel = new DecisionTreeModel(fv, this);
// }else
if (c.getOptionValue("guide", "data_split_column").toString().length() == 0) {
instanceModel = new AtomicModel(-1, fv, this);
} else {
instanceModel = new FeatureDivideModel(fv, this);
}
}
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append(modelName + ", ");
for (DecisionModel model : children.values()) {
sb.append(model.toString() + ", ");
}
return sb.toString();
}
}
| 37.83908 | 149 | 0.727825 |
043f710e2caffa8e57e81fa1e2193ede3a8a7c8b | 5,847 | java | Java | mlkit/app/src/main/java/com/google/firebase/example/mlkit/ImageLabelingActivity.java | jlara310/snippets-android | d9b18a31c9f7df33726024aeb6825daf22011954 | [
"Apache-2.0"
] | null | null | null | mlkit/app/src/main/java/com/google/firebase/example/mlkit/ImageLabelingActivity.java | jlara310/snippets-android | d9b18a31c9f7df33726024aeb6825daf22011954 | [
"Apache-2.0"
] | null | null | null | mlkit/app/src/main/java/com/google/firebase/example/mlkit/ImageLabelingActivity.java | jlara310/snippets-android | d9b18a31c9f7df33726024aeb6825daf22011954 | [
"Apache-2.0"
] | null | null | null | package com.google.firebase.example.mlkit;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.ml.vision.FirebaseVision;
import com.google.firebase.ml.vision.cloud.FirebaseVisionCloudDetectorOptions;
import com.google.firebase.ml.vision.common.FirebaseVisionImage;
import com.google.firebase.ml.vision.label.FirebaseVisionImageLabel;
import com.google.firebase.ml.vision.label.FirebaseVisionImageLabeler;
import com.google.firebase.ml.vision.label.FirebaseVisionOnDeviceImageLabelerOptions;
import java.util.List;
public class ImageLabelingActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
private void labelImages(FirebaseVisionImage image) {
// [START set_detector_options]
FirebaseVisionOnDeviceImageLabelerOptions options =
new FirebaseVisionOnDeviceImageLabelerOptions.Builder()
.setConfidenceThreshold(0.8f)
.build();
// [END set_detector_options]
// [START get_detector_default]
FirebaseVisionImageLabeler detector = FirebaseVision.getInstance()
.getOnDeviceImageLabeler();
// [END get_detector_default]
/*
// [START get_detector_options]
// Or, to set the minimum confidence required:
FirebaseVisionImageLabeled detector = FirebaseVision.getInstance()
.getOnDeviceImageLabeler(options);
// [END get_detector_options]
*/
// [START run_detector]
Task<List<FirebaseVisionImageLabel>> result =
detector.processImage(image)
.addOnSuccessListener(
new OnSuccessListener<List<FirebaseVisionImageLabel>>() {
@Override
public void onSuccess(List<FirebaseVisionImageLabel> labels) {
// Task completed successfully
// [START_EXCLUDE]
// [START get_labels]
for (FirebaseVisionImageLabel label: labels) {
String text = label.getText();
String entityId = label.getEntityId();
float confidence = label.getConfidence();
}
// [END get_labels]
// [END_EXCLUDE]
}
})
.addOnFailureListener(
new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
// Task failed with an exception
// ...
}
});
// [END run_detector]
}
private void labelImagesCloud(FirebaseVisionImage image) {
// [START set_detector_options_cloud]
FirebaseVisionCloudDetectorOptions options = new FirebaseVisionCloudDetectorOptions.Builder()
.setModelType(FirebaseVisionCloudDetectorOptions.LATEST_MODEL)
.setMaxResults(30)
.build();
// [END set_detector_options_cloud]
// [START get_detector_cloud]
FirebaseVisionImageLabeler detector = FirebaseVision.getInstance()
.getCloudImageLabeler();
// Or, to change the default settings:
// FirebaseVisionImageLabeler detector = FirebaseVision.getInstance()
// .getCloudImageLabeler(options);
// [END get_detector_cloud]
// [START run_detector_cloud]
Task<List<FirebaseVisionImageLabel>> result =
detector.processImage(image)
.addOnSuccessListener(
new OnSuccessListener<List<FirebaseVisionImageLabel>>() {
@Override
public void onSuccess(List<FirebaseVisionImageLabel> labels) {
// Task completed successfully
// [START_EXCLUDE]
// [START get_labels_cloud]
for (FirebaseVisionImageLabel label : labels) {
String text = label.getText();
String entityId = label.getEntityId();
float confidence = label.getConfidence();
}
// [END get_labels_cloud]
// [END_EXCLUDE]
}
})
.addOnFailureListener(
new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
// Task failed with an exception
// ...
}
});
// [END run_detector_cloud]
}
}
| 47.153226 | 101 | 0.499059 |
09b9c9e852177ed11538e82d8aa9b3ff8014c121 | 2,659 | lua | Lua | src/inventory/ItemStack.lua | rm-code/On-The-Roadside | e4017d8a272a6bf9a78d5290bdfcad9a214f6f53 | [
"MIT"
] | 30 | 2016-09-14T14:00:25.000Z | 2021-09-29T13:28:37.000Z | src/inventory/ItemStack.lua | rm-code/On-The-Roadside | e4017d8a272a6bf9a78d5290bdfcad9a214f6f53 | [
"MIT"
] | 128 | 2016-07-31T00:50:35.000Z | 2019-05-05T20:32:09.000Z | src/inventory/ItemStack.lua | rm-code/Hoost | e4017d8a272a6bf9a78d5290bdfcad9a214f6f53 | [
"MIT"
] | 2 | 2016-09-21T14:55:05.000Z | 2016-11-29T12:10:05.000Z | ---
-- @module ItemStack
--
-- ------------------------------------------------
-- Required Modules
-- ------------------------------------------------
local Class = require( 'lib.Middleclass' )
-- ------------------------------------------------
-- Module
-- ------------------------------------------------
local ItemStack = Class( 'ItemStack' )
-- ------------------------------------------------
-- Public Methods
-- ------------------------------------------------
function ItemStack:initialize( id )
if not id or type( id ) ~= 'string' then
error( 'Expected a parameter of type "string".' )
end
self.id = id
self.items = {}
end
function ItemStack:addItem( item )
assert( item:getID() == self.id, 'ID doesn\'t fit the stack' )
self.items[#self.items + 1] = item
return true
end
function ItemStack:removeItem( item )
for i = 1, #self.items do
if self.items[i] == item then
table.remove( self.items, i )
return true
end
end
return false
end
function ItemStack:getWeight()
local weight = 0
for i = 1, #self.items do
weight = weight + self.items[i]:getWeight()
end
return weight
end
function ItemStack:getVolume()
local volume = 0
for i = 1, #self.items do
volume = volume + self.items[i]:getVolume()
end
return volume
end
function ItemStack:split()
if #self.items > 1 then
local count = math.floor( #self.items * 0.5 )
local newStack = ItemStack( self.id )
for i = 1, count do
newStack:addItem( self.items[i] )
self:removeItem( self.items[i] )
end
return newStack
end
return self
end
function ItemStack:serialize()
local t = {
['ItemStack'] = true,
['id'] = self.id,
['items'] = {}
}
for i = 1, #self.items do
t['items'][i] = self.items[i]:serialize()
end
return t
end
function ItemStack:isSameType( itemType, subType )
return self.items[#self.items]:isSameType( itemType, subType )
end
function ItemStack:getItem()
return self.items[#self.items]
end
function ItemStack:getItems()
return self.items
end
function ItemStack:getItemType()
return self.items[#self.items]:getItemType()
end
function ItemStack:getSubType()
return self.items[#self.items]:getSubType()
end
function ItemStack:getDescriptionID()
return self.items[#self.items]:getDescriptionID()
end
function ItemStack:getID()
return self.id
end
function ItemStack:getItemCount()
return #self.items
end
function ItemStack:isEmpty()
return #self.items == 0
end
return ItemStack
| 21.443548 | 66 | 0.559233 |
6815e6596b1fd2500a9b02f123bb4a81f39c1bf7 | 23,232 | html | HTML | publications.html | shamsimam/shamsimam.github.io | 21c83f5849316b690fc961226df3c63437d51dda | [
"CC-BY-3.0"
] | null | null | null | publications.html | shamsimam/shamsimam.github.io | 21c83f5849316b690fc961226df3c63437d51dda | [
"CC-BY-3.0"
] | null | null | null | publications.html | shamsimam/shamsimam.github.io | 21c83f5849316b690fc961226df3c63437d51dda | [
"CC-BY-3.0"
] | null | null | null | <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!--
Design by Free CSS Templates
http://www.freecsstemplates.org
Released for free under a Creative Commons Attribution 2.5 License
Name : FronzenAge
Description: A two-column, fixed-width template suitable for business sites and blogs.
Version : 1.0
Released : 20071108
-->
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Shams M Imam - Publications</title>
<meta name="keywords" content="shams imam, rice university, habanero-java, habanero-scala, cnc-scala, cnc-python"/>
<meta name="description" content=""/>
<link href="css/style.css" rel="stylesheet" type="text/css" media="screen"/>
<script type="text/javascript" src="js/jquery-1.7.1.min.js"></script>
<!--[if IE]>
<style type="text/css">
#sidebar #calendar {
background-position: 0px 20px;
}
</style>
<![endif]-->
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-35448649-1']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</head>
<body>
<div id="logo">
<h1>Shams Imam</h1>
<h2><a
href="http://www.rice.edu/"><img
src="images/logo.png" alt="Rice University Logo"
title="Rice University"/></a></h2>
</div>
<div id="menu">
<ul>
<li class="first"><a href="index.html" accesskey="1" title="Read About Me">About Me</a></li>
<li><a href="publications.html" class="selected" accesskey="2" title="Publications">Publications</a></li>
<li><a href="cv_resume.html" accesskey="3" title="Resume">Resume</a></li>
<li><a href="contact_me.html" accesskey="4" title="How to contact me?">Contact</a></li>
</ul>
<div id="search">
<form action="http://www.rice.edu/Internet/search/query.php" method="GET"
name="searchform" id="searchform" style="width: 100px; min-width: 200px;">
<fieldset>
<input type="hidden" name="tab" value="Web"/>
<input type="text" name="search" id="s" class="textfield" maxlength="255" size="15" name="searchText"
alt="search engine"/>
<input id="x" type="image" name="imageField" src="images/img10.jpg"/>
</fieldset>
</form>
</div>
</div>
<hr/>
<!-- start page -->
<div id="page">
<!-- start content -->
<div id="content">
<div id="publications" class="post">
<h2 class="title"><a href="#">Publications and Papers</a></h2>
<div class="entry">
<ul>
<li>
<a href="papers/2015-phd-thesis-shams.pdf">Cooperative Execution of Parallel Tasks with Synchronization Constraints</a>.
<b>Shams Imam</b>.
PhD Thesis, (defended) May 2015, (submitted) October 2015.
<span align="right">
<a href="papers/2015-phd-thesis-shams.pdf"><img src="images/icon-pdf.png" alt="link to paper"/></a>
<a href="papers/2015-phd-thesis-shams-slides.pdf"><img src="images/icon-ppt.png" alt="link to slides"/></a>
<a href="papers/2015-phd-thesis-shams.bib"><img src="images/icon-bibtex.png" alt="bibtex entry"/></a>
</span>
</li>
<li>
<a href="http://pppj2015.cs.fit.edu/">HJlib-CL: Reducing the Gap Between the JVM and Accelerators</a>.
Max Grossman, <b>Shams Imam</b>, Vivek Sarkar.
12th International Conference on the Principles and Practice of Programming on the Java Platform (PPPJ'15), September 2015.
<span align="right">
<a href="https://wiki.rice.edu/confluence/download/attachments/4425835/PPPJ2015_Grossman.pdf?version=1&modificationDate=1440159863431&api=v2"><img src="images/icon-pdf.png" alt="link to paper"/></a>
</span>
</li>
<li>
<a href="http://www.europar2015.org/program.html">A Composable Deadlock-free Approach to Object-based Isolation</a>.
<b>Shams Imam</b>, Jisheng Zhao, Vivek Sarkar.
21st International European Conference on Parallel and Distributed Computing (Euro-Par'15), August 2015.
<span align="right">
<a href="papers/2015-europar-object-isolation.pdf"><img src="images/icon-pdf.png" alt="link to paper"/></a>
</span>
</li>
<li>
<a href="http://www.europar2015.org/program.html">Load Balancing Prioritized Tasks via Work-Stealing</a>.
<b>Shams Imam</b>, Vivek Sarkar.
21st International European Conference on Parallel and Distributed Computing (Euro-Par'15), August 2015.
<span align="right">
<a href="papers/2015-europar-wst-priority.pdf"><img src="images/icon-pdf.png" alt="link to paper"/></a>
</span>
</li>
<li>
<a href="http://2015.ecoop.org/track/research-track#event-overview">The Eureka Programming Model for Speculative Task Parallelism</a>.
<b>Shams Imam</b>, Vivek Sarkar.
29th European Conference on Object-Oriented Programming (ECOOP), July 2015.
<span align="right">
<a href="papers/2015-ecoop-eureka.pdf"><img src="images/icon-pdf.png" alt="link to paper"/></a>
</span>
</li>
<li>
<a href="http://soft.vub.ac.be/AGERE14/#papers">Selectors: Actors with Multiple Guarded Mailboxes</a>.
<b>Shams Imam</b>, Vivek Sarkar.
4th International Workshop on Programming based on Actors, Agents, and Decentralized Control (AGERE! 2014), October 2014.
<span align="right">
<a href="papers/2014-agere-selector.pdf"><img src="images/icon-pdf.png" alt="link to paper"/></a>
<a href="papers/2014-agere-selector-slides.pdf"><img src="images/icon-ppt.png" alt="link to slides"/></a>
<a href="papers/2014-agere-selector.bib"><img src="images/icon-bibtex.png" alt="bibtex entry"/></a>
</span>
</li>
<li>
<a href="http://soft.vub.ac.be/AGERE14/#papers">Savina - An Actor Benchmark Suite</a>.
<b>Shams Imam</b>, Vivek Sarkar.
4th International Workshop on Programming based on Actors, Agents, and Decentralized Control (AGERE! 2014), October 2014.
<span align="right">
<a href="papers/2014-agere-savina.pdf"><img src="images/icon-pdf.png" alt="link to paper"/></a>
<a href="papers/2014-agere-savina-slides.pdf"><img src="images/icon-ppt.png" alt="link to slides"/></a>
<a href="papers/2014-agere-savina.bib"><img src="images/icon-bibtex.png" alt="bibtex entry"/></a>
</span>
</li>
<li>
<a href="http://2014.splashcon.org/event/splash2014-posters-hj-viz-a-new-tool-for-visualizing-debugging-and-optimizing-parallel-programs">HJ-Viz: A New Tool for Visualizing, Debugging and Optimizing Parallel Programs</a>.
Peter Elmers, Hongyu Li, <b>Shams Imam</b>, Vivek Sarkar.
SPLASH 2014 Poster Session, October 2014. [accepted as poster with accompanying extended abstract].
<span align="right">
<a href="papers/2014-splash-hjviz.pdf"><img src="images/icon-pdf.png" alt="link to paper"/></a>
<!--
<a href="papers/-slides.pdf"><img src="images/icon-ppt.png" alt="link to slides"/></a>
<a href="papers/.bib"><img src="images/icon-bibtex.png" alt="bibtex entry"/></a>
-->
</span>
</li>
<li>
<a href="http://dl.acm.org/citation.cfm?id=2647514">Habanero-Java Library: a Java 8 Framework for Multicore Programming</a>.
<b>Shams Imam</b>, Vivek Sarkar.
11th International Conference on the Principles and Practice of Programming on the Java Platform: virtual machines, languages, and tools (PPPJ'14), September 2014.
<span align="right">
<a href="papers/2014-pppj-hjlib.pdf"><img src="images/icon-pdf.png" alt="link to paper"/></a>
<a href="papers/2014-pppj-hjlib-slides.pdf"><img src="images/icon-ppt.png" alt="link to slides"/></a>
<a href="papers/2014-pppj-hjlib.bib"><img src="images/icon-bibtex.png" alt="bibtex entry"/></a>
</span>
</li>
<li>
<a href="http://link.springer.com/chapter/10.1007/978-3-662-44202-9_25">Cooperative Scheduling of Parallel Tasks with General Synchronization Patterns</a>.
<b>Shams Imam</b>, Vivek Sarkar.
28th European Conference on Object-Oriented Programming (ECOOP), July 2014.
<span align="right">
<a href="papers/2014-ecoop-cooperative-scheduling.pdf"><img src="images/icon-pdf.png" alt="link to paper"/></a>
<a href="papers/2014-ecoop-cooperative-scheduling-slides.pdf"><img src="images/icon-ppt.png" alt="link to slides"/></a>
<a href="papers/2014-ecoop-cooperative-scheduling.bib"><img src="images/icon-bibtex.png" alt="bibtex entry"/></a>
</span>
</li>
<li>
<a href="http://dl.acm.org/citation.cfm?id=2627374&CFID=434602778&CFTOKEN=66234309">Exploiting Implicit Parallelism in Dynamic Array Programming Languages</a>.
<b>Shams Imam</b>, Vivek Sarkar, David Leibs, Peter B. Kessler.
ACM SIGPLAN International Workshop on Libraries, Languages and Compilers for Array Programming (ARRAY '14), June 2014.
<span align="right">
<a href="papers/2014-array-implicit-parallelism-j.pdf"><img src="images/icon-pdf.png" alt="link to paper"/></a>
<a href="papers/2014-array-implicit-parallelism-j-slides.pdf"><img src="images/icon-ppt.png" alt="link to slides"/></a>
<a href="papers/2014-array-implicit-parallelism-j.bib"><img src="images/icon-bibtex.png" alt="bibtex entry"/></a>
</span>
</li>
<li>
<a href="http://x10.sourceforge.net/documentation/papers/X10Workshop2014/x1014-imam.pdf">A Case for Cooperative Scheduling in X10's Managed Runtime</a>.
<b>Shams Imam</b>, Vivek Sarkar.
The 2014 X10 Workshop (X10'14), June 2014.
<span align="right">
<a href="papers/2014-x10-cooperative-scheduling.pdf"><img src="images/icon-pdf.png" alt="link to paper"/></a>
<a href="papers/2014-x10-cooperative-scheduling-slides.pdf"><img src="images/icon-ppt.png" alt="link to slides"/></a>
<a href="papers/2014-x10-cooperative-scheduling.bib"><img src="images/icon-bibtex.png" alt="bibtex entry"/></a>
</span>
</li>
<li>
<a href="http://lampwww.epfl.ch/~hmiller/scala2013/program.html">Implicit Parallelism in a Functional Subset of Scala</a>.
<b>Shams Imam</b>, Robert Cartwright, Vivek Sarkar.
The Fourth Annual Scala Workshop (Scala2013), July 2013.
[accepted as presentation]
<span align="right">
<a href="papers/2013-scala-implicit-parallelism.pdf"><img src="images/icon-pdf.png" alt="link to paper"/></a>
<a href="papers/2013-scala-implicit-parallelism-slides.pdf"><img src="images/icon-ppt.png" alt="link to slides"/></a>
<a href="papers/2013-scala-implicit-parallelism.bib"><img src="images/icon-bibtex.png" alt="bibtex entry"/></a>
</span>
</li>
<li>
<a href="http://dl.acm.org/citation.cfm?id=2384671">Integrating Task Parallelism with Actors</a>.
<b>Shams Imam</b>, Vivek Sarkar.
Conference on Object-Oriented Programming, Systems, Languages, and Applications (OOPSLA), October 2012.
<span align="right">
<a href="papers/2012-oopsla-actors.pdf"><img src="images/icon-pdf.png" alt="link to paper"/></a>
<a href="papers/2012-oopsla-actors-slides.pdf"><img src="images/icon-ppt.png" alt="link to slides"/></a>
<a href="papers/2012-oopsla-actors.bib"><img src="images/icon-bibtex.png" alt="bibtex entry"/></a>
</span>
</li>
<li>
<a href="https://www.usenix.org/conference/hotpar12/cnc-python-multicore-programming-high-productivity">CnC-Python:
Multicore Programming with High Productivity</a>.
<b>Shams Imam</b>, Vivek Sarkar.
4th USENIX Workshop on Hot Topics in Parallelism (HotPar '12), June 2012.
[accepted as poster with accompanying paper]
<span align="right">
<a href="papers/2012-hotpar-cnc-python.pdf"><img src="images/icon-pdf.png" alt="link to paper"/></a>
<a href="papers/2012-hotpar-cnc-python-poster.pdf"><img src="images/icon-ppt.png" alt="link to slides"/></a>
<a href="papers/2012-hotpar-cnc-python.bib"><img src="images/icon-bibtex.png" alt="bibtex entry"/></a>
</span>
</li>
<li>
<a href="https://wiki.rice.edu/confluence/download/attachments/4425835/shams_imam_masters_thesis.pdf?version=1&modificationDate=1341990652748">Habanero-Scala:
A Hybrid Programming model integrating Fork/Join and Actor models</a>.
<b>Shams Imam</b>.
Master's Thesis, May 2012.
<!span align="right">
<a href="papers/2012-thesis-habanero-scala.pdf"><img src="images/icon-pdf.png" alt="link to paper"/></a>
<a href="papers/2012-thesis-habanero-scala-slides.pdf"><img src="images/icon-ppt.png" alt="link to slides"/></a>
<a href="papers/2012-thesis-habanero-scala.bib"><img src="images/icon-bibtex.png" alt="bibtex entry"/></a>
</span>
</li>
<li>
<a href="http://days2012.scala-lang.org/sites/days2012/files/imam_habanero.pdf">Habanero-Scala:
Async-Finish Programming in Scala</a>.
<b>Shams Imam</b>, Vivek Sarkar.
The Third Scala Workshop (Scala Days 2012), April 2012.
<span align="right">
<a href="papers/2012-days-habanero-scala.pdf"><img src="images/icon-pdf.png" alt="link to paper"/></a>
<a href="papers/2012-days-habanero-scala-slides.pdf"><img src="images/icon-ppt.png" alt="link to slides"/></a>
<a href="papers/2012-days-habanero-scala.bib"><img src="images/icon-bibtex.png" alt="bibtex entry"/></a>
</span>
</li>
<li>
<a href="http://pgas11.rice.edu/papers/PrantlEtAl-Chapel-Interoperability-PGAS11.pdf">Interfacing Chapel
with Traditional HPC Programming Languages</a>.
Adrian Prantl, Thomas Epperly, <b>Shams Imam</b>, Vivek Sarkar.
PGAS11 Proceedings, October 2011.
<span align="right">
<a href="papers/2011-pgas-chapel.pdf"><img src="images/icon-pdf.png" alt="link to paper"/></a>
<a href="papers/2011-pgas-chapel.bib"><img src="images/icon-bibtex.png" alt="bibtex entry"/></a>
</span>
</li>
<li>
<a href="http://ieeexplore.ieee.org/xpl/articleDetails.jsp?arnumber=4802980">A Lossless Image
Compression Technique Using Generic Peano Pattern Mask Tree</a>.
Mohammad Kabir Hossain, <b>Shams Imam</b>, K. Shajadul Hasan, William Perrizo.
ICCIT 2008: Proceedings of the 11th International Conference on Computer and Information Technology,
December 2008.
</li>
<li>
<a href="http://ieeexplore.ieee.org/xpl/articleDetails.jsp?arnumber=4133496">Transformations on Images
Stored in Peano Mask Trees</a>.
Mohammad Kabir Hossain, <b>Shams Imam</b>, S. M. Rezaul Hoque.
IEEE INMIC 2005: Proceedings of the 9th International Multitopic Conference, December 2005.
</li>
<li>
<a href="http://shams.web.rice.edu/A New Technique for Lossless Image Compression using PPM-Tree.pdf"
title="A New Technique for Lossless Image Compression using PPM-Tree"
>A New Technique for Lossless Image Compression using PPM-Tree.</a>
<b>Shams Imam</b>, S. M. Rezaul Hoque, Mohammad Kabir Hossain, William Perrizo.
ICCIT 2005: Proceedings of the 8th International Conference on Computer and Information Technology,
December 2005.
</li>
<li>
<a href="http://shams.web.rice.edu/Algorithm for Shifting Images Stored in Peano Mask Trees.pdf"
title="Algorithm for Shifting Images Stored in Peano Mask Trees"
>Algorithm for Shifting Images Stored in Peano Mask Trees.</a>
S. M. Rezaul Hoque, <b>Shams Imam</b>, Mohammad Kabir Hossain, William Perrizo.
ICCIT 2005: Proceedings of the 8th International Conference on Computer and Information Technology,
December 2005.
</li>
</ul>
</div>
<h2 class="title"><a href="#">Talks / Tutorials</a></h2>
<div class="entry">
<ul>
<li>
<a href="https://sites.google.com/site/ppopp2014/home/workshops-and-tutorials">Habanero-Java: Multicore Programming for the Masses</a>.
Symposium on Principles and Practice of Parallel Programming 2014, February 2014.
</li>
<li>
<a href="http://chapel.cray.com/presentations/SC13/03-futures-imam.pdf">Chapel Futures</a>.
Chapel Lightning Talks, SuperComputing 2013, November 2013.
</li>
<li>
<a href="https://www.clear.rice.edu/comp600/2013-fall/smi1.html">Cooperative Scheduling of
Parallel Tasks in the Presence of Synchronization Patterns</a>.
Graduate Research Seminar, Rice University, October 2013.
</li>
<li>
Parallelizing Compressive Sensing MRI via CnC-Babel and Matlab.
The Fourth Annual Concurrent Collections Workshop, December 2012.
Collaborators: Richard Baraniuk, Zoran Budimlic, Michael Burke, Kath Knobe, Vivek Sarkar, Jianing Shi.
</li>
<li>
Adding J into the Alphabet Soup.
End of Internship Tech Talk, Oracle Labs, August 2012.
</li>
<li>
<a href="http://skillsmatter.com/podcast/agile-testing/cnc-scala-multicore-parallelism">CnC-Scala: a
Declarative Approach to Multicore Parallelism</a>.
The Third Scala Workshop (Scala Days 2012), April 2012.
</li>
<li>
<a href="http://cnc11.hpcgarage.org/slides/Imam.pdf">CnC-Babel: a Multi-Language Implementation of the Concurrent Collections Model.</a>
The Third Annual Concurrent Collections Workshop, September 2011.
Collaborators: Adrian Prantl (LLNL), Vivek Sarkar (Rice).
</li>
<li>
<a href="http://www.clear.rice.edu/comp600/2011-fall/shams.html">Interfacing Chapel with traditional HPC
programming languages</a>.
Graduate Research Seminar, Rice University, September 2011.
</li>
</ul>
</div>
</div>
</div>
<!-- end content -->
<!-- start sidebar -->
<div id="sidebar">
<ul>
<li>
<h2>Profile</h2>
<ul>
<li><img src="images/icon-cv.png"/> <a href="http://shams.web.rice.edu/resume.pdf" title="Shams Imam - Resume">Resume</a> (pdf)</li>
<li><img src="images/icon-linkedin.png"/> <a href="http://www.linkedin.com/in/shamsm" title="Shams Imam - LinkedIn Profile">LinkedIn</a></li>
<li><img src="images/icon-google-scholar.png"/> <a href="http://scholar.google.com/citations?user=Pi4tcLAAAAAJ" title="Shams Imam - Google Scholar Profile">Google Scholar</a></li>
</ul>
</li>
<li>
<h2>Projects</h2>
<ul>
<li><a href="http://habanero.rice.edu/hj.html" title="HJ parallel programming language">Habanero-Java</a>
<li><a href="http://wiki.rice.edu/confluence/display/PARPROG/HJ+Library" title="HJ-lib: Pure Java library for parallel programming">Habanero-Java Library</a></li>
<li><a href="http://habanero-scala.rice.edu/" title="HS parallel programming library">Habanero-Scala</a></li>
<li><a href="http://github.com/shamsmahmood/savina" title="Actor Benchmark Suite">Savina</a></li>
<li><a href="http://cnc-scala.rice.edu/" title="Scala implementation of CnC">CnC-Scala</a></li>
<li><a href="http://cnc-python.rice.edu/" title="Python implementation of CnC">CnC-Python</a></li>
<li><a href="http://compose-hpc.sourceforge.net/" title="BRAID Language Interoperability">BRAID</a></li>
</ul>
</li>
</ul>
</div>
<!-- end sidebar -->
<!-- start statcounter -->
<script type="text/javascript">
var sc_project = 7766571;
var sc_invisible = 1;
var sc_security = "9e11e6dc";
</script>
<script type="text/javascript" src="http://www.statcounter.com/counter/counter.js"></script>
<!-- end statcounter-->
</div>
<!-- end page -->
<div id="footer">
<p class="legal">©2015 Rice University. All rights reserved.</p>
<p class="credit">Designed by <a href="http://www.nodethirtythree.com/">NodeThirtyThree</a> + <a
href="http://www.freecsstemplates.org/">Free CSS Templates</a></p>
</div>
</body>
</html>
| 60.976378 | 243 | 0.581913 |
86f63de30d0199ed288d56a61e07d05604e7fdcb | 1,502 | sql | SQL | authorization-server/src/main/resources/data-mysql.sql | nrdio/spring-security-oauth2 | a528177cf3f61f22435a4d111cbaecf082bb2d65 | [
"MIT"
] | 5 | 2019-05-13T19:24:33.000Z | 2019-10-08T13:45:15.000Z | authorization-server/src/main/resources/data-mysql.sql | nrdio/spring-security-oauth2 | a528177cf3f61f22435a4d111cbaecf082bb2d65 | [
"MIT"
] | null | null | null | authorization-server/src/main/resources/data-mysql.sql | nrdio/spring-security-oauth2 | a528177cf3f61f22435a4d111cbaecf082bb2d65 | [
"MIT"
] | 1 | 2019-10-07T13:35:03.000Z | 2019-10-07T13:35:03.000Z | -- 'password'
REPLACE INTO oauth_client_details
(client_id, client_secret, scope, authorized_grant_types,
web_server_redirect_uri, authorities, access_token_validity,
refresh_token_validity, additional_information, autoapprove)
VALUES ('clientx',
'$2a$10$TYaGY7tqqM9kwdBJg9GOresSf/orSMGU5dy.Dmu75ARASx7L0LovG', 'payments,accounts',
'password,authorization_code,refresh_token,client_credentials', 'https://localhost:8080/oauth',
'read,write', 28800, 86400, null, true);
-- empty password
REPLACE INTO oauth_client_details
(client_id, client_secret, scope, authorized_grant_types,
web_server_redirect_uri, authorities, access_token_validity,
refresh_token_validity, additional_information, autoapprove)
VALUES ('clienty',
'$2a$10$OLDOz3q7Cs.cEPH6rUK0u.SkjYbJSB8zgXAEyGiGNKxG1ZKXW5Bgi', 'payments,accounts',
'authorization_code,refresh_token', 'https://localhost:8080/code',
'read,write', 36000, 36000, null, true);
REPLACE INTO users(`username`, `password`, `enabled`)
VALUES ('userx', '$2a$10$TYaGY7tqqM9kwdBJg9GOresSf/orSMGU5dy.Dmu75ARASx7L0LovG', true);
REPLACE INTO users(`username`, `password`, `enabled`)
VALUES ('usery', '$2a$10$TYaGY7tqqM9kwdBJg9GOresSf/orSMGU5dy.Dmu75ARASx7L0LovG', true);
REPLACE INTO authorities (`username`, `authority`)
VALUES ('userx', 'ROLE_ADMIN');
REPLACE INTO authorities (`username`, `authority`)
VALUES ('userx', 'ROLE_USER');
REPLACE INTO authorities (`username`, `authority`)
VALUES ('usery', 'ROLE_ADMIN');
| 46.9375 | 103 | 0.767643 |
88c35af7854e05f021c957deecd8af9f9bd6d5e9 | 2,429 | lua | Lua | crematorfaction/addons/vfire_immolator/lua/effects/vfirethrower_jet2.lua | JohnyReaper/johny-helix-plugins | 34dbf812710d894d2393b84d5bf367f28388dd1d | [
"MIT"
] | 1 | 2020-12-08T16:30:41.000Z | 2020-12-08T16:30:41.000Z | crematorfaction/addons/vfire_immolator/lua/effects/vfirethrower_jet2.lua | JohnyReaper/johny-helix-plugins | 34dbf812710d894d2393b84d5bf367f28388dd1d | [
"MIT"
] | 1 | 2020-09-28T22:01:54.000Z | 2020-09-28T22:01:54.000Z | crematorfaction/addons/vfire_immolator/lua/effects/vfirethrower_jet2.lua | JohnyReaper/johny-helix-plugins | 34dbf812710d894d2393b84d5bf367f28388dd1d | [
"MIT"
] | 4 | 2020-04-18T16:27:28.000Z | 2021-11-19T02:50:04.000Z | function EFFECT:Init(data)
self.wep = data:GetEntity()
self.owner = self.wep:GetOwner()
self:SetRenderOrigin(self.owner:GetPos())
local mins, maxs = self.owner:GetRenderBounds()
self:SetRenderBounds(mins, maxs, Vector(500, 500, 500))
-- Used to determine when to spawn the next clientside fireball
self.lastFireBall = 0
-- Used in the think hook to avoid early dismissals
self.startTime = CurTime()
end
local beamMat = Material("effects/combinemuzzle2_dark")
function EFFECT:Render()
local eyeAngs = self.owner:EyeAngles()
local pos
if GetViewEntity() == owner then
pos = self.wep:GetShootPosition()
else
pos = self.wep:GetShootPosition()
end
local vel = eyeAngs:Forward() * math.Rand(2300, 2700) + eyeAngs:Up() * math.random(200,400)
-- Should we disable the clientside balls assistance for singleplayer, where it's not needed?
if CurTime() > self.lastFireBall then
local lifeTime = math.Rand(0.3, 0.7)
CreateCSVFireBall(10, pos, vel * 0.3415, lifeTime)
self.lastFireBall = CurTime() + 0.01
end
-- Draw a beam
render.SetMaterial(beamMat)
render.DrawBeam(pos, pos + vel * 0.0335, math.Rand(6, 10), math.Rand(0, 1), 1, Color(255, 255, 255, 255))
-- Draw following particles
local pe = ParticleEmitter(pos, false)
local p = pe:Add("effects/combinemuzzle2_dark", pos + vel * 0.003)
p:SetDieTime(0.2)
p:SetVelocity(vel)
p:SetGravity(Vector(0, 0, -1750))
p:SetAirResistance(math.Rand(600, 1000))
p:SetStartAlpha(math.Rand(100, 200))
p:SetEndAlpha(0)
p:SetStartSize(math.Rand(3, 4))
p:SetEndSize(math.Rand(8, 30))
p:SetRoll(math.Rand(0, math.pi))
p:SetRollDelta(math.Rand(-40, 40))
pe:Finish()
-- Draw a light
local dLight = DynamicLight(self.wep:EntIndex())
if dLight then
dLight.Pos = pos
dLight.r = 255
dLight.g = 100
dLight.b = 80
dLight.Brightness = 2
dLight.Decay = 30000
dLight.Size = 250
dLight.DieTime = CurTime() + 0.2
end
end
-- Kill the effect
function EFFECT:Think()
self:SetRenderOrigin(self.owner:GetPos())
local mins, maxs = self.owner:GetRenderBounds()
self:SetRenderBounds(mins, maxs, Vector(500, 500, 500))
if !IsValid(self.wep) or (self.wep:GetClass() != "weapon_vfirethrower" and self.wep:GetClass() != "weapon_crem_immolator") then return false end
if CurTime() < self.startTime + 0.1 then return true end
return self.wep:GetShooting()
end | 30.746835 | 146 | 0.690408 |
e7787bfcad7b80bf46bc3b556d60243717e2b5d2 | 4,403 | kt | Kotlin | src/main/kotlin/net/timafe/letsgo2/web/rest/PlaceResource.kt | tillkuhn/letsgo2 | 62994d7b25eff595dfa1b4144096d8614b81389a | [
"Apache-2.0"
] | null | null | null | src/main/kotlin/net/timafe/letsgo2/web/rest/PlaceResource.kt | tillkuhn/letsgo2 | 62994d7b25eff595dfa1b4144096d8614b81389a | [
"Apache-2.0"
] | null | null | null | src/main/kotlin/net/timafe/letsgo2/web/rest/PlaceResource.kt | tillkuhn/letsgo2 | 62994d7b25eff595dfa1b4144096d8614b81389a | [
"Apache-2.0"
] | null | null | null | package net.timafe.letsgo2.web.rest
import io.github.jhipster.web.util.HeaderUtil
import io.github.jhipster.web.util.ResponseUtil
import net.timafe.letsgo2.domain.Place
import net.timafe.letsgo2.repository.PlaceRepository
import net.timafe.letsgo2.web.rest.errors.BadRequestAlertException
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Value
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.*
import java.net.URI
import java.net.URISyntaxException
import javax.validation.Valid
private const val ENTITY_NAME = "place"
/**
* REST controller for managing [net.timafe.letsgo2.domain.Place].
*/
@RestController
@RequestMapping("/api")
class PlaceResource(
private val placeRepository: PlaceRepository
) {
private val log = LoggerFactory.getLogger(javaClass)
@Value("\${jhipster.clientApp.name}")
private var applicationName: String? = null
/**
* `POST /places` : Create a new place.
*
* @param place the place to create.
* @return the [ResponseEntity] with status `201 (Created)` and with body the new place, or with status `400 (Bad Request)` if the place has already an ID.
* @throws URISyntaxException if the Location URI syntax is incorrect.
*/
@PostMapping("/places")
fun createPlace(@Valid @RequestBody place: Place): ResponseEntity<Place> {
log.debug("REST request to save Place : {}", place)
if (place.id != null) {
throw BadRequestAlertException(
"A new place cannot already have an ID",
ENTITY_NAME, "idexists"
)
}
val result = placeRepository.save(place)
return ResponseEntity.created(URI("/api/places/" + result.id))
.headers(HeaderUtil.createEntityCreationAlert(applicationName, true, ENTITY_NAME, result.id.toString()))
.body(result)
}
/**
* `PUT /places` : Updates an existing place.
*
* @param place the place to update.
* @return the [ResponseEntity] with status `200 (OK)` and with body the updated place,
* or with status `400 (Bad Request)` if the place is not valid,
* or with status `500 (Internal Server Error)` if the place couldn't be updated.
* @throws URISyntaxException if the Location URI syntax is incorrect.
*/
@PutMapping("/places")
fun updatePlace(@Valid @RequestBody place: Place): ResponseEntity<Place> {
log.debug("REST request to update Place : {}", place)
if (place.id == null) {
throw BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull")
}
val result = placeRepository.save(place)
return ResponseEntity.ok()
.headers(
HeaderUtil.createEntityUpdateAlert(
applicationName, true, ENTITY_NAME,
place.id.toString()
)
)
.body(result)
}
/**
* `GET /places` : get all the places.
*
* @return the [ResponseEntity] with status `200 (OK)` and the list of places in body.
*/
@GetMapping("/places")
fun getAllPlaces(): MutableIterable<Place> {
log.debug("REST request to get all Places")
// var p = Place()
return placeRepository.findAll()
}
/**
* `GET /places/:id` : get the "id" place.
*
* @param id the id of the place to retrieve.
* @return the [ResponseEntity] with status `200 (OK)` and with body the place, or with status `404 (Not Found)`.
*/
@GetMapping("/places/{id}")
fun getPlace(@PathVariable id: String): ResponseEntity<Place> {
log.debug("REST request to get Place : {}", id)
val place = placeRepository.findById(id)
return ResponseUtil.wrapOrNotFound(place)
}
/**
* `DELETE /places/:id` : delete the "id" place.
*
* @param id the id of the place to delete.
* @return the [ResponseEntity] with status `204 (NO_CONTENT)`.
*/
@DeleteMapping("/places/{id}")
fun deletePlace(@PathVariable id: String): ResponseEntity<Void> {
log.debug("REST request to delete Place : {}", id)
placeRepository.deleteById(id)
return ResponseEntity.noContent()
.headers(HeaderUtil.createEntityDeletionAlert(applicationName, true, ENTITY_NAME, id.toString())).build()
}
}
| 35.508065 | 159 | 0.645696 |
65e8a8e1fb98bfb1306db990d94e63d40775fc69 | 445 | asm | Assembly | libsrc/msx/msx_vram.asm | dex4er/deb-z88dk | 9ee4f23444fa6f6043462332a1bff7ae20a8504b | [
"ClArtistic"
] | 1 | 2018-09-04T23:07:24.000Z | 2018-09-04T23:07:24.000Z | libsrc/msx/msx_vram.asm | dex4er/deb-z88dk | 9ee4f23444fa6f6043462332a1bff7ae20a8504b | [
"ClArtistic"
] | null | null | null | libsrc/msx/msx_vram.asm | dex4er/deb-z88dk | 9ee4f23444fa6f6043462332a1bff7ae20a8504b | [
"ClArtistic"
] | null | null | null | ;
; MSX specific routines
; by Stefano Bodrato, 29/11/2007
;
; int msx_vram();
;
; Detects the VRAM size (in KB)
;
; $Id: msx_vram.asm,v 1.1 2007/12/03 07:29:40 stefano Exp $
;
XLIB msx_vram
msx_vram:
ld a,(0FAFCh) ; mode
and 00000110b ; extract VRAM size
ld hl,16 ; assume 16K (MSX1)
ret z ; good assumption
cp 00000010b ; 64K?
ld l,64 ; assume so
ret z ; good assumption
add hl,hl ; 128K
ret
| 17.8 | 60 | 0.611236 |
49a3deca249be5ce5999cb137f98b5064cdf03f9 | 92 | html | HTML | framework/views/.errors/404.html | zbzalex-work/regenix | bff2b431299b0509a9df9fa30f313ccc1c723b47 | [
"Apache-2.0"
] | null | null | null | framework/views/.errors/404.html | zbzalex-work/regenix | bff2b431299b0509a9df9fa30f313ccc1c723b47 | [
"Apache-2.0"
] | null | null | null | framework/views/.errors/404.html | zbzalex-work/regenix | bff2b431299b0509a9df9fa30f313ccc1c723b47 | [
"Apache-2.0"
] | null | null | null | {extends '.errors/main'}
{set title: 'Not found', subTitle: 'Not found'}
{$e->getMessage()} | 23 | 47 | 0.652174 |
74c6794646b0ef685d75676bf65dbaeb06c3b07b | 909 | js | JavaScript | utils/generateMarkdown.js | AlvinZC4/Good-README-Generator | 11c78d404ad7709f5b5602d46606b148e137b81e | [
"MIT"
] | null | null | null | utils/generateMarkdown.js | AlvinZC4/Good-README-Generator | 11c78d404ad7709f5b5602d46606b148e137b81e | [
"MIT"
] | null | null | null | utils/generateMarkdown.js | AlvinZC4/Good-README-Generator | 11c78d404ad7709f5b5602d46606b148e137b81e | [
"MIT"
] | null | null | null | // function to generate markdown for README
function generateMarkdown(data, image) {
return `# ${data.title}
${data.description}
${image}
***
## Table of Contents:
1. [How to Install ${data.title}](#Installation)
2. [Using ${data.title}](#How%20To%20Use%20This%20Application)
3. [Testing ${data.title}](#Test%20Code)
4. [Contribution Guidlines](#Contribution%20Guidelines)
5. [Ask Us Questions](#Ask%20Questions)
6. [Licenses](#License)
***
## Installation
${data.install}
## How to Use This Application
${data.usage}
## Test Code
${data.tests}
## Contribution Guidelines
${data.contribute}
## Ask Questions
Visit my GitHub Page: [My GitHub Profile Page](https://github.com/${data.github})
-OR-
Drop me an e-mail at: ${data.questions}
## License
This applicaton is covered under the ${data.license}
`;
}
module.exports = generateMarkdown;
| 17.480769 | 83 | 0.664466 |
386f56574a66b215849aa547efbc2e5e7d811228 | 708 | kt | Kotlin | src/commonTest/kotlin/ModelFactory.kt | TheSaan/minigdx | ca4065239c1d9e1f7f9a4d21f535e7a2f082c65a | [
"MIT"
] | 109 | 2021-04-05T04:00:38.000Z | 2022-03-24T11:54:38.000Z | src/commonTest/kotlin/ModelFactory.kt | TheSaan/minigdx | ca4065239c1d9e1f7f9a4d21f535e7a2f082c65a | [
"MIT"
] | 4 | 2021-05-06T15:24:22.000Z | 2022-02-02T16:55:22.000Z | src/commonTest/kotlin/ModelFactory.kt | TheSaan/minigdx | ca4065239c1d9e1f7f9a4d21f535e7a2f082c65a | [
"MIT"
] | 8 | 2021-04-26T07:51:09.000Z | 2022-02-04T15:24:45.000Z | import com.dwursteisen.minigdx.scene.api.model.Normal
import com.dwursteisen.minigdx.scene.api.model.Position
import com.dwursteisen.minigdx.scene.api.model.Vertex
import com.github.dwursteisen.minigdx.GameContext
import com.github.dwursteisen.minigdx.Resolution
object ModelFactory {
fun vertex(x: Number, y: Number, z: Number, nx: Number = 1f, ny: Number = 1f, nz: Number = 1f): Vertex {
return Vertex(
position = Position(x.toFloat(), y.toFloat(), z.toFloat()),
normal = Normal(nx.toFloat(), ny.toFloat(), nz.toFloat())
)
}
fun gameContext() = GameContext(
MockPlatformContext(createGameConfiguration()),
Resolution(100, 100)
)
}
| 33.714286 | 108 | 0.685028 |
6e9b15151794bac7dca358d59c3f0fa411d6f75d | 771 | kt | Kotlin | zircon.core/src/commonMain/kotlin/org/hexworks/zircon/api/dsl/component/ButtonDsl.kt | falconepl/zircon | 226f7fa88af1cf3092f2c1ac91a9be5a9d2c6203 | [
"Apache-2.0"
] | 708 | 2017-07-09T10:53:52.000Z | 2022-03-27T16:38:10.000Z | zircon.core/src/commonMain/kotlin/org/hexworks/zircon/api/dsl/component/ButtonDsl.kt | falconepl/zircon | 226f7fa88af1cf3092f2c1ac91a9be5a9d2c6203 | [
"Apache-2.0"
] | 351 | 2017-07-10T17:56:42.000Z | 2022-02-13T11:46:33.000Z | zircon.core/src/commonMain/kotlin/org/hexworks/zircon/api/dsl/component/ButtonDsl.kt | falconepl/zircon | 226f7fa88af1cf3092f2c1ac91a9be5a9d2c6203 | [
"Apache-2.0"
] | 233 | 2017-07-10T17:07:49.000Z | 2022-03-15T16:45:33.000Z | package org.hexworks.zircon.api.dsl.component
import org.hexworks.zircon.api.builder.component.ButtonBuilder
import org.hexworks.zircon.api.component.Button
import org.hexworks.zircon.api.component.Container
import org.hexworks.zircon.api.component.builder.base.BaseContainerBuilder
/**
* Creates a new [Button] using the component builder DSL and returns it.
*/
fun buildButton(init: ButtonBuilder.() -> Unit): Button =
ButtonBuilder.newBuilder().apply(init).build()
/**
* Creates a new [Button] using the component builder DSL, adds it to the
* receiver [BaseContainerBuilder] it and returns the [Button].
*/
fun <T : BaseContainerBuilder<*, *>> T.button(
init: ButtonBuilder.() -> Unit
): Button = buildChildFor(this, ButtonBuilder.newBuilder(), init)
| 36.714286 | 74 | 0.758755 |
afca3fb29a9177e0a4a0c1a9e40071ce89b9ab27 | 348 | html | HTML | _includes/directory.html | lee-yunseok/Jekyll-Personal-Website | 09c0265f569e97763fa9faff2268da6ea1cdd7fa | [
"MIT"
] | 2 | 2019-11-09T20:45:44.000Z | 2019-11-12T04:38:24.000Z | _includes/directory.html | lee-yunseok/jekyll-personal-website | 09c0265f569e97763fa9faff2268da6ea1cdd7fa | [
"MIT"
] | null | null | null | _includes/directory.html | lee-yunseok/jekyll-personal-website | 09c0265f569e97763fa9faff2268da6ea1cdd7fa | [
"MIT"
] | null | null | null | <div><h2 {% if site.style == 'dark' %}class="text-white"{% endif %}>{{ page.description }}</h2>
<ul class="posts">
{% for post in page.posts %}
<li>
<span class="post-date">{{ post.date | date: "%b %-d, %Y" }}</span>
<a class="post-link" href="{{ post.url | prepend: site.baseurl }}">{{ post.title }}</a>
</li>
{% endfor %}
</ul>
</div> | 34.8 | 95 | 0.545977 |
fe1121018db2e68427bf54ab46a961c24e6b4cd2 | 889 | asm | Assembly | audio/sfx/cry1e_2.asm | adhi-thirumala/EvoYellow | 6fb1b1d6a1fa84b02e2d982f270887f6c63cdf4c | [
"Unlicense"
] | 16 | 2018-08-28T21:47:01.000Z | 2022-02-20T20:29:59.000Z | audio/sfx/cry1e_2.asm | adhi-thirumala/EvoYellow | 6fb1b1d6a1fa84b02e2d982f270887f6c63cdf4c | [
"Unlicense"
] | 5 | 2019-04-03T19:53:11.000Z | 2022-03-11T22:49:34.000Z | audio/sfx/cry1e_2.asm | adhi-thirumala/EvoYellow | 6fb1b1d6a1fa84b02e2d982f270887f6c63cdf4c | [
"Unlicense"
] | 2 | 2019-12-09T19:46:02.000Z | 2020-12-05T21:36:30.000Z | SFX_Cry1E_2_Ch1:
dutycycle 240
unknownsfx0x20 6, 242, 0, 6
unknownsfx0x20 6, 226, 64, 6
unknownsfx0x20 6, 210, 128, 6
unknownsfx0x20 6, 226, 192, 6
unknownsfx0x20 6, 210, 0, 7
unknownsfx0x20 6, 194, 64, 7
unknownsfx0x20 6, 178, 128, 7
unknownsfx0x20 8, 161, 192, 7
endchannel
SFX_Cry1E_2_Ch2:
dutycycle 17
unknownsfx0x20 3, 8, 1, 0
unknownsfx0x20 6, 194, 193, 5
unknownsfx0x20 6, 178, 2, 6
unknownsfx0x20 6, 162, 65, 6
unknownsfx0x20 6, 178, 130, 6
unknownsfx0x20 6, 162, 194, 6
unknownsfx0x20 6, 146, 1, 7
unknownsfx0x20 6, 162, 66, 7
unknownsfx0x20 8, 129, 129, 7
endchannel
SFX_Cry1E_2_Ch3:
unknownnoise0x20 6, 8, 1
unknownnoise0x20 5, 226, 92
unknownnoise0x20 5, 194, 76
unknownnoise0x20 5, 210, 60
unknownnoise0x20 5, 178, 44
unknownnoise0x20 5, 194, 28
unknownnoise0x20 5, 162, 27
unknownnoise0x20 5, 146, 26
unknownnoise0x20 8, 129, 24
endchannel
| 22.794872 | 30 | 0.732283 |
e75f77bc7f723101e1429451467b3379e45e6375 | 1,849 | js | JavaScript | index.js | sagebind/teto-bot | 535e8a691a3aff80c8091819b3619f057817a5b8 | [
"MIT"
] | null | null | null | index.js | sagebind/teto-bot | 535e8a691a3aff80c8091819b3619f057817a5b8 | [
"MIT"
] | 1 | 2020-12-17T06:20:03.000Z | 2020-12-17T07:27:14.000Z | index.js | sagebind/teto-bot | 535e8a691a3aff80c8091819b3619f057817a5b8 | [
"MIT"
] | null | null | null | const core = require('@actions/core');
const github = require('@actions/github');
// Constants for this particular repo.
const botUser = 'teto-bot';
const botRepo = 'sagebind/teto-bot';
async function main() {
try {
// Extract command
const match = github.context.payload.comment.body.match(`^@${botUser}(?:\\s+(\\S+))?`);
if (!match) {
return;
}
const commandName = match[1];
const token = core.getInput('token');
const octokit = github.getOctokit(token);
let client_payload = {
repository: `${github.context.repo.owner}/${github.context.repo.repo}`,
repository_owner: github.context.repo.owner,
comment: github.context.payload.comment,
issue: github.context.payload.issue,
};
// If this comment is on a pull request, fetch additional info about the pull request.
if (client_payload.issue.pull_request) {
client_payload.pull_request = (await octokit.pulls.get({
repo: github.context.repo.repo,
owner: github.context.repo.owner,
pull_number: github.context.payload.issue.number,
})).data;
}
const [owner, repo] = botRepo.split('/');
await octokit.repos.createDispatchEvent({
owner: owner,
repo: repo,
event_type: commandName + '-command',
client_payload,
});
// Confirm success by reacting to the comment.
await octokit.reactions.createForIssueComment({
owner: github.context.repo.owner,
repo: github.context.repo.repo,
comment_id: github.context.payload.comment.id,
content: '+1',
});
} catch (error) {
core.setFailed(error.message);
}
}
main();
| 31.338983 | 95 | 0.579773 |
fbd26f2fc5c4af49b070ebf2f9b8e1a574bcb64a | 540 | java | Java | javaSE/src/com/joker/reflection/Test2.java | jokerzzccc/sturdy-doodle | 6456ce75883eda2b194fd8c39ed1c2ddb026fbf1 | [
"Apache-2.0"
] | null | null | null | javaSE/src/com/joker/reflection/Test2.java | jokerzzccc/sturdy-doodle | 6456ce75883eda2b194fd8c39ed1c2ddb026fbf1 | [
"Apache-2.0"
] | null | null | null | javaSE/src/com/joker/reflection/Test2.java | jokerzzccc/sturdy-doodle | 6456ce75883eda2b194fd8c39ed1c2ddb026fbf1 | [
"Apache-2.0"
] | null | null | null | package com.joker.reflection;
/**
* 获取 类加载器
*/
public class Test2 {
public static void main(String[] args) {
//获得系统类加载器
ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();
System.out.println(
systemClassLoader
);
//获得系统类加载器的父类,扩展类加载器
ClassLoader parent = systemClassLoader.getParent();
System.out.println(parent);
//获得扩展类加载器的父类,根加载器(c/c++编写)
ClassLoader parent1 = parent.getParent();
System.out.println(parent1);
}
}
| 25.714286 | 75 | 0.618519 |
b008dbde4fdc4547cf9687bf05e9c7cea8761346 | 1,245 | rs | Rust | intercom-attributes/tests/data/ui/comstruct-api.rs | Rantanen/com-export-rs | 4333bc1e58cb121809cc2ee8b2d392a66360815c | [
"MIT"
] | 45 | 2017-11-06T06:27:08.000Z | 2021-12-26T19:54:25.000Z | intercom-attributes/tests/data/ui/comstruct-api.rs | Rantanen/com-export-rs | 4333bc1e58cb121809cc2ee8b2d392a66360815c | [
"MIT"
] | 131 | 2017-12-05T03:18:58.000Z | 2021-11-28T23:16:12.000Z | intercom-attributes/tests/data/ui/comstruct-api.rs | Rantanen/com-export-rs | 4333bc1e58cb121809cc2ee8b2d392a66360815c | [
"MIT"
] | 7 | 2017-12-06T08:38:09.000Z | 2021-03-27T14:47:08.000Z | extern crate intercom;
use intercom::{ComItf, ComRc, ComResult};
#[intercom::com_interface]
pub trait MyInterface
{
fn interface_method(&self) {}
}
#[intercom::com_class(MyStruct, MyInterface)]
pub struct MyStruct;
impl MyInterface for MyStruct
{
fn interface_method(&self) {}
}
#[intercom::com_interface]
impl MyStruct
{
fn struct_method(&self) {}
}
pub fn from_trait_itf(itf: &ComItf<dyn MyInterface>)
{
let _: ComRc<dyn MyInterface> = ComRc::from(itf);
let _: ComRc<dyn MyInterface> = itf.to_owned();
let _: ComResult<ComRc<MyStruct>> = ComItf::query_interface(itf);
}
pub fn from_struct_itf(itf: &ComItf<MyStruct>)
{
let _: ComRc<MyStruct> = ComRc::from(itf);
let _: ComRc<MyStruct> = itf.to_owned();
let _: ComResult<ComRc<dyn MyInterface>> = ComItf::query_interface(itf);
}
pub fn from_struct(s1: intercom::ComBox<MyStruct>, s2: intercom::ComBox<MyStruct>)
{
let _: ComRc<dyn MyInterface> = ComRc::from(s1);
let _: ComRc<MyStruct> = ComRc::from(s2);
}
pub fn from_struct_ref(s: &intercom::ComBox<MyStruct>)
{
let _: ComRc<dyn MyInterface> = ComRc::from(s);
let _: ComRc<MyStruct> = ComRc::from(s);
}
pub fn pass_comrc(rc: ComRc<dyn MyInterface>)
{
from_trait_itf(&rc);
}
| 21.842105 | 82 | 0.688353 |
394acf6b4f78b3530977ac540998ed704d7183a6 | 2,830 | lua | Lua | __hj_bak/hj212/hisdb/utils.lua | freeioe/freeioe_example_apps | c4a13c1ac0b0bb41397e2a916538ae1eb5d10535 | [
"MIT"
] | 6 | 2020-04-10T15:00:23.000Z | 2021-10-02T03:45:11.000Z | __hj_bak/hj212/hisdb/utils.lua | freeioe/freeioe_example_apps | c4a13c1ac0b0bb41397e2a916538ae1eb5d10535 | [
"MIT"
] | 1 | 2021-07-11T07:23:53.000Z | 2021-07-11T07:23:53.000Z | __hj_bak/hj212/hisdb/utils.lua | freeioe/freeioe_example_apps | c4a13c1ac0b0bb41397e2a916538ae1eb5d10535 | [
"MIT"
] | 5 | 2019-06-25T06:55:35.000Z | 2021-08-29T12:45:37.000Z | local date = require 'date'
local _M = {}
local function to_seconds(val)
return math.floor(date.diff(val:toutc(), date(0)):spanseconds())
end
-- Duration Start Time
function _M.duration_base(duration, start)
assert(duration, 'Duration missing')
local now = start and date(start):tolocal() or date(false) -- local time
now:setseconds(0)
now:setminutes(0)
now:sethours(0)
local c, unit = string.match(duration, '^(%d+)(%w+)$')
c = tonumber(c)
unit = string.lower(unit)
if unit == 'd' then
end
if unit == 'm' then
now:setday(1)
end
if unit == 'y' then
now:setday(1)
now:setmonth(1)
end
return to_seconds(now)
end
-- Duration DIV
function _M.duration_div(start_time, end_time, duration)
local c, unit = string.match(duration, '^(%d+)(%w+)$')
c = tonumber(c)
unit = string.lower(unit)
if unit == 'd' then
return date.diff(date(end_time):tolocal(), date(start_time):tolocal()):spandays() / c
end
if unit == 'm' then
local diff = 0
local t = date(start_time):tolocal()
local te = date(end_time):tolocal()
while t:addmonths(c) < te do
diff = diff + 1
end
return diff
end
if unit == 'y' then
local diff = 0
local t = date(start_time)
local te = date(end_time):tolocal()
while t:addyears(c) < te do
diff = diff + 1
end
return diff
end
return nil, 'Invalid duration'
end
--- Duration END Time
function _M.duration_add(start_time, duration)
local c, unit = string.match(duration, '^(%d+)(%w+)$')
c = tonumber(c)
unit = string.lower(unit)
local start = date(start_time):tolocal()
if unit == 'd' then
return to_seconds(start:adddays(c))
end
if unit == 'm' then
return to_seconds(start:addmonths(c))
end
if unit == 'y' then
return to_seconds(start:addyears(c))
end
return nil, 'Invalid duration'
end
function _M.duration_list(start_time, end_time, base, duration)
local c, unit = string.match(duration, '^(%d+)(%w+)$')
c = tonumber(c)
unit = string.lower(unit)
local list = {}
local t = date(base):tolocal()
local ts = date(start_time):tolocal()
local te = date(end_time):tolocal()
if unit == 'd' then
while t <= te do
if t > ts or t:copy():adddays(c) > ts then
list[#list + 1] = to_seconds(t)
end
list[#list + 1] = t
if t:adddays(c) > te then
list[#list + 1] = to_seconds(t)
break
end
end
end
if unit == 'm' then
while t <= te do
if t > ts or t:copy():addmonths(c) > ts then
list[#list + 1] = to_seconds(t)
end
list[#list + 1] = t
if t:adddays(1) > te then
list[#list + 1] = to_seconds(t)
break
end
end
end
if unit == 'y' then
while t <= te do
if t > ts or t:copy():adddays(1) > ts then
list[#list + 1] = to_seconds(t)
end
list[#list + 1] = t
if t:adddays(1) > te then
list[#list + 1] = to_seconds(t)
break
end
end
end
return list
end
return _M
| 21.769231 | 87 | 0.637456 |
5023023f4c4605ac8f5fec4b1c74783c38cd3b44 | 3,351 | go | Go | store/tests/automation_sessions_test.go | tnissen375/corteza-server | 83720d11ff2a94f52813a2fefcd8d20473a89e78 | [
"Apache-2.0"
] | 409 | 2019-06-01T07:12:13.000Z | 2022-03-31T14:41:13.000Z | store/tests/automation_sessions_test.go | tnissen375/corteza-server | 83720d11ff2a94f52813a2fefcd8d20473a89e78 | [
"Apache-2.0"
] | 243 | 2019-06-19T11:46:44.000Z | 2022-03-21T17:12:30.000Z | store/tests/automation_sessions_test.go | tnissen375/corteza-server | 83720d11ff2a94f52813a2fefcd8d20473a89e78 | [
"Apache-2.0"
] | 121 | 2019-06-01T07:12:21.000Z | 2022-03-29T15:16:54.000Z | package tests
import (
"context"
"testing"
"github.com/cortezaproject/corteza-server/automation/types"
"github.com/cortezaproject/corteza-server/pkg/filter"
"github.com/cortezaproject/corteza-server/pkg/id"
"github.com/cortezaproject/corteza-server/store"
_ "github.com/joho/godotenv/autoload"
"github.com/stretchr/testify/require"
)
func testAutomationSessions(t *testing.T, s store.AutomationSessions) {
var (
ctx = context.Background()
req = require.New(t)
makeNew = func(wfID uint64, completed bool) *types.Session {
ses := &types.Session{
ID: id.Next(),
WorkflowID: wfID,
CreatedAt: *now(),
}
if completed {
ses.CompletedAt = now()
}
return ses
}
truncAndCreate = func(t *testing.T) (*require.Assertions, *types.Session) {
req := require.New(t)
req.NoError(s.TruncateAutomationSessions(ctx))
res := makeNew(0, false)
req.NoError(s.CreateAutomationSession(ctx, res))
return req, res
}
)
t.Run("create", func(t *testing.T) {
req := require.New(t)
wf := &types.Session{
ID: id.Next(),
CreatedAt: *now(),
}
req.NoError(s.CreateAutomationSession(ctx, wf))
})
t.Run("lookup by ID", func(t *testing.T) {
req, wf := truncAndCreate(t)
fetched, err := s.LookupAutomationSessionByID(ctx, wf.ID)
req.NoError(err)
req.Equal(wf.ID, fetched.ID)
req.NotNil(fetched.CreatedAt)
})
t.Run("update", func(t *testing.T) {
req, wf := truncAndCreate(t)
wf.Status = types.SessionCompleted
req.NoError(s.UpdateAutomationSession(ctx, wf))
fetched, err := s.LookupAutomationSessionByID(ctx, wf.ID)
req.NoError(err)
req.Equal(wf.ID, fetched.ID)
req.Equal(types.SessionCompleted, fetched.Status)
})
t.Run("delete", func(t *testing.T) {
t.Run("by Session", func(t *testing.T) {
req, wf := truncAndCreate(t)
req.NoError(s.DeleteAutomationSession(ctx, wf))
_, err := s.LookupAutomationSessionByID(ctx, wf.ID)
req.EqualError(err, store.ErrNotFound.Error())
})
t.Run("by ID", func(t *testing.T) {
req, wf := truncAndCreate(t)
req.NoError(s.DeleteAutomationSessionByID(ctx, wf.ID))
_, err := s.LookupAutomationSessionByID(ctx, wf.ID)
req.EqualError(err, store.ErrNotFound.Error())
})
})
t.Run("search", func(t *testing.T) {
prefill := []*types.Session{
makeNew(1001, false),
makeNew(1001, false),
makeNew(1001, false),
makeNew(1001, false),
makeNew(1001, true),
}
count := len(prefill)
prefill[4].CompletedAt = &prefill[4].CreatedAt
valid := count - 1
req.NoError(s.TruncateAutomationSessions(ctx))
req.NoError(s.CreateAutomationSession(ctx, prefill...))
// search for all valid
set, f, err := s.SearchAutomationSessions(ctx, types.SessionFilter{})
req.NoError(err)
req.Len(set, valid) // we've deleted one
// search for ALL
set, f, err = s.SearchAutomationSessions(ctx, types.SessionFilter{Completed: filter.StateInclusive})
req.NoError(err)
req.Len(set, count) // we've deleted one
// search for deleted only
set, f, err = s.SearchAutomationSessions(ctx, types.SessionFilter{Completed: filter.StateExclusive})
req.NoError(err)
req.Len(set, 1) // we've deleted one
// find all prefixed
set, f, err = s.SearchAutomationSessions(ctx, types.SessionFilter{WorkflowID: []uint64{1001}})
req.NoError(err)
req.Len(set, 4)
_ = f // dummy
})
}
| 26.808 | 102 | 0.682184 |
14b0c9a1a6de210a7814347be0ce6c30453c1511 | 918 | swift | Swift | Sources/App/Models/Scheme/PostTag.swift | rb-de0/yubatake | 36585bc5a213d9d88948c5be3b9533ea517bd5ec | [
"MIT"
] | 4 | 2018-08-19T19:16:17.000Z | 2021-03-07T11:56:57.000Z | Sources/App/Models/Scheme/PostTag.swift | rb-de0/yubatake | 36585bc5a213d9d88948c5be3b9533ea517bd5ec | [
"MIT"
] | 34 | 2018-05-26T04:41:17.000Z | 2021-09-27T21:30:37.000Z | Sources/App/Models/Scheme/PostTag.swift | rb-de0/note | 36585bc5a213d9d88948c5be3b9533ea517bd5ec | [
"MIT"
] | null | null | null | import Fluent
import Vapor
final class PostTag: Model {
static let schema = "post_tag"
@ID(custom: .id)
var id: Int?
@Parent(key: "post_id")
var post: Post
@Parent(key: "tag_id")
var tag: Tag
}
struct CreatePostTag: Migration {
func prepare(on database: Database) -> EventLoopFuture<Void> {
database.schema(PostTag.schema)
.field(.id, .int64, .identifier(auto: true))
.field("post_id", .int64, .required)
.field("tag_id", .int64, .required)
.foreignKey("post_id", references: Post.schema, "id", onDelete: .cascade, onUpdate: .restrict)
.foreignKey("tag_id", references: Tag.schema, "id", onDelete: .cascade, onUpdate: .restrict)
.ignoreExisting()
.create()
}
func revert(on database: Database) -> EventLoopFuture<Void> {
database.schema(PostTag.schema).delete()
}
}
| 26.228571 | 106 | 0.606754 |
04b1ec90782950331c0ae9b8d0fc0216796fb7d0 | 2,981 | java | Java | backend/src/MessageParser.java | Heinzen/Filmemotion | 69f1dbff943b829476c7ded2314b771ea3c2dc39 | [
"Apache-2.0"
] | null | null | null | backend/src/MessageParser.java | Heinzen/Filmemotion | 69f1dbff943b829476c7ded2314b771ea3c2dc39 | [
"Apache-2.0"
] | null | null | null | backend/src/MessageParser.java | Heinzen/Filmemotion | 69f1dbff943b829476c7ded2314b771ea3c2dc39 | [
"Apache-2.0"
] | null | null | null | import org.json.JSONArray;
import org.json.JSONObject;
public final class MessageParser {
private MessageParser(){}
private static String requestType;
public static void parseParameters(String input) {
try{
System.out.println("Parsing JSONObject");
System.out.println(input);
JSONObject message = new JSONObject(input);
requestType = message.getString("request-type");
String parameter;
switch(requestType){
case "GET":
parameter = message.getString("parameter");
handleFunctionCalls(parameter, null);
break;
case "POST":
parameter = message.getString("parameter");
if(parameter.equalsIgnoreCase("userid")){
int userId = message.getInt("value");
handleFunctionCalls(parameter,""+userId);
}
else if(parameter.equalsIgnoreCase("userEmotionData")){
JSONArray j = message.getJSONArray("value");
handleFunctionCalls(parameter, j.toString());
}
else if(parameter.equalsIgnoreCase("acceptMovie")){
int acceptedMovieId = message.getInt("value");
handleFunctionCalls(parameter, ""+acceptedMovieId);
}
}
}catch (Exception e){ }
}
private static void handleFunctionCalls(String parameter, String value){
//Request movie posters
if(parameter.equalsIgnoreCase("poster")){
JSONArray posterResponse = MovieFactory.getMoviePosters();
System.out.println(posterResponse.toString());
Context.setResponseMessage(posterResponse.toString());
}
//Requests top movies
else if(parameter.equalsIgnoreCase("topmovies")) {
JSONArray posterResponse = MovieFactory.getTopMovies();
System.out.println(posterResponse.toString());
Context.setResponseMessage(posterResponse.toString());
}
//Sets userID for current session
else if(parameter.equalsIgnoreCase("userId")){
System.out.println("Creating user for ID: "+value);
new UserParser(value, Context.getDampeningFactor());
Context.setResponseMessage(null);
}
//Parses user emotion
else if(parameter.equalsIgnoreCase("userEmotionData")){
UserParser.parseFaceAttributes(value);
UserParser.buildUserDataForMood();
UserParser.selectContent(Context.getTopContentAmount(), Context.getBottomContentAmount());
}
//Accepts movie
else if(parameter.equalsIgnoreCase("acceptMovie")){
UserParser.getGenreForAcceptance(Integer.parseInt(value));
Context.setResponseMessage(null);
}
}
}
| 41.985915 | 102 | 0.585709 |
f05da004efb57fa8123a5d8084bba03a6cd27ce9 | 623 | py | Python | create_tacacs.py | cromulon-actual/ise_automation | de3fbb762c3e1f4f41d81dda3bd2d33a11db1d58 | [
"MIT"
] | null | null | null | create_tacacs.py | cromulon-actual/ise_automation | de3fbb762c3e1f4f41d81dda3bd2d33a11db1d58 | [
"MIT"
] | null | null | null | create_tacacs.py | cromulon-actual/ise_automation | de3fbb762c3e1f4f41d81dda3bd2d33a11db1d58 | [
"MIT"
] | null | null | null | from ciscoisesdk import IdentityServicesEngineAPI
from ciscoisesdk.exceptions import ApiError
from dotenv import load_dotenv
import os
from pprint import pprint as ppr
load_dotenv()
admin = os.getenv("ISE_ADMIN")
pw = os.getenv("ISE_PW")
base_url = os.getenv("ISE_URL")
api = IdentityServicesEngineAPI(
username=admin, password=pw, base_url=base_url, version="3.0.0", verify=False)
print("=" * 50)
# Get Admin Users
search_result = api.admin_user.get_all()
ppr(search_result.response)
print("=" * 50)
# Get All TACACS Users
search_result = api.tacacs_profile.get_all()
ppr(search_result.response)
print("=" * 50)
| 23.074074 | 82 | 0.764045 |
41dc391f18d80ee1167edff17e49571cb926de63 | 237 | dart | Dart | lib/src/Laravel/tableCreate.dart | zeeshux7860/material_x | bbe258ad347edcc2485ba840487b9e3099804014 | [
"Apache-2.0"
] | 7 | 2020-04-25T04:46:53.000Z | 2022-01-04T15:59:39.000Z | lib/src/Laravel/tableCreate.dart | zeeshux7860/material_x | bbe258ad347edcc2485ba840487b9e3099804014 | [
"Apache-2.0"
] | 1 | 2022-01-04T15:59:28.000Z | 2022-01-04T15:59:28.000Z | lib/src/Laravel/tableCreate.dart | zeeshux7860/material_x | bbe258ad347edcc2485ba840487b9e3099804014 | [
"Apache-2.0"
] | null | null | null | import './database_structure.dart';
import './ListLaravel.dart';
String laravelTableCreate(String tableName, List tableColumn) {
var tableList = tableColumn.dblist();
var table = dbStructure(tableName, tableList);
return table;
}
| 26.333333 | 63 | 0.759494 |
d8e186292c4dabc9b7979653ad891d66130ed744 | 2,514 | kt | Kotlin | subprojects/gradle/cd/src/test/kotlin/com/avito/ci/Utils.kt | bugtsa/avito-android | 6ef9f3d70c253e8bf6e1e26c47ee5389fb118e4a | [
"Apache-2.0"
] | null | null | null | subprojects/gradle/cd/src/test/kotlin/com/avito/ci/Utils.kt | bugtsa/avito-android | 6ef9f3d70c253e8bf6e1e26c47ee5389fb118e4a | [
"Apache-2.0"
] | null | null | null | subprojects/gradle/cd/src/test/kotlin/com/avito/ci/Utils.kt | bugtsa/avito-android | 6ef9f3d70c253e8bf6e1e26c47ee5389fb118e4a | [
"Apache-2.0"
] | 1 | 2021-09-30T19:36:44.000Z | 2021-09-30T19:36:44.000Z | package com.avito.ci
import com.avito.test.gradle.TestResult
import com.avito.test.gradle.gradlew
import com.google.common.truth.Truth
import okhttp3.mockwebserver.RecordedRequest
import java.io.File
fun TestResult.assertAffectedModules(taskName: String, expectedModules: Set<String>) {
assertThat().buildSuccessful()
@Suppress("NAME_SHADOWING")
val expectedModules = expectedModules
.map { it.normalizeModuleName() }
.toSet()
val actualModules = output
.split("\n")
.filter { it.contains(":$taskName ") }
.map { it.substringBefore(":$taskName ") }
.toSet()
Truth.assertWithMessage("Task $taskName has executed for modules: $expectedModules")
.that(actualModules)
.containsExactlyElementsIn(expectedModules)
}
fun detectChangedModules(
projectDir: File,
vararg args: String
): TestResult {
return gradlew(projectDir, "generateModulesReport", *args)
}
fun TestResult.assertMarkedModules(
projectDir: File,
implementation: Set<String>,
unitTests: Set<String>,
androidTests: Set<String>
) {
assertModulesInReport(File(projectDir, IMPLEMENTATION_MODULES_REPORT_PATH), implementation)
assertModulesInReport(File(projectDir, UNIT_TEST_MODULES_REPORT_PATH), unitTests)
assertModulesInReport(File(projectDir, ANDROID_TEST_MODULES_REPORT_PATH), androidTests)
}
fun RecordedRequest.bodyContains(body: CharSequence): Boolean {
return this.body.toString().contains(body)
}
@Suppress("NAME_SHADOWING")
private fun TestResult.assertModulesInReport(
report: File,
expectedModules: Set<String>
) {
assertThat().buildSuccessful()
val expectedModules = expectedModules
.map { it.normalizeModuleName() }
.toSet()
val actualModules: Set<String> = report.readReport().toSet()
Truth.assertWithMessage("Changed modules in ${report.name}")
.that(actualModules)
.containsExactlyElementsIn(expectedModules)
}
private fun String.normalizeModuleName() = if (this.startsWith(':')) this else ":$this"
private fun File.readReport(): List<String> = readLines()
.filterNot { it.isBlank() }
.map { it.trim() }
const val KOTLIN_SOURCE_SET = "src/main/kotlin"
const val IMPLEMENTATION_MODULES_REPORT_PATH = "build/reports/modules/implementation-modules.txt"
const val UNIT_TEST_MODULES_REPORT_PATH = "build/reports/modules/unit-tests-modules.txt"
const val ANDROID_TEST_MODULES_REPORT_PATH = "build/reports/modules/android-tests-modules.txt"
| 31.822785 | 97 | 0.736277 |
c44d6d4b9f6b2e0ed01bd304bbc6e894c53f9e77 | 8,106 | asm | Assembly | dino/lc/scene.asm | zengfr/arcade_game_romhacking_sourcecode_top_secret_data | a4a0c86c200241494b3f1834cd0aef8dc02f7683 | [
"Apache-2.0"
] | 6 | 2020-10-14T15:29:10.000Z | 2022-02-12T18:58:54.000Z | dino/lc/scene.asm | zengfr/arcade_game_romhacking_sourcecode_top_secret_data | a4a0c86c200241494b3f1834cd0aef8dc02f7683 | [
"Apache-2.0"
] | null | null | null | dino/lc/scene.asm | zengfr/arcade_game_romhacking_sourcecode_top_secret_data | a4a0c86c200241494b3f1834cd0aef8dc02f7683 | [
"Apache-2.0"
] | 1 | 2020-12-17T08:59:10.000Z | 2020-12-17T08:59:10.000Z | copyright zengfr site:http://github.com/zengfr/romhack
018078 move.b ($4d9,A5), D0
01807C lsl.w #2, D0
01807E moveq #$0, D1
018080 move.b ($786,A5), D1
018084 add.w D1, D0
018086 move.b ($c,PC,D0.w), D1
01808A subq.b #1, D1
;--------
01E3C4 lsl.w #4, D0
01E3C6 lea ($2c,PC,D0.w), A0
01E3CA moveq #$0, D0
01E3CC move.b ($786,A5), D0
01E3D0 lsl.w #2, D0
01E3D2 lea (A0,D0.w), A0
01E3D6 move.w (A0)+, D0
;--------
0AAAC4 move.l #$0, D0
0AAACA move.l (A0), D2
0AAACC move.w D0, (A0)
0AAACE move.w D0, ($2,A0)
0AAAD2 cmp.l (A0), D0
0AAAD4 bne $aaafc
0AAAD8 move.l D2, (A0)+
;--------
020D3E movea.l ($56,A6), A4
020D42 tst.w ($0,A4)
020D46 beq $20d56
020D56 move.b ($a,A4), ($4a,A6)
020D5C jsr $acd0.l
020D62 lea ($73c,A5), A6
020D66 jsr $8a44.l
;--------
0089E0 dbra D6, $89c0
0089E4 rts
0089E6 move.b ($4d9,A5), -(A7)
0089EA move.b ($786,A5), -(A7)
0089EE asl.w #3, D0
0089F0 lea ($6c,PC,D0.w), A0
0089F4 move.b (A0)+, ($4d9,A5)
;--------
02072C bge $2073a
02072E cmpi.b #$f, ($5,A6)
020734 bge $2073a
020736 clr.b ($4a,A6)
02073A clr.b ($6d,A6)
02073E clr.b ($78,A6)
020742 clr.b ($6c,A6)
;--------
00FC0A movea.l ($22,PC,D0.w), A0
00FC0E movea.l ($3e,PC,D0.w), A1
00FC12 moveq #$0, D0
00FC14 move.b ($786,A5), D0
00FC18 add.w D0, D0
00FC1A add.w D0, D0
00FC1C move.l (A0,D0.w), ($8,A4)
;--------
0AAABC jmp $4ce.l
0AAAC2 movea.l A0, A3
0AAAC4 move.l #$0, D0
0AAACA move.l (A0), D2
0AAACC move.w D0, (A0)
0AAACE move.w D0, ($2,A0)
0AAAD2 cmp.l (A0), D0
;--------
004E22 move.w ($32,PC,D0.w), D0
004E26 lea ($2e,PC,D0.w), A0
004E2A moveq #$0, D0
004E2C move.b ($786,A5), D0
004E30 add.w D0, D0
004E32 move.w D0, D1
004E34 lsl.w #3, D0
;--------
008A28 bsr $8c20
008A2C movea.l (A7)+, A0
008A2E move.b (A0)+, ($4d9,A5)
008A32 move.b (A0)+, ($786,A5)
008A36 bsr $8d92
008A3A move.b (A7)+, ($786,A5)
008A3E move.b (A7)+, ($4d9,A5)
;--------
01D97C add.w D0, D0
01D97E movea.l ($30,PC,D0.w), A0
01D982 moveq #$0, D0
01D984 move.b ($786,A5), D0
01D988 add.w D0, D0
01D98A adda.w D0, A0
01D98C move.b (A0)+, ($4de,A5)
;--------
008A04 bsr $8e4c
008A08 movea.l (A7)+, A0
008A0A move.b (A0)+, ($4d9,A5)
008A0E move.b (A0)+, ($786,A5)
008A12 move.l A0, -(A7)
008A14 bsr $8a8e
008A18 bsr $8aae
;--------
018A9E bsr $18c88
018AA2 move.b #$2, ($4,A6)
018AA8 jsr $655e.l
018AAE tst.b ($786,A5)
018AB2 bne $18b36
018AB6 cmpi.b #$1, ($4d9,A5)
018ABC beq $18aca
;--------
022CCC movea.l #$2311e, A0
022CD2 movea.l (A0,D0.w), A0
022CD6 moveq #$0, D0
022CD8 move.b ($786,A5), D0
022CDC move.w D0, D1
022CDE add.w D0, D0
022CE0 lsl.w #3, D1
;--------
022DCE move.w ($14,PC,D0.w), D0
022DD2 lea ($10,PC,D0.w), A0
022DD6 moveq #$0, D0
022DD8 move.b ($786,A5), D0
022DDC adda.l D0, A0
022DDE move.b (A0), ($5f,A6)
022DE2 rts
;--------
0130FC moveq #$0, D3
0130FE move.b ($4d9,A5), D3
013102 lsl.w #3, D3
013104 move.b ($786,A5), D4
013108 add.w D4, D4
01310A add.w D4, D3
01310C move.w (A0,D3.w), D3
;--------
01DA2C lsl.w #2, D0
01DA2E movea.l ($34,PC,D0.w), A0
01DA32 moveq #$0, D0
01DA34 move.b ($786,A5), D0
01DA38 add.w D0, D0
01DA3A adda.w D0, A0
01DA3C move.b (A0)+, ($4de,A5)
;--------
0089EE asl.w #3, D0
0089F0 lea ($6c,PC,D0.w), A0
0089F4 move.b (A0)+, ($4d9,A5)
0089F8 move.b (A0)+, ($786,A5)
0089FC move.l A0, -(A7)
0089FE clr.w $9157fe.l
008A04 bsr $8e4c
;--------
00A56A add.w D0, D0
00A56C add.w D0, D0
00A56E moveq #$0, D1
00A570 move.b ($786,A5), D1
00A574 add.w D1, D0
00A576 move.b ($a,PC,D0.w), D0
00A57A moveq #$0, D1
;--------
008A2E move.b (A0)+, ($4d9,A5)
008A32 move.b (A0)+, ($786,A5)
008A36 bsr $8d92
008A3A move.b (A7)+, ($786,A5)
008A3E move.b (A7)+, ($4d9,A5)
008A42 rts
008A44 clr.w $9157fe.l
;--------
01E088 lsl.w #2, D0
01E08A movea.l (A0,D0.w), A0
01E08E moveq #$0, D0
01E090 move.b ($786,A5), D0
01E094 lsl.w #4, D0
01E096 lea (A0,D0.w), A0
01E09A tst.b ($4cf,A5)
;--------
008E4E move.b ($4d9,A5), D0
008E52 lsl.w #4, D0
008E54 moveq #$0, D1
008E56 move.b ($786,A5), D1
008E5A add.w D1, D1
008E5C add.w D1, D1
008E5E add.w D1, D0
;--------
0AAADC bne $aaaca
0AAADE movea.l A3, A0
0AAAE0 move.l #$ffffffff, D0
0AAAE6 move.l (A0), D2
0AAAE8 move.w D0, (A0)
0AAAEA move.w D0, ($2,A0)
0AAAEE cmp.l (A0), D0
;--------
01DA40 move.b ($4e4,A5), ($4dd,A5)
01DA46 tst.b ($4d9,A5)
01DA4A bne $1da56
01DA4C cmpi.b #$2, ($786,A5)
01DA52 bne $1da56
01DA54 rts
01DA56 clr.b ($3334,A5)
;--------
0209CC move.w ($4,A4), ($50,A6)
0209D2 move.w ($6,A4), ($52,A6)
0209D8 move.w ($8,A4), ($54,A6)
0209DE move.b ($a,A4), ($4a,A6)
0209E4 move.b ($b,A4), ($5,A6)
0209EA clr.w ($6,A6)
0209EE move.b ($c,A4), ($4b,A6)
;--------
012BF6 move.w (A0,D0.w), D1
012BFA adda.w D1, A0
012BFC moveq #$0, D0
012BFE move.b ($786,A5), D0
012C02 add.w D0, D0
012C04 move.w (A0,D0.w), D0
012C08 adda.w D0, A0
;--------
008A18 bsr $8aae
008A1C movea.l (A7)+, A0
008A1E move.b (A0)+, ($4d9,A5)
008A22 move.b (A0)+, ($786,A5)
008A26 move.l A0, -(A7)
008A28 bsr $8c20
008A2C movea.l (A7)+, A0
;--------
0207D0 lsl.w #2, D0
0207D2 movea.l #$21580, A0
0207D8 movea.l (A0,D0.w), A0
0207DC move.b ($786,A5), D0
0207E0 move.w D0, D1
0207E2 add.w D0, D0
0207E4 lsl.w #3, D1
;--------
008AB0 move.b ($4d9,A5), D0
008AB4 lsl.w #4, D0
008AB6 moveq #$0, D1
008AB8 move.b ($786,A5), D1
008ABC add.w D1, D1
008ABE add.w D1, D1
008AC0 add.w D1, D0
;--------
020C76 movea.l ($56,A6), A4
020C7A tst.w ($0,A4)
020C7E beq $20c8e
020C8E move.b ($a,A4), ($4a,A6)
020C94 jsr $acd0.l
020C9A lea ($73c,A5), A6
020C9E jsr $8a44.l
;--------
022E24 move.b ($4d9,A5), D0
022E28 add.w D0, D0
022E2A add.w D0, D0
022E2C move.b ($786,A5), D2
022E30 add.w D2, D0
022E32 move.b ($20,PC,D0.w), D0
022E36 beq $22e50
;--------
020F44 move.b ($4d9,A5), D1
020F48 add.w D1, D1
020F4A add.w D1, D1
020F4C add.b ($786,A5), D1
020F50 move.b ($6,PC,D1.w), ($74,A6)
020F56 rts
021086 tst.b ($6,A6)
;--------
0AAACE move.w D0, ($2,A0)
0AAAD2 cmp.l (A0), D0
0AAAD4 bne $aaafc
0AAAD8 move.l D2, (A0)+
0AAADA cmpa.l A0, A1
0AAADC bne $aaaca
0AAADE movea.l A3, A0
;--------
00041E movea.l #$ff0000, A0
000424 move.w #$3fff, D0
000428 moveq #$0, D1
00042A move.l D1, (A0)+
00042C dbra D0, $42a
000430 reset
000432 move.b #$80, $800030.l
;--------
004D1C moveq #$0, D0
004D1E move.l D0, (A4)+
004D20 move.l D0, (A4)+
004D22 move.l D0, (A4)+
004D24 move.l D0, (A4)+
004D26 move.l D0, (A4)+
004D28 move.l D0, (A4)+
;--------
008C22 move.b ($4d9,A5), D0
008C26 lsl.w #4, D0
008C28 moveq #$0, D1
008C2A move.b ($786,A5), D1
008C2E add.w D1, D1
008C30 add.w D1, D1
008C32 add.w D1, D0
;--------
0AAACA move.l (A0), D2
0AAACC move.w D0, (A0)
0AAACE move.w D0, ($2,A0)
0AAAD2 cmp.l (A0), D0
0AAAD4 bne $aaafc
0AAAD8 move.l D2, (A0)+
0AAADA cmpa.l A0, A1
;--------
0AAAEA move.w D0, ($2,A0)
0AAAEE cmp.l (A0), D0
0AAAF0 bne $aaafc
0AAAF4 move.l D2, (A0)+
0AAAF6 cmpa.l A0, A1
0AAAF8 bne $aaae6
0AAAFA jmp (A6)
;--------
01031C move.b ($4d9,A5), D0
010320 lsl.w #3, D0
010322 moveq #$0, D1
010324 move.b ($786,A5), D1
010328 add.w D1, D1
01032A add.w D1, D0
01032C move.w ($10,PC,D0.w), ($4e8,A5)
;--------
copyright zengfr site:http://github.com/zengfr/romhack
| 25.570978 | 54 | 0.533925 |
44dd54332f4cf22b676fe0faddb3d7df15678f49 | 357 | asm | Assembly | src/Ninu.Emulator.Tests/Cpu/TestFiles/stack.6502.asm | jorgy343/Ninu | e0fb8b4edeb15eee2199bfb9a8e64bb838d9114c | [
"MIT"
] | null | null | null | src/Ninu.Emulator.Tests/Cpu/TestFiles/stack.6502.asm | jorgy343/Ninu | e0fb8b4edeb15eee2199bfb9a8e64bb838d9114c | [
"MIT"
] | null | null | null | src/Ninu.Emulator.Tests/Cpu/TestFiles/stack.6502.asm | jorgy343/Ninu | e0fb8b4edeb15eee2199bfb9a8e64bb838d9114c | [
"MIT"
] | null | null | null | .include "..\..\..\Cpu\TestFiles\std.6502.asm"
* = $0000
.byte $00
; Beginning of tests.
* = $c000
.init
; Basic test of pha and pla.
lda #$37
pha
lda #$00
pla
; Basic test of php and plp.
lda #$00
php
lda #$ff
plp
.done
* = $fff0
rti
* = $fffa
nmiVector .addr $fff0
resetVector .addr $c000
irqVector .addr $fff0 | 11.15625 | 48 | 0.568627 |
1c00351a81bf87ef74c62f3d061331d1b37555db | 125 | lua | Lua | assets/preload/custom_notetypes/GifPopup.lua | Nskakaka/Psych-Engine-0.4.2-Android-Port | ffac0ab69e5adc449e43e7acf2a125ef2b689c01 | [
"Apache-2.0"
] | null | null | null | assets/preload/custom_notetypes/GifPopup.lua | Nskakaka/Psych-Engine-0.4.2-Android-Port | ffac0ab69e5adc449e43e7acf2a125ef2b689c01 | [
"Apache-2.0"
] | null | null | null | assets/preload/custom_notetypes/GifPopup.lua | Nskakaka/Psych-Engine-0.4.2-Android-Port | ffac0ab69e5adc449e43e7acf2a125ef2b689c01 | [
"Apache-2.0"
] | 1 | 2022-02-27T19:40:34.000Z | 2022-02-27T19:40:34.000Z |
function onEvent(n,v1,v2)
if n == "GifPopup" then
if osfunction then
os.execute("speed.gif")
end
end
end
| 12.5 | 27 | 0.616 |
8d602c351c597c06bafa5dfb9b3bd869dfebbc8f | 1,635 | kt | Kotlin | src/main/kotlin/io/toolebox/gradle/gitversioner/core/tag/GitTagger.kt | yschimke/gradle-git-versioner | bb661e25644adcd70a9a74451b557be1cd566a66 | [
"MIT"
] | 19 | 2018-07-24T08:15:50.000Z | 2022-03-16T15:10:36.000Z | src/main/kotlin/io/toolebox/gradle/gitversioner/core/tag/GitTagger.kt | yschimke/gradle-git-versioner | bb661e25644adcd70a9a74451b557be1cd566a66 | [
"MIT"
] | 18 | 2018-10-02T13:33:35.000Z | 2022-03-29T13:18:36.000Z | src/main/kotlin/io/toolebox/gradle/gitversioner/core/tag/GitTagger.kt | yschimke/gradle-git-versioner | bb661e25644adcd70a9a74451b557be1cd566a66 | [
"MIT"
] | 5 | 2018-11-26T22:41:37.000Z | 2022-01-31T09:29:52.000Z | package io.toolebox.gradle.gitversioner.core.tag
import com.jcraft.jsch.JSch
import java.io.File
import org.eclipse.jgit.api.Git
import org.eclipse.jgit.transport.CredentialsProvider
import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider
class GitTagger(private val gitFolder: File, private val config: TaggerConfig) {
fun tag(version: String) {
configureHostChecking(config)
val credentialsProvider = createCredentialsProvider(config)
val prefixedVersion = "${config.prefix}$version"
val git = Git.open(gitFolder)
val tagCommand = git.tag().setName(prefixedVersion)
if (config.useCommitMessage) {
tagCommand.setMessage(getLastCommitMessage(git))
}
tagCommand.call()
git.push().add(prefixedVersion).setCredentialsProvider(credentialsProvider).call()
}
private fun getLastCommitMessage(git: Git) =
git.log().setMaxCount(1).call().iterator().next().fullMessage
private fun configureHostChecking(config: TaggerConfig) {
if (config.strictHostChecking) {
JSch.setConfig("StrictHostKeyChecking", "yes")
} else {
JSch.setConfig("StrictHostKeyChecking", "no")
}
}
private fun createCredentialsProvider(config: TaggerConfig): CredentialsProvider? {
with(config) {
return when {
username != null -> UsernamePasswordCredentialsProvider(username, password)
token != null -> UsernamePasswordCredentialsProvider(token, "")
else -> CredentialsProvider.getDefault()
}
}
}
}
| 36.333333 | 91 | 0.675229 |
3f6821db18d86e09619f8d2402e700848a640509 | 2,670 | kt | Kotlin | app/src/main/java/com/github/teracy/roompagingsample/data/paging/DietMemberPageKeyedDataSource.kt | teracy/RoomPagingSample | 9ab546c5b8994da9c0d6ead40b98e2cb4faea371 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/github/teracy/roompagingsample/data/paging/DietMemberPageKeyedDataSource.kt | teracy/RoomPagingSample | 9ab546c5b8994da9c0d6ead40b98e2cb4faea371 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/github/teracy/roompagingsample/data/paging/DietMemberPageKeyedDataSource.kt | teracy/RoomPagingSample | 9ab546c5b8994da9c0d6ead40b98e2cb4faea371 | [
"Apache-2.0"
] | null | null | null | package com.github.teracy.roompagingsample.data.paging
import android.arch.lifecycle.MutableLiveData
import android.arch.paging.PageKeyedDataSource
import com.github.teracy.roompagingsample.data.db.AppDatabase
import com.github.teracy.roompagingsample.data.db.entity.DietMemberEntity
class DietMemberPageKeyedDataSource(private val database: AppDatabase, private val limit: Int, private val name: String?) : PageKeyedDataSource<Int, DietMember>() {
// ローディング表示
val loading: MutableLiveData<Boolean> = MutableLiveData()
override fun loadInitial(params: LoadInitialParams<Int>, callback: LoadInitialCallback<Int, DietMember>) {
// 最初のページ取得
getDietMember(0) { dietMembers, next ->
callback.onResult(dietMembers, null, next)
}
}
override fun loadAfter(params: LoadParams<Int>, callback: LoadCallback<Int, DietMember>) {
// 次のページ取得
getDietMember(params.key) { dietMembers, next ->
callback.onResult(dietMembers, next)
}
}
override fun loadBefore(params: LoadParams<Int>, callback: LoadCallback<Int, DietMember>) {
// 前のページ取得:利用しない
}
private fun getDietMember(offset: Int, callback: (dietMembers: List<DietMember>, next: Int?) -> Unit) {
loading.postValue(true)
val list = if (name == null || name.trim().isEmpty()) {
database.dietMemberDao().getDietMembersLimitOffset(limit, offset)
} else {
database.dietMemberDao().getDietMembersByNameLimitOffset("$name%", limit, offset)
}.map { it.convert() }
callback(list, offset + limit)
loading.postValue(false)
}
/**
* Roomの議員Entity→表示用議員情報に変換
*/
private fun DietMemberEntity.convert(): DietMember {
val election =
when (house) {
REPRESENTATIVES -> {
constituency?.let {
// 選挙区
house + it + "区"
} ?: block?.let {
// 比例区
house + it + "ブロック"
}
}
COUNCILORS -> {
constituency?.let {
// 選挙区
house + it + "選挙区"
} ?: block?.let {
// 比例区
house + it + "代表"
}
}
else -> ""
} ?: ""
return DietMember(id, name, kana, election, party)
}
} | 38.142857 | 165 | 0.521348 |
e316f48bcd6b20affbfced32797b1e2836463674 | 1,580 | kt | Kotlin | module_base/src/main/java/com/linda/module_base/view/VideoCollectionHorizontalScrollCardItemView.kt | zhoulinda/eyepetizer_kotlin | 7dfc8eef169fd16326dc64560edf9ebb21618b05 | [
"MIT"
] | 72 | 2021-02-28T09:52:04.000Z | 2022-03-28T09:24:31.000Z | module_base/src/main/java/com/linda/module_base/view/VideoCollectionHorizontalScrollCardItemView.kt | zhoulinda/eyepetizer_kotlin | 7dfc8eef169fd16326dc64560edf9ebb21618b05 | [
"MIT"
] | null | null | null | module_base/src/main/java/com/linda/module_base/view/VideoCollectionHorizontalScrollCardItemView.kt | zhoulinda/eyepetizer_kotlin | 7dfc8eef169fd16326dc64560edf9ebb21618b05 | [
"MIT"
] | 12 | 2021-03-02T06:18:05.000Z | 2022-03-18T02:59:40.000Z | package com.linda.module_base.view
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.FrameLayout
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CircleCrop
import com.bumptech.glide.request.RequestOptions
import com.linda.module_base.R
import com.linda.module_base.bean.Card
import kotlinx.android.synthetic.main.view_video_collection_item_card.view.*
/**
* 描述 :
*
* @author: linda
* email: zhoulinda@lexue.com
* 创建日期: 2021/2/22
*/
class VideoCollectionHorizontalScrollCardItemView : FrameLayout {
constructor(context: Context) : this(context, null)
constructor(context: Context, attributeSet: AttributeSet?) : this(context, attributeSet, 0)
constructor(context: Context, attributeSet: AttributeSet?, defStyleAttr: Int) : super(
context,
attributeSet,
defStyleAttr
) {
init(context)
}
private fun init(context: Context) {
LayoutInflater.from(context).inflate(R.layout.view_video_collection_item_card, this, true)
}
fun setData(card: Card) {
card.run {
Glide.with(context)
.load(data?.content?.data?.cover?.feed)
.into(image)
Glide.with(context)
.load(data?.content?.data?.author?.icon)
.apply(RequestOptions.bitmapTransform(CircleCrop()))
.into(portrait)
videoTitle.text = data?.header?.title
description.text = data?.header?.description
}
}
} | 30.384615 | 98 | 0.679114 |
93b16738ab6209f3ff1fc4be9a4af60e1e272d95 | 1,768 | rs | Rust | src/main.rs | skrzepto/tictactoe-rust | c83931a83b50746db077d1e79b96d35894920eb8 | [
"MIT"
] | null | null | null | src/main.rs | skrzepto/tictactoe-rust | c83931a83b50746db077d1e79b96d35894920eb8 | [
"MIT"
] | null | null | null | src/main.rs | skrzepto/tictactoe-rust | c83931a83b50746db077d1e79b96d35894920eb8 | [
"MIT"
] | null | null | null | mod board {
use std::cell::Cell;
#[derive(Copy, Clone, PartialEq)]
pub enum Square {
Empty,
Black,
White
}
pub struct GameState {
pub squares_filled: i32,
pub winner: Square,
pub board: [[Square;3]; 3]
}
impl GameState {
fn check_horizontal (&mut self) {
let res = self.board.iter()
.map(|&r| validate(r))
.filter(|&cell| cell != Square::Empty)
.collect::<Vec<Square>>();
if res.len() > 0 {
self.winner = res[0];
}
}
fn check_vertical (game: GameState) {
}
pub fn inspectBoard(game: GameState) {
// across
// vertical
// diagonal
// two option top left, bottom left
}
}
fn validate(row: [Square;3]) -> Square {
let non_empty = row.iter()
.filter(|&&cell| cell != Square::Empty)
.collect::<Vec<&Square>>();
if non_empty.len() == 3 {
let black_elements = row.iter()
.filter(|&&cell| cell == Square::Black)
.collect::<Vec<&Square>>();
if black_elements.len() == 3 {
return Square::Black;
} else if black_elements.len() == 0 {
return Square::White;
}
}
return Square::Empty;
}
pub fn init () -> GameState {
GameState {
squares_filled: 0,
winner: Square::Empty,
board: [[Square::Empty; 3]; 3]
}
}
}
mod validation {
use board::Square;
use board::GameState;
}
fn main() {
let board = board::init();
println!("Hello, world!");
} | 21.560976 | 55 | 0.455882 |
2cf70c9c95201eabda8f8eb658cfc481e2fd991c | 8,040 | lua | Lua | runner/el53/builtin/mainmenu/dlg_config_world.lua | samarth-ramesh/mtlauncher | 14f4c2b83a39a7775e6dd09ccf60f1382c4a8837 | [
"MIT"
] | null | null | null | runner/el53/builtin/mainmenu/dlg_config_world.lua | samarth-ramesh/mtlauncher | 14f4c2b83a39a7775e6dd09ccf60f1382c4a8837 | [
"MIT"
] | 1 | 2021-02-13T03:06:31.000Z | 2021-02-13T03:08:33.000Z | runner/el53/builtin/mainmenu/dlg_config_world.lua | samarth-ramesh/mtlauncher | 14f4c2b83a39a7775e6dd09ccf60f1382c4a8837 | [
"MIT"
] | null | null | null | --Minetest
--Copyright (C) 2013 sapier
--
--This program is free software; you can redistribute it and/or modify
--it under the terms of the GNU Lesser General Public License as published by
--the Free Software Foundation; either version 2.1 of the License, or
--(at your option) any later version.
--
--This program is distributed in the hope that it will be useful,
--but WITHOUT ANY WARRANTY; without even the implied warranty of
--MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
--GNU Lesser General Public License for more details.
--
--You should have received a copy of the GNU Lesser General Public License along
--with this program; if not, write to the Free Software Foundation, Inc.,
--51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
--------------------------------------------------------------------------------
local enabled_all = false
local function modname_valid(name)
return not name:find("[^a-z0-9_]")
end
local function init_data(data)
data.list = filterlist.create(
pkgmgr.preparemodlist,
pkgmgr.comparemod,
function(element, uid)
if element.name == uid then
return true
end
end,
function(element, criteria)
if criteria.hide_game and
element.is_game_content then
return false
end
if criteria.hide_modpackcontents and
element.modpack ~= nil then
return false
end
return true
end,
{
worldpath = data.worldspec.path,
gameid = data.worldspec.gameid
})
if data.selected_mod > data.list:size() then
data.selected_mod = 0
end
data.list:set_filtercriteria({
hide_game = data.hide_gamemods,
hide_modpackcontents = data.hide_modpackcontents
})
data.list:add_sort_mechanism("alphabetic", sort_mod_list)
data.list:set_sortmode("alphabetic")
end
local function get_formspec(data)
if not data.list then
init_data(data)
end
local mod = data.list:get_list()[data.selected_mod] or {name = ""}
local retval =
"size[11.5,7.5,true]" ..
"label[0.5,0;" .. fgettext("World:") .. "]" ..
"label[1.75,0;" .. data.worldspec.name .. "]"
if mod.is_modpack or mod.type == "game" then
local info = minetest.formspec_escape(
core.get_content_info(mod.path).description)
if info == "" then
if mod.is_modpack then
info = fgettext("No modpack description provided.")
else
info = fgettext("No game description provided.")
end
end
retval = retval ..
"textarea[0.25,0.7;5.75,7.2;;" .. info .. ";]"
else
local hard_deps, soft_deps = pkgmgr.get_dependencies(mod.path)
local hard_deps_str = table.concat(hard_deps, ",")
local soft_deps_str = table.concat(soft_deps, ",")
retval = retval ..
"label[0,0.7;" .. fgettext("Mod:") .. "]" ..
"label[0.75,0.7;" .. mod.name .. "]"
if hard_deps_str == "" then
if soft_deps_str == "" then
retval = retval ..
"label[0,1.25;" ..
fgettext("No (optional) dependencies") .. "]"
else
retval = retval ..
"label[0,1.25;" .. fgettext("No hard dependencies") ..
"]" ..
"label[0,1.75;" .. fgettext("Optional dependencies:") ..
"]" ..
"textlist[0,2.25;5,4;world_config_optdepends;" ..
soft_deps_str .. ";0]"
end
else
if soft_deps_str == "" then
retval = retval ..
"label[0,1.25;" .. fgettext("Dependencies:") .. "]" ..
"textlist[0,1.75;5,4;world_config_depends;" ..
hard_deps_str .. ";0]" ..
"label[0,6;" .. fgettext("No optional dependencies") .. "]"
else
retval = retval ..
"label[0,1.25;" .. fgettext("Dependencies:") .. "]" ..
"textlist[0,1.75;5,2.125;world_config_depends;" ..
hard_deps_str .. ";0]" ..
"label[0,3.9;" .. fgettext("Optional dependencies:") ..
"]" ..
"textlist[0,4.375;5,1.8;world_config_optdepends;" ..
soft_deps_str .. ";0]"
end
end
end
retval = retval ..
"button[3.25,7;2.5,0.5;btn_config_world_save;" ..
fgettext("Save") .. "]" ..
"button[5.75,7;2.5,0.5;btn_config_world_cancel;" ..
fgettext("Cancel") .. "]" ..
"button[9,7;2.5,0.5;btn_config_world_cdb;" ..
fgettext("Find More Mods") .. "]"
if mod.name ~= "" and not mod.is_game_content then
if mod.is_modpack then
if pkgmgr.is_modpack_entirely_enabled(data, mod.name) then
retval = retval ..
"button[5.5,0.125;3,0.5;btn_mp_disable;" ..
fgettext("Disable modpack") .. "]"
else
retval = retval ..
"button[5.5,0.125;3,0.5;btn_mp_enable;" ..
fgettext("Enable modpack") .. "]"
end
else
retval = retval ..
"checkbox[5.5,-0.125;cb_mod_enable;" .. fgettext("enabled") ..
";" .. tostring(mod.enabled) .. "]"
end
end
if enabled_all then
retval = retval ..
"button[8.95,0.125;2.5,0.5;btn_disable_all_mods;" ..
fgettext("Disable all") .. "]"
else
retval = retval ..
"button[8.95,0.125;2.5,0.5;btn_enable_all_mods;" ..
fgettext("Enable all") .. "]"
end
return retval ..
"tablecolumns[color;tree;text]" ..
"table[5.5,0.75;5.75,6;world_config_modlist;" ..
pkgmgr.render_packagelist(data.list) .. ";" .. data.selected_mod .."]"
end
local function handle_buttons(this, fields)
if fields.world_config_modlist then
local event = core.explode_table_event(fields.world_config_modlist)
this.data.selected_mod = event.row
core.settings:set("world_config_selected_mod", event.row)
if event.type == "DCL" then
pkgmgr.enable_mod(this)
end
return true
end
if fields.key_enter then
pkgmgr.enable_mod(this)
return true
end
if fields.cb_mod_enable ~= nil then
pkgmgr.enable_mod(this, core.is_yes(fields.cb_mod_enable))
return true
end
if fields.btn_mp_enable ~= nil or
fields.btn_mp_disable then
pkgmgr.enable_mod(this, fields.btn_mp_enable ~= nil)
return true
end
if fields.btn_config_world_save then
local filename = this.data.worldspec.path .. DIR_DELIM .. "world.mt"
local worldfile = Settings(filename)
local mods = worldfile:to_table()
local rawlist = this.data.list:get_raw_list()
for i = 1, #rawlist do
local mod = rawlist[i]
if not mod.is_modpack and
not mod.is_game_content then
if modname_valid(mod.name) then
worldfile:set("load_mod_" .. mod.name,
mod.enabled and "true" or "false")
elseif mod.enabled then
gamedata.errormessage = fgettext_ne("Failed to enable mo" ..
"d \"$1\" as it contains disallowed characters. " ..
"Only characters [a-z0-9_] are allowed.",
mod.name)
end
mods["load_mod_" .. mod.name] = nil
end
end
-- Remove mods that are not present anymore
for key in pairs(mods) do
if key:sub(1, 9) == "load_mod_" then
worldfile:remove(key)
end
end
if not worldfile:write() then
core.log("error", "Failed to write world config file")
end
this:delete()
return true
end
if fields.btn_config_world_cancel then
this:delete()
return true
end
if fields.btn_config_world_cdb then
this.data.list = nil
local dlg = create_store_dlg("mod")
dlg:set_parent(this)
this:hide()
dlg:show()
return true
end
if fields.btn_enable_all_mods then
local list = this.data.list:get_raw_list()
for i = 1, #list do
if not list[i].is_game_content
and not list[i].is_modpack then
list[i].enabled = true
end
end
enabled_all = true
return true
end
if fields.btn_disable_all_mods then
local list = this.data.list:get_raw_list()
for i = 1, #list do
if not list[i].is_game_content
and not list[i].is_modpack then
list[i].enabled = false
end
end
enabled_all = false
return true
end
return false
end
function create_configure_world_dlg(worldidx)
local dlg = dialog_create("sp_config_world", get_formspec, handle_buttons)
dlg.data.selected_mod = tonumber(
core.settings:get("world_config_selected_mod")) or 0
dlg.data.worldspec = core.get_worlds()[worldidx]
if not dlg.data.worldspec then
dlg:delete()
return
end
dlg.data.worldconfig = pkgmgr.get_worldconfig(dlg.data.worldspec.path)
if not dlg.data.worldconfig or not dlg.data.worldconfig.id or
dlg.data.worldconfig.id == "" then
dlg:delete()
return
end
return dlg
end
| 26.188925 | 80 | 0.666045 |
1260b1be00f7d8033a61b354b1987d2f92fefef3 | 1,844 | h | C | velox/functions/prestosql/types/TimestampWithTimeZoneType.h | vancexu/velox | fa076fd9eab6ae4090ed9b9b91c4e7658d4ee1e4 | [
"Apache-2.0"
] | 1 | 2022-01-06T20:10:07.000Z | 2022-01-06T20:10:07.000Z | velox/functions/prestosql/types/TimestampWithTimeZoneType.h | vancexu/velox | fa076fd9eab6ae4090ed9b9b91c4e7658d4ee1e4 | [
"Apache-2.0"
] | null | null | null | velox/functions/prestosql/types/TimestampWithTimeZoneType.h | vancexu/velox | fa076fd9eab6ae4090ed9b9b91c4e7658d4ee1e4 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* 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.
*/
#pragma once
#include "velox/expression/VectorUdfTypeSystem.h"
#include "velox/type/Type.h"
#include "velox/vector/VectorTypeUtils.h"
namespace facebook::velox {
/// Represents timestamp with time zone as a number of milliseconds since epoch
/// and time zone ID.
class TimestampWithTimeZoneType : public RowType {
TimestampWithTimeZoneType()
: RowType({"timestamp", "timezone"}, {BIGINT(), SMALLINT()}) {}
public:
static const std::shared_ptr<const TimestampWithTimeZoneType>& get() {
static const std::shared_ptr<const TimestampWithTimeZoneType> instance =
std::shared_ptr<TimestampWithTimeZoneType>(
new TimestampWithTimeZoneType());
return instance;
}
std::string toString() const override {
return "TIMESTAMP WITH TIME ZONE";
}
};
inline bool isTimestampWithTimeZoneType(const TypePtr& type) {
// Pointer comparison works since this type is a singleton.
return TimestampWithTimeZoneType::get() == type;
}
inline std::shared_ptr<const TimestampWithTimeZoneType>
TIMESTAMP_WITH_TIME_ZONE() {
return TimestampWithTimeZoneType::get();
}
// Type used for function registration.
using TimestampWithTimezone = Row<int64_t, int16_t>;
} // namespace facebook::velox
| 31.793103 | 79 | 0.741866 |
07d706d7c8389a552a0384d6ac95f45bd5d9ebb6 | 4,180 | ps1 | PowerShell | Source/Public/Set-SCMrkAuth.ps1 | ScriptingChris/SCPSMeraki | 76eaec3e09daffcd8a97c05ab94a8ba24865bd12 | [
"MIT"
] | 1 | 2021-08-13T17:26:44.000Z | 2021-08-13T17:26:44.000Z | Source/Public/Set-SCMrkAuth.ps1 | ScriptingChris/SCPSMeraki | 76eaec3e09daffcd8a97c05ab94a8ba24865bd12 | [
"MIT"
] | 1 | 2021-12-20T03:53:06.000Z | 2021-12-20T03:53:06.000Z | Source/Public/Set-SCMrkAuth.ps1 | ScriptingChris/SCPSMeraki | 76eaec3e09daffcd8a97c05ab94a8ba24865bd12 | [
"MIT"
] | 1 | 2021-08-15T14:15:38.000Z | 2021-08-15T14:15:38.000Z | function Set-SCMrkAuth {
<#
.SYNOPSIS
Cmdlet for connecting to Meraki Dashboard API.
.DESCRIPTION
Cmdlet whitch which will authenticate your API key with Meraki Dashboard
The cmdlet is necessary for not having to provide the API Key for the
follwing cmdlets you will use.
.EXAMPLE
PS C:\> Set-SCMrkAuth -ApiKey "<api_key>"
This example will connect to the Meraki Dashboard API. If you have multiple Organisations
attached to your API key, the cmdlet will atumatically connect you to the firs Organisation.
.EXAMPLE
PS C:\> Set-SCMrkAuth -ApiKey "<api_key>" -OrgId "<organisation_id>"
This examplel will connect you to the Merakii Dashboard API, and to the specific organisation
specified with the parameter OrgId
.PARAMETER ApiKey
ApiKey for Meraki Dashboard. Check following Meraki Docs to see how to get a Dashboard API Key:
https://documentation.meraki.com/General_Administration/Other_Topics/Cisco_Meraki_Dashboard_API#:~:text=For%20access%20to%20the%20API,to%20generate%20an%20API%20key.
.PARAMETER OrgId
Organisation Id for the specific Organisation you want to connect to. If you only have a single
organisation, you can skip this parameter. If you have multiple Organisations but don't provide
an organisation id the cmdlet will automatically connect you to the first organisation it
retrieves.
.INPUTS
System.String[] - You can pipe the ApiKey as a string into the cmdlet
.OUTPUTS
System.String[] - The cmdlet returns a string with successfull statement, if connection was successfull
.NOTES
n/a
.Link
Online Help: https://scriptingchris.tech
#>
[CmdletBinding()]
param (
[Parameter(Mandatory=$true, HelpMessage="Please provide and API Key:", ValueFromPipeline=$true)]
[ValidateLength(38,41)]
[String]$ApiKey,
[Parameter(Mandatory=$false)]
[ValidateNotNullOrEmpty()]
[String]$OrgId
)
Begin {
Write-Verbose -Message "Initiating Meraki Dashboard Authentication with ApiKey: $($ApiKey)"
}
Process {
if(!($OrgId)){
Write-Verbose -Message "Authenticating to Meraki Dashboard API"
try {
$OrgId = Invoke-PRMerakiApiCall -Method GET -Resource "/organizations" -ApiKey $ApiKey | Select-Object -ExpandProperty Id -First 1
Write-Verbose -Message "Setting the OrgId: $($OrgId) Variable as Script Scope"
New-Variable -Name OrgId -Value $OrgId.ToString() -Scope Script -Force
Write-Output -InputObject "Successfully conncted to Meraki API!"
}
catch {
$statusCode = $_.Exception.Response.StatusCode.value__
$statusDescription = $_.Exception.Response.StatusDescription
}
}
elseif($OrgId){
Write-Verbose -Message "Validating Organisation Id provided in parameter agains Meraki Dashboard API"
try {
$OrgIds = Invoke-PRMerakiApiCall -Method GET -Resource "/organizations" -ApiKey $ApiKey | Select-Object -ExpandProperty Id
if($OrgIds -contains $OrgId){
Write-Verbose -Message "Setting the OrgId: $($Orgid) Variable as Script Scope"
New-Variable -Name OrgId -Value $OrgId.ToString() -Scope Script -Force
Write-Output -InputObject "Successfully conncted to Meraki API!"
}
else {
$statusCode = $_.Exception.Response.StatusCode.value__
$statusDescription = "Organisation Id provided in Parameter, was not found in your Meraki Dashboard"
}
}
catch {
$statusCode = $_.Exception.Response.StatusCode.value__
$statusDescription = $_.Exception.Response.StatusDescription
}
}
}
End {
if($statusCode){
Write-Error -Message "Status code: $($statusCode), Error Description: $($statusDescription)"
}
}
} | 45.934066 | 173 | 0.635885 |
b4ef8c856d0d2d55dfe175c443d4f07da5d520e7 | 6,560 | lua | Lua | vm/classreader.lua | davidgiven/luje | c580adea62d30cec68505fa99b68e815c59f702c | [
"Apache-2.0",
"BSD-2-Clause-FreeBSD"
] | 51 | 2016-01-29T20:22:26.000Z | 2021-11-05T01:29:13.000Z | vm/classreader.lua | davidgiven/luje | c580adea62d30cec68505fa99b68e815c59f702c | [
"Apache-2.0",
"BSD-2-Clause-FreeBSD"
] | 3 | 2016-01-25T21:34:53.000Z | 2016-01-25T21:35:29.000Z | vm/classreader.lua | davidgiven/luje | c580adea62d30cec68505fa99b68e815c59f702c | [
"Apache-2.0",
"BSD-2-Clause-FreeBSD"
] | 12 | 2016-01-29T20:22:27.000Z | 2020-06-23T12:40:35.000Z | -- Luje
-- © 2013 David Given
-- This file is redistributable under the terms of the
-- New BSD License. Please see the COPYING file in the
-- project root for the full text.
local ffi = require("ffi")
local Utils = require("Utils")
local Cast = require("Cast")
local dbg = Utils.Debug
local string_byte = string.byte
local string_sub = string.sub
local BBtoW = Cast.BBtoW
local BBtoSW = Cast.BBtoSW
local WWtoI = Cast.WWtoI
local WWtoSI = Cast.WWtoSI
local ItoF = Cast.ItoF
local ItoSI = Cast.ItoSI
local IItoL = Cast.IItoL
local IItoSL = Cast.IItoSL
local IItoD = Cast.IItoD
local function loadclass(classdata)
local classobj = {}
local pos = 1
local function u1()
local r = string_byte(classdata, pos)
pos = pos + 1
return r
end
local function u2()
local hi = u1()
local lo = u1()
return BBtoW(hi, lo)
end
local function u4()
local hi = u2()
local lo = u2()
return WWtoI(hi, lo)
end
local function s4()
local i = u4()
return ItoSI(i)
end
local function f4()
local i = u4()
return ItoF(i)
end
local function s8()
local hi = u4()
local lo = u4()
return IItoSL(hi, lo)
end
local function f8()
local hi = u4()
local lo = u4()
return IItoD(hi, lo)
end
local function utf8(count)
local s = string_sub(classdata, pos, pos+count-1)
pos = pos + count
return s
end
if (u4() ~= 0xcafebabe) then
return Utils.Throw("not a class file")
end
classobj.minor_version = u2()
classobj.major_version = u2()
-- Load constant pool
local ref_reader = function()
return {
class_index = u2(),
name_and_type_index = u2()
}, 1
end
local constant_reader =
{
[1] = function() -- CONSTANT_Utf8
local len = u2()
return utf8(len), 1
end,
[3] = function() -- CONSTANT_Integer
return bit.tobit(s4()), 1
end,
[4] = function() -- CONSTANT_Float
return f4(), 1
end,
[5] = function() -- CONSTANT_Long
return ffi.cast("int64_t", s8()), 2
end,
[6] = function() -- CONSTANT_Double
return f8(), 2
end,
[7] = function() -- CONSTANT_Class
return {
tag = "CONSTANT_class",
name_index = u2()
}, 1
end,
[8] = function() -- CONSTANT_String
return {
tag = "CONSTANT_String",
string_index = u2()
}, 1
end,
[9] = ref_reader, -- CONSTANT_Fieldref
[10] = ref_reader, -- CONSTANT_Methodref
[11] = ref_reader, -- CONSTANT_InterfaceMethodref
[12] = function() -- CONSTANT_NameAndType
return {
tag = "CONSTANT_NameAndType",
name_index = u2(),
descriptor_index = u2()
}, 1
end
}
local constant_pool_count = u2()
classobj.constants = {}
do
local i = 1
while (i < constant_pool_count) do
local tag = u1()
local reader = constant_reader[tag]
if not reader then
Utils.Throw("invalid constant pool tag "..tag)
end
local c, d = reader()
if not c then
Utils.Throw("unimplemented constant pool tag "..tag)
end
classobj.constants[i] = c
i = i + d
end
end
-- More miscellaneous fields
classobj.access_flags = u2()
classobj.this_class = u2()
classobj.super_class = u2()
-- Load interfaces list
local interfaces_count = u2()
classobj.interfaces = {}
for i = 0, interfaces_count-1 do
classobj.interfaces[i] = u2()
end
-- Function to load an attribute --- we'll use this later.
local attributes
local attribute_reader = {
["ConstantValue"] = function()
local constantvalue_index = u2()
local constantvalue = classobj.constants[constantvalue_index]
return {
value = constantvalue
}
end,
["Code"] = function()
local a = {}
a.max_stack = u2()
a.max_locals = u2()
local code_length = u4()
a.code = utf8(code_length)
local exception_table_length = u2()
a.exception_table = {}
for i = 1, exception_table_length do
a.exception_table[i] = {
start_pc = u2(),
end_pc = u2(),
handler_pc = u2(),
catch_type = u2()
}
end
a.attributes = attributes()
return a
end,
["Exceptions"] = function()
local number_of_exceptions = u2()
local a = {}
for i = 1, number_of_exceptions do
a[i] = u2()
end
return a
end,
["InnerClasses"] = function()
local number_of_classes = u2()
local a = {}
for i = 1, number_of_classes do
a[i] = {
inner_class_info_index = u2(),
outer_class_info_index = u2(),
inner_name_index = u2(),
inner_class_access_flags = u2()
}
end
return a
end,
["Synthetic"] = function()
return {};
end,
["SourceFile"] = function()
return {
sourcefile_index = u2()
}
end,
["LineNumberTable"] = function()
local line_number_table_length = u2()
local a = {}
for i = 1, line_number_table_length do
a[i] = {
start_pc = u2(),
line_number = u2()
}
end
return a
end,
["LocalVariableTable"] = function()
local local_variable_table_length = u2()
local a = {}
for i = 1, local_variable_table_length do
a[i] = {
start_pc = u2(),
length = u2(),
name_index = u2(),
descriptor_index = u2(),
index = u2()
}
end
return a
end,
["Deprecated"] = function()
return {};
end,
}
-- Ignore these for now, as we don't use it and it's a pain to
-- parse
--
for _, e in ipairs({"LocalVariableTypeTable", "StackMapTable", "Signature",
"RuntimeVisibleAnnotations"}) do
attribute_reader[e] = function() return {} end
end
local function attribute()
local attribute_name_index = u2()
local attribute_name = classobj.constants[attribute_name_index]
local reader = attribute_reader[attribute_name]
if not reader then
Utils.Throw("unknown attribute with name "..attribute_name)
end
local len = u4()
local oldpos = pos
local a = reader()
if (a == nil) then
Utils.Throw("unimplemented attribute "..attribute_name)
end
a.attribute_name = attribute_name
pos = oldpos + len
return a
end
attributes = function()
local attributes_count = u2()
local a = {}
for i = 1, attributes_count do
a[i] = attribute()
end
return a
end
-- Fields.
local fields_count = u2()
classobj.fields = {}
for i = 1, fields_count do
classobj.fields[i] = {
access_flags = u2(),
name_index = u2(),
descriptor_index = u2(),
attributes = attributes()
}
end
-- Methods.
local methods_count = u2()
classobj.methods = {}
for i = 1, methods_count do
classobj.methods[i] = {
access_flags = u2(),
name_index = u2(),
descriptor_index = u2(),
attributes = attributes()
}
end
classobj.attributes = attributes()
return classobj
end
return loadclass
| 19.014493 | 76 | 0.637957 |
034a4a0a3668c4f5c3d99d9a7905fa1f645a4945 | 1,803 | kt | Kotlin | src/main/kotlin/com/github/kvnxiao/discord/commands/fun/RollCommand.kt | kvnxiao/operator-6o | de5dcd86e0c7b6df2093f2f419c6b3e703f56d53 | [
"Apache-2.0"
] | null | null | null | src/main/kotlin/com/github/kvnxiao/discord/commands/fun/RollCommand.kt | kvnxiao/operator-6o | de5dcd86e0c7b6df2093f2f419c6b3e703f56d53 | [
"Apache-2.0"
] | 63 | 2020-02-12T13:39:05.000Z | 2022-03-28T10:06:05.000Z | src/main/kotlin/com/github/kvnxiao/discord/commands/fun/RollCommand.kt | kvnxiao/operator-6o | de5dcd86e0c7b6df2093f2f419c6b3e703f56d53 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright 2019 Ze Hao (Kevin) Xiao
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.kvnxiao.discord.commands.`fun`
import com.github.kvnxiao.discord.command.annotation.Descriptor
import com.github.kvnxiao.discord.command.annotation.Id
import com.github.kvnxiao.discord.command.annotation.Permissions
import com.github.kvnxiao.discord.command.context.Context
import com.github.kvnxiao.discord.command.executable.Command
import org.springframework.stereotype.Component
import reactor.core.publisher.Mono
import java.util.concurrent.ThreadLocalRandom
@Component
@Id("roll")
@Descriptor(
description = "Rolls a random number out of the provided bound (inclusive). Defaults to 100 if no bound is given.",
usage = "%A | %A <bound>"
)
@Permissions(allowDirectMessaging = true)
class RollCommand : Command {
override fun execute(ctx: Context): Mono<Void> =
Mono.justOrEmpty(ctx.args.arguments)
.map { it.toLong() }
.onErrorReturn(100L)
.filter { it > 0L }
.switchIfEmpty(Mono.just(100L))
.flatMap {
ctx.channel.createMessage(
ThreadLocalRandom.current().nextLong(it + 1).toString()
)
}
.then()
}
| 36.795918 | 119 | 0.694398 |
81e95cf8d4f6376c6c32d0e3034ce9e57a74ef2e | 21,859 | go | Go | adapter/strategy/web/web.go | wayfair-contribs/app-identity-and-access-adapter | 9bd4db941873104f58e7bb1bdb9ae01fd1b86ddd | [
"Apache-2.0"
] | 84 | 2019-07-01T06:21:22.000Z | 2022-03-29T23:57:30.000Z | adapter/strategy/web/web.go | wayfair-contribs/app-identity-and-access-adapter | 9bd4db941873104f58e7bb1bdb9ae01fd1b86ddd | [
"Apache-2.0"
] | 26 | 2019-11-25T17:51:14.000Z | 2021-07-27T11:30:23.000Z | adapter/strategy/web/web.go | wayfair-contribs/app-identity-and-access-adapter | 9bd4db941873104f58e7bb1bdb9ae01fd1b86ddd | [
"Apache-2.0"
] | 35 | 2019-07-29T16:58:01.000Z | 2021-11-23T06:15:19.000Z | package webstrategy
import (
"errors"
"net/http"
"strings"
"sync"
"time"
"k8s.io/api/core/v1"
"k8s.io/client-go/kubernetes"
"github.com/gogo/googleapis/google/rpc"
"github.com/gogo/protobuf/types"
"github.com/gorilla/securecookie"
"go.uber.org/zap"
"gopkg.in/mgo.v2/bson"
"istio.io/api/mixer/adapter/model/v1beta1"
policy "istio.io/api/policy/v1beta1"
"istio.io/istio/mixer/pkg/status"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"github.com/ibm-cloud-security/app-identity-and-access-adapter/adapter/authserver"
"github.com/ibm-cloud-security/app-identity-and-access-adapter/adapter/client"
"github.com/ibm-cloud-security/app-identity-and-access-adapter/adapter/config"
oAuthError "github.com/ibm-cloud-security/app-identity-and-access-adapter/adapter/errors"
"github.com/ibm-cloud-security/app-identity-and-access-adapter/adapter/networking"
policiesV1 "github.com/ibm-cloud-security/app-identity-and-access-adapter/adapter/pkg/apis/policies/v1"
adapterPolicy "github.com/ibm-cloud-security/app-identity-and-access-adapter/adapter/policy"
"github.com/ibm-cloud-security/app-identity-and-access-adapter/adapter/policy/engine"
"github.com/ibm-cloud-security/app-identity-and-access-adapter/adapter/strategy"
"github.com/ibm-cloud-security/app-identity-and-access-adapter/adapter/validator"
"github.com/ibm-cloud-security/app-identity-and-access-adapter/config/template"
)
const (
bearer = "Bearer"
logoutEndpoint = "/oidc/logout"
callbackEndpoint = "/oidc/callback"
location = "location"
setCookie = "Set-Cookie"
sessionCookie = "oidc-cookie"
hashKey = "HASH_KEY"
blockKey = "BLOCK_KEY"
defaultNamespace = "istio-system"
defaultKeySecret = "appidentityandaccessadapter-cookie-sig-enc-keys"
// Cookies to use when we revert to statelessness
// accessTokenCookie = "appidentityandaccessadapter-access-cookie"
// idTokenCookie = "appidentityandaccessadapter-identity-cookie"
// refreshTokenCookie = "appidentityandaccessadapter-identity-cookie"
)
// WebStrategy handles OAuth 2.0 / OIDC flows
type WebStrategy struct {
ctx *config.Config
tokenUtil validator.TokenValidator
kubeClient kubernetes.Interface
// mutex protects all fields below
mutex *sync.Mutex
encrpytor Encryptor
tokenCache *sync.Map
}
// Encryptor signs and encrypts values. Used for cookie encryption
type Encryptor interface {
Encode(name string, value interface{}) (string, error)
Decode(name, value string, dst interface{}) error
}
// OidcCookie represents a token stored in browser
type OidcCookie struct {
Value string
Expiration time.Time
}
// New creates an instance of an OIDC protection agent.
func New(ctx *config.Config, kubeClient kubernetes.Interface) strategy.Strategy {
w := &WebStrategy{
ctx: ctx,
tokenUtil: validator.NewTokenValidator(adapterPolicy.OIDC),
kubeClient: kubeClient,
mutex: &sync.Mutex{},
tokenCache: new(sync.Map),
}
// Instantiate the secure cookie encryption instance by
// reading or creating a new HMAC and AES symmetric key
_, err := w.getSecureCookie()
if err != nil {
zap.L().Warn("Could not sync signing / encryption secrets, will retry later", zap.Error(err))
}
return w
}
// HandleAuthnZRequest acts as the entry point to an OAuth 2.0 / OIDC flow. It processes OAuth 2.0 / OIDC requests.
func (w *WebStrategy) HandleAuthnZRequest(r *authnz.HandleAuthnZRequest, action *engine.Action) (*authnz.HandleAuthnZResponse, error) {
if strings.HasSuffix(r.Instance.Request.Path, logoutEndpoint) {
zap.L().Debug("Received logout request.", zap.String("client_name", action.Client.Name()))
return w.handleLogout(r, action)
}
if strings.HasSuffix(r.Instance.Request.Path, callbackEndpoint) {
if r.Instance.Request.Params.Error != "" {
zap.L().Debug("An error occurred during authentication", zap.String("error_query_param", r.Instance.Request.Params.Error))
return w.handleErrorCallback(errors.New(r.Instance.Request.Params.Error))
} else if r.Instance.Request.Params.Code != "" {
zap.L().Debug("Received authorization code")
return w.handleAuthorizationCodeCallback(r.Instance.Request.Params.Code, r.Instance.Request, action)
} else {
zap.L().Debug("Unexpected response on callback endpoint /oidc/callback. Triggering re-authentication.")
return w.handleAuthorizationCodeFlow(r.Instance.Request, action)
}
}
// Not in an OAuth 2.0 / OIDC flow, check for current authn/z session
res, err := w.isAuthorized(r.Instance.Request.Headers.Cookies, action)
if res != nil || err != nil {
return res, err
}
zap.L().Debug("Handling new user authentication")
return w.handleAuthorizationCodeFlow(r.Instance.Request, action)
}
// isAuthorized checks for the existence of valid cookies
// returns an error in the event of an Internal Server Error
func (w *WebStrategy) isAuthorized(cookies string, action *engine.Action) (*authnz.HandleAuthnZResponse, error) {
if action.Client == nil {
zap.L().Warn("Internal server error: OIDC client not provided")
return nil, errors.New("invalid OIDC configuration")
}
// Parse Cookies
header := http.Header{}
header.Add("Cookie", cookies)
request := http.Request{Header: header}
sessionCookie, err := request.Cookie(buildTokenCookieName(sessionCookie, action.Client))
if err != nil {
zap.L().Debug("Current session does not exist.", zap.String("client_name", action.Client.Name()))
return nil, nil
}
// Load session information
var session *authserver.TokenResponse
if storedSession, ok := w.tokenCache.Load(sessionCookie.Value); !ok {
zap.L().Debug("Tokens not found in cache.", zap.String("client_name", action.Client.Name()))
return nil, nil
} else if session, ok = storedSession.(*authserver.TokenResponse); !ok {
zap.L().Debug("Tokens not found in cache.", zap.String("client_name", action.Client.Name()))
return nil, nil
}
zap.L().Debug("Found active session", zap.String("client_name", action.Client.Name()), zap.String("session_id", sessionCookie.Value))
// Validate session
userInfoEndpoint := action.Client.AuthorizationServer().UserInfoEndpoint()
keySet := action.Client.AuthorizationServer().KeySet()
handleTokenValidationError := func(validationErr *oAuthError.OAuthError) (*authnz.HandleAuthnZResponse, error) {
if validationErr.Msg == oAuthError.ExpiredTokenError().Msg {
zap.L().Debug("Tokens have expired", zap.String("client_name", action.Client.Name()))
return w.handleRefreshTokens(sessionCookie.Value, session, action.Client, action.Rules)
}
zap.L().Debug("Tokens are invalid - starting a new session", zap.String("client_name", action.Client.Name()), zap.String("session_id", sessionCookie.Value), zap.Error(validationErr))
w.tokenCache.Delete(sessionCookie.Value)
return nil, nil
}
if validationErr := w.tokenUtil.Validate(session.AccessToken, validator.Access, keySet, action.Rules, userInfoEndpoint); validationErr != nil {
return handleTokenValidationError(validationErr)
}
if validationErr := w.tokenUtil.Validate(session.IdentityToken, validator.ID, keySet, action.Rules, userInfoEndpoint); validationErr != nil {
return handleTokenValidationError(validationErr)
}
zap.L().Debug("User is currently authenticated")
// Pass request through to service
return &authnz.HandleAuthnZResponse{
Result: &v1beta1.CheckResult{Status: status.WithMessage(rpc.OK, "User is authenticated")},
Output: &authnz.OutputMsg{
Authorization: strings.Join([]string{bearer, session.AccessToken, session.IdentityToken}, " "),
},
}, nil
}
// handleRefreshTokens attempts to update an expired session using the refresh token flow
func (w *WebStrategy) handleRefreshTokens(sessionID string, session *authserver.TokenResponse, c client.Client, rules []policiesV1.Rule) (*authnz.HandleAuthnZResponse, error) {
if session.RefreshToken == "" {
zap.L().Debug("Refresh token not provided", zap.String("client_name", c.Name()))
return nil, nil
}
userInfoEndpoint := c.AuthorizationServer().UserInfoEndpoint()
keySet := c.AuthorizationServer().KeySet()
if tokens, err := c.RefreshToken(session.RefreshToken); err != nil {
zap.L().Info("Could not retrieve tokens using the refresh token", zap.String("client_name", c.Name()), zap.Error(err))
return nil, nil
} else if validationErr := w.tokenUtil.Validate(tokens.AccessToken, validator.Access, keySet, rules, userInfoEndpoint); validationErr != nil {
zap.L().Debug("Could not validate Access tokens. Beginning a new session.", zap.String("client_name", c.Name()), zap.String("session_id", sessionID), zap.Error(validationErr))
return nil, nil
} else if validationErr := w.tokenUtil.Validate(tokens.IdentityToken, validator.ID, keySet, rules, userInfoEndpoint); validationErr != nil {
zap.L().Debug("Could not validate Id tokens. Beginning a new session.", zap.String("client_name", c.Name()), zap.String("session_id", sessionID), zap.Error(validationErr))
return nil, nil
} else {
zap.L().Debug("Updated tokens using refresh token", zap.String("client_name", c.Name()), zap.String("session_id", sessionID))
cookie := generateSessionIDCookie(c, &sessionID)
w.tokenCache.Store(cookie.Value, tokens)
return &authnz.HandleAuthnZResponse{
Result: &v1beta1.CheckResult{Status: status.WithMessage(rpc.OK, "User is authenticated")},
Output: &authnz.OutputMsg{
Authorization: strings.Join([]string{bearer, tokens.AccessToken, tokens.IdentityToken}, " "),
SessionCookie: cookie.String(),
},
}, nil
}
}
// handleErrorCallback returns an Unauthenticated CheckResult
func (w *WebStrategy) handleErrorCallback(err error) (*authnz.HandleAuthnZResponse, error) {
message := "internal server error"
if err != nil {
message = err.Error()
}
return &authnz.HandleAuthnZResponse{
Result: &v1beta1.CheckResult{Status: rpc.Status{
Code: int32(rpc.UNAUTHENTICATED),
Message: message,
}},
}, nil
}
// handleLogout processes logout requests by deleting session cookies and returning to the base path
func (w *WebStrategy) handleLogout(r *authnz.HandleAuthnZRequest, action *engine.Action) (*authnz.HandleAuthnZResponse, error) {
header := http.Header{}
header.Add("Cookie", r.Instance.Request.Headers.Cookies)
request := http.Request{Header: header}
cookieName := buildTokenCookieName(sessionCookie, action.Client)
if cookie, err := request.Cookie(cookieName); err == nil {
zap.L().Debug("Deleting active session", zap.String("client_name", action.Client.Name()), zap.String("session_id", cookie.Value))
w.tokenCache.Delete(cookie.Value)
}
redirectURL := strings.Split(r.Instance.Request.Path, logoutEndpoint)[0]
cookies := []*http.Cookie{
{
Name: cookieName,
Value: "deleted",
Path: "/",
Expires: time.Now().Add(-100 * time.Hour),
},
}
return buildSuccessRedirectResponse(redirectURL, cookies), nil
}
/*
func (w *WebStrategy) handleLogout(path string, action *engine.Action) (*authnz.HandleAuthnZResponse, error) {
// Uncomment when we go stateless
expiration := time.Now().Add(-100 * time.Hour)
cookies := make([]*http.Cookie, 3)
for i, name := range []string{accessTokenCookie, idTokenCookie, refreshTokenCookie} {
cookies[i] = &http.Cookie{
Name: buildTokenCookieName(name, action.Client),
Value: "deleted",
Path: "/",
Expires: expiration,
}
}
redirectURL := strings.Split(path, logoutEndpoint)[0]
return buildSuccessRedirectResponse(redirectURL, cookies), nil
}
*/
// handleAuthorizationCodeCallback processes a successful OAuth 2.0 callback containing a authorization code
func (w *WebStrategy) handleAuthorizationCodeCallback(code interface{}, request *authnz.RequestMsg, action *engine.Action) (*authnz.HandleAuthnZResponse, error) {
err := w.validateState(request, action.Client)
if err != nil {
zap.L().Info("OIDC callback: could not validate state parameter", zap.Error(err), zap.String("client_name", action.Client.Name()))
return w.handleErrorCallback(err)
}
redirectURI := buildRequestURL(request)
// Exchange authorization grant code for tokens
response, err := action.Client.ExchangeGrantCode(code.(string), redirectURI)
if err != nil {
zap.L().Info("OIDC callback: Could not retrieve tokens", zap.Error(err), zap.String("client_name", action.Client.Name()))
return w.handleErrorCallback(err)
}
userInfoEndpoint := action.Client.AuthorizationServer().UserInfoEndpoint()
keySet := action.Client.AuthorizationServer().KeySet()
validationErr := w.tokenUtil.Validate(response.AccessToken, validator.Access, keySet, action.Rules, userInfoEndpoint)
if validationErr != nil {
zap.L().Info("OIDC callback: Access token failed validation", zap.Error(validationErr), zap.String("client_name", action.Client.Name()))
return w.handleErrorCallback(validationErr)
}
validationErr = w.tokenUtil.Validate(response.IdentityToken, validator.ID, keySet, action.Rules, userInfoEndpoint)
if validationErr != nil {
zap.L().Info("OIDC callback: ID token failed validation", zap.Error(validationErr), zap.String("client_name", action.Client.Name()))
return w.handleErrorCallback(validationErr)
}
cookie := generateSessionIDCookie(action.Client, nil)
w.tokenCache.Store(cookie.Value, response)
zap.L().Debug("OIDC callback: created new active session: ", zap.String("client_name", action.Client.Name()), zap.String("session_id", cookie.Value))
if action.RedirectUri != "" {
redirectURI = action.RedirectUri
}
return buildSuccessRedirectResponse(redirectURI, []*http.Cookie{cookie}), nil
}
// handleAuthorizationCodeFlow initiates an OAuth 2.0 / OIDC authorization_code grant flow.
func (w *WebStrategy) handleAuthorizationCodeFlow(request *authnz.RequestMsg, action *engine.Action) (*authnz.HandleAuthnZResponse, error) {
redirectURI := buildRequestURL(request) + callbackEndpoint
// / Build and store session state
state, stateCookie, err := w.buildStateParam(action.Client)
if err != nil {
zap.L().Info("Could not generate state parameter", zap.Error(err), zap.String("client_name", action.Client.Name()))
return nil, err
}
zap.S().Debugf("Initiating redirect to identity provider using redirect URL: %s", redirectURI)
return &authnz.HandleAuthnZResponse{
Result: &v1beta1.CheckResult{
Status: rpc.Status{
Code: int32(rpc.UNAUTHENTICATED), // Response tells Mixer to reject request
Message: "Redirecting to identity provider",
Details: []*types.Any{status.PackErrorDetail(&policy.DirectHttpResponse{
Code: policy.Found, // Response Mixer remaps on request
Headers: map[string]string{
location: generateAuthorizationURL(action.Client, redirectURI, state),
setCookie: stateCookie.String(),
},
})},
},
},
}, nil
}
// getSecureCookie retrieves the SecureCookie encryption struct in a
// thread safe manner.
func (w *WebStrategy) getSecureCookie() (Encryptor, error) {
// Allow all threads to check if instance already exists
if w.encrpytor != nil {
return w.encrpytor, nil
}
w.mutex.Lock()
// Once this thread has the lock check again to see if it had been set while waiting
if w.encrpytor != nil {
w.mutex.Unlock()
return w.encrpytor, nil
}
// We need to generate a new key set
sc, err := w.generateSecureCookie()
w.mutex.Unlock()
return sc, err
}
// generateSecureCookie instantiates a SecureCookie instance using either the preconfigured
// key secret cookie or a dynamically generated pair.
func (w *WebStrategy) generateSecureCookie() (Encryptor, error) {
var secret interface{}
// Check if key set was already configured. This should occur during helm install
secret, err := networking.Retry(3, 1, func() (interface{}, error) {
return w.kubeClient.CoreV1().Secrets(defaultNamespace).Get(defaultKeySecret, metav1.GetOptions{})
})
if err != nil {
zap.S().Infof("Secret %v not found: %v. Another will be generated.", defaultKeySecret, err)
secret, err = w.generateKeySecret(w.ctx.HashKeySize.Value, w.ctx.BlockKeySize.Value)
if err != nil {
zap.L().Info("Failed to retrieve tokens", zap.Error(err))
return nil, err
}
}
if s, ok := secret.(*v1.Secret); ok {
zap.S().Infof("Synced secret: %v", defaultKeySecret)
w.encrpytor = securecookie.New(s.Data[hashKey], s.Data[blockKey])
return w.encrpytor, nil
} else {
zap.S().Error("Could not convert interface to secret")
return nil, errors.New("could not sync signing / encryption secrets")
}
}
// generateKeySecret builds and stores a key pair used for the signing and encryption
// of session cookies.
func (w *WebStrategy) generateKeySecret(hashKeySize int, blockKeySize int) (interface{}, error) {
data := make(map[string][]byte)
data[hashKey] = securecookie.GenerateRandomKey(hashKeySize)
data[blockKey] = securecookie.GenerateRandomKey(blockKeySize)
newSecret := v1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: defaultKeySecret,
Namespace: defaultNamespace,
},
Data: data,
}
return networking.Retry(3, 1, func() (interface{}, error) {
return w.kubeClient.CoreV1().Secrets(defaultNamespace).Create(&newSecret)
})
}
// generateEncryptedCookie creates an encodes and encrypts cookieData into an http.Cookie
func (w *WebStrategy) generateEncryptedCookie(cookieName string, cookieData *OidcCookie) (*http.Cookie, error) {
// encode the struct
data, err := bson.Marshal(&cookieData)
if err != nil {
zap.L().Warn("Could not marshal cookie data", zap.Error(err))
return nil, err
}
sc, err := w.getSecureCookie()
if err != nil {
zap.L().Warn("Could not get secure cookie instance", zap.Error(err))
return nil, err
}
// create the cookie
if encoded, err := sc.Encode(cookieName, data); err == nil {
return &http.Cookie{
Name: cookieName,
Value: encoded,
Path: "/",
Secure: false, // TODO: DO NOT RELEASE WITHOUT THIS FLAG SET TO TRUE
HttpOnly: false,
Expires: time.Now().Add(time.Hour * time.Duration(4)),
}, nil
} else {
zap.S().Error("Error encoding cookie: length: %s", len(encoded))
return nil, err
}
}
// parseAndValidateCookie parses a raw http.Cookie, performs basic validation
// and returns an OIDCCookie
func (w *WebStrategy) parseAndValidateCookie(cookie *http.Cookie) *OidcCookie {
if cookie == nil {
zap.L().Debug("Cookie does not exist")
return nil
}
sc, err := w.getSecureCookie()
if err != nil {
zap.L().Debug("Error getting securecookie", zap.Error(err))
return nil
}
value := []byte{}
if err := sc.Decode(cookie.Name, cookie.Value, &value); err != nil {
zap.L().Debug("Could not decode cookie:", zap.Error(err))
return nil
}
cookieObj := OidcCookie{}
if err := bson.Unmarshal(value, &cookieObj); err != nil {
zap.L().Debug("Could not unmarshal cookie:", zap.Error(err))
return nil
}
if cookieObj.Value == "" {
zap.L().Debug("Cookie does not have a token value")
return nil
}
if cookieObj.Expiration.Before(time.Now()) {
zap.S().Debug("Cookies have expired: %v - %v", cookieObj.Expiration, time.Now())
return nil
}
return &cookieObj
}
// buildSuccessRedirectResponse constructs a HandleAuthnZResponse containing a 302 redirect
// to the provided url with the accompanying cookie headers
func buildSuccessRedirectResponse(redirectURI string, cookies []*http.Cookie) *authnz.HandleAuthnZResponse {
headers := make(map[string]string)
headers[location] = strings.Split(redirectURI, callbackEndpoint)[0]
for _, cookie := range cookies {
headers[setCookie] = cookie.String()
zap.S().Debugf("Appending cookie to response: %s", cookie.String())
}
zap.S().Debugf("Authenticated. Redirecting to %s", headers[location])
return &authnz.HandleAuthnZResponse{
Result: &v1beta1.CheckResult{
Status: rpc.Status{
Code: int32(rpc.UNAUTHENTICATED), // Response tells Mixer to reject request
Message: "Successfully authenticated : redirecting to original URL",
Details: []*types.Any{status.PackErrorDetail(&policy.DirectHttpResponse{
Code: policy.Found, // Response Mixer remaps on request
Headers: headers,
})},
},
},
}
}
func (w *WebStrategy) buildStateParam(c client.Client) (string, *http.Cookie, error) {
state := randString(10)
cookieName := buildTokenCookieName(sessionCookie, c)
cookie, err := w.generateEncryptedCookie(cookieName, &OidcCookie{
Value: state,
Expiration: time.Now().Add(time.Hour),
})
return state, cookie, err
}
// validateState ensures the callback request state parameter matches the state stored in an encrypted session cookie
// Follows from OAuth 2.0 specification https://tools.ietf.org/html/rfc6749#section-4.1.1
func (w *WebStrategy) validateState(request *authnz.RequestMsg, c client.Client) error {
// Get state cookie from header
header := http.Header{
"Cookie": {request.Headers.Cookies},
}
r := http.Request{Header: header}
name := buildTokenCookieName(sessionCookie, c)
oidcStateCookie, err := r.Cookie(name)
if err != nil {
return errors.New("state parameter not provided")
}
// Parse encrypted state cookie
storedHttpCookie := w.parseAndValidateCookie(oidcStateCookie)
// Ensure state cookie is returned
if storedHttpCookie == nil {
stateError := errors.New("missing state parameter")
zap.L().Info("OIDC callback: missing stored state parameter", zap.Error(err))
return stateError
}
// Ensure state is returned on request from identity provider
if request.Params.State == "" {
stateError := errors.New("missing state parameter from callback")
zap.L().Info("OIDC callback: missing state parameter from identity provider", zap.Error(err))
return stateError
}
// Validate cookie state with stored state
if request.Params.State != storedHttpCookie.Value {
stateError := errors.New("invalid state parameter")
zap.L().Info("OIDC callback: missing or invalid state parameter", zap.Error(err))
return stateError
}
zap.L().Debug("OIDC callback: validated state parameter")
return nil
}
| 39.103757 | 184 | 0.734617 |
6471c9a1ce53da654057a8211610b7466d44c204 | 144 | tab | SQL | test/mapdata/reclass/reclass2_nodata.tab | VITObelgium/geodynamix | 6d3323bc4cae1b85e26afdceab2ecf3686b11369 | [
"MIT"
] | null | null | null | test/mapdata/reclass/reclass2_nodata.tab | VITObelgium/geodynamix | 6d3323bc4cae1b85e26afdceab2ecf3686b11369 | [
"MIT"
] | null | null | null | test/mapdata/reclass/reclass2_nodata.tab | VITObelgium/geodynamix | 6d3323bc4cae1b85e26afdceab2ecf3686b11369 | [
"MIT"
] | 1 | 2021-06-16T11:55:27.000Z | 2021-06-16T11:55:27.000Z | 0 0 100
0 1 101
0 2 102
0 nan 109
1 0 110
1 1 111
1 2 112
1 nan 119
2 0 120
2 1 121
2 2 122
2 nan 129
nan 0 190
nan 1 191
nan 2 192
nan nan 199
| 8.470588 | 11 | 0.666667 |
7de84378ab052efd3bfe019c5e74b04cecad1a6b | 803 | swift | Swift | CovidApp/CovidApp/Managers/App.swift | diegobootia/CovidApp | 6ff79a99ffebf9c2c1e48e24e97e5f4268bf3bba | [
"MIT"
] | null | null | null | CovidApp/CovidApp/Managers/App.swift | diegobootia/CovidApp | 6ff79a99ffebf9c2c1e48e24e97e5f4268bf3bba | [
"MIT"
] | null | null | null | CovidApp/CovidApp/Managers/App.swift | diegobootia/CovidApp | 6ff79a99ffebf9c2c1e48e24e97e5f4268bf3bba | [
"MIT"
] | null | null | null | //
// App.swift
// CovidApp
//
// Created by Diego Varangot on 24/4/21.
//
import UIKit
class App {
static let shared = App()
var token: String? {
didSet {
UserDefaults.standard.set(token, forKey: K.UserDefaultsKeys.token)
}
}
var isLoggedIn: Bool { return token != nil }
var deviceTokenData: Data? {
didSet {
guard let data = deviceTokenData else { return }
UserDefaults.standard.set(data, forKey: K.UserDefaultsKeys.deviceTokenData)
}
}
var statusBarStyle: UIStatusBarStyle = .lightContent
private init() {
token = UserDefaults.standard.string(forKey: K.UserDefaultsKeys.token)
deviceTokenData = UserDefaults.standard.data(forKey: K.UserDefaultsKeys.deviceTokenData)
}
}
| 22.942857 | 96 | 0.636364 |
7009729810d3d650d355d5f18bff30139ad26e32 | 2,134 | go | Go | vendor/github.com/docker/docker/daemon/network_operations.go | tetatetit/rancher_os | ba73b74dbb2375a5f7f5eae2ba1f189191295e17 | [
"Apache-2.0"
] | 3 | 2017-01-15T07:06:13.000Z | 2017-03-15T21:42:25.000Z | vendor/github.com/docker/docker/daemon/network_operations.go | tetatetit/rancher_os | ba73b74dbb2375a5f7f5eae2ba1f189191295e17 | [
"Apache-2.0"
] | 3 | 2021-05-21T00:20:07.000Z | 2022-02-26T10:49:36.000Z | vendor/github.com/docker/docker/daemon/network_operations.go | tetatetit/rancher_os | ba73b74dbb2375a5f7f5eae2ba1f189191295e17 | [
"Apache-2.0"
] | 2 | 2018-09-29T08:43:20.000Z | 2019-09-17T12:40:27.000Z | package daemon
import (
"fmt"
"os"
"github.com/docker/docker/container"
derr "github.com/docker/docker/errors"
networktypes "github.com/docker/engine-api/types/network"
)
func (daemon *Daemon) updateContainerNetworkSettings(container *container.Container, endpointsConfig map[string]*networktypes.EndpointSettings) error {
return nil
}
func (daemon *Daemon) updateNetwork(container *container.Container) error {
return nil
}
func (daemon *Daemon) allocateNetwork(container *container.Container) error {
return nil
}
func (daemon *Daemon) releaseNetwork(container *container.Container) {
if container.HostConfig.NetworkMode.IsContainer() || container.Config.NetworkDisabled {
return
}
}
func (daemon *Daemon) getNetworkedContainer(containerID, connectedContainerID string) (*container.Container, error) {
nc, err := daemon.GetContainer(connectedContainerID)
if err != nil {
return nil, err
}
if containerID == nc.ID {
return nil, fmt.Errorf("cannot join own network")
}
if !nc.IsRunning() {
err := fmt.Errorf("cannot join network of a non running container: %s", connectedContainerID)
return nil, derr.NewRequestConflictError(err)
}
if nc.IsRestarting() {
return nil, errContainerIsRestarting(connectedContainerID)
}
return nc, nil
}
func (daemon *Daemon) initializeNetworking(container *container.Container) error {
var err error
if container.HostConfig.NetworkMode.IsContainer() {
// we need to get the hosts files from the container to join
nc, err := daemon.getNetworkedContainer(container.ID, container.HostConfig.NetworkMode.ConnectedContainer())
if err != nil {
return err
}
container.HostnamePath = nc.HostnamePath
container.HostsPath = nc.HostsPath
container.ResolvConfPath = nc.ResolvConfPath
container.Config.Hostname = nc.Config.Hostname
container.Config.Domainname = nc.Config.Domainname
return nil
}
if container.HostConfig.NetworkMode.IsHost() {
container.Config.Hostname, err = os.Hostname()
if err != nil {
return err
}
}
if err := daemon.allocateNetwork(container); err != nil {
return err
}
return container.BuildHostnameFile()
}
| 27.358974 | 151 | 0.755389 |
1ff15d8351e0e672161df3846a5de2ebfb681230 | 19,629 | asm | Assembly | base/ntos/ke/i386/callout.asm | 987432340/wrk-v1.2 | 423d4c22b892bcc97778385bc0a646ed7a3cfbde | [
"Intel"
] | 1 | 2022-03-12T13:57:18.000Z | 2022-03-12T13:57:18.000Z | base/ntos/ke/i386/callout.asm | 987432340/wrk-v1.2 | 423d4c22b892bcc97778385bc0a646ed7a3cfbde | [
"Intel"
] | null | null | null | base/ntos/ke/i386/callout.asm | 987432340/wrk-v1.2 | 423d4c22b892bcc97778385bc0a646ed7a3cfbde | [
"Intel"
] | 1 | 2021-11-25T08:18:04.000Z | 2021-11-25T08:18:04.000Z | title "Call Out to User Mode"
;++
;
; Copyright (c) Microsoft Corporation. All rights reserved.
;
; You may only use this code if you agree to the terms of the Windows Research Kernel Source Code License agreement (see License.txt).
; If you do not agree to the terms, do not use the code.
;
;
; Module Name:
;
; callout.asm
;
; Abstract:
;
; This module implements the code necessary to call out from kernel
; mode to user mode.
;
;--
.386p
.xlist
include ks386.inc
include i386\kimacro.inc
include callconv.inc
include irqli386.inc
.list
extrn _KiServiceExit:PROC
extrn _KeUserCallbackDispatcher:DWORD
EXTRNP _KeBugCheck2,6
EXTRNP _MmGrowKernelStack,1
_TEXT SEGMENT DWORD PUBLIC 'CODE'
ASSUME DS:FLAT, ES:FLAT, SS:FLAT, FS:NOTHING, GS:NOTHING
page ,132
subttl "Call User Mode Function"
;++
;
; NTSTATUS
; KiCallUserMode (
; IN PVOID *Outputbuffer,
; IN PULONG OutputLength
; )
;
; Routine Description:
;
; This function calls a user mode function from kernel mode.
;
; N.B. This function calls out to user mode and the NtCallbackReturn
; function returns back to the caller of this function. Therefore,
; the stack layout must be consistent between the two routines.
;
; Arguments:
;
; OutputBuffer - Supplies a pointer to the variable that receives
; the address of the output buffer.
;
; OutputLength - Supplies a pointer to a variable that receives
; the length of the output buffer.
;
; Return Value:
;
; The final status of the call out function is returned as the status
; of the function.
;
; N.B. This function does not return to its caller. A return to the
; caller is executed when a NtCallbackReturn system service is
; executed.
;
; N.B. This function does return to its caller if a kernel stack
; expansion is required and the attempted expansion fails.
;
;--
;
; To support the debugger, the callback stack frame is now defined in i386.h.
; If the stack frame is changed, i386.h must be updated and geni386
; rebuilt and run, then rebuild this file and ntos\kd.
;
; The FPO record below must also be updated to correctly represent
; the stack frame.
;
cPublicProc _KiCallUserMode, 2
.FPO (3, 2, 4, 4, 0, 0)
;
; Save nonvolatile registers.
;
push ebp ; save nonvolatile registers
push ebx ;
push esi ;
push edi ;
mov ebx,PCR[PcPrcbData + PbCurrentThread] ; get current thread address
;
; Check if the current IRQL is above passive level.
;
if DBG
CurrentIrql ; get current IRQL
or al,al ; check if IRQL is passive level
jz short Kcb00 ; if z, IRQL at passive level
stdCall _KeBugCheck2,<IRQL_GT_ZERO_AT_SYSTEM_SERVICE,0,eax,0,0,0>
;
; Check if kernel APCs are disabled or a process is attached.
;
Kcb00: movzx eax,byte ptr[ebx]+ThApcStateIndex ; get APC state index
mov edx,[ebx]+ThCombinedApcDisable ; get kernel APC disable
or eax,eax ; check if process attached
jne short Kcb05 ; if ne, process is attached
or edx,edx ; check if kernel APCs disabled
jz short Kcb07 ; if z, kernel APCs enabled
Kcb05: stdCall _KeBugCheck2,<APC_INDEX_MISMATCH,0,eax,edx,0,0>
endif
;
; Check if sufficient room is available on the kernel stack for another
; system call.
;
Kcb07: lea eax,[esp]-KERNEL_LARGE_STACK_COMMIT ; compute bottom address
cmp eax,[ebx]+ThStackLimit ; check if limit exceeded
jae short Kcb10 ; if ae, limit not exceeded
stdCall _MmGrowKernelStack,<esp> ; attempt to grow kernel stack
or eax, eax ; check for successful completion
jne Kcb20 ; if ne, attempt to grow failed
;
; Get the address of the current thread and save the previous trap frame
; and callback stack addresses in the current frame. Also save the new
; callback stack address in the thread object.
;
Kcb10: push [ebx].ThCallbackStack ; save callback stack address
mov edx,[ebx].ThTrapFrame ; get current trap frame address
push edx ; save trap frame address
mov esi,[ebx].ThInitialStack ; get initial stack address
push esi ; save initial stack address
mov [ebx].ThCallbackStack,esp ; save callback stack address
KcbPrologEnd: ; help for the debugger
;
; Copy the numeric save area from the previous save area to the new save
; area and establish a new initial kernel stack.
;
; Make sure that the destination NPX Save area is 16-byte aligned
; as required by fxsave\fxrstor
;
and esp, 0fffffff0h ;
mov edi,esp ; set new initial stack address
sub esp,NPX_FRAME_LENGTH ; compute destination NPX save area
sub esi,NPX_FRAME_LENGTH ; compute source NPX save area
cli ; disable interrupts
mov ecx,[esi].FpControlWord ; copy NPX state to new frame
mov [esp].FpControlWord,ecx ;
mov ecx,[esi].FpStatusWord ;
mov [esp].FpStatusWord,ecx ;
mov ecx,[esi].FpTagWord ;
mov [esp].FpTagWord,ecx ;
mov ecx,[esi].FxMXCsr ;
mov [esp].FxMXCsr,ecx ;
mov ecx,[esi].FpCr0NpxState ;
mov [esp].FpCr0NpxState,ecx ;
mov esi,PCR[PcTss] ; get address of task switch segment
mov [ebx].ThInitialStack,edi ; reset initial stack address
mov ecx, esp ;
sub esp,TsV86Gs - TsHardwareSegSs ; bias for missing V86 fields
.errnz (EFLAGS_V86_MASK AND 0FF00FFFFh)
test byte ptr [edx]+TsEFlags+2,EFLAGS_V86_MASK/010000h ; is this a V86 frame?
jne @f
mov ecx, esp ; Use adjusted esp (normal case)
@@: mov [esi].TssEsp0,ecx ; set kernel entry stack address
;
; Construct a trap frame to facilitate the transfer into user mode via
; the standard system call exit.
;
sub esp,TsHardwareSegSs + 4 ; allocate trap frame
mov ebp,esp ; set address of trap frame
mov ecx,(TsHardwareSegSs - TsSegFs + 4) / 4; set repeat count
lea edi,[esp].TsSegFs ; set destination address
lea esi,[edx].TsSegFs ; set source address
rep movsd ; copy trap information
mov edi, [edx].TsDr7 ; Fetch control register
test edi, (NOT DR7_RESERVED_MASK) ; Do we need to restore Debug reg?
mov [esp].TsDr7, edi ; Save away Dr7
jnz short Kcb18 ; Yes, go save them.
Kcb15: mov eax,_KeUserCallbackDispatcher ; st address of callback dispatcher
mov [esp].TsEip,eax ;
mov eax,PCR[PcExceptionList] ; get current exception list
mov [esp].TsExceptionList,eax ; set previous exception list
mov eax,[edx].TsPreviousPreviousMode ; get previous mode
mov [esp].TsPreviousPreviousMode,eax ; set previous mode
sti ; enable interrupts
SET_DEBUG_DATA ; set system call debug data for exit
jmp _KiServiceExit ; exit through service dispatch
Kcb18:
mov ecx,(TsDr6 - TsDr0 + 4) / 4; set repeat count
lea edi,[esp].TsDr0 ; set destination address
lea esi,[edx].TsDr0 ; set source address
rep movsd ; copy trap information
jmp short Kcb15
;
; An attempt to grow the kernel stack failed.
;
Kcb20: pop edi ; restore nonvolitile register
pop esi ;
pop ebx ;
pop ebp ;
stdRET _KiCallUserMode
stdENDP _KiCallUserMode
page ,132
subttl "Switch Kernel Stack"
;++
;
; PVOID
; KeSwitchKernelStack (
; IN PVOID StackBase,
; IN PVOID StackLimit
; )
;
; Routine Description:
;
; This function switches to the specified large kernel stack.
;
; N.B. This function can ONLY be called when there are no variables
; in the stack that refer to other variables in the stack, i.e.,
; there are no pointers into the stack.
;
; Arguments:
;
; StackBase (esp + 4) - Supplies a pointer to the base of the new kernel
; stack.
;
; StackLimit (esp + 8) - Supplies a pointer to the limit of the new kernel
; stack.
;
; Return Value:
;
; The old kernel stack is returned as the function value.
;
;--
SsStkBs equ 4 ; new kernel stack base address
SsStkLm equ 8 ; new kernel stack limit address
cPublicProc _KeSwitchKernelStack, 2
;
; Save the address of the new stack and copy the old stack to the new
; stack.
;
push esi ; save string move registers
push edi ;
mov edx,PCR[PcPrcbData + PbCurrentThread] ; get current thread address
mov edi,[esp]+SsStkBs + 8 ; get new kernel stack base address
mov ecx,[edx].ThStackBase ; get current stack base address
sub ebp,ecx ; relocate the callers frame pointer
add ebp,edi ;
mov eax,[edx].ThTrapFrame ; relocate the current trap frame address
sub eax,ecx ;
add eax,edi ;
mov [edx].ThTrapFrame,eax ;
sub ecx,esp ; compute length of copy
sub edi,ecx ; set destination address of copy
mov esi,esp ; set source address of copy
push edi ; save new stack pointer address
rep movsb ; copy old stack to new stack
pop edi ; restore new stack pointer address
;
; Switch to the new kernel stack and return the address of the old kernel
; stack.
;
mov eax,[edx].ThStackBase ; get old kernel stack base address
mov ecx,[esp]+SsStkBs + 8 ; get new kernel stack base address
mov esi,[esp]+SsStkLm + 8 ; get new kernel stack limit address
cli ; disable interrupts
mov [edx].ThStackBase,ecx ; set new kernel stack base address
mov [edx].ThStackLimit,esi ; set new kernel stack limit address
mov byte ptr [edx].ThLargeStack, 1 ; set large stack TRUE
mov [edx].ThInitialStack,ecx ; set new initial stack address
mov esi,[edx].ThTrapFrame ; Get current trap frame address
mov edx,PCR[PcTss] ; get address of task switch segment
.errnz (EFLAGS_V86_MASK AND 0FF00FFFFh)
test byte ptr [esi]+TsEFlags+2,EFLAGS_V86_MASK/010000h ; is this a V86 frame?
lea ecx, dword ptr [ecx-NPX_FRAME_lENGTH] ; compute NPX save area address
jne @f
sub ecx,TsV86Gs - TsHardwareSegSs ; bias for missing V86 fields
@@: mov [edx].TssEsp0,ecx ; set kernel entry stack address
mov esp,edi ; set new stack pointer address
sti ;
pop edi ; restore string move registers
pop esi ;
stdRET _KeSwitchKernelStack
stdENDP _KeSwitchKernelStack
page ,132
subttl "Get User Mode Stack Address"
;++
;
; PULONG
; KiGetUserModeStackAddress (
; VOID
; )
;
; Routine Description:
;
; This function returns the address of the user stack address in the
; current trap frame.
;
; Arguments:
;
; None.
;
; Return Value:
;
; The address of the user stack address.
;
;--
cPublicProc _KiGetUserModeStackAddress, 0
mov eax,PCR[PcPrcbData + PbCurrentThread] ; get current thread address
mov eax,[eax].ThTrapFrame ; get current trap frame address
lea eax,[eax].TsHardwareEsp ; get address of stack address
stdRET _KiGetUserModeStackAddress
stdENDP _KiGetUserModeStackAddress
page ,132
subttl "Return from User Mode Callback"
;++
;
; NTSTATUS
; NtCallbackReturn (
; IN PVOID OutputBuffer OPTIONAL,
; IN ULONG OutputLength,
; IN NTSTATUS Status
; )
;
; Routine Description:
;
; This function returns from a user mode callout to the kernel
; mode caller of the user mode callback function.
;
; N.B. This function returns to the function that called out to user
; mode and the KiCallUserMode function calls out to user mode.
; Therefore, the stack layout must be consistent between the
; two routines.
;
; Arguments:
;
; OutputBuffer - Supplies an optional pointer to an output buffer.
;
; OutputLength - Supplies the length of the output buffer.
;
; Status - Supplies the status value returned to the caller of the
; callback function.
;
; Return Value:
;
; If the callback return cannot be executed, then an error status is
; returned. Otherwise, the specified callback status is returned to
; the caller of the callback function.
;
; N.B. This function returns to the function that called out to user
; mode is a callout is currently active.
;
;--
cPublicProc _NtCallbackReturn, 3
mov eax,PCR[PcPrcbData + PbCurrentThread] ; get current thread address
mov ecx,[eax].ThCallbackStack ; get callback stack address
test ecx, ecx
je CbExit ; if zero, no callback stack present
;
; Restore the current exception list from the saved exception list in the
; current trap frame, restore the trap frame and callback stack addresses,
; store the output buffer address and length, and set the service status.
;
mov ebx, [eax].ThTrapFrame ; get current trap frame address
mov edx, [ebx].TsExceptionList ; get saved exception list address
mov PCR[PcExceptionList], edx ; restore exception list address
mov edi, [esp] + 4 ; get output buffer address
mov esi, [esp] + 8 ; get output buffer length
mov ebp, [esp] + 12 ; get callout service status
mov ebx, [ecx].CuOutBf ; get address to store output buffer
mov [ebx], edi ; store output buffer address
mov ebx, [ecx].CuOutLn ; get address to store output length
mov [ebx], esi ; store output buffer length
mov ebx, [ecx] ; get previous initial stack address
cli ; disable interrupt
mov esi, [eax].ThInitialStack ; get source NPX save area address
mov [eax].ThInitialStack, ebx ; restore initial stack address
sub esi, NPX_FRAME_LENGTH ; compute source NPX save area
sub ebx, NPX_FRAME_LENGTH ; compute destination NPX save area
mov edx,[esi].FpControlWord ; copy NPX state to previous frame
mov [ebx].FpControlWord, edx ;
mov edx, [esi].FpStatusWord ;
mov [ebx].FpStatusWord, edx ;
mov edx, [esi].FpTagWord ;
mov [ebx].FpTagWord, edx ;
mov edx, [esi].FxMXCsr ;
mov [ebx].FxMXCsr, edx ;
mov edx, [esi].FpCr0NpxState ;
mov [ebx].FpCr0NpxState, edx ;
cmp ebp, STATUS_CALLBACK_POP_STACK
mov edi, [ecx].CuTrFr ; Fetch address of previous trap frame
jz short _NtCbCopyTrapFrame
_NtCbCopyTrapFrameRet:
and dword ptr [edi].TsDr7, 0 ; Assume original trap frame has no debug registers active
test byte ptr [eax].ThDebugActive, 0ffh
jne short _NtCbGetDebugRegs
_NtCbGetDebugRet:
mov edx, PCR[PcTss] ; Get address of task switch segment
lea esp, [ecx].CuCbStk ; Trim stack back to callback frame
.errnz (EFLAGS_V86_MASK AND 0FF00FFFFh)
test byte ptr [edi]+TsEFlags+2, EFLAGS_V86_MASK/010000h ; is this a V86 frame?
jne @f
sub ebx, TsV86Gs - TsHardwareSegSs ; bias for missing V86 fields
@@:
mov [edx].TssEsp0, ebx ; restore kernel entry stack address
mov [eax].ThTrapFrame, edi ; restore current trap frame address
sti ; enable interrupts
pop [eax].ThCallbackStack ; restore callback stack address
mov eax, ebp ; set callback service status
;
; Restore nonvolatile registers, clean call parameters from stack, and
; return to callback caller.
;
pop edi ; restore nonvolatile registers
pop esi ;
pop ebx ;
pop ebp ;
pop edx ; save return address
add esp, 8 ; remove parameters from stack
jmp edx ; return to callback caller
;
; edi - previous trap frame [in/out]
; ecx - callback stack [in/out]
; eax - current thread [in/out]
; esi/edx: available
;
_NtCbCopyTrapFrame:
mov ecx, (TsV86Es-TsSegFs)/4
mov esi, [eax].ThTrapFrame ; trap frame for this system call
.errnz (EFLAGS_V86_MASK AND 0FF00FFFFh)
test byte ptr [esi]+TsEFlags+2, EFLAGS_V86_MASK/010000h
mov edx, edi
lea edi, [edi].TsSegFs
jz short @f
add ecx, (KTRAP_FRAME_LENGTH-TsV86Es)/4
@@: lea esi, [esi].TsSegFs
rep movsd ; copy the relevant parts of the frame
mov ecx, [eax].ThCallbackStack
mov edi, edx ; restores ecx, edi
jmp _NtCbCopyTrapFrameRet
_NtCbGetDebugRegs:
;
; Copy debug registers from current frame to original frame.
;
mov esi, [eax].ThTrapFrame ; Get current trap frame
mov edx, [esi].TsDr0
mov [edi].TsDr0, edx
mov edx, [esi].TsDr1
mov [edi].TsDr1, edx
mov edx, [esi].TsDr2
mov [edi].TsDr2, edx
mov edx, [esi].TsDr3
mov [edi].TsDr3, edx
mov edx, [esi].TsDr6
mov [edi].TsDr6, edx
mov edx, [esi].TsDr7
mov [edi].TsDr7, edx
jmp _NtCbGetDebugRet
;
; No callback is currently active.
;
CbExit: mov eax, STATUS_NO_CALLBACK_ACTIVE ; set service status
stdRET _NtCallBackReturn
stdENDP _NtCallbackReturn
_TEXT ends
end
| 37.246679 | 135 | 0.573641 |
0434b1a34ea5ba6ba4d6ccab419efea4e1e29845 | 17,123 | java | Java | repo/repo-common/src/main/java/com/evolveum/midpoint/repo/common/activity/TaskActivityManager.java | mythoss/midpoint | 834b78d89fc7e423fdf52f0fece19a24ec4e5f27 | [
"Apache-2.0"
] | null | null | null | repo/repo-common/src/main/java/com/evolveum/midpoint/repo/common/activity/TaskActivityManager.java | mythoss/midpoint | 834b78d89fc7e423fdf52f0fece19a24ec4e5f27 | [
"Apache-2.0"
] | null | null | null | repo/repo-common/src/main/java/com/evolveum/midpoint/repo/common/activity/TaskActivityManager.java | mythoss/midpoint | 834b78d89fc7e423fdf52f0fece19a24ec4e5f27 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2010-2021 Evolveum and contributors
*
* This work is dual-licensed under the Apache License 2.0
* and European Union Public License. See LICENSE file for details.
*/
package com.evolveum.midpoint.repo.common.activity;
import java.util.*;
import java.util.stream.Collectors;
import com.evolveum.midpoint.prism.delta.ItemDelta;
import com.evolveum.midpoint.prism.path.ItemPath;
import com.evolveum.midpoint.repo.common.activity.run.CommonTaskBeans;
import com.evolveum.midpoint.repo.common.activity.run.distribution.WorkersReconciliation;
import com.evolveum.midpoint.repo.common.activity.run.distribution.WorkersReconciliationOptions;
import com.evolveum.midpoint.schema.GetOperationOptions;
import com.evolveum.midpoint.schema.SchemaService;
import com.evolveum.midpoint.schema.SelectorOptions;
import com.evolveum.midpoint.schema.util.task.*;
import com.evolveum.midpoint.schema.util.task.ActivityProgressInformationBuilder.InformationSource;
import com.evolveum.midpoint.schema.util.task.ActivityTreeUtil.ActivityStateInContext;
import com.evolveum.midpoint.task.api.Task;
import com.evolveum.midpoint.task.api.TaskManager;
import com.evolveum.midpoint.util.TreeNode;
import com.evolveum.midpoint.util.exception.CommonException;
import com.evolveum.midpoint.util.exception.ObjectNotFoundException;
import com.evolveum.midpoint.util.exception.SchemaException;
import com.evolveum.midpoint.util.logging.LoggingUtils;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import com.evolveum.midpoint.xml.ns._public.common.common_3.*;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import com.evolveum.midpoint.prism.PrismContext;
import com.evolveum.midpoint.repo.api.RepositoryService;
import com.evolveum.midpoint.schema.result.OperationResult;
import com.evolveum.midpoint.util.annotation.Experimental;
/**
* Provides common functionality related to activities (something like {@link TaskManager} does for tasks).
*/
@Experimental
@Component
public class TaskActivityManager {
private static final String OP_RECONCILE_WORKERS = TaskActivityManager.class.getName() + ".reconcileWorkers";
private static final String OP_RECONCILE_WORKERS_FOR_ACTIVITY = TaskActivityManager.class.getName() + ".reconcileWorkersForActivity";
private static final String OP_DELETE_ACTIVITY_STATE_AND_WORKERS = TaskActivityManager.class.getName() + ".deleteActivityStateAndWorkers";
private static final Trace LOGGER = TraceManager.getTrace(TaskActivityManager.class);
@Autowired private PrismContext prismContext;
@Autowired private SchemaService schemaService;
@Autowired @Qualifier("repositoryService") private RepositoryService plainRepositoryService;
@Autowired private TaskManager taskManager;
@Autowired private CommonTaskBeans beans;
// TODO reconsider the concept of resolver (as it is useless now - we have to fetch the subtasks manually!)
/** Assumes that the whole task tree is loaded. */
public ActivityProgressInformation getProgressInformationFromTaskTree(String rootTaskOid, OperationResult result)
throws SchemaException, ObjectNotFoundException {
return ActivityProgressInformation.fromRootTask(
getTaskWithSubtasks(rootTaskOid, result),
createTaskResolver(result),
InformationSource.FULL_STATE_ONLY);
}
public ActivityProgressInformation getProgressInformation(@NotNull String rootTaskOid, @NotNull InformationSource source,
@NotNull OperationResult result)
throws SchemaException, ObjectNotFoundException {
return ActivityProgressInformation.fromRootTask(
source == InformationSource.FULL_STATE_ONLY ?
getTaskWithSubtasks(rootTaskOid, result) :
getTaskWithoutSubtasks(rootTaskOid, result),
source);
}
public TreeNode<ActivityPerformanceInformation> getPerformanceInformation(String rootTaskOid, OperationResult result)
throws SchemaException, ObjectNotFoundException {
return ActivityTreeUtil.transformStates(
getTaskWithSubtasks(rootTaskOid, result),
createTaskResolver(result),
(path, state, workerStates, task) -> {
if (workerStates != null) {
return ActivityPerformanceInformation.forCoordinator(path, workerStates);
} else {
ActivityItemProcessingStatisticsType itemStats = getItemStats(state);
if (itemStats != null) {
return ActivityPerformanceInformation.forRegularActivity(path, itemStats, state.getProgress());
} else {
return ActivityPerformanceInformation.notApplicable(path);
}
}
});
}
private ActivityItemProcessingStatisticsType getItemStats(ActivityStateType state) {
return state != null && state.getStatistics() != null ?
state.getStatistics().getItemProcessing() : null;
}
private TaskResolver createTaskResolver(OperationResult result) {
return oid -> getTaskWithSubtasks(oid, result);
}
@NotNull
private TaskType getTaskWithSubtasks(String oid, OperationResult result) throws ObjectNotFoundException, SchemaException {
Collection<SelectorOptions<GetOperationOptions>> withChildren = schemaService.getOperationOptionsBuilder()
.item(TaskType.F_SUBTASK_REF).retrieve()
.build();
return taskManager.getTask(oid, withChildren, result)
.getUpdatedTaskObject()
.asObjectable();
}
@NotNull
private TaskType getTaskWithoutSubtasks(String oid, OperationResult result) throws ObjectNotFoundException, SchemaException {
return taskManager.getTask(oid, null, result)
.getUpdatedTaskObject()
.asObjectable();
}
public @NotNull Activity<?, ?> getActivity(Task rootTask, ActivityPath activityPath)
throws SchemaException {
return ActivityTree.create(rootTask, beans)
.getActivity(activityPath);
}
/**
* Note that we reconcile only workers for distributed activities that already have their state.
*/
public @NotNull Map<ActivityPath, WorkersReconciliationResultType> reconcileWorkers(@NotNull String rootTaskOid,
@NotNull OperationResult parentResult)
throws SchemaException, ObjectNotFoundException {
OperationResult result = parentResult.subresult(OP_RECONCILE_WORKERS)
.addParam("rootTaskOid", rootTaskOid)
.build();
try {
Task rootTask = taskManager.getTaskTree(rootTaskOid, result);
TaskType rootTaskBean = rootTask.getRawTaskObjectClonedIfNecessary().asObjectable();
Map<ActivityPath, WorkersReconciliationResultType> resultMap = new HashMap<>();
ActivityTreeUtil.processStates(rootTaskBean, TaskResolver.empty(), (path, state, workerStates, task) -> {
if (shouldReconcileActivity(workerStates, state)) {
resultMap.put(
path,
reconcileWorkersForActivity(rootTask, task, path, result));
}
});
return resultMap;
} catch (Throwable t) {
result.recordFatalError(t);
throw t;
} finally {
result.computeStatusIfUnknown();
}
}
private boolean shouldReconcileActivity(List<ActivityStateType> workerStates, ActivityStateType state) {
return workerStates != null &&
state != null && // actually, workerStates != null implies state != null
state.getRealizationState() == ActivityRealizationStateType.IN_PROGRESS_DISTRIBUTED;
}
/**
* Note: common exceptions are not propagated - these are reflected only in the operation result
*/
private @NotNull WorkersReconciliationResultType reconcileWorkersForActivity(@NotNull Task rootTask, @NotNull TaskType coordinatorTaskBean,
@NotNull ActivityPath path, OperationResult parentResult) {
OperationResult result = parentResult.subresult(OP_RECONCILE_WORKERS_FOR_ACTIVITY)
.addArbitraryObjectAsParam("rootTask", rootTask)
.addParam("coordinatorTask", coordinatorTaskBean)
.addArbitraryObjectAsParam("path", path)
.build();
try {
Task coordinatorTask = taskManager.createTaskInstance(coordinatorTaskBean.asPrismObject(), result);
WorkersReconciliationOptions options = new WorkersReconciliationOptions();
options.setDontCloseWorkersWhenWorkDone(true); // TODO
return new WorkersReconciliation(rootTask, coordinatorTask, path, options, beans)
.execute(result);
} catch (CommonException e) {
LoggingUtils.logUnexpectedException(LOGGER, "Couldn't reconcile workers for activity path '{}' in {}/{}", e, path,
coordinatorTaskBean, rootTask);
result.recordFatalError(e);
return new WorkersReconciliationResultType(prismContext)
.status(OperationResultStatusType.FATAL_ERROR);
} catch (Throwable t) {
result.recordFatalError(t);
throw t;
} finally {
result.computeStatusIfUnknown();
}
}
/**
* TODO somehow unify with TaskStatePurger
*/
public void deleteActivityStateAndWorkers(@NotNull String rootTaskOid, boolean deleteWorkers, long subtasksWaitTime,
OperationResult parentResult)
throws SchemaException, ObjectNotFoundException {
OperationResult result = parentResult.subresult(OP_DELETE_ACTIVITY_STATE_AND_WORKERS)
.addArbitraryObjectAsParam("rootTaskOid", rootTaskOid)
.addParam("deleteWorkers", deleteWorkers)
.addParam("subtasksWaitTime", subtasksWaitTime)
.build();
try {
boolean suspended = taskManager.suspendTaskTree(rootTaskOid, subtasksWaitTime, result);
if (!suspended) {
// TODO less harsh handling
throw new IllegalStateException("Not all tasks could be suspended. Please retry to operation.");
}
Task rootTask = taskManager.getTaskTree(rootTaskOid, result);
TaskType rootTaskBean = rootTask.getRawTaskObjectClonedIfNecessary().asObjectable();
TreeNode<ActivityStateInContext> stateTree = ActivityTreeUtil.toStateTree(rootTaskBean, TaskResolver.empty());
deleteWorkersOrTheirState(stateTree, deleteWorkers, result);
purgeOrDeleteActivityState(stateTree, result);
} catch (Throwable t) {
result.recordFatalError(t);
throw t;
} finally {
result.computeStatusIfUnknown();
}
}
private void deleteWorkersOrTheirState(TreeNode<ActivityStateInContext> root, boolean deleteWorkers, OperationResult result) {
root.acceptDepthFirst(node -> {
if (node.getUserObject().isCoordinator()) {
deleteActivityWorkersOrTheirState(node.getUserObject(), deleteWorkers, result);
}
});
}
private void deleteActivityWorkersOrTheirState(@NotNull ActivityStateInContext activityStateInContext,
boolean deleteWorkers, OperationResult result) {
TaskType coordinatorTaskBean = activityStateInContext.getTask();
ActivityPath activityPath = activityStateInContext.getActivityPath();
Set<String> workerOids =
ActivityTreeUtil.getSubtasksForPath(coordinatorTaskBean, activityPath, TaskResolver.empty()).stream()
.map(ObjectType::getOid)
.collect(Collectors.toSet());
if (deleteWorkers) {
taskManager.suspendAndDeleteTasks(workerOids, TaskManager.DO_NOT_WAIT, true, result);
LOGGER.info("Deleted workers: {}", workerOids);
} else {
for (String workerOid : workerOids) {
deleteCompleteState(workerOid, result);
}
}
}
private void deleteCompleteState(String taskOid, OperationResult result) {
try {
List<ItemDelta<?, ?>> modifications = prismContext.deltaFor(TaskType.class)
.item(TaskType.F_ACTIVITY_STATE).replace()
.asItemDeltas();
plainRepositoryService.modifyObject(TaskType.class, taskOid, modifications, result);
LOGGER.info("Deleted complete task activity state in {}", taskOid);
} catch (CommonException e) {
LoggingUtils.logUnexpectedException(LOGGER, "Couldn't delete activity state in {}", e, taskOid);
}
}
private void purgeOrDeleteActivityState(TreeNode<ActivityStateInContext> node, OperationResult result) {
ActivityStateInContext stateInContext = node.getUserObject();
if (stateInContext.getActivityState() == null) {
return;
}
TaskType taskBean = stateInContext.getTask();
if (ActivityTreeUtil.hasDelegatedActivity(node)) {
purgeState(taskBean, stateInContext.getActivityPath(), stateInContext.getActivityState(), result);
for (TreeNode<ActivityStateInContext> child : node.getChildren()) {
purgeOrDeleteActivityState(child, result);
}
} else {
deleteState(taskBean, stateInContext.getActivityPath(), result);
}
}
private void deleteState(TaskType task, ActivityPath activityPath, OperationResult result) {
try {
TaskActivityStateType taskActivityState = task.getActivityState();
ItemPath stateItemPath = ActivityStateUtil.getStateItemPath(taskActivityState, activityPath);
List<ItemDelta<?, ?>> itemDeltas;
if (activityPath.equals(ActivityStateUtil.getLocalRootPath(taskActivityState))) {
// This is the [local] root activity. Delete everything!
itemDeltas = PrismContext.get().deltaFor(TaskType.class)
.item(TaskType.F_ACTIVITY_STATE).replace()
.asItemDeltas();
} else {
Long id = ItemPath.toId(stateItemPath.last());
assert id != null;
itemDeltas = PrismContext.get().deltaFor(TaskType.class)
.item(stateItemPath.allExceptLast()).delete(new ActivityStateType().id(id))
.asItemDeltas();
}
plainRepositoryService.modifyObject(TaskType.class, task.getOid(), itemDeltas, result);
LOGGER.info("Deleted activity state for '{}' in {}", activityPath, task);
} catch (CommonException e) {
LoggingUtils.logUnexpectedException(LOGGER, "Couldn't delete state for activity path '{}' in {}", e, activityPath, task);
}
}
private void purgeState(TaskType task, ActivityPath activityPath, ActivityStateType activityState, OperationResult result) {
try {
TaskActivityStateType taskActivityState = task.getActivityState();
ItemPath stateItemPath = ActivityStateUtil.getStateItemPath(taskActivityState, activityPath);
List<ItemDelta<?, ?>> itemDeltas = PrismContext.get().deltaFor(TaskType.class)
.item(stateItemPath.append(ActivityStateType.F_RESULT_STATUS)).replace()
.item(stateItemPath.append(ActivityStateType.F_PROGRESS)).replace()
.item(stateItemPath.append(ActivityStateType.F_STATISTICS)).replace()
.item(stateItemPath.append(ActivityStateType.F_BUCKETING)).replace()
.item(stateItemPath.append(ActivityStateType.F_COUNTERS)).replace()
.asItemDeltas();
if (!(activityState.getWorkState() instanceof DelegationWorkStateType)) {
itemDeltas.addAll(
PrismContext.get().deltaFor(TaskType.class)
.item(stateItemPath.append(ActivityStateType.F_REALIZATION_STATE)).replace()
.item(stateItemPath.append(ActivityStateType.F_WORK_STATE)).replace()
.asItemDeltas());
}
plainRepositoryService.modifyObject(TaskType.class, task.getOid(), itemDeltas, result);
LOGGER.info("Purged activity state for '{}' in {}", activityPath, task);
} catch (CommonException e) {
LoggingUtils.logUnexpectedException(LOGGER, "Couldn't delete state for activity path '{}' in {}", e, activityPath, task);
}
}
}
| 50.659763 | 143 | 0.674064 |
a28177e1fb7f7502d7a233063fe0d390678ff763 | 25,303 | lua | Lua | extlib/ffi/uv.lua | sd-/luajit | 612f1797554b5dc3f1d64e4755b3fdc4f11b617a | [
"MIT"
] | 2 | 2016-03-24T22:49:47.000Z | 2018-07-15T04:02:46.000Z | extlib/ffi/uv.lua | sd-/luajit | 612f1797554b5dc3f1d64e4755b3fdc4f11b617a | [
"MIT"
] | null | null | null | extlib/ffi/uv.lua | sd-/luajit | 612f1797554b5dc3f1d64e4755b3fdc4f11b617a | [
"MIT"
] | null | null | null | //# include "uv-private/uv-win.h"
typedef enum uv_err_code {
UV_UKNOWN = -1,
UV_OK,
UV_EOF,
UV_EADDRINFO,
UV_EACCES,
UV_EAGAIN,
UV_EADDRINUSE,
UV_EADDRNOTAVAIL,
UV_EAFNOSUPPORT,
UV_EALREADY,
UV_EBADF,
UV_EBUSY,
UV_ECONNABORTED,
UV_ECONNREFUSED,
UV_ECONNRESET,
UV_EDESTADDRREQ,
UV_EFAULT,
UV_EHOSTUNREACH,
UV_EINTR,
UV_EINVAL,
UV_EISCONN,
UV_EMFILE,
UV_EMSGSIZE,
UV_ENETDOWN,
UV_ENETUNREACH,
UV_ENFILE,
UV_ENOBUFS,
UV_ENOMEM,
UV_ENOTDIR,
UV_EISDIR,
UV_ENONET,
UV_ENOTCONN,
UV_ENOTSOCK,
UV_ENOTSUP,
UV_ENOENT,
UV_ENOSYS,
UV_EPIPE,
UV_EPROTO,
UV_EPROTONOSUPPORT,
UV_EPROTOTYPE,
UV_ETIMEDOUT,
UV_ECHARSET,
UV_EAIFAMNOSUPPORT,
UV_EAISERVICE,
UV_EAISOCKTYPE,
UV_ESHUTDOWN,
UV_EEXIST,
UV_ESRCH,
UV_MAX_ERRORS
} uv_err_code;
typedef enum uv_handle_type {
UV_UNKNOWN_HANDLE = 0,
UV_TCP,
UV_UDP,
UV_NAMED_PIPE,
UV_TTY,
UV_FILE,
UV_TIMER,
UV_PREPARE,
UV_CHECK,
UV_IDLE,
UV_ASYNC,
UV_ARES_TASK,
UV_ARES_EVENT,
UV_PROCESS,
UV_FS_EVENT
} uv_handle_type;
typedef enum uv_req_type {
UV_UNKNOWN_REQ = 0,
UV_CONNECT,
UV_ACCEPT,
UV_READ,
UV_WRITE,
UV_SHUTDOWN,
UV_WAKEUP,
UV_UDP_SEND,
UV_FS,
UV_WORK,
UV_GETADDRINFO,
UV_REQ_TYPE_PRIVATE
} uv_req_type;
typedef enum uv_membership {
UV_LEAVE_GROUP = 0,
UV_JOIN_GROUP
} uv_membership;
typedef struct uv_loop_s uv_loop_t;
typedef struct uv_ares_task_s uv_ares_task_t;
typedef struct uv_err_s uv_err_t;
typedef struct uv_handle_s uv_handle_t;
typedef struct uv_stream_s uv_stream_t;
typedef struct uv_tcp_s uv_tcp_t;
typedef struct uv_udp_s uv_udp_t;
typedef struct uv_pipe_s uv_pipe_t;
typedef struct uv_tty_s uv_tty_t;
typedef struct uv_timer_s uv_timer_t;
typedef struct uv_prepare_s uv_prepare_t;
typedef struct uv_check_s uv_check_t;
typedef struct uv_idle_s uv_idle_t;
typedef struct uv_async_s uv_async_t;
typedef struct uv_getaddrinfo_s uv_getaddrinfo_t;
typedef struct uv_process_s uv_process_t;
typedef struct uv_counters_s uv_counters_t;
typedef struct uv_req_s uv_req_t;
typedef struct uv_shutdown_s uv_shutdown_t;
typedef struct uv_write_s uv_write_t;
typedef struct uv_connect_s uv_connect_t;
typedef struct uv_udp_send_s uv_udp_send_t;
typedef struct uv_fs_s uv_fs_t;
typedef struct uv_fs_event_s uv_fs_event_t;
typedef struct uv_work_s uv_work_t;
typedef uv_buf_t (* uv_alloc_cb )( uv_handle_t* handle, size_t suggested_size );
typedef void (* uv_read_cb )( uv_stream_t* stream, ssize_t nread, uv_buf_t buf );
typedef void (* uv_read2_cb )( uv_pipe_t* pipe, ssize_t nread, uv_buf_t buf, uv_handle_type pending );
typedef void (* uv_write_cb )( uv_write_t* req, int status );
typedef void (* uv_connect_cb )( uv_connect_t* req, int status );
typedef void (* uv_shutdown_cb )( uv_shutdown_t* req, int status );
typedef void (* uv_connection_cb )( uv_stream_t* server, int status );
typedef void (* uv_close_cb )( uv_handle_t* handle );
typedef void (* uv_timer_cb )( uv_timer_t* handle, int status );
typedef void (* uv_async_cb )( uv_async_t* handle, int status );
typedef void (* uv_prepare_cb )( uv_prepare_t* handle, int status );
typedef void (* uv_check_cb )( uv_check_t* handle, int status );
typedef void (* uv_idle_cb )( uv_idle_t* handle, int status );
typedef void (* uv_getaddrinfo_cb )( uv_getaddrinfo_t* handle, int status, struct addrinfo* res );
typedef void (* uv_exit_cb )( uv_process_t*, int exit_status, int term_signal );
typedef void (* uv_fs_cb )( uv_fs_t* req );
typedef void (* uv_work_cb )( uv_work_t* req );
typedef void (* uv_after_work_cb )( uv_work_t* req );
typedef void (* uv_fs_event_cb )( uv_fs_event_t* handle, const char* filename, int events, int status );
typedef struct uv_err_s {
uv_err_code code;
int sys_errno_;
} uv_err_s;
//#define UV_REQ_FIELDS \
// /* read-only */ \
// uv_req_type type; \
// /* public */ \
// void* data; \
// /* private */ \
// UV_REQ_PRIVATE_FIELDS
//
///* Abstract base class of all requests. */
//struct uv_req_s {
// UV_REQ_FIELDS
//};
//
//
///* Platform-specific request types */
//UV_PRIVATE_REQ_TYPES
struct uv_shutdown_s {
UV_REQ_FIELDS
uv_stream_t* handle;
uv_shutdown_cb cb;
UV_SHUTDOWN_PRIVATE_FIELDS
};
#define UV_HANDLE_FIELDS \
/* read-only */ \
uv_loop_t* loop; \
uv_handle_type type; \
/* public */ \
uv_close_cb close_cb; \
void* data; \
/* private */ \
UV_HANDLE_PRIVATE_FIELDS
/* The abstract base class of all handles. */
struct uv_handle_s {
UV_HANDLE_FIELDS
};
#define UV_STREAM_FIELDS \
/* number of bytes queued for writing */ \
size_t write_queue_size; \
uv_alloc_cb alloc_cb; \
uv_read_cb read_cb; \
uv_read2_cb read2_cb; \
/* private */ \
UV_STREAM_PRIVATE_FIELDS
/*
* uv_stream_t is a subclass of uv_handle_t
*
* uv_stream is an abstract class.
*
* uv_stream_t is the parent class of uv_tcp_t, uv_pipe_t, uv_tty_t, and
* soon uv_file_t.
*/
struct uv_stream_s {
UV_HANDLE_FIELDS
UV_STREAM_FIELDS
};
/* uv_write_t is a subclass of uv_req_t */
struct uv_write_s {
UV_REQ_FIELDS
uv_write_cb cb;
uv_stream_t* send_handle;
uv_stream_t* handle;
UV_WRITE_PRIVATE_FIELDS
};
/*
* uv_tcp_t is a subclass of uv_stream_t
*
* Represents a TCP stream or TCP server.
*/
struct uv_tcp_s {
UV_HANDLE_FIELDS
UV_STREAM_FIELDS
UV_TCP_PRIVATE_FIELDS
};
/* uv_connect_t is a subclass of uv_req_t */
struct uv_connect_s {
UV_REQ_FIELDS
uv_connect_cb cb;
uv_stream_t* handle;
UV_CONNECT_PRIVATE_FIELDS
};
/*
* UDP support.
*/
enum uv_udp_flags {
/* Disables dual stack mode. Used with uv_udp_bind6(). */
UV_UDP_IPV6ONLY = 1,
/*
* Indicates message was truncated because read buffer was too small. The
* remainder was discarded by the OS. Used in uv_udp_recv_cb.
*/
UV_UDP_PARTIAL = 2
};
/*
* Called after a uv_udp_send() or uv_udp_send6(). status 0 indicates
* success otherwise error.
*/
typedef void (*uv_udp_send_cb)(uv_udp_send_t* req, int status);
typedef void (*uv_udp_recv_cb)(uv_udp_t* handle, ssize_t nread, uv_buf_t buf,
struct sockaddr* addr, unsigned flags);
/* uv_udp_t is a subclass of uv_handle_t */
struct uv_udp_s {
UV_HANDLE_FIELDS
UV_UDP_PRIVATE_FIELDS
};
/* uv_udp_send_t is a subclass of uv_req_t */
struct uv_udp_send_s {
UV_REQ_FIELDS
uv_udp_t* handle;
uv_udp_send_cb cb;
UV_UDP_SEND_PRIVATE_FIELDS
};
/*
* uv_tty_t is a subclass of uv_stream_t
*
* Representing a stream for the console.
*/
struct uv_tty_s {
UV_HANDLE_FIELDS
UV_STREAM_FIELDS
UV_TTY_PRIVATE_FIELDS
};
/*
* uv_pipe_t is a subclass of uv_stream_t
*
* Representing a pipe stream or pipe server. On Windows this is a Named
* Pipe. On Unix this is a UNIX domain socket.
*/
struct uv_pipe_s {
UV_HANDLE_FIELDS
UV_STREAM_FIELDS
UV_PIPE_PRIVATE_FIELDS
int ipc; /* non-zero if this pipe is used for passing handles */
};
/*
* uv_prepare_t is a subclass of uv_handle_t.
*
* libev wrapper. Every active prepare handle gets its callback called
* exactly once per loop iteration, just before the system blocks to wait
* for completed i/o.
*/
struct uv_prepare_s {
UV_HANDLE_FIELDS
UV_PREPARE_PRIVATE_FIELDS
};
struct uv_check_s {
UV_HANDLE_FIELDS
UV_CHECK_PRIVATE_FIELDS
};
uv_loop_t* uv_loop_new( );
void uv_loop_delete( uv_loop_t* );
uv_loop_t* uv_default_loop( );
int uv_run( uv_loop_t* );
void uv_ref( uv_loop_t* );
void uv_unref( uv_loop_t* );
void uv_update_time( uv_loop_t* );
int64_t uv_now( uv_loop_t* );
uv_err_t uv_last_error( uv_loop_t* );
const char* uv_strerror( uv_err_t err );
const char* uv_err_name( uv_err_t err );
int uv_shutdown( uv_shutdown_t* req, uv_stream_t* handle, uv_shutdown_cb cb );
int uv_is_active( uv_handle_t* handle );
void uv_close( uv_handle_t* handle, uv_close_cb close_cb );
uv_buf_t uv_buf_init( char* base, size_t len );
size_t uv_strlcpy( char* dst, const char* src, size_t size );
size_t uv_strlcat( char* dst, const char* src, size_t size );
int uv_listen( uv_stream_t* stream, int backlog, uv_connection_cb cb );
int uv_accept( uv_stream_t* server, uv_stream_t* client );
int uv_read_start( uv_stream_t*, uv_alloc_cb alloc_cb, uv_read_cb read_cb );
int uv_read_stop( uv_stream_t* );
int uv_read2_start( uv_stream_t*, uv_alloc_cb alloc_cb, uv_read2_cb read_cb );
int uv_write( uv_write_t* req, uv_stream_t* handle, uv_buf_t bufs[], int bufcnt, uv_write_cb cb );
int uv_write2( uv_write_t* req, uv_stream_t* handle, uv_buf_t bufs[], int bufcnt, uv_stream_t* send_handle, uv_write_cb cb );
int uv_tcp_init( uv_loop_t*, uv_tcp_t* handle );
int uv_tcp_nodelay( uv_tcp_t* handle, int enable );
int uv_tcp_keepalive( uv_tcp_t* handle, int enable, unsigned int delay );
int uv_tcp_simultaneous_accepts(
uv_tcp_t* handle, int enable );
int uv_tcp_bind( uv_tcp_t* handle, struct sockaddr_in );
int uv_tcp_bind6( uv_tcp_t* handle, struct sockaddr_in6 );
int uv_tcp_getsockname( uv_tcp_t* handle, struct sockaddr* name, int* namelen );
int uv_tcp_getpeername( uv_tcp_t* handle, struct sockaddr* name, int* namelen );
int uv_tcp_connect( uv_connect_t* req, uv_tcp_t* handle, struct sockaddr_in address, uv_connect_cb cb );
int uv_tcp_connect6( uv_connect_t* req, uv_tcp_t* handle, struct sockaddr_in6 address, uv_connect_cb cb );
int uv_udp_init( uv_loop_t*, uv_udp_t* handle );
int uv_udp_bind( uv_udp_t* handle, struct sockaddr_in addr, unsigned flags );
int uv_udp_bind6( uv_udp_t* handle, struct sockaddr_in6 addr, unsigned flags );
int uv_udp_getsockname( uv_udp_t* handle, struct sockaddr* name, int* namelen );
int uv_udp_set_membership(
uv_udp_t* handle, const char* multicast_addr, const char* interface_addr, uv_membership membership );
int uv_udp_send( uv_udp_send_t* req, uv_udp_t* handle, uv_buf_t bufs[], int bufcnt, struct sockaddr_in addr, uv_udp_send_cb send_cb );
int uv_udp_send6( uv_udp_send_t* req, uv_udp_t* handle, uv_buf_t bufs[], int bufcnt, struct sockaddr_in6 addr, uv_udp_send_cb send_cb );
int uv_udp_recv_start( uv_udp_t* handle, uv_alloc_cb alloc_cb, uv_udp_recv_cb recv_cb );
int uv_udp_recv_stop( uv_udp_t* handle );
int uv_tty_init( uv_loop_t*, uv_tty_t*, uv_file fd, int readable );
int uv_tty_set_mode( uv_tty_t*, int mode );
void uv_tty_reset_mode( );
int uv_tty_get_winsize( uv_tty_t*, int* width, int* height );
uv_handle_type
uv_guess_handle( uv_file file );
int uv_pipe_init( uv_loop_t*, uv_pipe_t* handle, int ipc );
void uv_pipe_open( uv_pipe_t*, uv_file file );
int uv_pipe_bind( uv_pipe_t* handle, const char* name );
void uv_pipe_connect( uv_connect_t* req, uv_pipe_t* handle, const char* name, uv_connect_cb cb);
void uv_pipe_pending_instances(
uv_pipe_t* handle, int count );
int uv_prepare_init( uv_loop_t*, uv_prepare_t* prepare );
int uv_prepare_start( uv_prepare_t* prepare, uv_prepare_cb cb );
int uv_prepare_stop( uv_prepare_t* prepare );
int uv_check_init( uv_loop_t*, uv_check_t* check );
int uv_check_start( uv_check_t* check, uv_check_cb cb );
int uv_check_stop( uv_check_t* check );
/*
* uv_idle_t is a subclass of uv_handle_t.
*
* libev wrapper. Every active idle handle gets its callback called
* repeatedly until it is stopped. This happens after all other types of
* callbacks are processed. When there are multiple "idle" handles active,
* their callbacks are called in turn.
*/
struct uv_idle_s {
UV_HANDLE_FIELDS
UV_IDLE_PRIVATE_FIELDS
};
int uv_idle_init(uv_loop_t*, uv_idle_t* idle);
int uv_idle_start(uv_idle_t* idle, uv_idle_cb cb);
int uv_idle_stop(uv_idle_t* idle);
/*
* uv_async_t is a subclass of uv_handle_t.
*
* libev wrapper. uv_async_send wakes up the event
* loop and calls the async handle's callback There is no guarantee that
* every uv_async_send call leads to exactly one invocation of the callback;
* The only guarantee is that the callback function is called at least once
* after the call to async_send. Unlike all other libuv functions,
* uv_async_send can be called from another thread.
*/
struct uv_async_s {
UV_HANDLE_FIELDS
UV_ASYNC_PRIVATE_FIELDS
};
int uv_async_init(uv_loop_t*, uv_async_t* async,
uv_async_cb async_cb);
/*
* This can be called from other threads to wake up a libuv thread.
*
* libuv is single threaded at the moment.
*/
int uv_async_send(uv_async_t* async);
/*
* uv_timer_t is a subclass of uv_handle_t.
*
* Wraps libev's ev_timer watcher. Used to get woken up at a specified time
* in the future.
*/
struct uv_timer_s {
UV_HANDLE_FIELDS
UV_TIMER_PRIVATE_FIELDS
};
int uv_timer_init(uv_loop_t*, uv_timer_t* timer);
int uv_timer_start(uv_timer_t* timer, uv_timer_cb cb,
int64_t timeout, int64_t repeat);
int uv_timer_stop(uv_timer_t* timer);
/*
* Stop the timer, and if it is repeating restart it using the repeat value
* as the timeout. If the timer has never been started before it returns -1 and
* sets the error to UV_EINVAL.
*/
int uv_timer_again(uv_timer_t* timer);
/*
* Set the repeat value. Note that if the repeat value is set from a timer
* callback it does not immediately take effect. If the timer was non-repeating
* before, it will have been stopped. If it was repeating, then the old repeat
* value will have been used to schedule the next timeout.
*/
void uv_timer_set_repeat(uv_timer_t* timer, int64_t repeat);
int64_t uv_timer_get_repeat(uv_timer_t* timer);
/* c-ares integration initialize and terminate */
int uv_ares_init_options(uv_loop_t*,
ares_channel *channelptr, struct ares_options *options, int optmask);
/* TODO remove the loop argument from this function? */
void uv_ares_destroy(uv_loop_t*, ares_channel channel);
/*
* uv_getaddrinfo_t is a subclass of uv_req_t
*
* Request object for uv_getaddrinfo.
*/
struct uv_getaddrinfo_s {
UV_REQ_FIELDS
/* read-only */
uv_loop_t* loop; \
UV_GETADDRINFO_PRIVATE_FIELDS
};
/*
* Asynchronous getaddrinfo(3).
*
* Return code 0 means that request is accepted and callback will be called
* with result. Other return codes mean that there will not be a callback.
* Input arguments may be released after return from this call.
*
* uv_freeaddrinfo() must be called after completion to free the addrinfo
* structure.
*
* On error NXDOMAIN the status code will be non-zero and UV_ENOENT returned.
*/
int uv_getaddrinfo(uv_loop_t*, uv_getaddrinfo_t* handle,
uv_getaddrinfo_cb getaddrinfo_cb, const char* node, const char* service,
const struct addrinfo* hints);
void uv_freeaddrinfo(struct addrinfo* ai);
/* uv_spawn() options */
typedef struct uv_process_options_s {
uv_exit_cb exit_cb; /* Called after the process exits. */
const char* file; /* Path to program to execute. */
/*
* Command line arguments. args[0] should be the path to the program. On
* Windows this uses CreateProcess which concatenates the arguments into a
* string this can cause some strange errors. See the note at
* windows_verbatim_arguments.
*/
char** args;
/*
* This will be set as the environ variable in the subprocess. If this is
* NULL then the parents environ will be used.
*/
char** env;
/*
* If non-null this represents a directory the subprocess should execute
* in. Stands for current working directory.
*/
char* cwd;
/*
* TODO describe how this works.
*/
int windows_verbatim_arguments;
/*
* The user should supply pointers to initialized uv_pipe_t structs for
* stdio. This is used to to send or receive input from the subprocess.
* The user is responsible for calling uv_close on them.
*/
uv_pipe_t* stdin_stream;
uv_pipe_t* stdout_stream;
uv_pipe_t* stderr_stream;
} uv_process_options_t;
/*
* uv_process_t is a subclass of uv_handle_t
*/
struct uv_process_s {
UV_HANDLE_FIELDS
uv_exit_cb exit_cb;
int pid;
UV_PROCESS_PRIVATE_FIELDS
};
/* Initializes uv_process_t and starts the process. */
int uv_spawn(uv_loop_t*, uv_process_t*,
uv_process_options_t options);
/*
* Kills the process with the specified signal. The user must still
* call uv_close on the process.
*/
int uv_process_kill(uv_process_t*, int signum);
/* Kills the process with the specified signal. */
uv_err_t uv_kill(int pid, int signum);
/*
* uv_work_t is a subclass of uv_req_t
*/
struct uv_work_s {
UV_REQ_FIELDS
uv_loop_t* loop;
uv_work_cb work_cb;
uv_after_work_cb after_work_cb;
UV_WORK_PRIVATE_FIELDS
};
/* Queues a work request to execute asynchronously on the thread pool. */
int uv_queue_work(uv_loop_t* loop, uv_work_t* req,
uv_work_cb work_cb, uv_after_work_cb after_work_cb);
/*
* File System Methods.
*
* The uv_fs_* functions execute a blocking system call asynchronously (in a
* thread pool) and call the specified callback in the specified loop after
* completion. If the user gives NULL as the callback the blocking system
* call will be called synchronously. req should be a pointer to an
* uninitialized uv_fs_t object.
*
* uv_fs_req_cleanup() must be called after completion of the uv_fs_
* function to free any internal memory allocations associated with the
* request.
*/
typedef enum {
UV_FS_UNKNOWN = -1,
UV_FS_CUSTOM,
UV_FS_OPEN,
UV_FS_CLOSE,
UV_FS_READ,
UV_FS_WRITE,
UV_FS_SENDFILE,
UV_FS_STAT,
UV_FS_LSTAT,
UV_FS_FSTAT,
UV_FS_FTRUNCATE,
UV_FS_UTIME,
UV_FS_FUTIME,
UV_FS_CHMOD,
UV_FS_FCHMOD,
UV_FS_FSYNC,
UV_FS_FDATASYNC,
UV_FS_UNLINK,
UV_FS_RMDIR,
UV_FS_MKDIR,
UV_FS_RENAME,
UV_FS_READDIR,
UV_FS_LINK,
UV_FS_SYMLINK,
UV_FS_READLINK,
UV_FS_CHOWN,
UV_FS_FCHOWN
} uv_fs_type;
/* uv_fs_t is a subclass of uv_req_t */
struct uv_fs_s {
UV_REQ_FIELDS
uv_loop_t* loop;
uv_fs_type fs_type;
uv_fs_cb cb;
ssize_t result;
void* ptr;
char* path;
int errorno;
UV_FS_PRIVATE_FIELDS
};
/*
* This flag can be used with uv_fs_symlink on Windows
* to specify whether path argument points to a directory.
*/
#define UV_FS_SYMLINK_DIR 0x0001
enum uv_fs_event {
UV_RENAME = 1,
UV_CHANGE = 2
};
struct uv_fs_event_s {
UV_HANDLE_FIELDS
char* filename;
UV_FS_EVENT_PRIVATE_FIELDS
};
enum uv_fs_event_flags {
/*
* By default, if the fs event watcher is given a directory name, we will
* watch for all events in that directory. This flags overrides this behavior
* and makes fs_event report only changes to the directory entry itself. This
* flag does not affect individual files watched.
* This flag is currently not implemented yet on any backend.
*/
UV_FS_EVENT_WATCH_ENTRY = 1,
/*
* By default uv_fs_event will try to use a kernel interface such as inotify
* or kqueue to detect events. This may not work on remote filesystems such
* as NFS mounts. This flag makes fs_event fall back to calling stat() on a
* regular interval.
* This flag is currently not implemented yet on any backend.
*/
UV_FS_EVENT_STAT = 2
};
void uv_fs_req_cleanup(uv_fs_t* req);
int uv_fs_close(uv_loop_t* loop, uv_fs_t* req, uv_file file,
uv_fs_cb cb);
int uv_fs_open(uv_loop_t* loop, uv_fs_t* req, const char* path,
int flags, int mode, uv_fs_cb cb);
int uv_fs_read(uv_loop_t* loop, uv_fs_t* req, uv_file file,
void* buf, size_t length, off_t offset, uv_fs_cb cb);
int uv_fs_unlink(uv_loop_t* loop, uv_fs_t* req, const char* path,
uv_fs_cb cb);
int uv_fs_write(uv_loop_t* loop, uv_fs_t* req, uv_file file,
void* buf, size_t length, off_t offset, uv_fs_cb cb);
int uv_fs_mkdir(uv_loop_t* loop, uv_fs_t* req, const char* path,
int mode, uv_fs_cb cb);
int uv_fs_rmdir(uv_loop_t* loop, uv_fs_t* req, const char* path,
uv_fs_cb cb);
int uv_fs_readdir(uv_loop_t* loop, uv_fs_t* req,
const char* path, int flags, uv_fs_cb cb);
int uv_fs_stat( uv_loop_t* loop, uv_fs_t* req, const char* path, uv_fs_cb cb );
int uv_fs_fstat( uv_loop_t* loop, uv_fs_t* req, uv_file file, uv_fs_cb cb );
int uv_fs_rename( uv_loop_t* loop, uv_fs_t* req, const char* path, const char* new_path, uv_fs_cb cb);
int uv_fs_fsync( uv_loop_t* loop, uv_fs_t* req, uv_file file, uv_fs_cb cb );
int uv_fs_fdatasync( uv_loop_t* loop, uv_fs_t* req, uv_file file, uv_fs_cb cb);
int uv_fs_ftruncate( uv_loop_t* loop, uv_fs_t* req, uv_file file, off_t offset, uv_fs_cb cb);
int uv_fs_sendfile( uv_loop_t* loop, uv_fs_t* req, uv_file out_fd, uv_file in_fd, off_t in_offset, size_t length, uv_fs_cb cb);
int uv_fs_chmod( uv_loop_t* loop, uv_fs_t* req, const char* path, int mode, uv_fs_cb cb);
int uv_fs_utime( uv_loop_t* loop, uv_fs_t* req, const char* path, double atime, double mtime, uv_fs_cb cb);
int uv_fs_futime( uv_loop_t* loop, uv_fs_t* req, uv_file file, double atime, double mtime, uv_fs_cb cb);
int uv_fs_lstat( uv_loop_t* loop, uv_fs_t* req, const char* path, uv_fs_cb cb);
int uv_fs_link( uv_loop_t* loop, uv_fs_t* req, const char* path, const char* new_path, uv_fs_cb cb);
int uv_fs_symlink( uv_loop_t* loop, uv_fs_t* req, const char* path, const char* new_path, int flags, uv_fs_cb cb);
int uv_fs_readlink( uv_loop_t* loop, uv_fs_t* req, const char* path, uv_fs_cb cb);
int uv_fs_fchmod( uv_loop_t* loop, uv_fs_t* req, uv_file file, int mode, uv_fs_cb cb);
int uv_fs_chown( uv_loop_t* loop, uv_fs_t* req, const char* path, int uid, int gid, uv_fs_cb cb);
int uv_fs_fchown( uv_loop_t* loop, uv_fs_t* req, uv_file file, int uid, int gid, uv_fs_cb cb);
void uv_loadavg( double avg[3] );
int uv_fs_event_init( uv_loop_t* loop, uv_fs_event_t* handle, const char* filename, uv_fs_event_cb cb, int flags);
struct sockaddr_in
uv_ip4_addr(const char* ip, int port);
struct sockaddr_in6
uv_ip6_addr(const char* ip, int port);
int uv_ip4_name(struct sockaddr_in* src, char* dst, size_t size);
int uv_ip6_name(struct sockaddr_in6* src, char* dst, size_t size);
int uv_exepath(char* buffer, size_t* size);
uv_err_t uv_cwd(char* buffer, size_t size);
uv_err_t uv_chdir(const char* dir);
uint64_t uv_get_free_memory(void);
uint64_t uv_get_total_memory(void);
uint64_t uv_hrtime(void);
uv_err_t uv_dlopen(const char* filename, uv_lib_t* library);
uv_err_t uv_dlclose(uv_lib_t library);
uv_err_t uv_dlsym(uv_lib_t library, const char* name, void** ptr);
int uv_mutex_init(uv_mutex_t* handle);
void uv_mutex_destroy(uv_mutex_t* handle);
void uv_mutex_lock(uv_mutex_t* handle);
int uv_mutex_trylock(uv_mutex_t* handle);
void uv_mutex_unlock(uv_mutex_t* handle);
int uv_rwlock_init(uv_rwlock_t* rwlock);
void uv_rwlock_destroy(uv_rwlock_t* rwlock);
void uv_rwlock_rdlock(uv_rwlock_t* rwlock);
int uv_rwlock_tryrdlock(uv_rwlock_t* rwlock);
void uv_rwlock_rdunlock(uv_rwlock_t* rwlock);
void uv_rwlock_wrlock(uv_rwlock_t* rwlock);
int uv_rwlock_trywrlock(uv_rwlock_t* rwlock);
void uv_rwlock_wrunlock(uv_rwlock_t* rwlock);
int uv_thread_create(uv_thread_t *tid, void (*entry)(void *arg), void *arg);
int uv_thread_join(uv_thread_t *tid);
/* the presence of these unions force similar struct layout */
union uv_any_handle {
uv_tcp_t tcp;
uv_pipe_t pipe;
uv_prepare_t prepare;
uv_check_t check;
uv_idle_t idle;
uv_async_t async;
uv_timer_t timer;
uv_getaddrinfo_t getaddrinfo;
uv_fs_event_t fs_event;
};
union uv_any_req {
uv_req_t req;
uv_write_t write;
uv_connect_t connect;
uv_shutdown_t shutdown;
uv_fs_t fs_req;
uv_work_t work_req;
};
struct uv_counters_s {
uint64_t eio_init;
uint64_t req_init;
uint64_t handle_init;
uint64_t stream_init;
uint64_t tcp_init;
uint64_t udp_init;
uint64_t pipe_init;
uint64_t tty_init;
uint64_t prepare_init;
uint64_t check_init;
uint64_t idle_init;
uint64_t async_init;
uint64_t timer_init;
uint64_t process_init;
uint64_t fs_event_init;
};
struct uv_loop_s {
UV_LOOP_PRIVATE_FIELDS
/* list used for ares task handles */
uv_ares_task_t* uv_ares_handles_;
/* Various thing for libeio. */
uv_async_t uv_eio_want_poll_notifier;
uv_async_t uv_eio_done_poll_notifier;
uv_idle_t uv_eio_poller;
/* Diagnostic counters */
uv_counters_t counters;
/* The last error */
uv_err_t last_err;
/* User data - use this for whatever. */
void* data;
};
| 31.16133 | 150 | 0.710034 |
dbdf3f0558022153fe5208d45c6621a1b2ca6a11 | 651 | sql | SQL | loaders/clickhouse/studies_log.sql | thehyve/genetics-backend | 81d09bf5c70c534a59940eddfcd9c8566d2b2ec1 | [
"Apache-2.0"
] | 6 | 2019-06-01T11:17:41.000Z | 2021-09-24T14:06:30.000Z | loaders/clickhouse/studies_log.sql | opentargets/genetics-backend | 1ab0314f9fe4b267f8ffb5ed94187d55fbb3431c | [
"Apache-2.0"
] | 7 | 2018-11-28T10:06:21.000Z | 2020-01-26T18:55:39.000Z | loaders/clickhouse/studies_log.sql | thehyve/genetics-backend | 81d09bf5c70c534a59940eddfcd9c8566d2b2ec1 | [
"Apache-2.0"
] | 4 | 2019-05-09T13:57:57.000Z | 2021-08-03T18:19:16.000Z | create database if not exists ot;
create table if not exists ot.studies_log (
study_id String,
pmid Nullable(String),
pub_date Nullable(String),
pub_journal Nullable(String),
pub_title Nullable(String),
pub_author Nullable(String),
has_sumstats UInt8,
trait_reported String,
source Nullable(String),
trait_efos Array(String) default [],
ancestry_initial Array(String) default [],
ancestry_replication Array(String) default [],
n_initial Nullable(UInt32),
n_replication Nullable(UInt32),
n_cases Nullable(UInt32),
trait_category Nullable(String) default 'Uncategorised',
num_assoc_loci Nullable(UInt32))
engine = Log;
| 31 | 58 | 0.769585 |
5a8d49c7d630c0e7e51bbabcdcbc60697102f698 | 1,383 | lua | Lua | Demos/Content/Entities/light.lua | Sh1ft0/alpha | 6726d366f0c8d2e1434b87f815b2644ebf170adf | [
"Apache-2.0"
] | null | null | null | Demos/Content/Entities/light.lua | Sh1ft0/alpha | 6726d366f0c8d2e1434b87f815b2644ebf170adf | [
"Apache-2.0"
] | null | null | null | Demos/Content/Entities/light.lua | Sh1ft0/alpha | 6726d366f0c8d2e1434b87f815b2644ebf170adf | [
"Apache-2.0"
] | null | null | null | -- Copyright 2014-2015 Jason R. Wendlandt
--
-- 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.
-- component data table
components = {
root = {
type = "light",
transform = {
position = { x = 0.0, y = 0.0, z = 0.0 },
rotation = { x = 0.0, y = 0.0, z = 0.0 },
scale = { x = 1.0, y = 1.0, z = 1.0 }
},
light = {
type = "point",
color = { r = 1.0, g = 1.0, b = 0.5, a = 1.0 },
intensity = 0.8,
ambient_intensity = 0.2,
distance = 50.0,
},
components = {
-- components can exist inside other components
visible_mesh = {
type = "mesh",
model = "Models/cube.am",
transform = {
position = { x = 0.0, y = 0.0, z = 0.0 },
rotation = { x = 0.0, y = 0.0, z = 0.0 },
scale = { x = 0.25, y = 0.25, z = 0.25 }
},
material = "Materials/lightyellow.lua",
},
}
}
}
| 30.065217 | 75 | 0.574837 |
cb398174eb8894bfa79be9006457a322e180c103 | 400 | swift | Swift | NetworkPlatform/Entries/Location+Mapping.swift | bsmerbeckuri/CleanArchitectureRxSwift | be0fa13488b42da0e6929389a2e2d07cdfabccb2 | [
"MIT"
] | 2 | 2019-08-02T04:08:35.000Z | 2019-08-24T07:18:48.000Z | NetworkPlatform/Entries/Location+Mapping.swift | JeaSungLEE/CleanArchitectureRxSwift | 55c852bbd7b4e5f9ee30426e2acdb7b038e848be | [
"MIT"
] | null | null | null | NetworkPlatform/Entries/Location+Mapping.swift | JeaSungLEE/CleanArchitectureRxSwift | 55c852bbd7b4e5f9ee30426e2acdb7b038e848be | [
"MIT"
] | 1 | 2021-11-11T16:32:08.000Z | 2021-11-11T16:32:08.000Z | //
// Location+Mapping.swift
// CleanArchitectureRxSwift
//
// Created by Andrey Yastrebov on 10.03.17.
// Copyright © 2017 sergdort. All rights reserved.
//
import Domain
import ObjectMapper
extension Location: ImmutableMappable {
// JSON -> Object
public init(map: Map) throws {
longitude = try map.value("longitude")
latitude = try map.value("latitude")
}
}
| 20 | 51 | 0.665 |
3b1ae8f313b270bbf84344351f6c24ecacfdaeb0 | 963 | swift | Swift | ios/SinchVoipRemoteVideoManager.swift | suraneti/react-native-sinch-voip | 34ee9a74b08bbfc1fbf6a6fe5d9b3db7b7c3776b | [
"MIT"
] | 1 | 2021-11-19T20:42:02.000Z | 2021-11-19T20:42:02.000Z | ios/SinchVoipRemoteVideoManager.swift | suraneti/react-native-sinch-voip | 34ee9a74b08bbfc1fbf6a6fe5d9b3db7b7c3776b | [
"MIT"
] | 4 | 2021-02-03T18:17:00.000Z | 2022-01-04T09:43:52.000Z | ios/SinchVoipRemoteVideoManager.swift | suraneti/react-native-sinch-voip | 34ee9a74b08bbfc1fbf6a6fe5d9b3db7b7c3776b | [
"MIT"
] | 1 | 2021-03-19T09:07:13.000Z | 2021-03-19T09:07:13.000Z | //
// SinchVoipLocalVideoManager.swift
//
// Created by Gwenole ROTON on 16/11/2020.
import Foundation
import Sinch
@available(iOS 10.0, *)
@objc(SinchVoipRemoteVideoManager)
class SinchVoipRemoteVideoManager: RCTViewManager {
static let sharedInstance = SinchVoipRemoteVideoManager()
// Size will be override by the RN style
var superView = UIView(frame: CGRect(x: 0, y: 0, width: 1, height: 1))
var remoteView: UIView? = nil
override private init() {
super.init()
}
override static func requiresMainQueueSetup() -> Bool {
return true
}
override func view() -> UIView! {
let vc = SinchVoip.sharedInstance!.videoController
remoteView = vc?.remoteView()
remoteView?.contentMode = UIView.ContentMode.scaleAspectFill
remoteView?.backgroundColor = .darkGray
superView.addSubview(remoteView!)
return superView
}
}
| 24.692308 | 74 | 0.652129 |
3bdc58f2923dd6ff9153e3a44fbe02da86571c7d | 6,486 | html | HTML | bulletin/2021-02.html | scare96crow/draft.kusamura.org | 153cb9425b837fadc6f224f0e81b23eb31663ec8 | [
"MIT"
] | null | null | null | bulletin/2021-02.html | scare96crow/draft.kusamura.org | 153cb9425b837fadc6f224f0e81b23eb31663ec8 | [
"MIT"
] | null | null | null | bulletin/2021-02.html | scare96crow/draft.kusamura.org | 153cb9425b837fadc6f224f0e81b23eb31663ec8 | [
"MIT"
] | null | null | null | <!DOCTYPE HTML>
<html lang="ja">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>草むら通信(2021年2月)ウェブ版 - 多摩草むらの会</title>
<link rel="author" href="mailto:info@kusamura.org" />
<link rel="stylesheet" type="text/css" href="bulletin.css" />
<script type="text/javascript" src="/script/step_scroll.js"></script>
<!--[if lt IE 9]><script type="text/javascript" src="http://ie7-js.googlecode.com/svn/version/2.1(beta4)/IE9.js"></script><![endif]-->
</head>
<body>
<header>
<h1>草むら通信(2021年2月)ウェブ版</h1>
<?= call_html_template('global-header-nav') ?>
</header>
<article>
<section>
<h2>目次</h2>
<dl class="toc">
<dt>巻頭言</dt>
<dd><a href="#preface">春告げ鳥を待ちつつ</a> <cite>代表理事 風間美代子</cite></dd>
<dt>寄稿 医療のおはなし</dt>
<dd><a href="#medic">サプリメントと薬</a> <cite>北野調剤薬局桜ヶ丘店 薬剤師 齋藤 伸介</cite></dd>
<dt>トピックス</a></dt>
<dd><a href="#t1">年頭所感は動画配信としました</a></dd>
<dd><a href="#t2">クラウドファンディングへのご協力ありがとうございました</a></dd>
<dd><a href="#t3">中高生のチャリティームービープロジェクト</a></dd>
<dt>理事紹介</dt>
<dd><a href="#director">村上 秀平</a></dd>
</dl>
</section>
</article>
<article id="preface">
<section>
<h2>春告げ鳥を待ちつつ</h2>
<p>春とは名ばかりの寒風吹きすさぶ中だというのに、梅の花の香りがそっと匂うようになりました。どんなに寒くても、季節をきちんと感じて咲く花たちの律儀さには本当に感心すると同時に勇気をもらいます。</p>
<p>最近「命」について考えさせられる事が多くなりました。昨年末には、長い間草むらのメンバーさんでいらしたお二人の方が、病気で残念ながらお亡くなりになりました。その死をメンバーさん達に知らせるべきかどうか迷うところではありますが、人ひとりが一生懸命生きた証は、隠せるものではなく隠す必要もありません。その方のことをいつまでも心の中に思い出として残している事が何よりの供養だと思います。</p>
<p>生と死はいつも隣り合わせです。それを辛くても乗り越えていくところに本当の自立があると思います。どんな事でも上から目線ではなく本当にメンバーさん達と共に情報を共有し合ってお互いの力を信じて、どんな事も話し合いながら信頼の元に進んでいくのではないでしょうか。~慈悲~あらゆるものを大切に扱う心、もう一度噛み締めてみたいと思います。</p>
<p>今の草むらにぴったりの詩を見つけました。<q>「我は草なり/伸びんとす/伸びられるとき/伸びんとす/伸びられぬ日は/伸びぬなり*」</q>伸びられない時も実は地中で根っこを伸ばしています。春はもうすぐです。皆様と共に明るい日差しを浴びられますよう祈っております。<cite>* 高見順著『敗戦日記』から</cite></p>
<p class="by"><cite>代表理事 風間美代子</cite></p>
</section>
</article>
<article id="medic">
<section>
<h2><small class="sub-title">寄稿 医療のおはなし</small> サプリメントと薬</h2>
<p>最近では、健康のためにサプリメントを飲んでいる人も多いかと思います。サプリメントは薬ではないので、薬と一緒に飲んでも安全だと思っている方もいらっしゃるのではないでしょうか。</p>
<p>サプリメントは食品に分類されますが、食品も薬と一緒に取ることで薬の効果を弱めたり、逆に薬が効きすぎてしまう場合があります。例えば血圧の薬であるカルシウム拮抗薬は、グレープフルーツジュースと一緒に飲むと薬が効きすぎてしまいます。</p>
<p>サプリメントでは、クロレラ含有製品はビタミンKを多く含むため、血液凝固防止薬ワルファリンの作用を弱めてしまいます。また、ハーブの一種であるセント・ジョーンズ・ワートは気管支喘息薬などの効果を弱めたり、一部の抗うつ薬の作用を強めてしまうので注意が必要です。</p>
<p>薬局では調剤だけでなく、薬・サプリメント・介護用品・健康についての相談なども行っていますので、気になることがありましたら、お気軽にお越しください</p>
<p class="by"><cite>北野調剤薬局高尾店 薬剤師 川口 泰男</cite></p>
</section>
</article>
<article>
<section>
<h2>トピックス</h2>
<section id="t1">
<h3>年頭所感は動画配信としました</h3>
<p>例年、新年会の場で年頭所感を発表しておりましたが、今年はコロナ感染防止対策から全員が一堂に会する事を避け、ビデオを作成し各事業所で見ていただきました。</p>
</section>
<section id="t2">
<h3>クラウドファンディングへのご協力ありがとうございました</h3>
<p>令和2年11月から令和3年1月にかけて、多摩草むらの会としての初めての試み「クラウドファンディング」を実施しました。また、日本フィランソロピー協会主催のクラウドファンディング「中高生によるチャリティームービープロジェクト【コロナに負けるな!NPO 支援】」も同時期に実施されました。こちらでは、中高生70 名それぞれが創意工夫し、85 秒の動画に込めた想いをNPO応援動画が公開されました。</p>
<p>準備段階から多くの方々のご協力、ご助言を頂きました。そして公開後は全国各地の皆様から暖かいご支援を頂きました。ご支援、ご協力いただいた皆様には厚く御礼申し上げます。</p>
<p>なお、法人では継続的に皆様のご寄付を募集しております。認定NPO法人としてご寄付には所得控除もしくは税額控除が受けられます。よろしくお願いいたします。</p>
</section>
<section id="t3">
<h3>中高生のチャリティームービープロジェクト</h3>
<p>ご紹介した「コロナに負けるな!NPO 支援」。クラウドファウンディングで多摩草むらの会の応援ビデオを作成していただいた、5つのチーム名とビデオタイトルを紹介します。</p>
<section>
<h4><a href="https://www.philanthropy.or.jp/charitymovie/kusamura/">TEAM KUSAMURA<img style="float:left;margin:0 1em 1em 0;" src="images/2021-02_01.jpg" alt="" /></a></h4>
<ul>
<li><a href="https://www.philanthropy.or.jp/charitymovie/movie/kusamura1/">#01 平第三中学校 1年生チーム「「夢」を考えるみなさんへ」</a></li>
<li><a href="https://www.philanthropy.or.jp/charitymovie/movie/kusamura2/">#02 パワフォーチーム「あなたの小さな支援が大きなパワーに」</a></li>
<li><a href="https://www.philanthropy.or.jp/charitymovie/movie/kusamura3/">#03 バターカップ三姉妹「個性を生かせる社会を作るために」</a></li>
<li><a href="https://www.philanthropy.or.jp/charitymovie/movie/kusamura4/">#04 チーム深川二中「二チューちゃんとうさぎさん」</a></li>
<li><a href="https://www.philanthropy.or.jp/charitymovie/movie/kusamura5/">#05 Ochiai Team「Diversity」</a></li>
</ul>
</section>
<p>このプロジェクトは、本プロジェクトを通じて、学生、NPO、企業人と多世代間協働によるSDGs推進と、世代・立場を超えた信頼を軸にしたコミュニケ―ション力の醸成を目指すもので、コロナ感染拡大の中、取材や打ち合わせそして作品を仕上げるまでのプロセスはすべてオンラインで行われました。</p>
</section>
</section>
</article>
<article id="director">
<section>
<h2>理事紹介</h2>
<p>草むら通信アンケート結果から、組織運営を担う皆様の紹介を行います。二回目は認定NPO法人多摩草むらの会代表理事、村上 秀平氏のご紹介です。</p>
<section>
<h3>村上 秀平(理事年数:NPO法人多摩草むらの会理事16年)<img style="float:left;margin:0 1em 1em 0;" src="images/2021-02_02.jpg" alt="" /></h3>
<dl class="q_and_a">
<dt>理事としての経験の中で良かったことは?</dt>
<dd>当初の家族会への参画から、法人としての多摩草むらの会への飛躍と発展に少しでも協力できたと思えることかな。</dd>
<dt>これから草むらでやりたいことは?</dt>
<dd>メンバーの皆さんが地域で楽しく、明るく暮らせる環境整備に微力を尽くしたい。</dd>
<dt>好きなことは?</dt>
<dd>趣味は、社交ダンス、水彩画等絵を描くこと、カラオケ等歌うこと、音楽を聴くこと、毎日のサウナ浴。動物、特にワンちゃん。食べ物は寿司、鰻重他美味しいもの全て。</dd>
</dl>
<section>
<h4>【 読者へのメッセージ 】</h4>
<p>メンバーの皆さんは私の仲間・家族も同然、皆さんと共に歩む・遊ぶ・悩む・休む「草むら」であり続けるために、これからもよろしくお願いします。</p>
</section>
</section>
</section>
</article>
<article>
<section>
<h2>草むら通信アーカイブ</h2>
<ul>
<li><a rel="prev" href="2021-01">2021年1月</a></li>
<li><a rel="next" href="2021-03">2021年3月</a></li>
</ul>
</section>
</article>
<footer>
<address>2013 © NPO法人 多摩草むらの会</address>
<?= call_html_template('global-footer-nav') ?>
</footer>
</body>
</html> | 54.504202 | 218 | 0.602529 |
70d4a32cea2d818b1c0db566b37eb6f8a5262ebd | 2,686 | c | C | benchmarks/Angha_original/extr_base64_mbedtls_base64_decode/extr_base64_mbedtls_base64_decode.c | ComputerSystemsLab/OptimizationCache | 9c30ae120673e57b772ea42e29e087f775aa9de9 | [
"Apache-2.0"
] | 2 | 2021-03-11T00:46:25.000Z | 2021-07-08T16:44:58.000Z | benchmarks/Angha_original/extr_base64_mbedtls_base64_decode/extr_base64_mbedtls_base64_decode.c | ComputerSystemsLab/OptimizationCache | 9c30ae120673e57b772ea42e29e087f775aa9de9 | [
"Apache-2.0"
] | null | null | null | benchmarks/Angha_original/extr_base64_mbedtls_base64_decode/extr_base64_mbedtls_base64_decode.c | ComputerSystemsLab/OptimizationCache | 9c30ae120673e57b772ea42e29e087f775aa9de9 | [
"Apache-2.0"
] | null | null | null | #define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
/* Type definitions */
typedef int uint32_t ;
/* Variables and functions */
int MBEDTLS_ERR_BASE64_BUFFER_TOO_SMALL ;
int MBEDTLS_ERR_BASE64_INVALID_CHARACTER ;
int* base64_dec_map ;
int mbedtls_base64_decode( unsigned char *dst, size_t dlen, size_t *olen,
const unsigned char *src, size_t slen )
{
size_t i, n;
uint32_t j, x;
unsigned char *p;
/* First pass: check for validity and get output length */
for( i = n = j = 0; i < slen; i++ )
{
/* Skip spaces before checking for EOL */
x = 0;
while( i < slen && src[i] == ' ' )
{
++i;
++x;
}
/* Spaces at end of buffer are OK */
if( i == slen )
break;
if( ( slen - i ) >= 2 &&
src[i] == '\r' && src[i + 1] == '\n' )
continue;
if( src[i] == '\n' )
continue;
/* Space inside a line is an error */
if( x != 0 )
return( MBEDTLS_ERR_BASE64_INVALID_CHARACTER );
if( src[i] == '=' && ++j > 2 )
return( MBEDTLS_ERR_BASE64_INVALID_CHARACTER );
if( src[i] > 127 || base64_dec_map[src[i]] == 127 )
return( MBEDTLS_ERR_BASE64_INVALID_CHARACTER );
if( base64_dec_map[src[i]] < 64 && j != 0 )
return( MBEDTLS_ERR_BASE64_INVALID_CHARACTER );
n++;
}
if( n == 0 )
{
*olen = 0;
return( 0 );
}
/* The following expression is to calculate the following formula without
* risk of integer overflow in n:
* n = ( ( n * 6 ) + 7 ) >> 3;
*/
n = ( 6 * ( n >> 3 ) ) + ( ( 6 * ( n & 0x7 ) + 7 ) >> 3 );
n -= j;
if( dst == NULL || dlen < n )
{
*olen = n;
return( MBEDTLS_ERR_BASE64_BUFFER_TOO_SMALL );
}
for( j = 3, n = x = 0, p = dst; i > 0; i--, src++ )
{
if( *src == '\r' || *src == '\n' || *src == ' ' )
continue;
j -= ( base64_dec_map[*src] == 64 );
x = ( x << 6 ) | ( base64_dec_map[*src] & 0x3F );
if( ++n == 4 )
{
n = 0;
if( j > 0 ) *p++ = (unsigned char)( x >> 16 );
if( j > 1 ) *p++ = (unsigned char)( x >> 8 );
if( j > 2 ) *p++ = (unsigned char)( x );
}
}
*olen = p - dst;
return( 0 );
} | 25.826923 | 77 | 0.484363 |
505b98d8f9a46aca62f1e2cb219867a95133e1c4 | 31,158 | html | HTML | public/v2/guide/unit-testing.html | sanskritnotes/sanskritnotes.com | 931f247cf09fbd482eeaf32e4af0ce02d10d11b6 | [
"MIT"
] | null | null | null | public/v2/guide/unit-testing.html | sanskritnotes/sanskritnotes.com | 931f247cf09fbd482eeaf32e4af0ce02d10d11b6 | [
"MIT"
] | null | null | null | public/v2/guide/unit-testing.html | sanskritnotes/sanskritnotes.com | 931f247cf09fbd482eeaf32e4af0ce02d10d11b6 | [
"MIT"
] | null | null | null |
<!DOCTYPE html>
<html lang="en">
<head>
<title>Unit Testing — Sanskrit Notes संस्कृत टिप्पणी</title>
<meta charset="utf-8">
<meta name="description" content="Sanskrit Notes संस्कृत टिप्पणी - A easy modern introduction to the ancient language.">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<meta property="og:type" content="article">
<meta property="og:title" content="Unit Testing — Vue.js">
<meta property="og:description" content="Sanskrit Notes संस्कृत टिप्पणी - A easy modern introduction to the ancient language.">
<meta property="og:image" content="https://sanskritnotes.com//images/logo.png">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Unit Testing — Vue.js">
<meta name="twitter:description" content="Sanskrit Notes संस्कृत टिप्पणी - A easy modern introduction to the ancient language.">
<meta name="twitter:image" content="https://sanskritnotes.com/images/logo.png">
<link rel="icon" href="/images/logo.png" type="image/x-icon">
<link href='//fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600|Roboto Mono' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Dosis:500&text=Vue.js' rel='stylesheet' type='text/css'>
<!-- main page styles -->
<link rel="stylesheet" href="/css/page.css">
<!-- this needs to be loaded before guide's inline scripts -->
<script src="/js/vue.js"></script>
<script>window.PAGE_TYPE = "guide"</script>
<!-- ga -->
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', '', 'sanskritnotes.com');
ga('send', 'pageview');
</script>
</head>
<body class="docs"> <div id="mobile-bar" >
<a class="menu-button"></a>
<a class="logo" href="/"></a>
</div>
<div id="header">
<a id="logo" href="/">
<img src="/images/sanskritnotes_logo.png">
<span>Sanskrit Notes संस्कृत टिप्पणी</span>
</a>
<ul id="nav">
<li>
<form id="search-form">
<input type="text" id="search-query-nav" class="search-query st-default-search-input">
</form>
</li>
<!-- <li><a href="/v2/guide/" class="nav-link current">Guide</a></li> -->
<li><a href="/v2/api/" class="nav-link">Notes</a></li>
<!-- <li><a href="/v2/examples/" class="nav-link">Examples</a></li> -->
<!-- <li class="nav-dropdown-container ecosystem">
<a class="nav-link">Ecosystem</a><span class="arrow"></span>
<ul class="nav-dropdown">
<li><h4>Help</h4></li>
<li><ul>
<li><a href="http://forum.vuejs.org" class="nav-link" target="_blank">Forum</a></li>
<li><a href="https://gitter.im/vuejs/vue" class="nav-link" target="_blank">Chat</a></li>
<li><a href="https://github.com/vuejs-templates" class="nav-link" target="_blank">Templates</a></li>
</ul></li>
<li><h4>News</h4></li>
<li><ul>
<li><a href="https://twitter.com/vuejs" class="nav-link" target="_blank">Twitter</a></li>
<li><a href="https://medium.com/the-vue-point" class="nav-link" target="_blank">Blog</a></li>
<li><a href="https://vuejobs.com/?ref=vuejs" class="nav-link" target="_blank">Jobs</a></li>
</ul></li>
<li><h4>Core Plugins</h4></li>
<li><ul>
<li><a href="https://router.vuejs.org/" class="nav-link" target="_blank">Vue Router</a></li>
<li><a href="https://vuex.vuejs.org/" class="nav-link" target="_blank">Vuex</a></li>
</ul></li>
<li><h4>Resource Lists</h4></li>
<li><ul>
<li><a href="https://github.com/vuejs" class="nav-link" target="_blank">Official Repos</a></li>
<li><a href="https://github.com/vuejs/awesome-vue" class="nav-link" target="_blank">Awesome Vue</a></li>
</ul></li>
</ul>
</li>
-->
<!-- <li class="nav-dropdown-container language">
<a class="nav-link">Translations</a><span class="arrow"></span>
<ul class="nav-dropdown">
<li><a href="https://cn.vuejs.org/" class="nav-link" target="_blank">中文</a></li>
<li><a href="https://jp.vuejs.org/" class="nav-link" target="_blank">日本語</a></li>
<li><a href="https://ru.vuejs.org/" class="nav-link" target="_blank">Русский</a></li>
<li><a href="https://kr.vuejs.org/" class="nav-link" target="_blank">한국어</a></li>
<li><a href="https://br.vuejs.org/" class="nav-link" target="_blank">Português</a></li>
</ul>
</li>
-->
<!-- <li>
<a href="https://vue.threadless.com" target="_blank" class="nav-link shop">Shop</a>
<span class="new-label">NEW!</span>
</li> -->
</ul>
</div>
<div id="main" class="fix-sidebar">
<div class="sidebar">
<ul class="main-menu">
<li>
<form id="search-form">
<input type="text" id="search-query-sidebar" class="search-query st-default-search-input">
</form>
</li>
<!-- <li><a href="/v2/guide/" class="nav-link current">Guide</a></li> -->
<li><a href="/v2/api/" class="nav-link">Notes</a></li>
<!-- <li><a href="/v2/examples/" class="nav-link">Examples</a></li> -->
<!-- <li class="nav-dropdown-container ecosystem">
<a class="nav-link">Ecosystem</a><span class="arrow"></span>
<ul class="nav-dropdown">
<li><h4>Help</h4></li>
<li><ul>
<li><a href="http://forum.vuejs.org" class="nav-link" target="_blank">Forum</a></li>
<li><a href="https://gitter.im/vuejs/vue" class="nav-link" target="_blank">Chat</a></li>
<li><a href="https://github.com/vuejs-templates" class="nav-link" target="_blank">Templates</a></li>
</ul></li>
<li><h4>News</h4></li>
<li><ul>
<li><a href="https://twitter.com/vuejs" class="nav-link" target="_blank">Twitter</a></li>
<li><a href="https://medium.com/the-vue-point" class="nav-link" target="_blank">Blog</a></li>
<li><a href="https://vuejobs.com/?ref=vuejs" class="nav-link" target="_blank">Jobs</a></li>
</ul></li>
<li><h4>Core Plugins</h4></li>
<li><ul>
<li><a href="https://router.vuejs.org/" class="nav-link" target="_blank">Vue Router</a></li>
<li><a href="https://vuex.vuejs.org/" class="nav-link" target="_blank">Vuex</a></li>
</ul></li>
<li><h4>Resource Lists</h4></li>
<li><ul>
<li><a href="https://github.com/vuejs" class="nav-link" target="_blank">Official Repos</a></li>
<li><a href="https://github.com/vuejs/awesome-vue" class="nav-link" target="_blank">Awesome Vue</a></li>
</ul></li>
</ul>
</li>
-->
<!-- <li class="nav-dropdown-container language">
<a class="nav-link">Translations</a><span class="arrow"></span>
<ul class="nav-dropdown">
<li><a href="https://cn.vuejs.org/" class="nav-link" target="_blank">中文</a></li>
<li><a href="https://jp.vuejs.org/" class="nav-link" target="_blank">日本語</a></li>
<li><a href="https://ru.vuejs.org/" class="nav-link" target="_blank">Русский</a></li>
<li><a href="https://kr.vuejs.org/" class="nav-link" target="_blank">한국어</a></li>
<li><a href="https://br.vuejs.org/" class="nav-link" target="_blank">Português</a></li>
</ul>
</li>
-->
<!-- <li>
<a href="https://vue.threadless.com" target="_blank" class="nav-link shop">Shop</a>
<span class="new-label">NEW!</span>
</li> -->
</ul>
<div class="list">
<div class="main-sponsor">
<!-- <span>Platinum Sponsor</span><br>
<a href="https://stdlib.com" target="_blank" class="logo">
<img src="/images/stdlib.png">
</a> -->
</div>
<!-- <a class="become-backer" href="/support-vuejs">
Become a Sponsor
</a> -->
<h2>
<!-- Guide
<select class="version-select">
<option value="SELF" selected>2.0</option>
<option value="v1">1.0</option>
<option value="012">0.12</option>
<option value="011">0.11</option>
</select>
-->
</h2>
<ul class="menu-root">
<li><h3>Essentials</h3></li>
<li>
<a href="/v2/guide/installation.html" class="sidebar-link">Installation</a>
</li>
<li>
<a href="/v2/guide/index.html" class="sidebar-link">Introduction</a>
</li>
<li>
<a href="/v2/guide/instance.html" class="sidebar-link">The Vue Instance</a>
</li>
<li>
<a href="/v2/guide/syntax.html" class="sidebar-link">Template Syntax</a>
</li>
<li>
<a href="/v2/guide/computed.html" class="sidebar-link">Computed Properties and Watchers</a>
</li>
<li>
<a href="/v2/guide/class-and-style.html" class="sidebar-link">Class and Style Bindings</a>
</li>
<li>
<a href="/v2/guide/conditional.html" class="sidebar-link">Conditional Rendering</a>
</li>
<li>
<a href="/v2/guide/list.html" class="sidebar-link">List Rendering</a>
</li>
<li>
<a href="/v2/guide/events.html" class="sidebar-link">Event Handling</a>
</li>
<li>
<a href="/v2/guide/forms.html" class="sidebar-link">Form Input Bindings</a>
</li>
<li>
<a href="/v2/guide/components.html" class="sidebar-link">Components</a>
</li>
<li><h3>Advanced</h3></li>
<li>
<a href="/v2/guide/reactivity.html" class="sidebar-link">Reactivity in Depth</a>
</li>
<li>
<a href="/v2/guide/transitions.html" class="sidebar-link">Transition Effects</a>
</li>
<li>
<a href="/v2/guide/transitioning-state.html" class="sidebar-link">Transitioning State</a>
</li>
<li>
<a href="/v2/guide/render-function.html" class="sidebar-link">Render Functions</a>
</li>
<li>
<a href="/v2/guide/custom-directive.html" class="sidebar-link">Custom Directives</a>
</li>
<li>
<a href="/v2/guide/mixins.html" class="sidebar-link">Mixins</a>
</li>
<li>
<a href="/v2/guide/plugins.html" class="sidebar-link">Plugins</a>
</li>
<li>
<a href="/v2/guide/single-file-components.html" class="sidebar-link">Single File Components</a>
</li>
<li>
<a href="/v2/guide/deployment.html" class="sidebar-link">Production Deployment Tips</a>
</li>
<li>
<a href="/v2/guide/routing.html" class="sidebar-link">Routing</a>
</li>
<li>
<a href="/v2/guide/state-management.html" class="sidebar-link">State Management</a>
</li>
<li>
<a href="/v2/guide/unit-testing.html" class="sidebar-link current">Unit Testing</a>
</li>
<li>
<a href="/v2/guide/ssr.html" class="sidebar-link">Server-Side Rendering</a>
</li>
<li>
<a href="/v2/guide/typescript.html" class="sidebar-link">TypeScript Support</a>
</li>
<li><h3>Migrating</h3></li>
<li>
<a href="/v2/guide/migration.html" class="sidebar-link">Migration from Vue 1.x</a>
</li>
<li>
<a href="/v2/guide/migration-vue-router.html" class="sidebar-link">Migration from Vue Router 0.7.x</a>
</li>
<li>
<a href="/v2/guide/migration-vuex.html" class="sidebar-link">Migration from Vuex 0.6.x to 1.0</a>
</li>
<li><h3>Meta</h3></li>
<li>
<a href="/v2/guide/comparison.html" class="sidebar-link">Comparison with Other Frameworks</a>
</li>
<li>
<a href="/v2/guide/join.html" class="sidebar-link">Join the Vue.js Community!</a>
</li>
</ul>
</div>
</div>
<div class="content guide with-sidebar unit-testing-guide">
<div id="ad">
<!-- <span>Sponsored By</span><br>
<a href="http://www.thedifferenceengine.io/" target="_blank"
style="background-color: rgba(0,0,0,.85); padding: 10px 0">
<img src="/images/tde.png">
</a> -->
<!-- <script async type="text/javascript" src="//cdn.carbonads.com/carbon.js?zoneid=1673&serve=C6AILKT&placement=vuejs" id="_carbonads_js"></script> -->
</div>
<h1>Unit Testing</h1>
<h2 id="Setup-and-Tooling"><a href="#Setup-and-Tooling" class="headerlink" title="Setup and Tooling"></a>Setup and Tooling</h2><p>Anything compatible with a module-based build system will work, but if you’re looking for a specific recommendation, try the <a href="http://karma-runner.github.io" target="_blank" rel="external">Karma</a> test runner. It has a lot of community plugins, including support for <a href="https://github.com/webpack/karma-webpack" target="_blank" rel="external">Webpack</a> and <a href="https://github.com/Nikku/karma-browserify" target="_blank" rel="external">Browserify</a>. For detailed setup, please refer to each project’s respective documentation, though these example Karma configurations for <a href="https://github.com/vuejs-templates/webpack/blob/master/template/test/unit/karma.conf.js" target="_blank" rel="external">Webpack</a> and <a href="https://github.com/vuejs-templates/browserify/blob/master/template/karma.conf.js" target="_blank" rel="external">Browserify</a> may help you get started.</p>
<h2 id="Simple-Assertions"><a href="#Simple-Assertions" class="headerlink" title="Simple Assertions"></a>Simple Assertions</h2><p>In terms of code structure for testing, you don’t have to do anything special in your components to make them testable. Just export the raw options:</p>
<figure class="highlight html"><table><tr><td class="code"><pre><div class="line"><span class="tag"><<span class="name">template</span>></span></div><div class="line"> <span class="tag"><<span class="name">span</span>></span>{{ message }}<span class="tag"></<span class="name">span</span>></span></div><div class="line"><span class="tag"></<span class="name">template</span>></span></div><div class="line"></div><div class="line"><span class="tag"><<span class="name">script</span>></span><span class="javascript"></span></div><div class="line"> <span class="keyword">export</span> <span class="keyword">default</span> {</div><div class="line"> data () {</div><div class="line"> <span class="keyword">return</span> {</div><div class="line"> <span class="attr">message</span>: <span class="string">'hello!'</span></div><div class="line"> }</div><div class="line"> },</div><div class="line"> created () {</div><div class="line"> <span class="keyword">this</span>.message = <span class="string">'bye!'</span></div><div class="line"> }</div><div class="line"> }</div><div class="line"><span class="tag"></<span class="name">script</span>></span></div></pre></td></tr></table></figure>
<p>When you test that component, all you have to do is import the object along with Vue to make many common assertions:</p>
<figure class="highlight js"><table><tr><td class="code"><pre><div class="line"><span class="comment">// Import Vue and the component being tested</span></div><div class="line"><span class="keyword">import</span> Vue <span class="keyword">from</span> <span class="string">'vue'</span></div><div class="line"><span class="keyword">import</span> MyComponent <span class="keyword">from</span> <span class="string">'path/to/MyComponent.vue'</span></div><div class="line"></div><div class="line"><span class="comment">// Here are some Jasmine 2.0 tests, though you can</span></div><div class="line"><span class="comment">// use any test runner / assertion library combo you prefer</span></div><div class="line">describe(<span class="string">'MyComponent'</span>, () => {</div><div class="line"> <span class="comment">// Inspect the raw component options</span></div><div class="line"> it(<span class="string">'has a created hook'</span>, () => {</div><div class="line"> expect(<span class="keyword">typeof</span> MyComponent.created).toBe(<span class="string">'function'</span>)</div><div class="line"> })</div><div class="line"></div><div class="line"> <span class="comment">// Evaluate the results of functions in</span></div><div class="line"> <span class="comment">// the raw component options</span></div><div class="line"> it(<span class="string">'sets the correct default data'</span>, () => {</div><div class="line"> expect(<span class="keyword">typeof</span> MyComponent.data).toBe(<span class="string">'function'</span>)</div><div class="line"> <span class="keyword">const</span> defaultData = MyComponent.data()</div><div class="line"> expect(defaultData.message).toBe(<span class="string">'hello!'</span>)</div><div class="line"> })</div><div class="line"></div><div class="line"> <span class="comment">// Inspect the component instance on mount</span></div><div class="line"> it(<span class="string">'correctly sets the message when created'</span>, () => {</div><div class="line"> <span class="keyword">const</span> vm = <span class="keyword">new</span> Vue(MyComponent).$mount()</div><div class="line"> expect(vm.message).toBe(<span class="string">'bye!'</span>)</div><div class="line"> })</div><div class="line"></div><div class="line"> <span class="comment">// Mount an instance and inspect the render output</span></div><div class="line"> it(<span class="string">'renders the correct message'</span>, () => {</div><div class="line"> <span class="keyword">const</span> Ctor = Vue.extend(MyComponent)</div><div class="line"> <span class="keyword">const</span> vm = <span class="keyword">new</span> Ctor().$mount()</div><div class="line"> expect(vm.$el.textContent).toBe(<span class="string">'bye!'</span>)</div><div class="line"> })</div><div class="line">})</div></pre></td></tr></table></figure>
<h2 id="Writing-Testable-Components"><a href="#Writing-Testable-Components" class="headerlink" title="Writing Testable Components"></a>Writing Testable Components</h2><p>A lot of component’s render output are primarily determined by the props they receive. In fact, if a component’s render output solely depends on its props, it becomes quite straightforward to test, similar to asserting the return value of a pure function with different arguments. Take a contrived example:</p>
<figure class="highlight html"><table><tr><td class="code"><pre><div class="line"><span class="tag"><<span class="name">template</span>></span></div><div class="line"> <span class="tag"><<span class="name">p</span>></span>{{ msg }}<span class="tag"></<span class="name">p</span>></span></div><div class="line"><span class="tag"></<span class="name">template</span>></span></div><div class="line"></div><div class="line"><span class="tag"><<span class="name">script</span>></span><span class="javascript"></span></div><div class="line"> <span class="keyword">export</span> <span class="keyword">default</span> {</div><div class="line"> <span class="attr">props</span>: [<span class="string">'msg'</span>]</div><div class="line"> }</div><div class="line"><span class="tag"></<span class="name">script</span>></span></div></pre></td></tr></table></figure>
<p>You can assert its render output with different props using the <code>propsData</code> option:</p>
<figure class="highlight js"><table><tr><td class="code"><pre><div class="line"><span class="keyword">import</span> Vue <span class="keyword">from</span> <span class="string">'vue'</span></div><div class="line"><span class="keyword">import</span> MyComponent <span class="keyword">from</span> <span class="string">'./MyComponent.vue'</span></div><div class="line"></div><div class="line"><span class="comment">// helper function that mounts and returns the rendered text</span></div><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">getRenderedText</span> (<span class="params">Component, propsData</span>) </span>{</div><div class="line"> <span class="keyword">const</span> Ctor = Vue.extend(Component)</div><div class="line"> <span class="keyword">const</span> vm = <span class="keyword">new</span> Ctor({ propsData }).$mount()</div><div class="line"> <span class="keyword">return</span> vm.$el.textContent</div><div class="line">}</div><div class="line"></div><div class="line">describe(<span class="string">'MyComponent'</span>, () => {</div><div class="line"> it(<span class="string">'renders correctly with different props'</span>, () => {</div><div class="line"> expect(getRenderedText(MyComponent, {</div><div class="line"> <span class="attr">msg</span>: <span class="string">'Hello'</span></div><div class="line"> })).toBe(<span class="string">'Hello'</span>)</div><div class="line"></div><div class="line"> expect(getRenderedText(MyComponent, {</div><div class="line"> <span class="attr">msg</span>: <span class="string">'Bye'</span></div><div class="line"> })).toBe(<span class="string">'Bye'</span>)</div><div class="line"> })</div><div class="line">})</div></pre></td></tr></table></figure>
<h2 id="Asserting-Asynchronous-Updates"><a href="#Asserting-Asynchronous-Updates" class="headerlink" title="Asserting Asynchronous Updates"></a>Asserting Asynchronous Updates</h2><p>Since Vue <a href="reactivity.html#Async-Update-Queue">performs DOM updates asynchronously</a>, assertions on DOM updates resulting from state change will have to be made in a <code>Vue.nextTick</code> callback:</p>
<figure class="highlight js"><table><tr><td class="code"><pre><div class="line"><span class="comment">// Inspect the generated HTML after a state update</span></div><div class="line">it(<span class="string">'updates the rendered message when vm.message updates'</span>, done => {</div><div class="line"> <span class="keyword">const</span> vm = <span class="keyword">new</span> Vue(MyComponent).$mount()</div><div class="line"> vm.message = <span class="string">'foo'</span></div><div class="line"></div><div class="line"> <span class="comment">// wait a "tick" after state change before asserting DOM updates</span></div><div class="line"> Vue.nextTick(<span class="function"><span class="params">()</span> =></span> {</div><div class="line"> expect(vm.$el.textContent).toBe(<span class="string">'foo'</span>)</div><div class="line"> done()</div><div class="line"> })</div><div class="line">})</div></pre></td></tr></table></figure>
<p>We are planning to work on a collection of common test helpers that makes it even simpler to render components with different constraints (e.g. shallow rendering that ignores child components) and assert their output.</p>
<div class="guide-links">
<span>← <a href="/v2/guide/state-management.html">State Management</a></span>
<span style="float:right"><a href="/v2/guide/ssr.html">Server-Side Rendering</a> →</span>
</div>
<div class="footer">
Caught a mistake or want to contribute to the documentation?
<a href="https://github.com/vuejs/vuejs.org/blob/master/src/v2/guide/unit-testing.md" target="_blank">
Edit this page on Github!
</a>
</div>
</div>
</div>
<script src="/js/smooth-scroll.min.js"></script>
<!-- main custom script for sidebars, version selects etc. -->
<script src="/js/css.escape.js"></script>
<script src="/js/common.js"></script>
<!-- search -->
<link href="//cdn.jsdelivr.net/docsearch.js/1/docsearch.min.css" rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="/css/search.css">
<script src="//cdn.jsdelivr.net/docsearch.js/1/docsearch.min.js"></script>
<script>
[
'#search-query-nav',
'#search-query-sidebar'
].forEach(function (selector) {
if (!document.querySelector(selector)) return
// search index defaults to v2
var match = window.location.pathname.match(/^\/(v\d+)/)
var version = match ? match[1] : 'v2'
docsearch({
appId: 'BH4D9OD16A',
apiKey: '85cc3221c9f23bfbaa4e3913dd7625ea',
indexName: 'vuejs',
inputSelector: selector,
algoliaOptions: { facetFilters: ["version:" + version] }
})
})
</script>
<!-- fastclick -->
<script src="//cdnjs.cloudflare.com/ajax/libs/fastclick/1.0.6/fastclick.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
FastClick.attach(document.body)
}, false)
</script>
</body>
</html>
| 47.569466 | 2,913 | 0.498652 |
90c63938f777d28b9e14a8996c89c2206cd45915 | 823 | py | Python | app/database.py | perymerdeka/fastapi-fullstack-boilerplate | c62c0c41a18cbf28e12ece4ca83091d7d864616d | [
"MIT"
] | 70 | 2021-10-03T22:27:18.000Z | 2022-02-24T06:29:13.000Z | app/database.py | perymerdeka/fastapi-fullstack-boilerplate | c62c0c41a18cbf28e12ece4ca83091d7d864616d | [
"MIT"
] | 2 | 2021-10-08T02:46:56.000Z | 2022-01-02T04:26:31.000Z | app/database.py | perymerdeka/fastapi-fullstack-boilerplate | c62c0c41a18cbf28e12ece4ca83091d7d864616d | [
"MIT"
] | 4 | 2021-10-05T04:41:27.000Z | 2022-01-21T07:39:01.000Z | from contextlib import contextmanager
from typing import Callable
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm.session import Session
from .settings import SQLALCHEMY_URL, SQLALCHEMY_USER, SQLALCHEMY_PASSWORD
SQLALCHEMY_DATABASE_URL = SQLALCHEMY_URL
engine = create_engine(
SQLALCHEMY_DATABASE_URL,
connect_args=dict(user=SQLALCHEMY_USER, password=SQLALCHEMY_PASSWORD),
)
SessionLocal: Callable[..., Session] = sessionmaker(
autocommit=False, autoflush=False, bind=engine
)
Base = declarative_base()
@contextmanager
def get_db_session():
"""Starts a database session as a context manager.
"""
session = SessionLocal()
try:
yield session
finally:
session.close() | 26.548387 | 74 | 0.778858 |
2f3ea69fcd29bd391cfa05aa0c1645cc60478352 | 242 | php | PHP | app/MemberStatus.php | mangelosalvio/icpep | b474d15d7a850b0c8fd6c21314cca1b1008ec2b5 | [
"MIT"
] | null | null | null | app/MemberStatus.php | mangelosalvio/icpep | b474d15d7a850b0c8fd6c21314cca1b1008ec2b5 | [
"MIT"
] | null | null | null | app/MemberStatus.php | mangelosalvio/icpep | b474d15d7a850b0c8fd6c21314cca1b1008ec2b5 | [
"MIT"
] | null | null | null | <?php
namespace App;
class MemberStatus {
public static $type_of_member = [
'A' => 'ASSOCIATE',
'R' => 'REGULAR'
];
public static $type_of_application = [
'N' => 'NEW',
'R' => 'RENEWAL'
];
} | 15.125 | 42 | 0.491736 |
46b3af2b9431118a3b32f218e5ab03c2f8d232fe | 22,643 | html | HTML | n_templates/task.html | SandStormHoldings/ScratchDocs | 24f3e4239781791385c0a14056335ec5f043b533 | [
"MIT"
] | 1 | 2018-05-18T15:45:35.000Z | 2018-05-18T15:45:35.000Z | n_templates/task.html | SandStormHoldings/ScratchDocs | 24f3e4239781791385c0a14056335ec5f043b533 | [
"MIT"
] | null | null | null | n_templates/task.html | SandStormHoldings/ScratchDocs | 24f3e4239781791385c0a14056335ec5f043b533 | [
"MIT"
] | null | null | null | <%inherit file="/base.html" />
<%def name="sel(name,lst,val,attr='')">
<select class="form-control" name='${name}' ${attr}>
% for st in lst:
<option value='${st}' \
% if st==val:
selected=1 \
% endif
>${st}</option>
% endfor
</select>\
</%def>
<%def name="taskmenu()">
%if parents:
% if '/' in task._id:
<a href="${upr}/${"/".join(task._id.split('/')[0:-1])}" accesskey="u"><b>U</b>p ↑ </a>
% endif
---
% for pid,psum in parents:
<a title="${pid}" href="${upr}/${pid}">${psum}</a> ›
% endfor
%endif
% if task._id:
<h2 class="task-title">\
${self.icons(task.tags,'title-icon')}
${task._id} - ${task['summary']}\
<input class="btn btn-primary " type='button' value='reload' accesskey='r' onclick="location.reload()" />
</h2>
% if rev:
<small class='red'>showing rev <b>${rev}</b></small>
% endif
<small><center>
<%
kprt = participants[:] ;
if 'user' in kprt: kprt.remove(user)
%>
<span title="grant up to ${karma_per_day} points per day!">Grant \
<span style="color:#ff0000;">K</span><span style="color:#ff7f00;">a</span><span style="color:#ffff00;">r</span><span style="color:#00ff00;">m</span><span style="color:#00ffff;">a</span>
to:</span> ${sel('karma-new',['']+kprt,'')} <input type='checkbox' name='karma-plus' value='1' checked=1 title="disable to take back" />
</center></small>
<div style="text-align:center">
% if remaining_hours:
<span class="${remaining_hours<zerodelta and 'msg' or 'bold'}">\
${"%s remaining"%remaining_hours}\
</span>
% endif
%if task['summary'] != '':
<input class="btn btn-primary upd-btn " type='submit' value='Update' accesskey='a' />
<span class="divider-vertical"></span>
<input class="btn btn-default custom-link" type='button' accesskey='s' value='Subtask' data-link="${upr}/s/new/${task._id}" accesskey='n' />
<span class="divider-vertical"></span>
<input class="btn btn-default custom-link" type='button' value='History' data-link="${upr}/${task._id}/log" />
%else:
<input class="btn btn-default custom-link" type='submit' value='Summary' data-link="${upr}/${task._id}" />
%endif
</div>
<script type='text/javascript'>
$('.show_in_gantt').click(function(ev) {
var res = /show_in_gantt_(.*)$/.exec(ev.target.id);
var tid = res[1];
var pst = {'show_in_gantt':ev.target.checked}
$.post("/"+tid+"/show_in_gantt",pst);
});
</script>
% endif
<ul class="nav nav-pills">
% if task._id:
<!-- <li><a href="${upr}/${task._id}" accesskey="m">su<b>m</b>mary</a></li>
<li><a href="${upr}/${task._id}/log" accesskey='i'>h<b>i</b>story</a></li>
<li><a href="${upr}/${task._id}/j" accesskey='j'><b>j</b>ournal</a></li>
<li class="divider-vertical"></li>
<li><a href="${upr}/s/new/${task._id}" accesskey='s'><b>s</b>ubtask</a></li>
-->
% endif
</ul>
<hr />
</%def>
<%def name="content()">
<form id="taskForm" method='post' class="form-horizontal">
<input type="hidden" name="changed_at" value="${changed_at}" />
${taskmenu()}
% if msg:
<div class='msg'>${msg}</div>
% endif
<div class='wrap' style="display:table;width:100%;">
<div style="display:table-row;">
<div style="display:table-cell;width:50%;">
<h2 class="task-title">Info</h2>
% if under:
<h4>under ${under}</h4>
<input type='hidden' name='under' value="${under}" />
% endif
<input type='hidden' name='id' value="${task._id}" />
<div class="control-group">
<label for="summary" class="control-label">Created</label>
<div class="controls" style="line-height: 30px;">
${task.created_at}
</div>
</div>
<div class="control-group">
<label for="summary" class="control-label">Summary</label>
<div class="controls">
<input id="summary" class="form-control span7" type="text" name="summary" value="${task['summary']|h}" />
</div>
</div>
<div class="control-group">
<label class="control-label">Tags</label>
<div class="controls form-inline">
% for tag in task['tags']:
<label class="checkbox">
<input type='checkbox' name="tag-${tag|h}" checked=1 value=1 />
<a href="${upr}/tag/${tag}">${tag}</a> ;
</label>
% endfor
<input type='text' name='tag-new' value="" id="inp-add-tag" placeholder="add tag(s)"/> <span title="own priority indicator">${pri}</span> + <span title="dependent on tasks with pri sum">${dep_pri}</span></span>
</div>
</div>
<div class="control-group">
<label for="sel-status" class="control-label">S<b>t</b>atus</label>
<div class="controls">
<% assert hasattr(task,'status'),"%s has no status"%task._id %>
${self.sel('status',statuses,task.status,attr='accesskey="t" id="sel-status"')}
</div>
</div>
<hr />
% if task._id:
<div class="control-group">
<% used = [] %>
% for mgroup,ms in possible_metastates.items():
<label class="control-label">${mgroup}</label>
<div class="controls mini-table" >
% for k in ms:
<% if k in used: continue %>
<% used.append(k) %>
<% v = metastates.get(k) %>
<label> ${k}: </label>
${self.metastate_sel(task._id,
k,
(v and v.get('value') or ''),
colors,
possible_metastates[mgroup],
overrides,
metastates,
allow_empty=True,
total_hours=0)}
<br />
% endfor
</div><hr />
% endfor
</div>
% endif
<div class="control-group">
<label class="control-label">Assignee</label>
<div class="controls">
<a href="${upr}/assignments/${task.assignee}">${task.assignee}</a>
change to ${self.sel('assignee',['']+participants,task.assignee)}
</div>
</div>
<% hby = hasattr(task,'handled_by') and getattr(task,'handled_by') or None %>
<div class="control-group">
<label class="control-label">Handled by</label>
<div class="controls">
<a href="${upr}/assignments/${hby}">${hby}</a>
change to ${self.sel('handled_by',['']+participants,hby)}
</div>
</div>
<div class="control-group">
<label class="control-label">Cross-links</label>
<div class="controls">
add: <input type='text' name="add-cross_link" /><br />
<input type="hidden" name="cross_links" value="${",".join([task._id+"-"+i for i in cross_links])}" />
% for cl in cross_links:
<input type='checkbox' name='cross_link-${cl}' checked=1 value=1 /> <a href="${upr}/${cl}">${cl}</a> : ${summaries[cl]}<br />
% endfor
</div>
</div>
<div class="control-group">
<label class="control-label">Dependencies</label>
<div class="controls">
add: <input type='text' name="add-dependency" /><br />
<input type="hidden" name="dependencies" value="${",".join(["-".join(i) for i in dependencies])}" />
% for cl in dependencies:
<input type='checkbox' name='dependency-${cl}' checked=1 value=1 /> <a href="${upr}/${cl}">${cl}</a> : ${summaries[cl]}<br />
% endfor
</div>
</div>
% if len(fulldeps):
<div class="control-group">
<label class="control-label">Extended dependencies</label>
<div class="controls">
<ul>
% for cl in fulldeps:
<li><a href="${upr}/${cl['depid']}">${cl['depid']}</a>: ${summaries[cl['depid']]} (${" <- ".join(cl['path_info'])})</li>
% endfor
</ul>
</div>
</div>
% endif
% if len(dependants):
<div class="control-group">
<label class="control-label">Dependants</label>
<div class="controls">
<ul>
% for cl in dependants:
<li><a href="${upr}/${cl['tid']}">${cl['tid']}</a>: ${summaries[cl['tid']]} (${" <- ".join(cl['path_info'][:-1])})</li>
% endfor
</ul>
</div>
</div>
% endif
<div class="control-group">
<label class="control-label">Creator</label>
<div class="controls" style="line-height: 30px;">
<a href="${upr}/assignments/${task.creator}">${task.creator}</a>
</div>
</div>
% if task.links:
<div class="control-group">
<label class="control-label">Links</label>
<div class="controls">
<ul class="unstyled">
% for li in task.links:
<li> <input type='checkbox' name="link-${li['anchor']|h}" checked=1 value="${li['url']|h}" /> <a href="${li['url']}">${li['anchor']}</a> \
(<a href="https://chart.googleapis.com/chart?chs=200x200&cht=qr&chld=|1&chl=${li['url']|h}">qr</a>)
</li>
% endfor
</ul>
</div>
</div>
% endif
<div class="control-group">
<label class="control-label">Karma points</label>
<%
def flatten(rdarr,el):
for k in el[1]:
for k2 in el[1][k]:
if k2 not in rdarr: rdarr[k2]=0
rdarr[k2]+=el[1][k][k2]
return rdarr
karma = getattr(task,'karma',{})
karmaflat = reduce(flatten,karma.items(),{})
%>
<div class="controls">
% if hasattr(task,'karma'):
<ul class="unstyled">
<% kfitems = sorted(karmaflat.items(),key=lambda x:x[1],reverse=True) %>
% for kpart,kval in kfitems:
<li>${kpart}: ${kval}</li>
% endfor
</ul>
% endif
</div>
</div>
% if hasattr(task,'informed') and task.informed:
<div class="control-group">
<label class="control-label">Informed</label>
<div class="controls">
<ul class="unstyled">
% for inf in task.informed:
<li><input type="checkbox" name="informed-${inf|h}" checked=1 value=1 /><a href="${upr}/assignments/${inf}">${inf}</a></li>
% endfor
</ul>
</div>
</div>
% endif
% if task.branches:
<div class="control-group">
<label class="control-label">Repo/Branch</label>
<div class="controls" style="width: 80%;">
<table class="table table-hover">
<thead><tr>
<th>del</th>
<th>repo/branch</th>
% for db in diff_branches:
<th>${db}</th>
% endfor
</tr></thead>
% for br in task.branches:
<tr>
<% r,b = br.split('/') %>
<td><input type='checkbox' name="branches-${br|h}" value="1" checked=1 /></td>
<td><a href="${gwu}?p=${r}.git;a=shortlog;h=refs/heads/${b}">${r}/${b}</a></td>
% for db in diff_branches:
<td><a href="${gwu}?p=${r}.git;a=commitdiff;h=refs/heads/${b};hp=${db}">\
% if br in branches_by_target.get(db,[]):
<b>${db}</b>
% else:
${db}
% endif
</a></td>
% endfor
</tr>
% endfor
</table>
</div>
</div>
<div class="control-group">
<label class="control-label">Automerge</label>
<div class="controls" style="width: 80%;">
<pre>
<%
for tgt,branches in branches_by_target.items():
defr = branches[0].split('/')[1] #task.branches[0].split('/')[1]
context.write("# merge to %s:\n"%tgt)
context.write("./automerge.py --from=%s --to=%s --purge --linters --message='#%s: automerge to %s.' "%(defr,tgt,task._id,tgt)+' '.join([(rb.split('/')[1]!=defr and rb or rb.split('/')[0]) for rb in task.branches])+"\n\n")
%>\
</pre>
</div>
</div>
% endif
<h4 style="text-align:center;">Add information <a id='showtog' href="#" style="font-size:12px;font-weight:normal;">graphical repr</a></h4>
<div class="control-group">
<label class="control-label">Link</label>
<div class="controls mini-table">
<label>Description:</label> <input type='text' name='link-new-anchor' /> <br/>
<label>URL:</label> <input type='text' name='link-new-url' />
</div>
</div>
<div class="control-group">
<label class="control-label">Informed</label>
<div class="controls">
${sel('informed-new',['']+participants,'')}
</div>
</div>
<div class="control-group">
<label class="control-label">Repo/Branch</label>
<div class="controls" >
${sel('branches-new-repo',repos,'')} / <input type='text' name='branches-new-branch' />
</div>
</div>
<textarea id='content' class='content' name='unstructured'>${task.unstructured}</textarea>
<div id='contentwrapper'>
</div>
% if task._id:
<input class="btn btn-primary pull-right upd-btn" type='submit' value='Update' accesskey='a' style="position: relative;right: 2%;" />
% else:
<input class="btn btn-primary pull-right" type='submit' value='Create' accesskey='a' name='create' style="position: relative;right: 2%;"/>
% endif
</form>
</div>
<div style="display:table-cell;border-left:1px solid silver;padding-left: 20px;">
% if task._id:
<h2 class="task-title">Journal</h2>
<div class='journal'>
<h4>Add comment</h4>
<textarea id="journalEditor" class='content' name='content-journal' style="width:100%;"></textarea>
<input accesskey='a' type='submit' class="btn btn-primary pull-right" />
<h4>Log</h4>
% for jk,jg in j.items():
% for ji in reversed(jg):
<div class="message">
<span class="message-author"><a href="${upr}/assignments/${ji['creator']}">${ji['creator']}</a></span>
<span> | </span>
<span class="message-datetime">${ji['created_at']}</span>
% if not 'unq_key' in ji['attrs'].keys() and ji['attrs'].items():
<div class="message-status">
<b>changed status: </b>
${'; '.join([u'%s to "%s"'%(k,v) for k,v in ji['attrs'].items()])}
</div>
% endif
<div class="message-text">
% if ji['content']:
${ji['content']|n}
% endif
</div>
</div>
% endfor
% endfor
% if hasperm('gantt'):
<h4>Gantt attrs</h4>
<div class='gantt'>
% for k in sorted(gantt.keys()):
<% v= gantt[k] %>
% if k=='s':
${gantt_labels[k]}: <input type='checkbox' class='show_in_gantt' id='show_in_gantt_${task._id}' ${v and ' checked=1' or ''} /><br />
% else:
${gantt_labels[k]}: ${v}<br />
% endif
% endfor
</div>
% endif
</div>
% endif
</div>
</div>
</div>
% if len(children):
<h3>Sub tasks</h3>
${self.list_tasks(children)}
% endif
<script type='text/javascript'>
var tid = "${task._id}";
window.onload = function() {
$('.custom-link').on('click', function () {
location.href = $(this).attr('data-link');
})
document.getElementById('summary').focus();
document.getElementById('showtog').onclick = function(ev) {
var togel = document.getElementById('showtog');
var contel = document.getElementById('content');
var wrapel = document.getElementById('contentwrapper');
if (togel.innerHTML=='graphical repr')
{
var x = new XMLHttpRequest();
x.onreadystatechange = function() {
if(x.readyState == 4){
wrapel.innerHTML=x.response;
wrapel.style.display='';
contel.style.display='none';
}
}
x.open("GET",location.href.replace(location.pathname,'/repr'+location.pathname),true);
x.send(null);
togel.innerHTML='edit';
}
else
{
wrapel.style.display='none';
contel.style.display='';
togel.innerHTML='graphical repr';
}
ev.preventDefault();
}
function check_updatability(cb) {
var pst = {'changed_at':$('input[type=hidden][name=changed_at]').val()};
$.post("/"+tid+"/validate",pst,cb);
}
function updcheck(ev) {
ev.preventDefault();
check_updatability(function(res) {
var r = JSON.parse(res);
//console.log('received',r);
if (r.tid==tid && r.valid)
{
//console.log("firing submission event");
$('#taskForm').submit();
}
else
{
alert("the task has been changed by "+r.changed_by+" else at "+r.changed_at+". please reload the page and retry.");
}
});
}
$('.upd-btn').click(updcheck);
function check_updatability_cyclic() {
//console.log('checking upd');
check_updatability(function(res) {
var r = JSON.parse(res);
//console.log("res came in",r);
if (r.valid)
{
//$('.upd-btn').attr('disabled',false);
}
else
{
$('.upd-btn').attr('disabled',true);
$('.upd-btn').val('Changed by '+r.changed_by+' at '+r.changed_at);
$('#taskForm').attr('disabled',true);
}
setTimeout(check_updatability_cyclic,5000);
});
}
setTimeout(check_updatability_cyclic,5000);
}
</script>
<script>
$(function(){
Page.init();
});
var Page = {
usernames: JSON.parse('${usernames}'.replace(/'/g, '"')),
domain: '${upr}',
init: function(){
var journalMsgs = $('.journal .message-text');
if(journalMsgs.length > 0){
journalMsgs.forEach(function (msg) {
msg.innerHTML = marked(msg.innerHTML.trim());
$(msg).find('pre code').each(function(i, block) {
hljs.highlightBlock(block);
})
});
}
$('#taskForm').submit(Page.eventHandlers.onFormSubmit);
Page.simpleMDE.init();
},
simpleMDE:{
editor: undefined,
init: function(){
Page.simpleMDE.editor = new SimpleMDE({
element: $("#journalEditor")[0],
lineWrapping: true,
status: false,
renderingConfig: {
codeSyntaxHighlighting: true,
},
toolbar: [
"heading", "bold", "italic",
{
name: "underline",
action: Page.simpleMDE.customFunctions.underline,
className: "fa fa-underline",
title: "Underline Text"
},
"|",
"quote", "unordered-list", "ordered-list", "code", "table", "horizontal-rule", "|",
"link", "image", "|",
"preview", "guide"
]
});
},
customFunctions:{
base: function(editor, openTag, closeTag){
var cm = editor.codemirror;
var selectedText = cm.getSelection();
if(selectedText){
cm.replaceSelection(openTag + selectedText + closeTag);
}
},
underline: function(editor){
Page.simpleMDE.customFunctions.base(editor, "<span class='underline'>", "</span>");
}
}
},
eventHandlers:{
onFormSubmit: function(){
var text = Page.simpleMDE.editor.value();
var userRegex = new RegExp(Page.usernames.join("|"), "g");
text = text.replace(/(\d+\/)+\d{0,}/g, "[$&](" + Page.domain + "/$&)");
text = text.replace(userRegex, "[$&](" + Page.domain + "/assignments/$&)");
Page.simpleMDE.editor.value(text);
}
}
};
</script>
</%def>
<%def name="title()">${task and (getattr(task,'_id') and task._id+' - ' or '')+task.summary or ''}</%def>
| 38.77226 | 234 | 0.461511 |
74b11fa05c788f10c85ac0157a2dcc8a9fb9b929 | 150 | js | JavaScript | main-process/communication/async-msg.js | carbondigitalus/noux-gear-dbm-app | fa572599b8181ef0f1415f6980ee2c77870da95e | [
"MIT"
] | null | null | null | main-process/communication/async-msg.js | carbondigitalus/noux-gear-dbm-app | fa572599b8181ef0f1415f6980ee2c77870da95e | [
"MIT"
] | 6 | 2020-12-04T20:23:50.000Z | 2022-03-02T02:51:55.000Z | main-process/communication/async-msg.js | carbondigitalus/noux-gear-dbm-app | fa572599b8181ef0f1415f6980ee2c77870da95e | [
"MIT"
] | null | null | null | const { ipcMain } = require('electron');
ipcMain.on('asynchronous-message', (event, arg) => {
event.sender.send('asynchronous-reply', 'pong');
});
| 25 | 52 | 0.66 |
04a804b367e29902c7edd21ef011e9eba7b36f52 | 1,581 | java | Java | src/app/src/main/java/ir/webplex/android/core/helpers/ServiceCacheManager.java | m-sadegh-sh/WebPlex.Automation | 4cc240af070f5004ab62fde44086f56ccf364011 | [
"MIT"
] | null | null | null | src/app/src/main/java/ir/webplex/android/core/helpers/ServiceCacheManager.java | m-sadegh-sh/WebPlex.Automation | 4cc240af070f5004ab62fde44086f56ccf364011 | [
"MIT"
] | null | null | null | src/app/src/main/java/ir/webplex/android/core/helpers/ServiceCacheManager.java | m-sadegh-sh/WebPlex.Automation | 4cc240af070f5004ab62fde44086f56ccf364011 | [
"MIT"
] | null | null | null | package ir.webplex.android.core.helpers;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.view.LayoutInflater;
import android.view.inputmethod.InputMethodManager;
import ir.webplex.android.automation.AppController;
public final class ServiceCacheManager {
private static LayoutInflater mLayoutInflater;
private static InputMethodManager mInputMethodManager;
private static PackageManager mPackageManager;
private static PackageInfo mPackageInfo;
public static synchronized InputMethodManager getInputMethodManager() {
if (mInputMethodManager == null)
mInputMethodManager = (InputMethodManager) AppController.getInstance().getSystemService(Context.INPUT_METHOD_SERVICE);
return mInputMethodManager;
}
public static synchronized LayoutInflater getLayoutInflater() {
if (mLayoutInflater == null)
mLayoutInflater = (LayoutInflater) AppController.getInstance().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
return mLayoutInflater;
}
public static synchronized PackageInfo getPackageInfo() {
if (mPackageManager == null) {
mPackageManager = AppController.getInstance().getPackageManager();
try {
mPackageInfo = mPackageManager.getPackageInfo(AppController.getInstance().getPackageName(), 0);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
}
return mPackageInfo;
}
}
| 35.133333 | 130 | 0.729918 |
f64f3c09db4f7c79a2c21bf35be9958a8a40c49d | 1,783 | kt | Kotlin | example_mod_1_14_4/src/main/java/sharkbound/forge/firstmod/events/scheduler/TickHandlerEvents.kt | sharkbound/forge-projects | 3302ac118d6ed9da341b74c25e13edcc4e29a040 | [
"MIT"
] | null | null | null | example_mod_1_14_4/src/main/java/sharkbound/forge/firstmod/events/scheduler/TickHandlerEvents.kt | sharkbound/forge-projects | 3302ac118d6ed9da341b74c25e13edcc4e29a040 | [
"MIT"
] | null | null | null | example_mod_1_14_4/src/main/java/sharkbound/forge/firstmod/events/scheduler/TickHandlerEvents.kt | sharkbound/forge-projects | 3302ac118d6ed9da341b74c25e13edcc4e29a040 | [
"MIT"
] | null | null | null | package sharkbound.forge.firstmod.events.scheduler
import sharkbound.commonutils.extensions.max
abstract class TickHandler(val delayTicks: Int, val isRepeating: Boolean = false, val startDelay: Int = 0) {
enum class State { RUNNING, COMPLETED, SUSPENDED }
var ticksLeft = delayTicks
var state = State.RUNNING
var elapsedTicks = 0
var totalActivates = 0
protected var currentStartDelay = startDelay
abstract fun activate()
fun suspend() {
state = State.SUSPENDED
}
fun resume() {
state = State.RUNNING
}
fun reset() {
ticksLeft = delayTicks
state = State.RUNNING
currentStartDelay = startDelay
}
fun cancel() {
state = State.COMPLETED
}
val isStarted: Boolean
get() = currentStartDelay <= 0
val isRunning: Boolean
get() = isStarted && state == State.RUNNING
val isCompleted: Boolean
get() = state == State.COMPLETED
open fun tick() {
if (currentStartDelay > 0) currentStartDelay--
if (!isRunning) return
ticksLeft = (ticksLeft - 1) max 0
elapsedTicks++
if (ticksLeft == 0 && state == State.RUNNING) {
totalActivates++
activate()
state = State.COMPLETED
}
if (state == State.COMPLETED && ticksLeft == 0 && isRepeating) {
reset()
}
}
override fun toString(): String {
return "<${javaClass.simpleName} ticksLeft=$ticksLeft delayTicks=$delayTicks>"
}
}
class DefaultTickHandler(delayTicks: Int, isRepeating: Boolean, startDelay: Int = 0, val handler: DefaultTickHandler.() -> Unit) : TickHandler(delayTicks, isRepeating, startDelay) {
override fun activate() {
handler()
}
}
| 25.112676 | 181 | 0.616377 |
c47df2201c195609f8ed8f3690a9dbe5f4b9299a | 12,968 | c | C | devices/MIMXRT1176/drivers/fsl_lcdifv2.c | 1021256354/-imxrt-tool-flash-algo | d9ba0e517128734fc416cfd15e07a7bb48022f4c | [
"Apache-2.0"
] | 26 | 2020-01-10T02:26:22.000Z | 2022-02-20T16:10:51.000Z | devices/MIMXRT1176/drivers/fsl_lcdifv2.c | 1021256354/-imxrt-tool-flash-algo | d9ba0e517128734fc416cfd15e07a7bb48022f4c | [
"Apache-2.0"
] | null | null | null | devices/MIMXRT1176/drivers/fsl_lcdifv2.c | 1021256354/-imxrt-tool-flash-algo | d9ba0e517128734fc416cfd15e07a7bb48022f4c | [
"Apache-2.0"
] | 9 | 2020-08-05T02:08:11.000Z | 2021-12-01T02:08:20.000Z | /*
* Copyright 2019-2020 NXP
* All rights reserved.
*
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#include "fsl_lcdifv2.h"
/*******************************************************************************
* Definitions
******************************************************************************/
/* Component ID definition, used by tools. */
#ifndef FSL_COMPONENT_ID
#define FSL_COMPONENT_ID "platform.drivers.lcdifv2"
#endif
/*******************************************************************************
* Prototypes
******************************************************************************/
/*!
* @brief Get instance number for LCDIF module.
*
* @param base LCDIF peripheral base address
*/
static uint32_t LCDIFV2_GetInstance(LCDIFV2_Type *base);
/*!
* @brief Reset register value to default status.
*
* @param base LCDIF peripheral base address
*/
static void LCDIFV2_ResetRegister(LCDIFV2_Type *base);
/*******************************************************************************
* Variables
******************************************************************************/
/*! @brief Pointers to LCDIF bases for each instance. */
static LCDIFV2_Type *const s_lcdifv2Bases[] = LCDIFV2_BASE_PTRS;
#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL)
/*! @brief Pointers to LCDIF clock for each instance. */
static const clock_ip_name_t s_lcdifv2Clocks[] = LCDIFV2_CLOCKS;
#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */
/*******************************************************************************
* Codes
******************************************************************************/
static uint32_t LCDIFV2_GetInstance(LCDIFV2_Type *base)
{
uint32_t instance;
/* Find the instance index from base address mappings. */
for (instance = 0; instance < ARRAY_SIZE(s_lcdifv2Bases); instance++)
{
if (s_lcdifv2Bases[instance] == base)
{
break;
}
}
assert(instance < ARRAY_SIZE(s_lcdifv2Bases));
return instance;
}
static void LCDIFV2_ResetRegister(LCDIFV2_Type *base)
{
int32_t i;
base->DISP_PARA = 0U;
base->CTRL = 0x80000000U;
base->DISP_SIZE = 0U;
base->HSYN_PARA = 0x00C01803U;
base->VSYN_PARA = 0x00C01803U;
base->INT[0].INT_ENABLE = 0U;
base->INT[1].INT_ENABLE = 0U;
base->PDI_PARA = 0x00001000U;
base->WR_CTRL = 0x007C0000U;
base->BASE_ADDR = 0U;
base->PITCH = 0U;
for (i = 0; i < LCDIFV2_LAYER_COUNT; i++)
{
base->LAYER[i].CTRLDESCL5 = 0U;
base->LAYER[i].CTRLDESCL1 = 0U;
base->LAYER[i].CTRLDESCL2 = 0U;
base->LAYER[i].CTRLDESCL3 = 0U;
base->LAYER[i].CTRLDESCL4 = 0U;
base->LAYER[i].CTRLDESCL6 = 0U;
}
for (i = 0; i < LCDIFV2_CSC_COUNT; i++)
{
base->LAYER[i].CSC_COEF0 = 0x04000000U;
base->LAYER[i].CSC_COEF1 = 0x01230208U;
base->LAYER[i].CSC_COEF2 = 0x076B079CU;
}
/* Clear interrupt status. */
base->INT[0].INT_STATUS = 0xFFFFFFFFU;
base->INT[1].INT_STATUS = 0xFFFFFFFFU;
}
/*!
* brief Initializes the LCDIF v2.
*
* This function ungates the LCDIF v2 clock and release the peripheral reset.
*
* param base LCDIF v2 peripheral base address.
*/
void LCDIFV2_Init(LCDIFV2_Type *base)
{
#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL)
uint32_t instance = LCDIFV2_GetInstance(base);
/* Enable the clock. */
CLOCK_EnableClock(s_lcdifv2Clocks[instance]);
#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */
LCDIFV2_ResetRegister(base);
/* Out of reset. */
base->CTRL = 0U;
}
/*!
* brief Deinitializes the LCDIF peripheral.
*
* param base LCDIF peripheral base address.
*/
void LCDIFV2_Deinit(LCDIFV2_Type *base)
{
LCDIFV2_ResetRegister(base);
#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL)
uint32_t instance = LCDIFV2_GetInstance(base);
/* Disable the clock. */
CLOCK_DisableClock(s_lcdifv2Clocks[instance]);
#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */
}
/*!
* brief Reset the LCDIF v2.
*
* param base LCDIF peripheral base address.
*/
void LCDIFV2_Reset(LCDIFV2_Type *base)
{
LCDIFV2_ResetRegister(base);
/* Release and ready to work. */
base->CTRL = 0U;
}
/*!
* brief Gets the LCDIF display default configuration structure.
*
* param config Pointer to the LCDIF configuration structure.
*/
void LCDIFV2_DisplayGetDefaultConfig(lcdifv2_display_config_t *config)
{
assert(config);
config->panelWidth = 0U;
config->panelHeight = 0U;
config->hsw = 3U;
config->hfp = 3U;
config->hbp = 3U;
config->vsw = 3U;
config->vfp = 3U;
config->vbp = 3U;
config->polarityFlags = kLCDIFV2_VsyncActiveHigh | kLCDIFV2_HsyncActiveHigh | kLCDIFV2_DataEnableActiveHigh |
kLCDIFV2_DriveDataOnRisingClkEdge | kLCDIFV2_DataActiveHigh;
config->lineOrder = kLCDIFV2_LineOrderRGB;
}
/*!
* brief Set the LCDIF v2 display configurations.
*
* param base LCDIF peripheral base address.
* param config Pointer to the LCDIF configuration structure.
*/
void LCDIFV2_SetDisplayConfig(LCDIFV2_Type *base, const lcdifv2_display_config_t *config)
{
assert(config);
/* Configure the parameters. */
base->DISP_SIZE = (config->panelWidth << LCDIFV2_DISP_SIZE_DELTA_X_SHIFT) |
(config->panelHeight << LCDIFV2_DISP_SIZE_DELTA_Y_SHIFT);
base->HSYN_PARA = (config->hsw << LCDIFV2_HSYN_PARA_PW_H_SHIFT) | (config->hbp << LCDIFV2_HSYN_PARA_BP_H_SHIFT) |
(config->hfp << LCDIFV2_HSYN_PARA_FP_H_SHIFT);
base->VSYN_PARA = (config->vsw << LCDIFV2_VSYN_PARA_PW_V_SHIFT) | (config->vbp << LCDIFV2_VSYN_PARA_BP_V_SHIFT) |
(config->vfp << LCDIFV2_VSYN_PARA_FP_V_SHIFT);
base->DISP_PARA = LCDIFV2_DISP_PARA_LINE_PATTERN(config->lineOrder);
base->CTRL = (uint32_t)(config->polarityFlags);
}
/*!
* brief Set the color space conversion mode.
*
* Supports YUV2RGB and YCbCr2RGB.
*
* param base LCDIFv2 peripheral base address.
* param layerIndex Index of the layer.
* param mode The conversion mode.
*/
void LCDIFV2_SetCscMode(LCDIFV2_Type *base, uint8_t layerIndex, lcdifv2_csc_mode_t mode)
{
assert(layerIndex < LCDIFV2_CSC_COUNT);
/*
* The equations used for Colorspace conversion are:
*
* R = C0*(Y+Y_OFFSET) + C1(V+UV_OFFSET)
* G = C0*(Y+Y_OFFSET) + C3(U+UV_OFFSET) + C2(V+UV_OFFSET)
* B = C0*(Y+Y_OFFSET) + C4(U+UV_OFFSET)
*/
if (kLCDIFV2_CscYUV2RGB == mode)
{
base->LAYER[layerIndex].CSC_COEF0 = LCDIFV2_CSC_COEF0_ENABLE_MASK | LCDIFV2_CSC_COEF0_C0(0x100U) /* 1.00. */
| LCDIFV2_CSC_COEF0_Y_OFFSET(0x0U) /* 0. */
| LCDIFV2_CSC_COEF0_UV_OFFSET(0x0U); /* 0. */
base->LAYER[layerIndex].CSC_COEF1 = LCDIFV2_CSC_COEF1_C1(0x0123U) /* 1.140. */
| LCDIFV2_CSC_COEF1_C4(0x0208U); /* 2.032. */
base->LAYER[layerIndex].CSC_COEF2 = LCDIFV2_CSC_COEF2_C2(0x076BU) /* -0.851. */
| LCDIFV2_CSC_COEF2_C3(0x079BU); /* -0.394. */
}
else if (kLCDIFV2_CscYCbCr2RGB == mode)
{
base->LAYER[layerIndex].CSC_COEF0 = LCDIFV2_CSC_COEF0_ENABLE_MASK | LCDIFV2_CSC_COEF0_YCBCR_MODE_MASK |
LCDIFV2_CSC_COEF0_C0(0x12AU) /* 1.164. */
| LCDIFV2_CSC_COEF0_Y_OFFSET(0x1F0U) /* -16. */
| LCDIFV2_CSC_COEF0_UV_OFFSET(0x180U); /* -128. */
base->LAYER[layerIndex].CSC_COEF1 = LCDIFV2_CSC_COEF1_C1(0x0198U) /* 1.596. */
| LCDIFV2_CSC_COEF1_C4(0x0204U); /* 2.017. */
base->LAYER[layerIndex].CSC_COEF2 = LCDIFV2_CSC_COEF2_C2(0x0730U) /* -0.813. */
| LCDIFV2_CSC_COEF2_C3(0x079CU); /* -0.392. */
}
else
{
base->LAYER[layerIndex].CSC_COEF0 = 0U;
base->LAYER[layerIndex].CSC_COEF1 = 0U;
base->LAYER[layerIndex].CSC_COEF2 = 0U;
}
}
/*!
* brief Set the layer source buffer configuration.
*
* param base LCDIFv2 peripheral base address.
* param layerIndex Layer layerIndex.
* param config Pointer to the configuration.
*/
void LCDIFV2_SetLayerBufferConfig(LCDIFV2_Type *base, uint8_t layerIndex, const lcdifv2_buffer_config_t *config)
{
assert(config);
uint32_t reg;
base->LAYER[layerIndex].CTRLDESCL3 = config->strideBytes;
reg = base->LAYER[layerIndex].CTRLDESCL5;
reg = (reg & ~(LCDIFV2_CTRLDESCL5_BPP_MASK | LCDIFV2_CTRLDESCL5_YUV_FORMAT_MASK)) | (uint32_t)config->pixelFormat;
if (0U == (reg & LCDIFV2_CTRLDESCL5_AB_MODE_MASK))
{
reg |= LCDIFV2_CTRLDESCL5_SAFETY_EN_MASK;
}
base->LAYER[layerIndex].CTRLDESCL5 = reg;
}
/*!
* brief Set the store buffer configuration.
*
* param base LCDIFv2 peripheral base address.
* param config Pointer to the store buffer.
*/
void LCDIFV2_SetStoreBufferConfig(LCDIFV2_Type *base, const lcdifv2_store_buffer_config_t *config)
{
assert(config);
base->BASE_ADDR = config->bufferAddr;
base->PITCH = config->strideBytes;
base->WR_CTRL = (base->WR_CTRL & ~LCDIFV2_WR_CTRL_BPP_MASK) | LCDIFV2_WR_CTRL_BPP(config->pixelFormat);
}
/*!
* brief Set the LUT data.
*
* This function sets the specific layer LUT data, if useShadowLoad is true,
* call LCDIFV2_TriggerLayerShadowLoad after this function, the
* LUT will be loaded to the hardware during next vertical blanking period.
* If useShadowLoad is false, the LUT data is loaded to hardware directly.
*
* param base LCDIF v2 peripheral base address.
* param layerIndex Which layer to set.
* param lutData The LUT data to load.
* param count Count of lutData.
* retval kStatus_Success Set success.
* retval kStatus_Fail Previous LUT data is not loaded to hardware yet.
*/
status_t LCDIFV2_SetLut(
LCDIFV2_Type *base, uint8_t layerIndex, const uint32_t *lutData, uint16_t count, bool useShadowLoad)
{
assert(count < LCDIFV2_LUT_ENTRY_NUM);
uint32_t i;
status_t status;
/* Previous setting is not updated. */
if ((base->CLUT_LOAD & LCDIFV2_CLUT_LOAD_CLUT_UPDATE_EN_MASK) != 0U)
{
status = kStatus_Fail;
}
else
{
if (useShadowLoad)
{
base->CLUT_LOAD = LCDIFV2_CLUT_LOAD_SEL_CLUT_NUM(layerIndex) | LCDIFV2_CLUT_LOAD_CLUT_UPDATE_EN_MASK;
}
else
{
base->CLUT_LOAD = LCDIFV2_CLUT_LOAD_SEL_CLUT_NUM(layerIndex);
}
for (i = 0; i < count; i++)
{
base->CLUT_RAM[i + LCDIFV2_LUT_ENTRY_NUM * layerIndex] = lutData[i];
}
status = kStatus_Success;
}
return status;
}
/*!
* brief Set the layer alpha blend mode.
*
* param base LCDIFv2 peripheral base address.
* param layerIndex Index of the CSC unit.
* param config Pointer to the blend configuration.
*/
void LCDIFV2_SetLayerBlendConfig(LCDIFV2_Type *base, uint8_t layerIndex, const lcdifv2_blend_config_t *config)
{
assert(config);
uint32_t reg;
reg = base->LAYER[layerIndex].CTRLDESCL5;
reg &= ~(LCDIFV2_CTRLDESCL5_GLOBAL_ALPHA_MASK | LCDIFV2_CTRLDESCL5_AB_MODE_MASK |
LCDIFV2_CTRLDESCL5_PD_FACTOR_MODE_MASK | LCDIFV2_CTRLDESCL5_PD_ALPHA_MODE_MASK |
LCDIFV2_CTRLDESCL5_PD_COLOR_MODE_MASK | LCDIFV2_CTRLDESCL5_PD_GLOBAL_ALPHA_MODE_MASK |
LCDIFV2_CTRLDESCL5_SAFETY_EN_MASK);
reg |=
(LCDIFV2_CTRLDESCL5_GLOBAL_ALPHA(config->globalAlpha) | LCDIFV2_CTRLDESCL5_AB_MODE(config->alphaMode) |
LCDIFV2_CTRLDESCL5_PD_FACTOR_MODE(config->pdFactorMode) |
LCDIFV2_CTRLDESCL5_PD_ALPHA_MODE(config->pdAlphaMode) | LCDIFV2_CTRLDESCL5_PD_COLOR_MODE(config->pdColorMode) |
LCDIFV2_CTRLDESCL5_PD_GLOBAL_ALPHA_MODE(config->pdGlobalAlphaMode));
if (config->alphaMode == kLCDIFV2_AlphaDisable)
{
reg |= LCDIFV2_CTRLDESCL5_SAFETY_EN_MASK;
}
base->LAYER[layerIndex].CTRLDESCL5 = reg;
}
/*!
* brief Start the store.
*
* If repeat mode not enabled, the store function stops after one frame. If the
* repeat mode is enabled, the store continues working until reset the module.
*
* param base LCDIFv2 peripheral base address.
* param repeat Use repeat mode or not.
*/
void LCDIFV2_StartStore(LCDIFV2_Type *base, bool repeat)
{
uint32_t reg = LCDIFV2_WR_CTRL_ENABLE_MASK;
if (repeat)
{
reg |= LCDIFV2_WR_CTRL_REPEAT_MASK;
}
base->WR_CTRL |= reg;
}
| 32.42 | 120 | 0.625231 |
e9d23621fe1f07317904f9a6807751dea5fc09c6 | 1,937 | go | Go | pkg/pkg.go | abates/gack | 44f0d470c9e63ee63cd0fb3b2eb545476524a6d7 | [
"Apache-2.0"
] | 3 | 2017-11-06T16:24:08.000Z | 2018-09-05T07:01:50.000Z | pkg/pkg.go | abates/gack | 44f0d470c9e63ee63cd0fb3b2eb545476524a6d7 | [
"Apache-2.0"
] | null | null | null | pkg/pkg.go | abates/gack | 44f0d470c9e63ee63cd0fb3b2eb545476524a6d7 | [
"Apache-2.0"
] | null | null | null | package pkg
import (
"fmt"
"os"
"github.com/abates/gack"
"github.com/abates/gack/build"
"github.com/xor-gate/debpkg"
)
type debPackager struct {
config *gack.Config
}
func NewDebPackager(mux *gack.Mux) *debPackager {
return &debPackager{
config: mux.Config,
}
}
func (p *debPackager) clean(context *gack.Context) error {
fmt.Printf("Cleaning pkg/deb/*\n")
return os.RemoveAll("pkg/deb/")
}
func (p *debPackager) Execute(context *gack.Context) error {
fmt.Printf("Packaging %s\n", context.Target.Subject())
deb := debpkg.New()
defer deb.Close()
deb.SetName(p.config.PackageName)
deb.SetVersion(p.config.Version)
deb.SetArchitecture(context.Param("architecture"))
deb.SetMaintainer(p.config.Maintainer)
deb.SetMaintainerEmail(p.config.MaintainerEmail)
deb.SetHomepage(p.config.Homepage)
deb.SetShortDescription(p.config.ShortDescription)
deb.SetDescription(p.config.Description)
err := os.MkdirAll("pkg/deb/", 0755)
if err == nil {
deb.AddFile(fmt.Sprintf("build/%s", build.Name(p.config.PackageName, "linux", context.Param("architecture"))))
err = deb.Write(fmt.Sprintf("pkg/deb/%s_%s_%s.deb", p.config.PackageName, p.config.Version, context.Param("architecture")))
}
return err
}
func (p *debPackager) Register(mux *gack.Mux) error {
pkg := mux.Config.PackageName
for _, dependency := range build.Dependencies(mux) {
if dependency.Platform == "linux" {
mux.AddDependency("pkg/deb", fmt.Sprintf("pkg/deb/%s_%s_%s.deb", pkg, mux.Config.Version, dependency.Arch), nil)
}
}
mux.Register("pkg/deb/:package_:version_:architecture.deb", p, "build/:package_linux_:architecture")
mux.AddDependency("clean/pkg", "clean/pkg/deb", gack.ExecuteFunc(p.clean))
return nil
}
func Register(mux *gack.Mux) {
NewDebPackager(mux).Register(mux)
mux.AddDependency("clean", "clean/pkg", gack.ExecuteFunc(func(*gack.Context) error {
fmt.Printf("Cleaning pkg/*\n")
return os.RemoveAll("pkg/")
}))
}
| 27.671429 | 125 | 0.722251 |
7f4f14d69dd572955001fee2bda7eebecfef8292 | 949 | lua | Lua | lua/weapons/gmod_tool/stools/rd3_resdebug.lua | viral32111/spacebuild | efc7801527fe9e262a572ba1c50b463326d31386 | [
"Apache-2.0"
] | 6 | 2018-01-06T20:07:33.000Z | 2021-10-19T22:16:52.000Z | lua/weapons/gmod_tool/stools/rd3_resdebug.lua | viral32111/spacebuild | efc7801527fe9e262a572ba1c50b463326d31386 | [
"Apache-2.0"
] | null | null | null | lua/weapons/gmod_tool/stools/rd3_resdebug.lua | viral32111/spacebuild | efc7801527fe9e262a572ba1c50b463326d31386 | [
"Apache-2.0"
] | null | null | null | TOOL.Name = "Resource Debugger"
TOOL.Tab = "Spacebuild"
TOOL.Category = "Admin"
TOOL.AdminOnly = true
if (CLIENT) then
language.Add("tool.rd3_resdebug.name", "Resource Debugger")
language.Add("tool.rd3_resdebug.desc", "Spams an entity's resource table to the console.")
language.Add("tool.rd3_resdebug.0", "Primary: Serverside | Secondary: Clientside")
end
function TOOL:LeftClick(trace)
if (trace.Entity == nil) or (CLIENT) then return false end
if (not self:GetOwner():IsAdmin()) then
self:GetOwner():ChatPrint("This tool is admin only!")
return false
end
CAF.GetAddon("Resource Distribution").PrintDebug(trace.Entity)
return true
end
function TOOL:RightClick( trace )
if (trace.Entity == nil) or (SERVER) then return false end
if (not self:GetOwner():IsAdmin()) then
self:GetOwner():ChatPrint("This tool is admin only!")
return false
end
CAF.GetAddon("Resource Distribution").PrintDebug(trace.Entity)
return true
end | 26.361111 | 91 | 0.739726 |
834eaef33d6c79f1b5fc857046d5366fdc11e570 | 1,876 | swift | Swift | Package.swift | vox-humana/AppReviewPostman | 741125d17d7a71a46ae42fd31d9b3a78a3140ee1 | [
"MIT"
] | 1 | 2020-07-13T18:54:52.000Z | 2020-07-13T18:54:52.000Z | Package.swift | vox-humana/AppReviewPostman | 741125d17d7a71a46ae42fd31d9b3a78a3140ee1 | [
"MIT"
] | 3 | 2021-01-16T07:29:31.000Z | 2021-11-14T02:38:51.000Z | Package.swift | vox-humana/AppReviewPostman | 741125d17d7a71a46ae42fd31d9b3a78a3140ee1 | [
"MIT"
] | null | null | null | // swift-tools-version:5.5
import PackageDescription
let package = Package(
name: "AppReviewPostman",
products: [
.library(name: "AppReview", targets: ["AppReview"]),
.executable(name: "Postman", targets: ["Postman"]),
],
dependencies: [
.package(url: "https://github.com/apple/swift-nio.git", from: "2.33.0"),
.package(url: "https://github.com/apple/swift-nio-ssl.git", from: "2.16.1"),
.package(url: "https://github.com/apple/swift-log.git", from: "1.4.2"),
.package(url: "https://github.com/apple/swift-argument-parser", from: "1.0.1"),
.package(url: "https://github.com/AlwaysRightInstitute/mustache.git", from: "1.0.0"),
.package(name: "SnapshotTesting", url: "https://github.com/pointfreeco/swift-snapshot-testing.git", from: "1.9.0"),
],
targets: [
.target(
name: "AppReview",
dependencies: [
.product(name: "NIO", package: "swift-nio"),
.product(name: "NIOHTTP1", package: "swift-nio"),
.product(name: "NIOSSL", package: "swift-nio-ssl"),
.product(name: "Logging", package: "swift-log"),
"mustache",
]
),
.executableTarget(
name: "Postman",
dependencies: [
"AppReview",
.product(name: "NIO", package: "swift-nio"),
.product(name: "Logging", package: "swift-log"),
.product(name: "ArgumentParser", package: "swift-argument-parser"),
]
),
.testTarget(
name: "AppReviewPostmanTests",
dependencies: [
"AppReview",
"mustache",
"SnapshotTesting",
],
resources: [
.copy("feed.json"),
]
),
]
)
| 36.076923 | 123 | 0.509595 |
e09ea64131a322602bd103eb8155cedc76df67f6 | 312 | swift | Swift | Source/Common/Enumerations/SpecialChar.swift | dedeexe/githubstars | 31c5b5ab36d3c1553fd3c9fbda69673350151bf2 | [
"MIT"
] | null | null | null | Source/Common/Enumerations/SpecialChar.swift | dedeexe/githubstars | 31c5b5ab36d3c1553fd3c9fbda69673350151bf2 | [
"MIT"
] | null | null | null | Source/Common/Enumerations/SpecialChar.swift | dedeexe/githubstars | 31c5b5ab36d3c1553fd3c9fbda69673350151bf2 | [
"MIT"
] | null | null | null | //
// Icon.swift
// GitHubRating
//
// Created by dede.exe on 17/01/19.
// Copyright © 2019 dede.exe. All rights reserved.
//
import Foundation
enum SpecialChar {
case star
}
extension SpecialChar {
var icon : String {
switch self {
case .star: return "\u{2605}"
}
}
}
| 14.181818 | 51 | 0.586538 |
9057058846845b0118025e5af45f256c48762a27 | 3,652 | asm | Assembly | dos/DosExitList.asm | osfree-project/FamilyAPI | 2119a95cb2bbe6716ecacff4171866f6ea51b8d7 | [
"BSD-3-Clause"
] | 1 | 2021-11-25T14:01:48.000Z | 2021-11-25T14:01:48.000Z | dos/DosExitList.asm | osfree-project/FamilyAPI | 2119a95cb2bbe6716ecacff4171866f6ea51b8d7 | [
"BSD-3-Clause"
] | null | null | null | dos/DosExitList.asm | osfree-project/FamilyAPI | 2119a95cb2bbe6716ecacff4171866f6ea51b8d7 | [
"BSD-3-Clause"
] | 2 | 2021-11-05T06:48:43.000Z | 2021-12-06T08:07:38.000Z |
.8086
externdef DOSEXIT:far
public DOSEXITLIST
_DATA segment byte public 'DATA'
procad dd 0 ;address of exit proc
rc dw 0 ;RC
psp dw 0 ;PSP
_DATA ends
_TEXT segment byte public 'CODE'
stab label word
dw offset AddToList
dw offset Remove
dw offset Complete
vector dd 0 ;previous dos vector (21h)
DOSEXITLIST:
push BP
mov BP,SP
push DX
push SI
push DI
push ES
push ds
mov ax,_DATA
mov ds,ax
assume ds:_DATA
mov SI,[BP+10]
mov AX,1
cmp si,3
ja exit ;error
dec SI ;0,1,2
shl SI,1
jmp cs:[SI+stab]
AddToList: ;add to termination list
push BX
mov AH,062h ;get PSP
int 21h
mov [psp],BX
pop BX
cmp word ptr cs:[vector+2],0
jnz @F
call setint21
@@: mov AX,[BP+6] ;save address
mov DX,[BP+8]
mov word ptr [procad+0],AX
mov word ptr [procad+2],DX
jmp done
Remove: ;remove from termination list
cmp word ptr cs:[vector+2],0
je done
call restoreint21 ;dos vector restore
jmp done
Complete: ;termination processing complete
cmp word ptr cs:[vector+2],0
je @F
call restoreint21
@@:
MOV AX, 1
push AX
push [rc]
call DOSEXIT
done:
xor AX,AX
exit:
pop ds
pop ES
pop DI
pop SI
pop DX
mov SP,BP
pop BP
retf 6
savevektor proc near private
push bp
mov bp,sp
mov bx,cs
mov ax,000Ah ;get alias for CS
int 31h
jc @F
push ds
mov ds,ax
assume ds:_TEXT
mov ax,[bp+4]
mov word ptr [vector+0],ax
mov ax,[bp+6]
mov word ptr [vector+2],ax
mov bx,ds
pop ds
assume ds:_DATA
mov ax,1
int 31h
@@:
pop bp
ret 4
savevektor endp
;*** add to termination list ***
setint21:
mov AX,03521h
int 21h
push es
push bx
call savevektor
push DS
push CS
pop DS
mov DX,offset myint21
mov AX,02521h
int 21h
pop DS
ret
;*** routine raus ***
restoreint21:
push DS
mov AX,02521h
lds DX,cs:[vector]
int 21h
pop DS
xor AX,AX
push ax
push ax
call savevektor
ret
;*** termination handler int 21 ***
myint21:
pushf
cmp AH,04Ch
jne noterm
push ds
push AX
mov ax,_data
mov ds,ax
push BX
mov AH,062h
int 21h
cmp word ptr [psp],BX
pop BX
pop AX
je itsus
pop ds
noterm:
popf
jmp dword ptr CS:[vector]
itsus:
mov [rc],AX
pop ax
popf
push word ptr [procad+2]
push word ptr [procad+0]
mov ds,ax
retf
_TEXT ends
end
| 20.402235 | 64 | 0.412103 |
e880e7cd159ccf59d0e871ff46993f63253d02d8 | 2,135 | lua | Lua | meta/3rd/Cocos4.0/library/ccb.TextureBackend.lua | CppCXY/lua-language-server | b51c930f3cca060b10ab724666c9f5265cefd517 | [
"MIT"
] | 6 | 2018-11-20T10:51:35.000Z | 2018-11-30T23:12:52.000Z | meta/3rd/Cocos4.0/library/ccb.TextureBackend.lua | CppCXY/lua-language-server | b51c930f3cca060b10ab724666c9f5265cefd517 | [
"MIT"
] | null | null | null | meta/3rd/Cocos4.0/library/ccb.TextureBackend.lua | CppCXY/lua-language-server | b51c930f3cca060b10ab724666c9f5265cefd517 | [
"MIT"
] | null | null | null | ---@meta
---@class ccb.TextureBackend :cc.Ref
local TextureBackend={ }
ccb.TextureBackend=TextureBackend
---* Get texture format.<br>
---* return Texture format.
---@return int
function TextureBackend:getTextureFormat () end
---* Get texture type. Symbolic constant value can be either TEXTURE_2D or TEXTURE_CUBE.<br>
---* return Texture type.
---@return int
function TextureBackend:getTextureType () end
---* Update sampler<br>
---* param sampler Specifies the sampler descriptor.
---@param sampler cc.backend.SamplerDescriptor
---@return cc.backend.TextureBackend
function TextureBackend:updateSamplerDescriptor (sampler) end
---* Update texture description.<br>
---* param descriptor Specifies texture and sampler descriptor.
---@param descriptor cc.backend.TextureDescriptor
---@return cc.backend.TextureBackend
function TextureBackend:updateTextureDescriptor (descriptor) end
---* Get texture usage. Symbolic constant can be READ, WRITE or RENDER_TARGET.<br>
---* return Texture usage.
---@return int
function TextureBackend:getTextureUsage () end
---* Check if mipmap had generated before.<br>
---* return true if the mipmap has always generated before, otherwise false.
---@return boolean
function TextureBackend:hasMipmaps () end
---* / Generate mipmaps.
---@return cc.backend.TextureBackend
function TextureBackend:generateMipmaps () end
---* Read a block of pixels from the drawable texture<br>
---* param x,y Specify the window coordinates of the first pixel that is read from the drawable texture. This location is the lower left corner of a rectangular block of pixels.<br>
---* param width,height Specify the dimensions of the pixel rectangle. width and height of one correspond to a single pixel.<br>
---* param flipImage Specifies if needs to flip the image.<br>
---* param callback Specifies a call back function to deal with the image.
---@param x unsigned_int
---@param y unsigned_int
---@param width unsigned_int
---@param height unsigned_int
---@param flipImage boolean
---@param callback function
---@return cc.backend.TextureBackend
function TextureBackend:getBytes (x,y,width,height,flipImage,callback) end | 41.862745 | 181 | 0.769555 |
dda8093a106307e24fa3f279068bc07568b80534 | 4,208 | go | Go | services/cr/apis/ReleaseAuthorizationToken.go | zhaoxiangchun/jdcloud-sdk-go | abade87e78106bc9ce437cf871c6a1ce8c42242d | [
"Apache-2.0"
] | 27 | 2018-04-19T09:53:50.000Z | 2022-03-22T10:02:21.000Z | services/cr/apis/ReleaseAuthorizationToken.go | waytai/jdcloud-sdk-go | dcc6954ae4379f3123a4c777d315012431347450 | [
"Apache-2.0"
] | 15 | 2018-05-23T08:20:55.000Z | 2021-09-16T10:13:54.000Z | services/cr/apis/ReleaseAuthorizationToken.go | waytai/jdcloud-sdk-go | dcc6954ae4379f3123a4c777d315012431347450 | [
"Apache-2.0"
] | 32 | 2018-04-18T08:29:32.000Z | 2022-03-15T03:14:06.000Z | // Copyright 2018 JDCLOUD.COM
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// NOTE: This class is auto generated by the jdcloud code generator program.
package apis
import (
"github.com/jdcloud-api/jdcloud-sdk-go/core"
)
type ReleaseAuthorizationTokenRequest struct {
core.JDCloudRequest
/* 地域 ID */
RegionId string `json:"regionId"`
/* 注册表名称 */
RegistryName string `json:"registryName"`
/* 准备释放的 token ID,功能为指定token释放。 (Optional) */
AuthorizationToken *string `json:"authorizationToken"`
/* true 表示强制删除用户当前registry下所有有效token的标志;false 表示删除所有有效token。 (Optional) */
ForceAll *bool `json:"forceAll"`
}
/*
* param regionId: 地域 ID (Required)
* param registryName: 注册表名称 (Required)
*
* @Deprecated, not compatible when mandatory parameters changed
*/
func NewReleaseAuthorizationTokenRequest(
regionId string,
registryName string,
) *ReleaseAuthorizationTokenRequest {
return &ReleaseAuthorizationTokenRequest{
JDCloudRequest: core.JDCloudRequest{
URL: "/regions/{regionId}/registries/{registryName}:releaseAuthorizationToken",
Method: "POST",
Header: nil,
Version: "v1",
},
RegionId: regionId,
RegistryName: registryName,
}
}
/*
* param regionId: 地域 ID (Required)
* param registryName: 注册表名称 (Required)
* param authorizationToken: 准备释放的 token ID,功能为指定token释放。 (Optional)
* param forceAll: true 表示强制删除用户当前registry下所有有效token的标志;false 表示删除所有有效token。 (Optional)
*/
func NewReleaseAuthorizationTokenRequestWithAllParams(
regionId string,
registryName string,
authorizationToken *string,
forceAll *bool,
) *ReleaseAuthorizationTokenRequest {
return &ReleaseAuthorizationTokenRequest{
JDCloudRequest: core.JDCloudRequest{
URL: "/regions/{regionId}/registries/{registryName}:releaseAuthorizationToken",
Method: "POST",
Header: nil,
Version: "v1",
},
RegionId: regionId,
RegistryName: registryName,
AuthorizationToken: authorizationToken,
ForceAll: forceAll,
}
}
/* This constructor has better compatible ability when API parameters changed */
func NewReleaseAuthorizationTokenRequestWithoutParam() *ReleaseAuthorizationTokenRequest {
return &ReleaseAuthorizationTokenRequest{
JDCloudRequest: core.JDCloudRequest{
URL: "/regions/{regionId}/registries/{registryName}:releaseAuthorizationToken",
Method: "POST",
Header: nil,
Version: "v1",
},
}
}
/* param regionId: 地域 ID(Required) */
func (r *ReleaseAuthorizationTokenRequest) SetRegionId(regionId string) {
r.RegionId = regionId
}
/* param registryName: 注册表名称(Required) */
func (r *ReleaseAuthorizationTokenRequest) SetRegistryName(registryName string) {
r.RegistryName = registryName
}
/* param authorizationToken: 准备释放的 token ID,功能为指定token释放。(Optional) */
func (r *ReleaseAuthorizationTokenRequest) SetAuthorizationToken(authorizationToken string) {
r.AuthorizationToken = &authorizationToken
}
/* param forceAll: true 表示强制删除用户当前registry下所有有效token的标志;false 表示删除所有有效token。(Optional) */
func (r *ReleaseAuthorizationTokenRequest) SetForceAll(forceAll bool) {
r.ForceAll = &forceAll
}
// GetRegionId returns path parameter 'regionId' if exist,
// otherwise return empty string
func (r ReleaseAuthorizationTokenRequest) GetRegionId() string {
return r.RegionId
}
type ReleaseAuthorizationTokenResponse struct {
RequestID string `json:"requestId"`
Error core.ErrorResponse `json:"error"`
Result ReleaseAuthorizationTokenResult `json:"result"`
}
type ReleaseAuthorizationTokenResult struct {
} | 30.941176 | 95 | 0.723384 |
28a33b19660c6b5e8544a05339e81e7a6af5fc6b | 180 | psd1 | PowerShell | SNXT-SND/SNXT-SND.psd1 | rockbyo5/Skyrim-NX-Toolkit | 0097c1da6f2b76751884355ee688d11dffd1172c | [
"MIT"
] | 84 | 2018-08-07T12:37:35.000Z | 2022-01-07T09:16:49.000Z | SNXT-SND/SNXT-SND.psd1 | Lord-Akkrand/SkyrimNX | 22d5054af694337e9e7665dde86cb5af5bb78192 | [
"MIT"
] | 32 | 2018-08-07T00:25:02.000Z | 2021-10-06T03:25:56.000Z | SNXT-SND/SNXT-SND.psd1 | Lord-Akkrand/SkyrimNX | 22d5054af694337e9e7665dde86cb5af5bb78192 | [
"MIT"
] | 11 | 2018-09-12T00:05:08.000Z | 2021-01-28T18:51:40.000Z | $manifest = @{
Path = '.\SNXT-SND\SNXT-SND.psd1'
RootModule = 'SNXT-SND.psm1'
Author = 'Antony Marshall'
}
New-ModuleManifest @manifest | 30 | 50 | 0.533333 |
04bfc120df9b896fc7ca19e7eaf5849b0dae2f2d | 1,799 | java | Java | src/main/java/org/symcomp/wupsi/handlers/QuitHandler.java | symcomp/Wupsi | 89ea10cb75df3d378e147ae685d807191962c77a | [
"Apache-2.0"
] | 1 | 2016-06-30T12:29:16.000Z | 2016-06-30T12:29:16.000Z | src/main/java/org/symcomp/wupsi/handlers/QuitHandler.java | symcomp/Wupsi | 89ea10cb75df3d378e147ae685d807191962c77a | [
"Apache-2.0"
] | null | null | null | src/main/java/org/symcomp/wupsi/handlers/QuitHandler.java | symcomp/Wupsi | 89ea10cb75df3d378e147ae685d807191962c77a | [
"Apache-2.0"
] | null | null | null | //---------------------------------------------------------------------------
// Copyright 2006-2009
// Dan Roozemond, d.a.roozemond@tue.nl, (TU Eindhoven, Netherlands)
// Peter Horn, horn@math.uni-kassel.de (University Kassel, Germany)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//---------------------------------------------------------------------------
package org.symcomp.wupsi.handlers;
import org.symcomp.wupsi.Wupsifer;
import org.symcomp.scscp.SCSCPClient;
import java.util.Map;
/**
* handles the 'quit' command, which closes WUPSI.
*/
public class QuitHandler extends WupsiHandler {
Wupsifer w;
public QuitHandler(Wupsifer w) {
this.w = w;
}
public String command() {
return "quit";
}
public void handle(String in) {
Map<String,SCSCPClient> clients = w.getClients();
for (String n : clients.keySet()) {
w.info("# disconnecting "+n);
SCSCPClient client = clients.get(n);
client.quit();
}
w.info("# shutting down handlers");
for (WupsiHandler wh : w.getHandlers()) {
wh.shutdownHook();
}
w.info("# ...quitting");
System.exit(0);
}
public String help() {
return "quit";
}
}
| 29.983333 | 77 | 0.583658 |
a9b07e38959e0b0ac6a5f27d9334d3c1929fc2b0 | 365 | dart | Dart | notes/learn-bloc/bloc/posts_bloc.dart | learn-frame/learn-dart-and-flutter | 0dc5e43e45290ee915c0cfaed5c136be8087c5b7 | [
"BSD-3-Clause"
] | 1 | 2020-08-13T04:50:19.000Z | 2020-08-13T04:50:19.000Z | notes/learn-bloc/bloc/posts_bloc.dart | learn-frame/learn-dart-and-flutter | 0dc5e43e45290ee915c0cfaed5c136be8087c5b7 | [
"BSD-3-Clause"
] | null | null | null | notes/learn-bloc/bloc/posts_bloc.dart | learn-frame/learn-dart-and-flutter | 0dc5e43e45290ee915c0cfaed5c136be8087c5b7 | [
"BSD-3-Clause"
] | null | null | null | import 'dart:async';
import 'package:bloc/bloc.dart';
import 'package:meta/meta.dart';
part 'posts_event.dart';
part 'posts_state.dart';
class PostsBloc extends Bloc<PostsEvent, PostsState> {
PostsBloc() : super(PostsInitial());
@override
Stream<PostsState> mapEventToState(
PostsEvent event,
) async* {
// TODO: implement mapEventToState
}
}
| 19.210526 | 54 | 0.715068 |
1f64bb41eba45e16157a9aa0f1dd4c8bf76f0965 | 2,778 | css | CSS | styles/partials/calc-body.css | trybrito/devcalc | 8ec58eb1541a490ca317d6375f5ae12e8842c224 | [
"MIT"
] | null | null | null | styles/partials/calc-body.css | trybrito/devcalc | 8ec58eb1541a490ca317d6375f5ae12e8842c224 | [
"MIT"
] | null | null | null | styles/partials/calc-body.css | trybrito/devcalc | 8ec58eb1541a490ca317d6375f5ae12e8842c224 | [
"MIT"
] | null | null | null | main > div section#calc-body {
padding: 1.125rem 1.25rem 1.25rem;
}
section#calc-body div#display :is(input, p) {
letter-spacing: 0.75px;
}
div#display input {
text-align: right;
width: 100%;
height: 5.1875rem;
padding: 0 0.75rem 0 0.5rem;
background-color: var(--input-background);
color: var(--input-text);
font-size: 1.875rem;
outline: none;
border: none;
border-radius: 0.1875rem;
cursor: default;
}
div#display input::placeholder {
color: var(--input-text);
}
div#display input.stretch {
height: 5.75rem;
}
div#display input.has-result {
height: 2.875rem;
border-radius: 0.1875rem 0.1875rem 0 0;
padding-top: 0.375rem;
}
div#display input.has-result.stretch {
height: 3.25rem;
padding-top: 0.5rem;
}
div#display div#result-container {
text-align: right;
padding: 0 0.75rem 0.5rem 0.5rem;
background-color: var(--input-background);
border-radius: 0 0 0.1875rem 0.1875rem;
}
div#display div#result-container.stretch {
height: 2.5rem;
padding-bottom: 0.5rem;
}
div#result-container p {
max-width: 20.125rem;
font-size: 1.5rem;
color: var(--p-text);
cursor: default;
border-radius: 99px;
overflow-x: auto;
white-space: nowrap;
}
div#result-container.stretch p {
max-width: 26.375rem;
}
div#result-container p::-webkit-scrollbar {
display: none;
}
section#calc-body div#buttons-wrapper {
margin-top: 1.875rem;
}
div#buttons-wrapper button {
display: flex;
justify-content: center;
align-items: center;
width: 4.875rem;
height: 4.875rem;
font-size: 1.5rem;
font-weight: 500;
letter-spacing: 0.5px;
background-color: var(--button-background);
color: var(--button-text);
border-radius: 50%;
box-shadow: 0 0 0.125rem var(--button-border);
transition-duration: 0.25s;
}
div#buttons-wrapper button.letter-spacing {
letter-spacing: 0.75px;
}
div#buttons-wrapper button.colorized-button {
background-color: var(--colorized-button-background);
}
div#buttons-wrapper button.colorized-icon-button {
font-size: 1.775rem;
}
div#buttons-wrapper button:hover {
filter: brightness(0.95);
transform: scale(1.05);
}
div#buttons-wrapper button:active {
transform: scale(0.95);
}
div#header-container {
margin-bottom: 0.625rem;
padding-bottom: 0.625rem;
border-bottom: 0.125rem solid var(--header-line);
}
div#header-container > div,
div#main-container > div {
display: flex;
align-items: center;
gap: 0.625rem;
}
div#header-container > div + div,
div#main-container > div + div {
margin-top: 0.625rem;
}
div#header-container div div,
div#main-container div div {
padding-left: 0.625rem;
border-left: 0.125rem solid var(--header-line);
}
div#main-container > div:last-child > button:first-child {
width: 10.355rem;
border-radius: 99px;
}
| 19.027397 | 58 | 0.691505 |
5de86278b2b151734b5cabad09335c16dfed936f | 859 | h | C | src/read.h | tomjlw/VIP | 5ee62f815cacb4b48fbb8e3664eebb0fc47de092 | [
"MIT"
] | 1 | 2018-11-20T15:11:31.000Z | 2018-11-20T15:11:31.000Z | src/read.h | tomjlw/VIP | 5ee62f815cacb4b48fbb8e3664eebb0fc47de092 | [
"MIT"
] | null | null | null | src/read.h | tomjlw/VIP | 5ee62f815cacb4b48fbb8e3664eebb0fc47de092 | [
"MIT"
] | null | null | null |
#include <stdio.h>
#include <string.h>
int read(float *z, float *b)
{
char szTest[100000] = {0};
int index=0;
FILE *fp = fopen("../data/filter.txt", "r");
if(NULL == fp)
{ printf("failed to open dos.txt\n"); return 1; }
while(!feof(fp))
{
char* token;
float var;
char seps[] = " ";
memset(szTest, 0, sizeof(szTest));
fgets(szTest, sizeof(szTest) - 1, fp);
token =strtok(szTest, seps);
while(token != NULL)
{
index++;
sscanf(token,"%f",&var);
if (1<=index<=1201){z[index-1]=var;}
if(1203<=index<=1267){b[index-1203]=var;}
//if (index == 1){memcpy(z, input, sizeof z);}
//else {memcpy(b, input, sizeof b);}
token = strtok (NULL, seps);
}
}
fclose(fp);
return 0;
}
int len(float *a)
{
return sizeof(a)/sizeof(a[0]);
}
| 17.530612 | 54 | 0.519208 |
b36da0c35f8a9d3bcbcd0fc5320d5234b0f29f08 | 271 | asm | Assembly | programs/oeis/130/A130909.asm | neoneye/loda | afe9559fb53ee12e3040da54bd6aa47283e0d9ec | [
"Apache-2.0"
] | 22 | 2018-02-06T19:19:31.000Z | 2022-01-17T21:53:31.000Z | programs/oeis/130/A130909.asm | neoneye/loda | afe9559fb53ee12e3040da54bd6aa47283e0d9ec | [
"Apache-2.0"
] | 41 | 2021-02-22T19:00:34.000Z | 2021-08-28T10:47:47.000Z | programs/oeis/130/A130909.asm | neoneye/loda | afe9559fb53ee12e3040da54bd6aa47283e0d9ec | [
"Apache-2.0"
] | 5 | 2021-02-24T21:14:16.000Z | 2021-08-09T19:48:05.000Z | ; A130909: Simple periodic sequence (n mod 16).
; 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,0,1,2,3,4,5,6,7,8,9
mod $0,16
| 54.2 | 211 | 0.594096 |
0c983c89d954e199eb26dc9eb1e9dfde6cd61d8c | 1,395 | py | Python | day10/django/app4/dateview/updateTeachPlan.py | Vanessa-kriby/Python | 1fbef67852fb362712fc48fa5c3c29eac68fe202 | [
"Apache-2.0"
] | null | null | null | day10/django/app4/dateview/updateTeachPlan.py | Vanessa-kriby/Python | 1fbef67852fb362712fc48fa5c3c29eac68fe202 | [
"Apache-2.0"
] | null | null | null | day10/django/app4/dateview/updateTeachPlan.py | Vanessa-kriby/Python | 1fbef67852fb362712fc48fa5c3c29eac68fe202 | [
"Apache-2.0"
] | null | null | null | from app1.models import *
from app1.util.utils import *
def updateTeachPlan(request):
'''
get:
http://127.0.0.1:8000/app4/updateTeachPlan?tpno=001&credit=7.0&teach_date=2019-08-22&evaluation_method=考查
调用参数:
tpno:计划编号
credit:学分
teach_date:开课日期
evaluation_method:考察方式
post:
http://127.0.0.1:8000/app4/updateTeachPlan
'''
try:
if(request.method=='POST'):
teadata=json.loads(request.body)
data=teadata["data"]
for item in data:
# tpid=request.GET.get("tpno")
# cr=request.GET.get("credit")
# te=request.GET.get("teach_date")
# ev=request.GET.get("evaluation_method")
tpid=item["tpno"]
cr=item["credit"]
te=item["teach_date"]
ev=item["evaluation_method"]
result=TeachPlan.objects.filter(tpno=tpid).update(credit=cr,teach_date=te,evaluation_method=ev)
result=TeachPlan.objects.all().values("tpno","credit","teach_date","evaluation_method","department__dno","department__dname","course__cno","course__cname","teacher__tno","teacher__tname")
return showJsonresult(result)
except Exception as e:
response={}
response['msg']=str(e)
response['err_num']=1
return showJsonerror(response) | 35.769231 | 195 | 0.593548 |
5eb5238266b2bff9fefb8e424d6898cc80e9866c | 1,133 | kt | Kotlin | app/src/main/java/com/anhvt/weathersearch/presentation/di/MainModule.kt | anhvt52/weathersearch | ed6d186b20c4210187bc383e53f9a2b482c4776c | [
"Apache-2.0"
] | 5 | 2021-07-23T10:07:27.000Z | 2021-07-25T07:41:21.000Z | app/src/main/java/com/anhvt/weathersearch/presentation/di/MainModule.kt | anhvt52/weathersearch | ed6d186b20c4210187bc383e53f9a2b482c4776c | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/anhvt/weathersearch/presentation/di/MainModule.kt | anhvt52/weathersearch | ed6d186b20c4210187bc383e53f9a2b482c4776c | [
"Apache-2.0"
] | null | null | null | package com.anhvt.weathersearch.presentation.di
import com.anhvt.weathersearch.data.WeatherRepositoryImpl
import com.anhvt.weathersearch.data.datasource.LocalDatasource
import com.anhvt.weathersearch.data.datasource.RemoteDataSource
import com.anhvt.weathersearch.data.datasource.SearchWeatherLocalDataSourceImpl
import com.anhvt.weathersearch.data.datasource.SearchWeatherRemoteDataSourceImpl
import com.anhvt.weathersearch.domain.repository.WeatherRepository
import dagger.Binds
import dagger.Module
import dagger.hilt.InstallIn
import dagger.hilt.android.components.ViewModelComponent
import dagger.hilt.android.scopes.ViewModelScoped
@Module
@InstallIn(ViewModelComponent::class)
abstract class MainModule {
@Binds
@ViewModelScoped
abstract fun weatherRepository(
weatherRepositoryImpl: WeatherRepositoryImpl
): WeatherRepository
@Binds
abstract fun bindRemoteDataSource(
remoteDataSourceImpl: SearchWeatherRemoteDataSourceImpl
): RemoteDataSource
@Binds
abstract fun bindLocalDataSour(
localDataSourceImpl: SearchWeatherLocalDataSourceImpl
): LocalDatasource
} | 34.333333 | 80 | 0.830538 |
aae69889a9a3769f6d83a2160eae427bf101f650 | 2,554 | kt | Kotlin | formats/json/commonMain/src/kotlinx/serialization/json/JsonAnnotations.kt | LinusMuema/kotlinx.serialization | 41b3996b9818fd3041cbc5ae1aa362c7e37a586d | [
"Apache-2.0"
] | 3,866 | 2017-07-20T11:27:47.000Z | 2022-03-31T17:30:56.000Z | formats/json/commonMain/src/kotlinx/serialization/json/JsonAnnotations.kt | LinusMuema/kotlinx.serialization | 41b3996b9818fd3041cbc5ae1aa362c7e37a586d | [
"Apache-2.0"
] | 1,640 | 2017-09-22T19:29:40.000Z | 2022-03-31T08:27:04.000Z | formats/json/commonMain/src/kotlinx/serialization/json/JsonAnnotations.kt | LinusMuema/kotlinx.serialization | 41b3996b9818fd3041cbc5ae1aa362c7e37a586d | [
"Apache-2.0"
] | 648 | 2017-09-24T09:16:13.000Z | 2022-03-30T12:00:08.000Z | /*
* Copyright 2017-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.serialization.json
import kotlinx.serialization.*
import kotlinx.serialization.descriptors.*
import kotlinx.serialization.encoding.*
import kotlinx.serialization.json.internal.*
import kotlin.native.concurrent.*
/**
* Indicates that the field can be represented in JSON
* with multiple possible alternative names.
* [Json] format recognizes this annotation and is able to decode
* the data using any of the alternative names.
*
* Unlike [SerialName] annotation, does not affect JSON encoding in any way.
*
* Example of usage:
* ```
* @Serializable
* data class Project(@JsonNames("title") val name: String)
*
* val project = Json.decodeFromString<Project>("""{"name":"kotlinx.serialization"}""")
* println(project)
* val oldProject = Json.decodeFromString<Project>("""{"title":"kotlinx.coroutines"}""")
* println(oldProject)
* ```
*
* This annotation has lesser priority than [SerialName].
*
* @see JsonBuilder.useAlternativeNames
*/
@SerialInfo
@Target(AnnotationTarget.PROPERTY)
@ExperimentalSerializationApi
public annotation class JsonNames(vararg val names: String)
/**
* Specifies key for class discriminator value used during polymorphic serialization in [Json].
* Provided key is used only for an annotated class and its subclasses;
* to configure global class discriminator, use [JsonBuilder.classDiscriminator]
* property.
*
* This annotation is [inheritable][InheritableSerialInfo], so it should be sufficient to place it on a base class of hierarchy.
* It is not possible to define different class discriminators for different parts of class hierarchy.
* Pay attention to the fact that class discriminator, same as polymorphic serializer's base class, is
* determined statically.
*
* Example:
* ```
* @Serializable
* @JsonClassDiscriminator("message_type")
* abstract class Base
*
* @Serializable // Class discriminator is inherited from Base
* abstract class ErrorClass: Base()
*
* @Serializable
* class Message(val message: Base, val error: ErrorClass?)
*
* val message = Json.decodeFromString<Message>("""{"message": {"message_type":"my.app.BaseMessage", "message": "not found"}, "error": {"message_type":"my.app.GenericError", "error_code": 404}}""")
* ```
*
* @see JsonBuilder.classDiscriminator
*/
@InheritableSerialInfo
@Target(AnnotationTarget.CLASS)
@ExperimentalSerializationApi
public annotation class JsonClassDiscriminator(val discriminator: String)
| 34.986301 | 197 | 0.752545 |
f4f8767a6ee321c1864af6a41aabc37258f8f5e4 | 4,432 | go | Go | cmd/cmd/transactionReport.go | Nirothipan/product-mi-tooling | 7d3aa31c7f98e629bec8b26234b8c2d746058c11 | [
"Apache-2.0"
] | null | null | null | cmd/cmd/transactionReport.go | Nirothipan/product-mi-tooling | 7d3aa31c7f98e629bec8b26234b8c2d746058c11 | [
"Apache-2.0"
] | null | null | null | cmd/cmd/transactionReport.go | Nirothipan/product-mi-tooling | 7d3aa31c7f98e629bec8b26234b8c2d746058c11 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package cmd
import (
"fmt"
"github.com/spf13/cobra"
"github.com/wso2/product-mi-tooling/cmd/utils"
"github.com/wso2/product-mi-tooling/cmd/utils/artifactUtils"
"os"
"path/filepath"
"strconv"
"strings"
"time"
)
const transactionReportCmdLiteral = "report"
const transactionReportCmdShortDesc = "Generate transaction count summary report"
const transactionReportCmdLongDesc = "Generate the transaction count summary report at the given location for the " +
"given period of time.\nIf a location not provided, generate the report in current directory.\nIf an end date " +
"not provided, generate the report with values upto current date.\n\n"
var transactionReportCmdArgs = []string{
"[start] [end] --path=[destination-file-location]",
"[start] [end]",
"[start] --path=[destination-file-location]",
}
var transactionReportCmd = &cobra.Command{
Use: transactionReportCmdLiteral,
Short: transactionReportCmdShortDesc,
Long: transactionReportCmdLongDesc,
Run: func(cmd *cobra.Command, args []string) {
destinationFileLocation, _ := cmd.Flags().GetString("path")
if len(strings.TrimSpace(destinationFileLocation)) == 0 || destinationFileLocation == "." {
destinationFileLocation, _ = os.Getwd()
}
handleTransactionReportCmdArguments(args, destinationFileLocation)
},
}
func init() {
transactionCmd.AddCommand(transactionReportCmd)
transactionReportCmd.Flags().StringP("path", "p", "", "destination file location")
transactionReportCmd.SetHelpTemplate(transactionReportCmdLongDesc + utils.GetCmdUsageForArgsOnly(programName,
transactionCmdLiteral, transactionReportCmdLiteral, transactionReportCmdArgs) +
utils.GetCmdFlags(transactionCmdLiteral))
}
// Check arguments for "start" and "end" and execute get transaction report generation command.
// Print an error if no valid number of arguments.
func handleTransactionReportCmdArguments(args []string, targetPath string) {
// check for "start" and "end" args.
if len(args) == 0 {
fmt.Println("Mandatory argument [start] is missing. See the usage guide.\n\n" +
utils.GetCmdUsageForArgsOnly(programName, transactionCmdLiteral, transactionReportCmdLiteral,
transactionReportCmdArgs))
} else if len(args) == 1 {
executeTransactionReportGenerationCmd(targetPath, args[0], "")
} else if len(args) == 2 {
start := args[0]
end := args[1]
executeTransactionReportGenerationCmd(targetPath, start, end)
} else {
fmt.Println("Invalid number of arguments. See the usage guide.\n\n" + utils.GetCmdUsageForArgsOnly(programName,
transactionCmdLiteral, transactionReportCmdLiteral, transactionReportCmdArgs))
}
}
// Invoke ../management/transactions/report?start=[start]&end=[end] URL.
// Generate the report from the response.
func executeTransactionReportGenerationCmd(targetDirectory string, start string, end string) {
finalUrl, params := utils.GetUrlAndParams(utils.PrefixTransactions + "/" + utils.TransactionReportCmd,
"start", start)
params = utils.PutQueryParamsToMap(params, "end", end)
resp, err := utils.UnmarshalData(finalUrl, nil, params, &artifactUtils.TransactionCountInfo{})
if err == nil {
transactionCount := resp.(*artifactUtils.TransactionCountInfo)
fileName := "transaction-count-summary-" + strconv.FormatInt(time.Now().UnixNano(), 10) + ".csv"
destinationFilePath := filepath.Join(targetDirectory, fileName)
transactionCountLines := transactionCount.TransactionCounts
utils.WriteLinesToCSVFile(transactionCountLines, destinationFilePath)
fmt.Println("Transaction Count Report created in " + destinationFilePath)
} else {
errBody := resp.(string)
if len(errBody) > 0 {
fmt.Println(utils.LogPrefixError+errBody, err)
} else {
fmt.Println(utils.LogPrefixError+"Getting Information of Transaction Counts.", err)
}
}
}
| 40.290909 | 117 | 0.761056 |
f04ab36ef3e94f8716214625f760733bb0b62c82 | 1,437 | py | Python | chapter-7/chassis/demo.py | wallacei/microservices-in-action-copy | f9840464a1f9ec40622989e9e5377742246244f3 | [
"MIT"
] | 115 | 2017-11-06T08:12:07.000Z | 2022-02-25T09:56:59.000Z | chapter-7/chassis/demo.py | wallacei/microservices-in-action-copy | f9840464a1f9ec40622989e9e5377742246244f3 | [
"MIT"
] | 12 | 2017-08-05T14:51:35.000Z | 2020-12-01T11:05:14.000Z | chapter-7/chassis/demo.py | wallacei/microservices-in-action-copy | f9840464a1f9ec40622989e9e5377742246244f3 | [
"MIT"
] | 82 | 2017-08-05T09:41:12.000Z | 2022-02-18T00:57:39.000Z | import json
import datetime
import requests
from nameko.web.handlers import http
from nameko.timer import timer
from statsd import StatsClient
from circuitbreaker import circuit
class DemoChassisService:
name = "demo_chassis_service"
statsd = StatsClient('localhost', 8125, prefix='simplebank-demo')
@http('GET', '/health')
@statsd.timer('health')
def health(self, _request):
return json.dumps({'ok': datetime.datetime.utcnow().__str__()})
@http('GET', '/external')
@circuit(failure_threshold=5, expected_exception=ConnectionError)
@statsd.timer('external')
def external_request(self, _request):
response = requests.get('https://jsonplaceholder.typicode.com/posts/1')
return json.dumps({'code': response.status_code, 'body': response.text})
@http('GET', '/error')
@circuit(failure_threshold=5, expected_exception=ZeroDivisionError)
@statsd.timer('http_error')
def error_http_request(self):
return json.dumps({1 / 0})
class HealthCheckService:
name = "health_check_service"
statsd = StatsClient('localhost', 8125, prefix='simplebank-demo')
@timer(interval=10)
@statsd.timer('check_demo_service')
def check_demo_service(self):
response = requests.get('http://0.0.0.0:8000/health')
print("DemoChassisService HEALTH CHECK: status_code {}, response: {}".format(
response.status_code, response.text))
| 31.933333 | 85 | 0.701461 |
517fbf315552f1bcf67511ede9551db7f9ef6032 | 10,402 | kt | Kotlin | utilcode-kotlin/src/main/java/com/blankj/utilcode/util/Utils.kt | Seselin/AndroidUtilCode | b1a06bb707f90056d899a5c5396390ec44e26dce | [
"Apache-2.0"
] | null | null | null | utilcode-kotlin/src/main/java/com/blankj/utilcode/util/Utils.kt | Seselin/AndroidUtilCode | b1a06bb707f90056d899a5c5396390ec44e26dce | [
"Apache-2.0"
] | null | null | null | utilcode-kotlin/src/main/java/com/blankj/utilcode/util/Utils.kt | Seselin/AndroidUtilCode | b1a06bb707f90056d899a5c5396390ec44e26dce | [
"Apache-2.0"
] | null | null | null | @file:JvmName("Utils")
package com.blankj.utilcode.util
import android.annotation.SuppressLint
import android.app.Activity
import android.app.ActivityManager
import android.app.Application
import android.app.Application.ActivityLifecycleCallbacks
import android.content.Context
import android.content.res.Resources
import android.os.Bundle
import android.support.v4.content.FileProvider
import java.lang.reflect.InvocationTargetException
import java.util.*
@SuppressLint("StaticFieldLeak")
private var sApplication: Application? = null
private val ACTIVITY_LIFECYCLE = ActivityLifecycleImpl()
private const val PERMISSION_ACTIVITY_CLASS_NAME =
"com.blankj.utilcode.util.PermissionUtils\$PermissionUtils.PermissionActivity"
/**
* Init utils.
*
* Init it in the class of Application.
*
* @param context context
*/
fun init(context: Context?) {
if (context == null) {
init(getApplicationByReflect())
return
}
init(context.applicationContext as Application)
}
/**
* Init utils.
*
* Init it in the class of Application.
*
* @param app application
*/
fun init(app: Application?) {
if (sApplication == null) {
sApplication = app ?: getApplicationByReflect()
sApplication!!.registerActivityLifecycleCallbacks(ACTIVITY_LIFECYCLE)
}
}
/**
* Return the context of Application object.
*
* @return the context of Application object
*/
fun getApp(): Application {
if (sApplication != null) return sApplication as Application
val app = getApplicationByReflect()
init(app)
return app
}
private fun getApplicationByReflect(): Application {
try {
@SuppressLint("PrivateApi")
val activityThread = Class.forName("android.app.ActivityThread")
val thread = activityThread.getMethod("currentActivityThread").invoke(null)
val app = activityThread.getMethod("getApplication").invoke(thread)
?: throw NullPointerException("u should init first")
return app as Application
} catch (e: NoSuchMethodException) {
e.printStackTrace()
} catch (e: IllegalAccessException) {
e.printStackTrace()
} catch (e: InvocationTargetException) {
e.printStackTrace()
} catch (e: ClassNotFoundException) {
e.printStackTrace()
}
throw NullPointerException("u should init first")
}
internal fun getActivityLifecycle(): ActivityLifecycleImpl {
return ACTIVITY_LIFECYCLE
}
internal fun getActivityList(): LinkedList<Activity> {
return ACTIVITY_LIFECYCLE.mActivityList
}
fun getTopActivityOrApp(): Context {
return if (isAppForeground()) {
val topActivity = ACTIVITY_LIFECYCLE.topActivity
topActivity ?: getApp()
} else {
getApp()
}
}
internal fun isAppForeground(): Boolean {
val am = getApp().getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
val info = am.runningAppProcesses
if (info == null || info.size == 0) return false
for (aInfo in info) {
if (aInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
return aInfo.processName == getApp().packageName
}
}
return false
}
internal val ADAPT_SCREEN_ARGS = AdaptScreenArgs()
internal fun restoreAdaptScreen() {
val systemDm = Resources.getSystem().displayMetrics
val appDm = getApp().resources.displayMetrics
val activity = ACTIVITY_LIFECYCLE.topActivity
if (activity != null) {
val activityDm = activity.resources.displayMetrics
if (ADAPT_SCREEN_ARGS.isVerticalSlide) {
activityDm.density = activityDm.widthPixels / ADAPT_SCREEN_ARGS.sizeInPx.toFloat()
} else {
activityDm.density = activityDm.heightPixels / ADAPT_SCREEN_ARGS.sizeInPx.toFloat()
}
activityDm.scaledDensity = activityDm.density * (systemDm.scaledDensity / systemDm.density)
activityDm.densityDpi = (160 * activityDm.density).toInt()
appDm.density = activityDm.density
appDm.scaledDensity = activityDm.scaledDensity
appDm.densityDpi = activityDm.densityDpi
} else {
if (ADAPT_SCREEN_ARGS.isVerticalSlide) {
appDm.density = appDm.widthPixels / ADAPT_SCREEN_ARGS.sizeInPx.toFloat()
} else {
appDm.density = appDm.heightPixels / ADAPT_SCREEN_ARGS.sizeInPx.toFloat()
}
appDm.scaledDensity = appDm.density * (systemDm.scaledDensity / systemDm.density)
appDm.densityDpi = (160 * appDm.density).toInt()
}
}
internal fun cancelAdaptScreen() {
val systemDm = Resources.getSystem().displayMetrics
val appDm = getApp().resources.displayMetrics
val activity = ACTIVITY_LIFECYCLE.topActivity
if (activity != null) {
val activityDm = activity.resources.displayMetrics
activityDm.density = systemDm.density
activityDm.scaledDensity = systemDm.scaledDensity
activityDm.densityDpi = systemDm.densityDpi
}
appDm.density = systemDm.density
appDm.scaledDensity = systemDm.scaledDensity
appDm.densityDpi = systemDm.densityDpi
}
internal fun isAdaptScreen(): Boolean {
val systemDm = Resources.getSystem().displayMetrics
val appDm = getApp().resources.displayMetrics
return systemDm.density != appDm.density
}
internal class AdaptScreenArgs {
var sizeInPx: Int = 0
var isVerticalSlide: Boolean = false
}
internal class ActivityLifecycleImpl : ActivityLifecycleCallbacks {
val mActivityList: LinkedList<Activity> = LinkedList()
private val mStatusListenerMap: HashMap<Any, OnAppStatusChangedListener> = HashMap()
private var mForegroundCount = 0
private var mConfigCount = 0
var topActivity: Activity?
get() {
if (!mActivityList.isEmpty()) {
val topActivity = mActivityList.last
if (topActivity != null) {
return topActivity
}
}
val topActivityByReflect = topActivityByReflect
if (topActivityByReflect != null) {
topActivity = topActivityByReflect
}
return topActivityByReflect
}
private set(activity) {
if (PERMISSION_ACTIVITY_CLASS_NAME == activity?.javaClass?.name) return;
if (activity?.javaClass == PermissionUtils.PermissionActivity::class.java) return
if (mActivityList.contains(activity)) {
if (!mActivityList.last.equals(activity)) {
mActivityList.remove(activity)
mActivityList.addLast(activity)
}
} else {
mActivityList.addLast(activity)
}
}
private val topActivityByReflect: Activity?
get() {
try {
@SuppressLint("PrivateApi")
val activityThreadClass = Class.forName("android.app.ActivityThread")
val activityThread = activityThreadClass.getMethod("currentActivityThread").invoke(null)
val activitiesField = activityThreadClass.getDeclaredField("mActivityList")
activitiesField.isAccessible = true
val activities = activitiesField.get(activityThread) as Map<*, *>
for (activityRecord in activities.values) {
if (activityRecord == null) continue
val activityRecordClass = activityRecord.javaClass
val pausedField = activityRecordClass.getDeclaredField("paused")
pausedField.isAccessible = true
if (!pausedField.getBoolean(activityRecord)) {
val activityField = activityRecordClass.getDeclaredField("activity")
activityField.isAccessible = true
return activityField.get(activityRecord) as Activity
}
}
} catch (e: ClassNotFoundException) {
e.printStackTrace()
} catch (e: IllegalAccessException) {
e.printStackTrace()
} catch (e: InvocationTargetException) {
e.printStackTrace()
} catch (e: NoSuchMethodException) {
e.printStackTrace()
} catch (e: NoSuchFieldException) {
e.printStackTrace()
}
return null
}
fun addListener(obj: Any, listener: OnAppStatusChangedListener) {
mStatusListenerMap[obj] = listener
}
fun removeListener(obj: Any) {
mStatusListenerMap.remove(obj)
}
override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle) {
topActivity = activity
}
override fun onActivityStarted(activity: Activity) {
topActivity = activity
if (mForegroundCount <= 0) {
postStatus(true)
}
if (mConfigCount < 0) {
++mConfigCount
} else {
++mForegroundCount
}
}
override fun onActivityResumed(activity: Activity) {
topActivity = activity
}
override fun onActivityPaused(activity: Activity) {/**/
}
override fun onActivityStopped(activity: Activity) {
if (activity.isChangingConfigurations) {
--mConfigCount
} else {
--mForegroundCount
if (mForegroundCount <= 0) {
postStatus(false)
}
}
}
override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {/**/
}
override fun onActivityDestroyed(activity: Activity) {
mActivityList.remove(activity)
}
private fun postStatus(isForeground: Boolean) {
if (mStatusListenerMap.isEmpty()) return
for (onAppStatusChangedListener in mStatusListenerMap.values) {
if (isForeground) {
onAppStatusChangedListener.onForeground()
} else {
onAppStatusChangedListener.onBackground()
}
}
}
}
class FileProvider4UtilCode : FileProvider() {
override fun onCreate(): Boolean {
init(context)
return true
}
}
///////////////////////////////////////////////////////////////////////////
// interface
///////////////////////////////////////////////////////////////////////////
interface OnAppStatusChangedListener {
fun onForeground()
fun onBackground()
} | 32.50625 | 104 | 0.639492 |
77aad5d2e846cce7ac2b1ebaa2ba2b0b30a54771 | 2,530 | ps1 | PowerShell | Examples/InteractWithOtherModules/ScriptAnalyzer/Analyze_this.ps1 | edwardmjackson/ImportExcel | 5629536f155806d1456e00f8165441542bfe164f | [
"Apache-2.0"
] | 1,858 | 2015-03-27T20:07:07.000Z | 2022-03-31T17:05:56.000Z | Examples/InteractWithOtherModules/ScriptAnalyzer/Analyze_this.ps1 | danubie/ImportExcel | 1840ffcb770227a9bfd8b6e4bff715b42bc39398 | [
"Apache-2.0"
] | 1,071 | 2015-04-01T01:48:57.000Z | 2022-03-31T19:45:08.000Z | Examples/InteractWithOtherModules/ScriptAnalyzer/Analyze_this.ps1 | danubie/ImportExcel | 1840ffcb770227a9bfd8b6e4bff715b42bc39398 | [
"Apache-2.0"
] | 392 | 2015-03-31T19:45:24.000Z | 2022-03-24T21:33:16.000Z | <#
.Synopsis
Runs PsScriptAnalyzer against one or more folders and pivots the results to form a report.
.Example
Analyze_this.ps1
Invokes script analyzer on the current directory; creates a file in $env:temp and opens it in Excel
.Example
Analyze_this.ps1 -xlfile ..\mymodule.xlsx -quiet
Invokes script analyzer on the current directory; creates a file in the parent directory but does not open it
.Example
"." , (dir 'C:\Program Files\WindowsPowerShell\Modules\ImportExcel\') | .\examples\ScriptAnalyzer\Analyze_this.ps1
run from a developemnt directory for importExcel it will produce a report for that directory compared against installed versions
this creates the file in the default location and opens it
#>
[CmdletBinding()]
param (
[parameter(ValueFromPipeline = $true)]
$Path = $PWD,
$xlfile = "$env:TEMP\ScriptAnalyzer.xlsx",
$ChartType = 'BarClustered' ,
$PivotColumns = 'Location',
[switch]$Quiet
)
begin {
Remove-Item -Path $xlfile -ErrorAction SilentlyContinue
$xlparams = @{
Path = $xlfile
WorksheetName = 'FullResults'
AutoSize = $true
AutoFilter = $true
Activate = $true
Show = (-not $Quiet)
}
$pivotParams = @{
PivotTableName = 'BreakDown'
PivotData = @{RuleName = 'Count' }
PivotRows = 'Severity', 'RuleName'
PivotColumns = 'Location'
PivotTotals = 'Rows'
}
$dirsToProcess = @()
}
process {
if ($path.fullName) {$dirsToProcess += $path.fullName}
elseif ($path.path) {$dirsToProcess += $path.Path}
else {$dirsToProcess += $path}
}
end {
$pivotParams['-PivotChartDefinition'] = New-ExcelChartDefinition -ChartType $chartType -Column (1 + $dirsToProcess.Count) -Title "Script analysis" -LegendBold
$xlparams['PivotTableDefinition'] = New-PivotTableDefinition @pivotParams
$dirsToProcess | ForEach-Object {
$dirName = (Resolve-Path -Path $_) -replace "^.*\\(.*?)\\(.*?)$", '$1-$2'
Write-Progress -Activity "Running Script Analyzer" -CurrentOperation $dirName
Invoke-ScriptAnalyzer -Path $_ -ErrorAction SilentlyContinue |
Add-Member -MemberType NoteProperty -Name Location -Value $dirName -PassThru
} | Export-Excel @xlparams
Write-Progress -Activity "Running Script Analyzer" -Completed
}
| 40.15873 | 163 | 0.626482 |
7f33e859430766ab2256ea0dce39e9900d00795e | 10,227 | rs | Rust | src/net/driver/mod.rs | GabrielMajeri/async-std | d502453057223ab8ebcdcf4d0c514fb70687c2f9 | [
"Apache-2.0",
"MIT"
] | 3 | 2020-09-30T04:13:39.000Z | 2021-11-12T06:15:36.000Z | src/net/driver/mod.rs | GabrielMajeri/async-std | d502453057223ab8ebcdcf4d0c514fb70687c2f9 | [
"Apache-2.0",
"MIT"
] | null | null | null | src/net/driver/mod.rs | GabrielMajeri/async-std | d502453057223ab8ebcdcf4d0c514fb70687c2f9 | [
"Apache-2.0",
"MIT"
] | 2 | 2020-09-30T04:12:20.000Z | 2021-11-12T06:15:25.000Z | use std::fmt;
use std::sync::{Arc, Mutex};
use mio::{self, Evented};
use once_cell::sync::Lazy;
use slab::Slab;
use crate::io;
use crate::task::{Context, Poll, Waker};
use crate::utils::abort_on_panic;
/// Data associated with a registered I/O handle.
#[derive(Debug)]
struct Entry {
/// A unique identifier.
token: mio::Token,
/// Tasks that are blocked on reading from this I/O handle.
readers: Mutex<Vec<Waker>>,
/// Thasks that are blocked on writing to this I/O handle.
writers: Mutex<Vec<Waker>>,
}
/// The state of a networking driver.
struct Reactor {
/// A mio instance that polls for new events.
poller: mio::Poll,
/// A collection of registered I/O handles.
entries: Mutex<Slab<Arc<Entry>>>,
/// Dummy I/O handle that is only used to wake up the polling thread.
notify_reg: (mio::Registration, mio::SetReadiness),
/// An identifier for the notification handle.
notify_token: mio::Token,
}
impl Reactor {
/// Creates a new reactor for polling I/O events.
fn new() -> io::Result<Reactor> {
let poller = mio::Poll::new()?;
let notify_reg = mio::Registration::new2();
let mut reactor = Reactor {
poller,
entries: Mutex::new(Slab::new()),
notify_reg,
notify_token: mio::Token(0),
};
// Register a dummy I/O handle for waking up the polling thread.
let entry = reactor.register(&reactor.notify_reg.0)?;
reactor.notify_token = entry.token;
Ok(reactor)
}
/// Registers an I/O event source and returns its associated entry.
fn register(&self, source: &dyn Evented) -> io::Result<Arc<Entry>> {
let mut entries = self.entries.lock().unwrap();
// Reserve a vacant spot in the slab and use its key as the token value.
let vacant = entries.vacant_entry();
let token = mio::Token(vacant.key());
// Allocate an entry and insert it into the slab.
let entry = Arc::new(Entry {
token,
readers: Mutex::new(Vec::new()),
writers: Mutex::new(Vec::new()),
});
vacant.insert(entry.clone());
// Register the I/O event source in the poller.
let interest = mio::Ready::all();
let opts = mio::PollOpt::edge();
self.poller.register(source, token, interest, opts)?;
Ok(entry)
}
/// Deregisters an I/O event source associated with an entry.
fn deregister(&self, source: &dyn Evented, entry: &Entry) -> io::Result<()> {
// Deregister the I/O object from the mio instance.
self.poller.deregister(source)?;
// Remove the entry associated with the I/O object.
self.entries.lock().unwrap().remove(entry.token.0);
Ok(())
}
// fn notify(&self) {
// self.notify_reg
// .1
// .set_readiness(mio::Ready::readable())
// .unwrap();
// }
}
/// The state of the global networking driver.
static REACTOR: Lazy<Reactor> = Lazy::new(|| {
// Spawn a thread that waits on the poller for new events and wakes up tasks blocked on I/O
// handles.
std::thread::Builder::new()
.name("async-std/net".to_string())
.spawn(move || {
// If the driver thread panics, there's not much we can do. It is not a
// recoverable error and there is no place to propagate it into so we just abort.
abort_on_panic(|| {
main_loop().expect("async networking thread has panicked");
})
})
.expect("cannot start a thread driving blocking tasks");
Reactor::new().expect("cannot initialize reactor")
});
/// Waits on the poller for new events and wakes up tasks blocked on I/O handles.
fn main_loop() -> io::Result<()> {
let reactor = &REACTOR;
let mut events = mio::Events::with_capacity(1000);
loop {
// Block on the poller until at least one new event comes in.
reactor.poller.poll(&mut events, None)?;
// Lock the entire entry table while we're processing new events.
let entries = reactor.entries.lock().unwrap();
for event in events.iter() {
let token = event.token();
if token == reactor.notify_token {
// If this is the notification token, we just need the notification state.
reactor.notify_reg.1.set_readiness(mio::Ready::empty())?;
} else {
// Otherwise, look for the entry associated with this token.
if let Some(entry) = entries.get(token.0) {
// Set the readiness flags from this I/O event.
let readiness = event.readiness();
// Wake up reader tasks blocked on this I/O handle.
if !(readiness & reader_interests()).is_empty() {
for w in entry.readers.lock().unwrap().drain(..) {
w.wake();
}
}
// Wake up writer tasks blocked on this I/O handle.
if !(readiness & writer_interests()).is_empty() {
for w in entry.writers.lock().unwrap().drain(..) {
w.wake();
}
}
}
}
}
}
}
/// An I/O handle powered by the networking driver.
///
/// This handle wraps an I/O event source and exposes a "futurized" interface on top of it,
/// implementing traits `AsyncRead` and `AsyncWrite`.
pub struct Watcher<T: Evented> {
/// Data associated with the I/O handle.
entry: Arc<Entry>,
/// The I/O event source.
source: Option<T>,
}
impl<T: Evented> Watcher<T> {
/// Creates a new I/O handle.
///
/// The provided I/O event source will be kept registered inside the reactor's poller for the
/// lifetime of the returned I/O handle.
pub fn new(source: T) -> Watcher<T> {
Watcher {
entry: REACTOR
.register(&source)
.expect("cannot register an I/O event source"),
source: Some(source),
}
}
/// Returns a reference to the inner I/O event source.
pub fn get_ref(&self) -> &T {
self.source.as_ref().unwrap()
}
/// Polls the inner I/O source for a non-blocking read operation.
///
/// If the operation returns an error of the `io::ErrorKind::WouldBlock` kind, the current task
/// will be registered for wakeup when the I/O source becomes readable.
pub fn poll_read_with<'a, F, R>(&'a self, cx: &mut Context<'_>, mut f: F) -> Poll<io::Result<R>>
where
F: FnMut(&'a T) -> io::Result<R>,
{
// If the operation isn't blocked, return its result.
match f(self.source.as_ref().unwrap()) {
Err(err) if err.kind() == io::ErrorKind::WouldBlock => {}
res => return Poll::Ready(res),
}
// Lock the waker list.
let mut list = self.entry.readers.lock().unwrap();
// Try running the operation again.
match f(self.source.as_ref().unwrap()) {
Err(err) if err.kind() == io::ErrorKind::WouldBlock => {}
res => return Poll::Ready(res),
}
// Register the task if it isn't registered already.
if list.iter().all(|w| !w.will_wake(cx.waker())) {
list.push(cx.waker().clone());
}
Poll::Pending
}
/// Polls the inner I/O source for a non-blocking write operation.
///
/// If the operation returns an error of the `io::ErrorKind::WouldBlock` kind, the current task
/// will be registered for wakeup when the I/O source becomes writable.
pub fn poll_write_with<'a, F, R>(
&'a self,
cx: &mut Context<'_>,
mut f: F,
) -> Poll<io::Result<R>>
where
F: FnMut(&'a T) -> io::Result<R>,
{
// If the operation isn't blocked, return its result.
match f(self.source.as_ref().unwrap()) {
Err(err) if err.kind() == io::ErrorKind::WouldBlock => {}
res => return Poll::Ready(res),
}
// Lock the waker list.
let mut list = self.entry.writers.lock().unwrap();
// Try running the operation again.
match f(self.source.as_ref().unwrap()) {
Err(err) if err.kind() == io::ErrorKind::WouldBlock => {}
res => return Poll::Ready(res),
}
// Register the task if it isn't registered already.
if list.iter().all(|w| !w.will_wake(cx.waker())) {
list.push(cx.waker().clone());
}
Poll::Pending
}
/// Deregisters and returns the inner I/O source.
///
/// This method is typically used to convert `Watcher`s to raw file descriptors/handles.
#[allow(dead_code)]
pub fn into_inner(mut self) -> T {
let source = self.source.take().unwrap();
REACTOR
.deregister(&source, &self.entry)
.expect("cannot deregister I/O event source");
source
}
}
impl<T: Evented> Drop for Watcher<T> {
fn drop(&mut self) {
if let Some(ref source) = self.source {
REACTOR
.deregister(source, &self.entry)
.expect("cannot deregister I/O event source");
}
}
}
impl<T: Evented + fmt::Debug> fmt::Debug for Watcher<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Watcher")
.field("entry", &self.entry)
.field("source", &self.source)
.finish()
}
}
/// Returns a mask containing flags that interest tasks reading from I/O handles.
#[inline]
fn reader_interests() -> mio::Ready {
mio::Ready::all() - mio::Ready::writable()
}
/// Returns a mask containing flags that interest tasks writing into I/O handles.
#[inline]
fn writer_interests() -> mio::Ready {
mio::Ready::writable() | hup()
}
/// Returns a flag containing the hangup status.
#[inline]
fn hup() -> mio::Ready {
#[cfg(unix)]
let ready = mio::unix::UnixReady::hup().into();
#[cfg(not(unix))]
let ready = mio::Ready::empty();
ready
}
| 32.363924 | 100 | 0.566931 |
35d6addcfdaa26ffd51b5388924f6c78c3a8f4c3 | 715 | swift | Swift | swap/Data/Remote/API/ApiClient.swift | MaxHvesser/clarence-ios | bb19b6716347b4f53e8608efe61262d557c1b66d | [
"Apache-2.0"
] | 5 | 2020-04-10T10:21:48.000Z | 2021-01-16T18:09:36.000Z | swap/Data/Remote/API/ApiClient.swift | MaxHvesser/swap-ios | bb19b6716347b4f53e8608efe61262d557c1b66d | [
"Apache-2.0"
] | null | null | null | swap/Data/Remote/API/ApiClient.swift | MaxHvesser/swap-ios | bb19b6716347b4f53e8608efe61262d557c1b66d | [
"Apache-2.0"
] | null | null | null | //
// Created by Maximilian Hvesser-Lewis on 23/05/2020.
// Copyright (c) 2020 Hvesser. All rights reserved.
//
import Foundation
import Combine
struct ApiClient {
struct Response<T> {
let value: T
let response: URLResponse
}
func run<T: Decodable>(_ request: URLRequest) -> AnyPublisher<Response<T>, Error> {
URLSession.shared
.dataTaskPublisher(for: request)
.tryMap { result -> Response<T> in
let value = try JSONDecoder().decode(T.self, from: result.data)
return Response(value: value, response: result.response)
}
.receive(on: DispatchQueue.main)
.eraseToAnyPublisher()
}
} | 26.481481 | 87 | 0.606993 |
fff096dae89c1c56786791454eaa7a7462763f0a | 2,938 | html | HTML | sobre.html | Thiago-we/covid | 5c4daf10b8509b8ac38cd94c77f3562d82f6478c | [
"MIT"
] | null | null | null | sobre.html | Thiago-we/covid | 5c4daf10b8509b8ac38cd94c77f3562d82f6478c | [
"MIT"
] | null | null | null | sobre.html | Thiago-we/covid | 5c4daf10b8509b8ac38cd94c77f3562d82f6478c | [
"MIT"
] | null | null | null | <!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>COVID-19</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</head>
<body>
<h1>Quem somos</h1>
<p>
Somos uma Organização não-governamental cuja missão é trazer informação de maneira simples, através de pesquisas independentes e de fontes confiáveis e assim colaborar com os fatos combatendo fakenews. Durante esse processo temos ajudado a sociedade de forma ampla sem fins lucrativos. Temos avançado também com pesquisas em metodos naturais que servem como coadjuvantes para o tratamento das doenças e que ajudarão como um todo para se obter um estilo de vida mais saudavel.
</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Obcaecati nisi omnis qui maxime repellat, animi quaerat cupiditate eveniet cum corrupti? Reiciendis inventore nam commodi, rerum voluptatibus numquam ducimus nisi aut?</p>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Rem mollitia aliquam, blanditiis velit officiis impedit a? Facere tenetur provident corporis, quod rerum, unde quo quasi asperiores consequatur, perspiciatis ratione dolores!</p>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Consectetur incidunt doloribus at reiciendis! Veniam excepturi ex, commodi aspernatur facere omnis modi voluptates dignissimos. Voluptatum quia dolores porro animi nihil ex!</p>
<p>Lorem ipsum dolor sit amet consectetur, adipisicing elit. Ducimus dicta tempora, porro nemo tenetur recusandae incidunt repellendus temporibus officiis magni, ab numquam accusamus? Ea ullam hic, aut dignissimos voluptas veritatis.</p>
<p>Lorem ipsum, dolor sit amet consectetur adipisicing elit. Deleniti aut asperiores porro? A, assumenda dolores, nostrum labore inventore eaque neque reiciendis tempora earum delectus veritatis hic dolorum commodi ea ad.</p>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Perferendis odit, maxime doloribus aliquid ratione ea totam neque dolores dolorum veritatis velit provident cum vero sequi nihil voluptatibus. Laborum, consectetur officia?</p>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Animi laboriosam unde quo ea commodi sapiente quia earum deleniti soluta quisquam maiores totam, blanditiis necessitatibus nesciunt, ipsam voluptatem assumenda vel. Saepe.</p>
<style>
body {
background-color: black;
}
p {
color: white;
}
h1 {
color: blue;
}
</style>
</body>
</html> | 61.208333 | 481 | 0.7597 |
ca770009b7a460117ed2f4dbab9c9a842607c609 | 6,735 | ps1 | PowerShell | scripts/Get-AdoDevelopersReportFromGit.ps1 | pedalingcircles/adoutils | 22d8f9427e204ed05214bf61e7c2bafff175cee6 | [
"MIT"
] | null | null | null | scripts/Get-AdoDevelopersReportFromGit.ps1 | pedalingcircles/adoutils | 22d8f9427e204ed05214bf61e7c2bafff175cee6 | [
"MIT"
] | null | null | null | scripts/Get-AdoDevelopersReportFromGit.ps1 | pedalingcircles/adoutils | 22d8f9427e204ed05214bf61e7c2bafff175cee6 | [
"MIT"
] | null | null | null | #Requires -Version 7.0
<#
.Synopsis
Generates a report to identify all "developers" in an ADO organization.
.DESCRIPTION
Generates a report in markdown that outputs all "developers" or
more specifically all individuals that have committed code in an
Azure Git repo.
It clones all repos in an organization and uses the git shortlog
command to get all the users that have committed code since 1-1-2021
.PARAMETER Pat
Personal access token as a secure string type.
.PARAMETER Organization
The Azure DevOps organization.
.PARAMETER Legacy
Switch to indicate using the legacy REST api
such as *.visualstudio.com (un-tested)
.NOTES
The following reference documentation was used:
REST API: https://docs.microsoft.com/en-us/rest/api/azure/devops/?view=azure-devops-rest-6.1&viewFallbackFrom=azure-devops
Work with URLs in extensions and integrations: https://docs.microsoft.com/en-us/azure/devops/extend/develop/work-with-urls?view=azure-devops&tabs=http
Azure DevOps CLI: https://docs.microsoft.com/en-us/cli/azure/ext/azure-devops/?view=azure-cli-latest
Git shortlog: https://git-scm.com/docs/git-shortlog
This script uses a personal access token (PAT) but the type used is a secure string.
In order to pass this type in you can to convert the PAT to a secure string. Use this snippet of script:
$patss = ConvertTo-SecureString -String "ExamplePAT" -AsPlainText -Force
A shallow clone was tried but that is not supported by ADO. This would have made cloning much faster
due to not pulling the whole history.
The users data is only as good as the develoeprs git config setting for name and email. Most seem
fine, but there are non org emails.
This is a very raw script. There is some hardcoding of dates so just use as a reference.
#>
[CmdletBinding()]
param (
[Security.SecureString][Parameter(Mandatory=$true)] $Pat,
[string][Parameter(Mandatory=$true)] $Organization,
[switch] $Legacy
)
Import-Module (Join-Path $PSScriptRoot "/markdownreport/Get-MarkdownReportHelpers.psm1") -DisableNameChecking
$sw = [Diagnostics.Stopwatch]::StartNew()
function Get-RestCallWithContinuationTokenResult
{
[CmdletBinding()]
param
(
[string][Parameter(Mandatory=$true)] $Uri,
[string] $Method = "Get",
[Parameter(Mandatory=$true)] $Header
)
$result = Invoke-RestMethod -Uri $Uri -Method $Method -ResponseHeadersVariable responseHeaders -ContentType "application/json" -Headers $Header
$continuationToken = $responseHeaders["X-MS-ContinuationToken"]
$iterationCount = 0
$iteationCountLimit = 10
while ($continuationToken -and $($iterationCount -lt $iteationCountLimit)) {
$uriWithContinuationToken = $Uri + "&ContinuationToken=$continuationToken"
$pagedResult = Invoke-RestMethod -Uri $uriWithContinuationToken -Method $Method -ResponseHeadersVariable responseHeaders -ContentType "application/json" -Headers $Header
if ($pagedResult) {
$result.value += $pagedResult.value
$result.count += $pagedResult.count
}
$continuationToken = $responseHeaders["X-MS-ContinuationToken"]
Write-Verbose "Response had $($pagedResult.count)"
$iterationCount++
}
if ($iterationCount -gt ($iteationCountLimit - 1)) {
Write-Warning "Ran out of retries on finding paged groups. Results may be inaccurate."
}
return $result
}
$coreServer = "dev.azure.com/{0}" -f $Organization
if ($Legacy) {
$coreServer = "{0}.visualstudio.com" -f $Organization
}
Write-Host "Generating PAT token"
$encodedPat = [System.Text.Encoding]::ASCII.GetBytes($("{0}:{1}" -f "", $(ConvertFrom-SecureString -SecureString $Pat -AsPlainText)))
$token = [System.Convert]::ToBase64String($encodedPat)
$header = @{authorization = "Basic $token"}
Write-Host "Retrieving all Projects in organization"
$projectsUri = "https://{0}/_apis/projects?api-version={1}" -f $coreServer, "6.0"
$projectsResult = Get-RestCallWithContinuationTokenResult -Uri $projectsUri -Header $header -ErrorAction Stop
# Iterate through all projects to get all repos
$reposHashTable = @{}
Write-Host "Retrieving all Azure Repos"
$projectsResult.value | ForEach-Object {
$projectId = $_.id
$listRepoUri = "https://{0}/{1}/_apis/git/repositories?api-version={2}" -f $coreServer, $projectId, "6.0"
$reposResult = Invoke-RestMethod -Uri $listRepoUri -Method Get -ContentType "application/json" -Headers $header
$reposResult.value | ForEach-Object {
$isEmpty = $_.size -eq 0
$isDisabled = $_.isDisabled
$pushUri = "https://{0}/_apis/git/repositories/{1}/pushes?api-version={2}" -f $coreServer, $_.id, "6.1-preview.2"
$pushesError = $null
try {
$pushesResult = Invoke-RestMethod -Uri $pushUri -Method Get -ContentType "application/json" -Headers $header
} catch {
$pushesError = $_.Exception
}
$pushCount = $pushesResult.count
$isValid = (!$isEmpty -and !$isDisabled -and ($pushCount -gt 0))
$reposHashTable[$_.id] = @{
value=$_;
isValid=$isValid;
error=$pushesError
}
}
}
# Log repos to file
$reposFileContents = $reposHashTable | ConvertTo-Json
New-Item -Path . -Name "repos-$((New-Guid).Guid).json" -ItemType "file" -Value $reposFileContents
$developersArray = @()
$repoCount = $reposHashTable.Count
$currentRepoIteration = 1
$currentPath = (Get-Location).Path
$reposHashTable.keys | ForEach-Object {
Write-Host "Cloning $currentRepoIteration of $repoCount"
$currentRepoIteration++
if (($reposHashTable.Item($_).isValid -eq $false) -or ($reposHashTable.Item($_).error -ne $null)) {
return
}
New-Item -Path 'c:\' -Name "s" -ItemType "directory"
Set-Location -Path "C:\s"
$remoteUrl = $reposHashTable.Item($_).value.remoteUrl
git clone $remoteUrl
Set-Location -Path (Get-ChildItem).Name
$logResult = (git shortlog --summary --email --all --since="2021-01-01" --format="%aN`t%aE") | ConvertFrom-Csv -Delimiter "`t" -Header ("Number", "Email")
$emailArray = $logResult | ForEach-Object { $_.Email }
$developersArray += $emailArray
Set-Location -Path $currentPath
# hardcoded path and close to the root since some repos have very deep directories which fails on windows
Remove-Item -Path "c:\s" -Force -Recurse
}
[array]$uniqueDevelopers = $developersArray | Sort-Object | Get-Unique
$CsvArray = $uniqueDevelopers | Select-Object @{Name='Name';Expression={$_}}
$CsvArray | Export-Csv -Path "outfile.csv" -NoTypeInformation
Write-Output "Completed."
$sw.Stop()
$sw.Elapsed
| 39.617647 | 177 | 0.694284 |
e73d3a81dff244724778737035fa96b17e0f3aab | 346 | js | JavaScript | Web Mapping Application/widgets/Print/setting/nls/Setting_fr.js | SARscene/MapSAROnlinev4 | dc2d991bca4c3587a4119276da61747c0224307c | [
"CC0-1.0"
] | 6 | 2016-08-11T21:11:43.000Z | 2021-12-08T17:55:25.000Z | Web Mapping Application/widgets/Print/setting/nls/Setting_fr.js | SARscene/MapSAROnlinev4 | dc2d991bca4c3587a4119276da61747c0224307c | [
"CC0-1.0"
] | 7 | 2015-07-31T14:43:32.000Z | 2019-03-13T02:39:45.000Z | Web Mapping Application/widgets/Print/setting/nls/Setting_fr.js | SARscene/MapSAROnlinev4 | dc2d991bca4c3587a4119276da61747c0224307c | [
"CC0-1.0"
] | 2 | 2018-04-13T17:58:04.000Z | 2020-10-15T16:32:18.000Z | //>>built
define({"widgets/Print/setting/nls/strings":{serviceURL:"URL du service",defaultTitle:"Titre par d\u00e9faut",defaultAuthor:"Auteur par d\u00e9faut",defaultCopyright:"Copyright par d\u00e9faut",defaultFormat:"Format par d\u00e9faut",defaultLayout:"Mise en page par d\u00e9faut",warning:"Entr\u00e9e incorrecte",ok:"OK",_localized:{}}}); | 173 | 336 | 0.783237 |
afed5cecace055912cab14468a660cee6bd27eaf | 997 | html | HTML | manuscript/page-213/body.html | marvindanig/tales-of-the-jazz-age | 5c09053704c5597441b254cf53610818f5d9ad4a | [
"CECILL-B"
] | null | null | null | manuscript/page-213/body.html | marvindanig/tales-of-the-jazz-age | 5c09053704c5597441b254cf53610818f5d9ad4a | [
"CECILL-B"
] | null | null | null | manuscript/page-213/body.html | marvindanig/tales-of-the-jazz-age | 5c09053704c5597441b254cf53610818f5d9ad4a | [
"CECILL-B"
] | null | null | null | <div class="leaf flex"><div class="inner justify"><p>Fifth Avenue and Forty-fourth Street swarmed with the noon crowd. The wealthy, happy sun glittered in transient gold through the thick windows of the smart shops, lighting upon mesh bags and purses and strings of pearls in gray velvet cases; upon gaudy feather fans of many colors; upon the laces and silks of expensive dresses; upon the bad paintings and the fine period furniture in the elaborate show rooms of interior decorators.</p><p>Working-girls, in pairs and groups and swarms, loitered by these windows, choosing their future boudoirs from some resplendent display which included even a man's silk pajamas laid domestically across the bed. They stood in front of the jewelry stores and picked out their engagement rings, and their wedding rings and their platinum wrist watches, and then drifted on to inspect the feather fans and opera cloaks; meanwhile digesting the sandwiches and sundaes they had eaten for lunch.</p></div> </div> | 997 | 997 | 0.80341 |
3b869463800e2ea3ad3eb49f90482fc98d8c9907 | 1,277 | h | C | lib/cnet/drv/cnet_drv.h | CloudNativeDataPlane/cndp | cc83410b525bd3aacaf72ad12f8d4f4af5b28727 | [
"BSD-3-Clause"
] | null | null | null | lib/cnet/drv/cnet_drv.h | CloudNativeDataPlane/cndp | cc83410b525bd3aacaf72ad12f8d4f4af5b28727 | [
"BSD-3-Clause"
] | null | null | null | lib/cnet/drv/cnet_drv.h | CloudNativeDataPlane/cndp | cc83410b525bd3aacaf72ad12f8d4f4af5b28727 | [
"BSD-3-Clause"
] | null | null | null | /* SPDX-License-Identifier: BSD-3-Clause
* Copyright (c) 2016-2022 Intel Corporation
*/
#ifndef __CNET_DRV_H
#define __CNET_DRV_H
/**
* @file
* CNET Driver routines.
*/
#include <pktdev.h> // for pktdev_info
#include <net/ethernet.h> // for ether_addr
#include <cne_atomic.h> // for atomic_uint_least16_t
#include <stdint.h> // for uint16_t, uint32_t
#include <net/if.h>
#include "cne_common.h" // for __cne_cache_aligned
#include "cnet_const.h" // for iofunc_t
struct cnet;
#ifdef __cplusplus
extern "C" {
#endif
struct netif;
struct drv_entry {
struct netif *netif; /**< Pointer to netif structure */
struct pktdev_info info; /**< pktdev information */
} __cne_cache_aligned;
/**
* @brief Create the driver structure and initialize it
*
* @param cnet
* The cnet structure pointer to attach the driver structure
* @return
* -1 on error or 0 on success
*/
int cnet_drv_create(struct cnet *cnet);
/**
* @brief Destroy the driver structure and initialize it
*
* @param cnet
* The cnet structure pointer to detach the driver structure
* @return
* -1 on error or 0 on success
*/
int cnet_drv_destroy(struct cnet *cnet);
#ifdef __cplusplus
}
#endif
#endif /* __CNET_DRV_H */
| 21.283333 | 63 | 0.673453 |
280d0781158ebfc3236950c0ea94c0d726c7e1c6 | 25 | rb | Ruby | udemy/block_one.rb | esmaeilmirzaee/rubycode | 7ce8e58c4204a6e66f1e81ae28aacd409f4e73b9 | [
"Ruby"
] | null | null | null | udemy/block_one.rb | esmaeilmirzaee/rubycode | 7ce8e58c4204a6e66f1e81ae28aacd409f4e73b9 | [
"Ruby"
] | null | null | null | udemy/block_one.rb | esmaeilmirzaee/rubycode | 7ce8e58c4204a6e66f1e81ae28aacd409f4e73b9 | [
"Ruby"
] | null | null | null | 3.times { |i|
puts i
}
| 6.25 | 13 | 0.48 |
683d69ac383d172cccdb5fcfe6615f5b63914efa | 836 | lua | Lua | lua/hl_themes/one-light.lua | max397574/nvim-base16.lua | 525e4deb75a314c550ed1f644341afd49e64aebd | [
"MIT"
] | 24 | 2021-08-17T21:47:16.000Z | 2022-03-22T06:00:39.000Z | lua/hl_themes/one-light.lua | max397574/nvim-base16.lua | 525e4deb75a314c550ed1f644341afd49e64aebd | [
"MIT"
] | 28 | 2021-08-17T15:10:38.000Z | 2022-03-30T06:49:30.000Z | lua/hl_themes/one-light.lua | max397574/nvim-base16.lua | 525e4deb75a314c550ed1f644341afd49e64aebd | [
"MIT"
] | 72 | 2021-08-16T22:33:03.000Z | 2022-03-27T17:16:41.000Z | local colors = {
white = "#54555b",
darker_black = "#f5f5f5",
black = "#fafafa", -- nvim bg
black2 = "#f1f1f1",
one_bg = "#f0f0f0", -- real bg of onedark
one_bg2 = "#ececec",
one_bg3 = "#e7e7e7",
grey = "#cbcbcb",
grey_fg = "#c6c6c6",
grey_fg2 = "#b7b7b7",
light_grey = "#b7b7b7",
red = "#e6676e",
baby_pink = "#F07178",
pink = "#ff75a0",
line = "#e9e9e9", -- for lines like vertsplit
green = "#7b90c7",
vibrant_green = "#7eca9c",
nord_blue = "#5e5f65",
blue = "#28a2f4",
yellow = "#7e7e7e",
sun = "#dea95f",
purple = "#a28dcd",
dark_purple = "#8e79b9",
teal = "#519ABA",
orange = "#FF6A00",
cyan = "#a3b8ef",
statusline_bg = "#f0f0f0",
lightbg = "#d6d6d6",
lightbg2 = "#5e5f65",
pmenu_bg = "#5e5f65",
folder_bg = "#6C6C6C",
}
return colors
| 23.222222 | 48 | 0.555024 |
f478412ba1ba2c99272023a176f84187983170f5 | 882 | go | Go | pilotctl/types/jobbatch.go | Gennavar/onix | e67266e6a575922ad2d21e98ebe7358697ad2ad5 | [
"Apache-2.0"
] | 91 | 2018-04-26T19:12:39.000Z | 2022-03-26T08:53:39.000Z | pilotctl/types/jobbatch.go | Gennavar/onix | e67266e6a575922ad2d21e98ebe7358697ad2ad5 | [
"Apache-2.0"
] | 12 | 2019-08-23T00:57:13.000Z | 2022-03-04T06:42:54.000Z | pilotctl/types/jobbatch.go | Gennavar/onix | e67266e6a575922ad2d21e98ebe7358697ad2ad5 | [
"Apache-2.0"
] | 59 | 2018-07-01T20:15:47.000Z | 2022-03-10T14:34:56.000Z | package types
/*
Onix Config Manager - Pilot Control
Copyright (c) 2018-2021 by www.gatblau.org
Licensed under the Apache License, Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0
Contributors to this project, hereby assign copyright in this code to the project,
to be licensed under the same terms as the rest of the code.
*/
import "time"
// JobBatch a representation of a batch in the database
type JobBatch struct {
// the id of the job batch
BatchId int64 `json:"batch_id"`
// the name of the batch (not unique, a user-friendly name)
Name string `json:"name"`
// any relevant notes for the batch (not mandatory)
Notes string `json:"notes,omitempty"`
// creation time
Created time.Time `json:"created"`
// one or more search labels
Label []string `json:"label,omitempty"`
// owner
Owner string `json:"owner"`
// jobs
Jobs int `json:"jobs"`
}
| 29.4 | 94 | 0.722222 |
d9a0d901daf92964e92725756d1940e446b0511a | 643 | asm | Assembly | programs/oeis/026/A026644.asm | karttu/loda | 9c3b0fc57b810302220c044a9d17db733c76a598 | [
"Apache-2.0"
] | 1 | 2021-03-15T11:38:20.000Z | 2021-03-15T11:38:20.000Z | programs/oeis/026/A026644.asm | karttu/loda | 9c3b0fc57b810302220c044a9d17db733c76a598 | [
"Apache-2.0"
] | null | null | null | programs/oeis/026/A026644.asm | karttu/loda | 9c3b0fc57b810302220c044a9d17db733c76a598 | [
"Apache-2.0"
] | null | null | null | ; A026644: a(n) = a(n-1) + 2*a(n-2) + 2, for n>=3, where a(0)= 1, a(1)= 2, a(2)= 4.
; 1,2,4,10,20,42,84,170,340,682,1364,2730,5460,10922,21844,43690,87380,174762,349524,699050,1398100,2796202,5592404,11184810,22369620,44739242,89478484,178956970,357913940,715827882,1431655764,2863311530,5726623060,11453246122,22906492244,45812984490,91625968980,183251937962,366503875924,733007751850,1466015503700,2932031007402,5864062014804,11728124029610,23456248059220,46912496118442,93824992236884,187649984473770,375299968947540,750599937895082,1501199875790164,3002399751580330,6004799503160660
mov $1,2
pow $1,$0
mul $1,4
sub $1,5
div $1,3
add $1,1
| 64.3 | 502 | 0.799378 |
f26b0f0838f5fa8fb0072c60cb001a6f12c94699 | 2,451 | swift | Swift | Calculator/Model/CalculatorButtonItem.swift | hasancaslan/Calculator-SwiftUI | 0c6e8b023097a27c4aa52f4156282bb79400084c | [
"MIT"
] | 1 | 2021-02-25T15:55:50.000Z | 2021-02-25T15:55:50.000Z | Calculator/Model/CalculatorButtonItem.swift | hasancaslan/Calculator-SwiftUI | 0c6e8b023097a27c4aa52f4156282bb79400084c | [
"MIT"
] | null | null | null | Calculator/Model/CalculatorButtonItem.swift | hasancaslan/Calculator-SwiftUI | 0c6e8b023097a27c4aa52f4156282bb79400084c | [
"MIT"
] | null | null | null | //
// CalculatorButtonItem.swift
// Calculator
//
// Created by HASAN CAN on 2/16/21.
//
import Foundation
import SwiftUI
enum CalculatorButtonItem {
case digit(Int)
case dot
case operand(Operand)
case command(Command)
enum Operand: String {
case plus = "+"
case minus = "-"
case multiply = "×"
case divide = "÷"
case equal = "="
}
enum Command: String {
case clear = "AC"
case flip = "±"
case percent = "%"
}
}
extension CalculatorButtonItem {
var title: String {
switch self {
case let .digit(value):
return String(value)
case .dot:
return "."
case let .operand(operand):
return operand.rawValue
case let .command(command):
return command.rawValue
}
}
var spacing: CGFloat {
return 16
}
var size: CGSize {
let width = (UIScreen.main.bounds.width - 5 * spacing) / 4
switch self {
case let .digit(value):
if value == 0 {
return CGSize(width: width * 2 + spacing, height: width)
}
default:
break
}
return CGSize(width: width, height: width)
}
var background: Color {
switch self {
case .command:
return Color(red: 0.647, green: 0.647, blue: 0.647)
case .operand:
return Color(red: 0.941, green: 0.600, blue: 0.216)
case .digit, .dot:
return Color(red: 0.200, green: 0.200, blue: 0.200)
}
}
var foreground: Color {
switch self {
case .command:
return Color(.black)
default:
return Color(.white)
}
}
var font: Font {
switch self {
case .command:
return .system(size: 32)
case .operand:
return .system(size: 42)
default:
return .system(size: 36)
}
}
}
extension CalculatorButtonItem: Hashable {}
extension CalculatorButtonItem: CustomStringConvertible {
var description: String {
switch self {
case let .digit(num):
return String(num)
case .dot:
return "."
case let .operand(operand):
return operand.rawValue
case let .command(command):
return command.rawValue
}
}
}
| 19.766129 | 72 | 0.512852 |
7a42048aa4e99198b41b0851d846acc3d174af41 | 229 | kt | Kotlin | test/i_introduction/_11_SAM_Conversions/N11SAMConversionsKtTest.kt | dragneelfps/kotlin-koans | 3460b3d8456e43d18d101e5b93c9d762f59141c3 | [
"MIT"
] | null | null | null | test/i_introduction/_11_SAM_Conversions/N11SAMConversionsKtTest.kt | dragneelfps/kotlin-koans | 3460b3d8456e43d18d101e5b93c9d762f59141c3 | [
"MIT"
] | null | null | null | test/i_introduction/_11_SAM_Conversions/N11SAMConversionsKtTest.kt | dragneelfps/kotlin-koans | 3460b3d8456e43d18d101e5b93c9d762f59141c3 | [
"MIT"
] | null | null | null | package i_introduction._11_SAM_Conversions
import org.junit.Assert.assertEquals
import org.junit.Test
class N11SAMConversionsKtTest {
@Test fun testSort() {
assertEquals(listOf(5, 2, 1), task11())
}
}
| 20.818182 | 48 | 0.69869 |
d93765078f4a617f6bb3c1904874165672f5f5e6 | 3,831 | rs | Rust | src/dictionary.rs | Fifthrow/rust-kdb | 06ac2418a98fa1ad157156fef81c7e124d049d2d | [
"MIT"
] | 1 | 2020-11-19T11:24:17.000Z | 2020-11-19T11:24:17.000Z | src/dictionary.rs | Fifthrow/rust-kdb | 06ac2418a98fa1ad157156fef81c7e124d049d2d | [
"MIT"
] | null | null | null | src/dictionary.rs | Fifthrow/rust-kdb | 06ac2418a98fa1ad157156fef81c7e124d049d2d | [
"MIT"
] | 1 | 2020-11-19T11:24:22.000Z | 2020-11-19T11:24:22.000Z | use crate::list::List;
use crate::{any::Any, k::K};
use crate::{k_type::MIXED_LIST, kapi, type_traits::KObject};
use crate::{
k_type::{KTypeCode, DICT},
kbox::KBox,
type_traits::KTyped,
};
use std::{mem, ops::Index};
/// A key value based dictionary.
#[repr(transparent)]
pub struct Dictionary {
k: K,
}
impl Dictionary {
fn key_list_mut(&mut self) -> &mut KBox<List<Any>> {
unsafe { &mut *(&mut self.k.union.dict.k as *mut _ as *mut KBox<List<Any>>) }
}
fn value_list_mut(&mut self) -> &mut KBox<List<Any>> {
unsafe { &mut *(&mut self.k.union.dict.v as *mut _ as *mut KBox<List<Any>>) }
}
fn key_list(&self) -> &KBox<List<Any>> {
unsafe { &*(&self.k.union.dict.k as *const _ as *const KBox<List<Any>>) }
}
fn value_list(&self) -> &KBox<List<Any>> {
unsafe { &*(&self.k.union.dict.v as *const _ as *const KBox<List<Any>>) }
}
/// The number of items in the dictionary.
#[inline]
pub fn len(&self) -> usize {
self.key_list().len()
}
/// Returns true if the dictionary has no items.
#[inline]
pub fn is_empty(&self) -> bool {
self.len() == 0
}
/// Gets a slice containing all the keys in this dictionary.
#[inline]
pub fn keys(&self) -> &[KBox<Any>] {
&self.key_list()[..]
}
/// Gets a slice containing all the values in this dictionary.
#[inline]
pub fn values(&self) -> &[KBox<Any>] {
&self.value_list()[..]
}
/// Insert a specified key and value at the end of the dictionary.
/// No checks are done on uniqueness so duplicates are possible.
#[inline]
pub fn insert(&mut self, key: impl Into<KBox<Any>>, value: impl Into<KBox<Any>>) {
self.key_list_mut().push(key.into());
self.value_list_mut().push(value.into());
}
/// Gets a value by key. Note that KDB dictionaries are treated as unordered and hence this is an O(n) operation.
#[inline]
pub fn get<T: Into<KBox<Any>>>(&self, key: T) -> Option<&KBox<Any>> {
let key = key.into();
let index = self
.keys()
.iter()
.enumerate()
.find(|(_, k2)| unsafe { *k2.k.as_ptr() == *key.k.as_ptr() })
.map(|(i, _)| i)?;
self.values().get(index)
}
/// An iterator through every value in the KDB object
#[inline]
pub fn iter(&self) -> impl Iterator<Item = (&KBox<Any>, &KBox<Any>)> {
self.keys().iter().zip(self.values().iter())
}
}
impl<T> Index<T> for Dictionary
where
for<'a> T: Into<KBox<Any>>,
{
type Output = Any;
fn index(&self, index: T) -> &Self::Output {
self.get(index).unwrap()
}
}
impl KObject for Dictionary {
#[inline]
fn k_ptr(&self) -> *const K {
&self.k
}
#[inline]
fn k_ptr_mut(&mut self) -> *mut K {
&mut self.k
}
}
impl KTyped for Dictionary {
const K_TYPE: KTypeCode = DICT;
}
impl KBox<Dictionary> {
/// Create a new empty dictionary.
pub fn new_dict() -> Self {
unsafe {
let keys = kapi::ktn(MIXED_LIST.into(), 0) as *mut K;
let values = kapi::ktn(MIXED_LIST.into(), 0) as *mut K;
mem::transmute(kapi::xD(keys, values))
}
}
}
#[cfg(test)]
mod tests {
use crate::symbol;
use super::*;
#[test]
fn insert_appends_items_to_dictionary() {
let mut dict = KBox::new_dict();
dict.insert(symbol("Hello"), symbol("World"));
assert_eq!(dict.len(), 1);
}
#[test]
fn get_retrieves_items_by_key() {
let mut dict = KBox::new_dict();
dict.insert(symbol("Hello"), symbol("World"));
let val = dict.get(symbol("Hello")).unwrap();
assert_eq!(*val.as_ref(), *KBox::<Any>::from(symbol("World")).as_ref());
}
}
| 25.885135 | 117 | 0.557296 |
ec7318b8abea25761ca62a033d927ffe464324ba | 1,105 | lua | Lua | Class Examples/2017-05-11/Read/main.lua | lminsky/Programming-Mobile-Apps | 612d038c426817b3cdfc60cadebc2b4ed1d4dcc7 | [
"MIT"
] | null | null | null | Class Examples/2017-05-11/Read/main.lua | lminsky/Programming-Mobile-Apps | 612d038c426817b3cdfc60cadebc2b4ed1d4dcc7 | [
"MIT"
] | null | null | null | Class Examples/2017-05-11/Read/main.lua | lminsky/Programming-Mobile-Apps | 612d038c426817b3cdfc60cadebc2b4ed1d4dcc7 | [
"MIT"
] | null | null | null | -- Path for the file to read
local path = system.pathForFile( "in.txt")
-- Open the file handle
local file, errorString = io.open( path, "r" )
if not file then
-- Error occurred; output the cause
print( "File error: " .. errorString )
else
-- Read data from file
local contents = file:read( "*a" )
-- Output the file contents
-- print( "Contents of " .. path .. "\n" .. contents )
-- Close the file handle
io.close( file )
local lines = {}
local count = 1
local lineEnding = string.find(contents, "\n")
while lineEnding ~= nil do
local line = string.sub(contents, 1, lineEnding)
lines[count] = line
count = count + 1
contents = string.sub(contents, lineEnding + 1)
lineEnding = string.find(contents, "\n")
end
local prices = {}
for k,v in pairs(lines) do
local item = string.sub(v, 1, string.find(v, ",")-1)
local price = string.sub(v, string.find(v, ",")+1)
prices[item] = price
end
-- for k,v in pairs(prices) do
-- print(k,v)
-- end
print(prices["coffee"])
end
file = nil | 25.697674 | 58 | 0.595475 |
04d09dab4567eaa927b4bd3126bee64b34956449 | 1,357 | java | Java | app/src/main/java/com/zwy/neihan/mvp/model/MainTab2Model.java | blgktlp/NeiHanDuanZiTV-master | 1b137058f0bcda0b57d90f4ff7250fe5ad2ea08e | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/zwy/neihan/mvp/model/MainTab2Model.java | blgktlp/NeiHanDuanZiTV-master | 1b137058f0bcda0b57d90f4ff7250fe5ad2ea08e | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/zwy/neihan/mvp/model/MainTab2Model.java | blgktlp/NeiHanDuanZiTV-master | 1b137058f0bcda0b57d90f4ff7250fe5ad2ea08e | [
"Apache-2.0"
] | null | null | null | package com.zwy.neihan.mvp.model;
import android.app.Application;
import com.google.gson.Gson;
import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.integration.IRepositoryManager;
import com.jess.arms.mvp.BaseModel;
import com.zwy.neihan.mvp.contract.MainTab2Contract;
import com.zwy.neihan.mvp.model.api.service.CommonService;
import com.zwy.neihan.mvp.model.entity.HomeTabBean;
import java.util.ArrayList;
import javax.inject.Inject;
import io.reactivex.Observable;
@ActivityScope
public class MainTab2Model extends BaseModel implements MainTab2Contract.Model {
private Gson mGson;
private Application mApplication;
@Inject
public MainTab2Model(IRepositoryManager repositoryManager, Gson gson, Application application) {
super(repositoryManager);
this.mGson = gson;
this.mApplication = application;
}
@Override
public void onDestroy() {
super.onDestroy();
this.mGson = null;
this.mApplication = null;
}
/**
* 获取段友秀tabs
*
* @return
*/
@Override
public Observable<ArrayList<HomeTabBean>> getTab2Tabs() {
return mRepositoryManager.obtainRetrofitService(CommonService.class)
.getTab2Tabs().map(arrayListBaseJson -> {
return arrayListBaseJson.getData();
});
}
} | 26.607843 | 100 | 0.699337 |
de5f81ab9c8eae967c98337fc2771331731c9d26 | 1,024 | swift | Swift | HTWDD/Components/Canteen/Models/Meal.swift | Native1224/Htcampus | 5d40d6411f5dd3394fb7ce9886e59d053a7d411c | [
"MIT"
] | 19 | 2016-04-22T09:53:56.000Z | 2020-01-19T11:59:44.000Z | HTWDD/Components/Canteen/Models/Meal.swift | Native1224/Htcampus | 5d40d6411f5dd3394fb7ce9886e59d053a7d411c | [
"MIT"
] | 63 | 2016-11-16T14:54:46.000Z | 2019-10-21T15:49:41.000Z | HTWDD/Components/Canteen/Models/Meal.swift | Native1224/Htcampus | 5d40d6411f5dd3394fb7ce9886e59d053a7d411c | [
"MIT"
] | 4 | 2017-09-06T20:12:36.000Z | 2019-10-16T22:11:31.000Z | //
// Meal.swift
// HTWDD
//
// Created by Benjamin Herzog on 29.10.17.
// Copyright © 2017 HTW Dresden. All rights reserved.
//
import Foundation
struct Meal: Identifiable, Decodable {
let title: String
let canteen: String
let url: URL
let imageURL: URL?
let studentPrice: Double?
let employeePrice: Double?
let type: String
let counter: String
let information: [String]
// let additives: [String: String] // These two are supported, but cannot currently be decoded due to a bug. Will be fixed soon^^
// let allergens: [String: String]
let furtherNotes: [String]
private enum CodingKeys: String, CodingKey {
case title
case canteen = "mensa"
case url = "link"
case imageURL = "image"
case studentPrice
case employeePrice
case type = "mealType"
case counter = "mealCounter"
case information = "informations"
// case additives
// case allergens
case furtherNotes
}
}
| 23.813953 | 132 | 0.630859 |
66e129b4d0d828af047e1d943174b9b12b085811 | 1,098 | sql | SQL | src/test/tinc/tincrepo/mpp/gpdb/tests/storage/aoco_alter/aoco_alter_scenario_test/sql/create_multivarblock_table.sql | rodel-talampas/gpdb | 9c955e350334abbd922102f289f782697eb52069 | [
"PostgreSQL",
"Apache-2.0"
] | 1 | 2017-09-15T06:09:56.000Z | 2017-09-15T06:09:56.000Z | src/test/tinc/tincrepo/mpp/gpdb/tests/storage/aoco_alter/aoco_alter_scenario_test/sql/create_multivarblock_table.sql | rodel-talampas/gpdb | 9c955e350334abbd922102f289f782697eb52069 | [
"PostgreSQL",
"Apache-2.0"
] | 6 | 2018-08-04T07:51:37.000Z | 2018-11-26T07:09:44.000Z | src/test/tinc/tincrepo/mpp/gpdb/tests/storage/aoco_alter/aoco_alter_scenario_test/sql/create_multivarblock_table.sql | rodel-talampas/gpdb | 9c955e350334abbd922102f289f782697eb52069 | [
"PostgreSQL",
"Apache-2.0"
] | 1 | 2018-12-04T09:13:57.000Z | 2018-12-04T09:13:57.000Z | --
-- @created 2014-06-06 12:00:00
-- @modified 2014-06-06 12:00:00
-- @tags storage
-- @description AOCO multiple insert to create multiple var-block
DROP TABLE IF EXISTS multivarblock_tab;
CREATE TABLE multivarblock_tab (
c_custkey integer,
c_name character varying(25),
c_comment text,
c_rating float,
c_phone character(15),
c_acctbal numeric(15,2),
c_date date,
c_timestamp timestamp
)
WITH (checksum=true, appendonly=true, orientation=column, compresstype=quicklz, compresslevel=1) DISTRIBUTED BY (c_custkey);
insert into multivarblock_tab values( 1, 'aa','this is a looong text' , 3.5, '12121212',1000.34,'2015/10/10',now());
insert into multivarblock_tab values( 2, 'ab','this is also a looong text' , 4.5, '3456789',3000.45,'2014/08/10',now());
insert into multivarblock_tab values( 3, 'ac','this too is a looong text' , 1.5, '878787',500.54,'2014/04/04',now());
insert into multivarblock_tab (select i,'xx'||i, 'Can this be a long text please?',i+.5,'10'||i,100.23+i,cast(now() as date),cast(now() as timestamp) from generate_series(100,66900) i);
| 45.75 | 185 | 0.708561 |
1e4c50c7485f882c2a64a6e00d9f012762edf1b7 | 5,451 | swift | Swift | TripKit/VvoProvider.swift | kiliankoe/tripkit | 3ac306c170acd332322d2c50ef89d994aa03cbcf | [
"MIT"
] | null | null | null | TripKit/VvoProvider.swift | kiliankoe/tripkit | 3ac306c170acd332322d2c50ef89d994aa03cbcf | [
"MIT"
] | null | null | null | TripKit/VvoProvider.swift | kiliankoe/tripkit | 3ac306c170acd332322d2c50ef89d994aa03cbcf | [
"MIT"
] | null | null | null | import Foundation
public class VvoProvider: AbstractEfaProvider {
static let API_BASE = "http://efa.vvo-online.de:8080/dvb/"
static let STOPFINDER_ENDPOINT = "XSLT_STOPFINDER_REQUEST"
static let COORD_ENDPOINT = "XSLT_COORD_REQUEST"
static let DESKTOP_TRIP_ENDPOINT = "https://www.vvo-online.de/de/fahrplan/fahrplanauskunft/fahrten"
static let DESKTOP_DEPARTURES_ENDPOINT = "https://www.vvo-online.de/de/fahrplan/aktuelle-abfahrten-ankuenfte/abfahrten"
public init() {
super.init(networkId: .VVO, apiBase: VvoProvider.API_BASE, departureMonitorEndpoint: nil, tripEndpoint: nil, stopFinderEndpoint: VvoProvider.STOPFINDER_ENDPOINT, coordEndpoint: VvoProvider.COORD_ENDPOINT, tripStopTimesEndpoint: nil, desktopTripEndpoint: VvoProvider.DESKTOP_TRIP_ENDPOINT, desktopDeparturesEndpoint: VvoProvider.DESKTOP_DEPARTURES_ENDPOINT)
}
override func parseLine(id: String?, network: String?, mot: String?, symbol: String?, name: String?, longName: String?, trainType: String?, trainNum: String?, trainName: String?) -> Line {
if mot == "0" {
if trainName == "Twoje Linie Kolejowe", let symbol = symbol {
return Line(id: id, network: network, product: .highSpeedTrain, label: "TLK" + symbol)
} else if trainName == "Regionalbahn" && trainNum == nil {
return Line(id: id, network: network, product: .regionalTrain, label: nil)
} else if longName == "Ostdeutsche Eisenbahn GmbH" {
return Line(id: id, network: network, product: .regionalTrain, label: "OE")
} else if longName == "Meridian" {
return Line(id: id, network: network, product: .regionalTrain, label: "M")
} else if longName == "trilex" {
return Line(id: id, network: network, product: .regionalTrain, label: "TLX")
} else if trainName == "Trilex" && trainNum == nil {
return Line(id: id, network: network, product: .regionalTrain, label: "TLX")
} else if symbol == "U 28" { // Nationalparkbahn
return Line(id: id, network: network, product: .regionalTrain, label: "U28")
} else if symbol == "SB 71" { // Städtebahn Sachsen
return Line(id: id, network: network, product: .regionalTrain, label: "SB71")
} else if symbol == "RB 71" {
return Line(id: id, network: network, product: .regionalTrain, label: "RB71")
} else if trainName == "Fernbus" && trainNum == nil {
return Line(id: id, network: network, product: .regionalTrain, label: "Fernbus")
}
}
return super.parseLine(id: id, network: network, mot: mot, symbol: symbol, name: name, longName: longName, trainType: trainType, trainNum: trainNum, trainName: trainName)
}
override func queryTripsParameters(builder: UrlBuilder, from: Location, via: Location?, to: Location, date: Date, departure: Bool, products: [Product]?, optimize: Optimize?, walkSpeed: WalkSpeed?, accessibility: Accessibility?, options: [Option]?, desktop: Bool) {
if desktop {
builder.addParameter(key: "originid", value: locationValue(location: from))
if let via = via {
builder.addParameter(key: "viaid", value: locationValue(location: via))
}
builder.addParameter(key: "destinationid", value: locationValue(location: to))
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd.MM.yyyy"
dateFormatter.timeZone = timeZone
dateFormatter.locale = Locale(identifier: "de_DE")
let timeFormatter = DateFormatter()
timeFormatter.dateFormat = "HH:mm"
timeFormatter.timeZone = timeZone
timeFormatter.locale = Locale(identifier: "de_DE")
builder.addParameter(key: "date", value: dateFormatter.string(from: date))
builder.addParameter(key: "time", value: timeFormatter.string(from: date))
builder.addParameter(key: "arrival", value: !departure)
} else {
super.queryTripsParameters(builder: builder, from: from, via: via, to: to, date: date, departure: departure, products: products, optimize: optimize, walkSpeed: walkSpeed, accessibility: accessibility, options: options, desktop: desktop)
}
}
override func queryDeparturesParameters(builder: UrlBuilder, stationId: String, time: Date?, maxDepartures: Int, equivs: Bool, desktop: Bool) {
if desktop {
builder.addParameter(key: "stopid", value: stationId)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd.MM.yyyy"
dateFormatter.timeZone = timeZone
dateFormatter.locale = Locale(identifier: "de_DE")
let timeFormatter = DateFormatter()
timeFormatter.dateFormat = "HH:mm"
timeFormatter.timeZone = timeZone
timeFormatter.locale = Locale(identifier: "de_DE")
builder.addParameter(key: "date", value: dateFormatter.string(from: time ?? Date()))
builder.addParameter(key: "time", value: timeFormatter.string(from: time ?? Date()))
} else {
super.queryDeparturesParameters(builder: builder, stationId: stationId, time: time, maxDepartures: maxDepartures, equivs: equivs, desktop: desktop)
}
}
}
| 64.129412 | 364 | 0.645753 |