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
sequencelengths 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
sequencelengths 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
sequencelengths 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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6de5fede6f537d23cfb405ea62277b111806c5b8 | 9,695 | ts | TypeScript | client/src/statemachine/explore/garden.ts | stevenwaterman/NoTimeToStalk | 3884f3ad4c112b6c587e68d734f93bd68823b9bd | [
"MIT"
] | null | null | null | client/src/statemachine/explore/garden.ts | stevenwaterman/NoTimeToStalk | 3884f3ad4c112b6c587e68d734f93bd68823b9bd | [
"MIT"
] | null | null | null | client/src/statemachine/explore/garden.ts | stevenwaterman/NoTimeToStalk | 3884f3ad4c112b6c587e68d734f93bd68823b9bd | [
"MIT"
] | null | null | null | import { makeBackgrounds, MonologueNode, OptionNode } from "../controller";
import { atriumStart } from "./atrium";
import { balconyCharacters, bathroomWindowCharacters, confirmWeapon, hasBuff, isHoldingWeapon, isHostHere, loungeWindowCharacters, studyWindowCharacters } from "./explore";
import { getGlobalOptions } from "./global";
import { porchStart } from "./porch";
import { nodeStore, updateState } from "../state";
export type GardenFlags = {
lookAround: boolean;
graves: boolean;
fountain: boolean;
vegetables: boolean;
};
const backgrounds = makeBackgrounds("garden", [
"wide",
"wide1",
"wide2",
"wide3",
"grave1",
"grave2",
"fountain",
"chair",
"windows1",
"windows2",
"windows3",
"tree",
"treeTop",
"spade",
"vegetables"
])
export const gardenStartAtrium: MonologueNode = {
type: "MONOLOGUE",
onEnter: state => {
const wet = hasBuff(state, "wet") || !isHoldingWeapon(state, "umbrella");
updateState({ location: "garden", action: "leaving the house through the back door.", buffs: { wet }})(state);
},
backgroundUrl: backgrounds.wide,
text: state => [
"You walk through the back door into the luscious rear garden of the manor house.",
isHoldingWeapon(state, "umbrella") ? "It's raining, but your umbrella protects you." : "It's raining, and you're now wet."
],
next: () => nodeStore.set(gardenOptions)
}
export const gardenStartPorch: MonologueNode = {
type: "MONOLOGUE",
onEnter: state => {
const wet = hasBuff(state, "wet") || !isHoldingWeapon(state, "umbrella");
updateState({ location: "garden", action: "entering the garden from the porch.", buffs: { wet }})(state);
},
backgroundUrl: backgrounds.wide,
text: state => [
"You leave the porch to walk into the luscious rear garden of the manor house.",
isHoldingWeapon(state, "umbrella") ? "It's raining, but your umbrella protects you." : "It's raining, and you're now wet."
],
next: () => nodeStore.set(gardenOptions)
}
export const gardenStartIvy: MonologueNode = {
type: "MONOLOGUE",
onEnter: state => {
const wet = hasBuff(state, "wet") || !isHoldingWeapon(state, "umbrella");
updateState({ location: "garden", action: "climbing down from the balcony into the garden.", suspicious: true, buffs: { wet }})(state);
},
backgroundUrl: backgrounds.wide,
text: () => ["You find yourself in the luscious rear garden of the manor house."],
next: () => nodeStore.set(gardenOptions)
}
export const gardenStartStudy: MonologueNode = {
type: "MONOLOGUE",
onEnter: state => {
const wet = hasBuff(state, "wet") || !isHoldingWeapon(state, "umbrella");
updateState({ location: "garden", action: "climbing through the broken study window into the garden.", suspicious: true, buffs: { wet }})(state);
},
backgroundUrl: backgrounds.wide,
text: state => [
"You land in the luscious rear garden of the manor house.",
isHoldingWeapon(state, "umbrella") ? "It's raining, but your umbrella protects you." : "It's raining, and you're now wet."
],
next: () => nodeStore.set(gardenOptions)
}
const gardenOptions: OptionNode = {
type: "OPTION",
prompt: "What do you want to do?",
backgroundUrl: backgrounds.wide1,
options: [
{
visible: state => !state.explore.roomFlags.garden.lookAround,
text: "Look around",
next: () => nodeStore.set(lookAround)
},
{
visible: state => state.explore.roomFlags.garden.lookAround && !state.explore.roomFlags.garden.fountain,
text: "Inspect the fountain",
next: () => nodeStore.set(inspectFountain)
},
{
visible: state => state.explore.roomFlags.garden.lookAround,
text: "Look through the windows",
next: () => nodeStore.set(lookThroughWindows1)
},
{
visible: state => state.explore.roomFlags.garden.lookAround && !state.explore.roomFlags.garden.vegetables,
text: "Inspect the allotments",
next: () => nodeStore.set(inspectAllotments)
},
{
visible: state => state.explore.roomFlags.garden.lookAround && !state.explore.roomFlags.garden.graves,
text: "Inspect the graves",
next: () => nodeStore.set(inspectGraves1)
},
...getGlobalOptions(() => gardenOptions, backgrounds.wide),
{
visible: state => state.explore.roomFlags.garden.lookAround,
text: "Climb a tree",
next: () => nodeStore.set(climbTree)
},
{
visible: state => state.explore.roomFlags.garden.lookAround && isHoldingWeapon(state, "spade"),
text: "Pick up a spade",
next: state => confirmWeapon(state, gardenOptions, takeSpade),
disabledReasons: [{ disabled: isHostHere, reason: "You can't do that now, The Admiral will see you..." }]
},
{
text: "Go into the Atrium",
next: () => nodeStore.set(atriumStart)
},
{
text: "Go into the Porch",
next: () => nodeStore.set(porchStart)
},
]
}
const lookAround: MonologueNode = {
type: "MONOLOGUE",
onEnter: updateState({ action: "having a look around.", roomFlags: { garden: { lookAround: true }}}),
backgroundUrl: backgrounds.wide1,
text: () => ["You have a look around the garden, taking in all of the sights and the smells of your damp surroundings."],
next: () => nodeStore.set(lookAround2)
}
const lookAround2: MonologueNode = {
type: "MONOLOGUE",
backgroundUrl: backgrounds.wide2,
text: () => ["The candle-lit garden tries to give off comfy vibes, but you can't ignore the concerning number of graves under the tree."],
next: () => nodeStore.set(lookAround3)
}
const lookAround3: MonologueNode = {
type: "MONOLOGUE",
backgroundUrl: backgrounds.wide3,
text: () => ["You're sure it looks much more peaceful when it's not dark and rainy and on the night of a murder."],
next: () => nodeStore.set(gardenOptions)
}
const inspectGraves1: MonologueNode = {
type: "MONOLOGUE",
onEnter: updateState({ action: "reading the graves.", suspicious: true, roomFlags: { garden: { graves: true }}}),
backgroundUrl: backgrounds.grave1,
text: () => ["You inspect the graves under the tree. They don't look very old, but already the names have started to fade away."],
next: () => nodeStore.set(inspectGraves2)
}
const inspectGraves2: MonologueNode = {
type: "MONOLOGUE",
backgroundUrl: backgrounds.grave2,
text: () => ["There are fresh flowers left by the graves - the Admiral must care deeply for these people. You ponder their significance."],
next: () => nodeStore.set(gardenOptions)
}
const climbTree: MonologueNode = {
type: "MONOLOGUE",
onEnter: updateState({ action: "climbing the tree.", suspicious: true, buffs: { muddy: true } }),
backgroundUrl: backgrounds.tree,
sounds: [{ filePath: "effects/explore/garden/climbTree" }],
text: () => ["You decide to climb up the tree. It's a little slippery and you get muddy in the process, but you manage to lean on one of the sturdier branches."],
next: () => nodeStore.set(climbTreeTop)
}
const climbTreeTop: MonologueNode = {
type: "MONOLOGUE",
onEnter: updateState({ action: "sitting at the top of the tree.", suspicious: true }),
backgroundUrl: backgrounds.treeTop,
text: state => ["From the top of the tree, you can see the balcony.", ...balconyCharacters(state)],
next: () => nodeStore.set(gardenOptions)
}
const takeSpade: MonologueNode = {
type: "MONOLOGUE",
onEnter: updateState({ action: "picking up a spade.", weapon: "spade", suspicious: true, buffs: { wet: true }}),
sounds: [{filePath: "effects/explore/garden/spade"}],
backgroundUrl: backgrounds.spade,
text: () => [
"After assessing all your options of optimal garden tool to acquire, you take a spade.",
"The spade doesn't help protect you from the rain."
],
next: () => nodeStore.set(gardenOptions)
}
const inspectFountain: MonologueNode = {
type: "MONOLOGUE",
onEnter: updateState({ action: "looking in the fountain.", roomFlags: { garden: { fountain: true }}}),
backgroundUrl: backgrounds.fountain,
text: () => ["You take a look in the fountain. The water's a bit grimy from the leaves and dirt ending up in there, and you can barely hear it over the rain, but it looks adequately grand for this house."],
next: () => nodeStore.set(gardenOptions)
}
const inspectAllotments: MonologueNode = {
type: "MONOLOGUE",
onEnter: updateState({ action: "looking at the vegetables in the allotment.", roomFlags: { garden: { vegetables: true }}}),
backgroundUrl: backgrounds.vegetables,
text: () => [
"You look into the allotments and see a large variety of vegetables growing.",
"It's the harvest festival soon - something you read about during your degree. Every year, in the autumn, people would collect their finest fruits and vegetables from that year's harvest. Then, they'd perform a ritual where they left a sacrifice to the green giant, to ensure the next year's harvest was bountiful.",
"You'd love to ask the Admiral more about the green giant."
],
next: () => nodeStore.set(gardenOptions)
}
const lookThroughWindows1: MonologueNode = {
type: "MONOLOGUE",
onEnter: updateState({ action: "looking through the windows into the house." }),
backgroundUrl: backgrounds.windows2,
text: state => loungeWindowCharacters(state),
next: () => nodeStore.set(lookThroughWindows2)
}
const lookThroughWindows2: MonologueNode = {
type: "MONOLOGUE",
backgroundUrl: backgrounds.windows1,
text: state => studyWindowCharacters(state),
next: () => nodeStore.set(lookThroughWindows3)
}
const lookThroughWindows3: MonologueNode = {
type: "MONOLOGUE",
backgroundUrl: backgrounds.windows3,
text: state => bathroomWindowCharacters(state),
next: () => nodeStore.set(gardenOptions)
}
| 39.410569 | 321 | 0.685611 |
5822fd875e6bdc77be2228cb97f5af3b614b52e8 | 5,490 | css | CSS | src/styles/App.css | playneko/playneko-firebase | d9397d7365a990bcfe04262ff0f086da332bea6a | [
"MIT"
] | 1 | 2021-01-15T02:22:13.000Z | 2021-01-15T02:22:13.000Z | src/styles/App.css | playneko/playneko-firebase | d9397d7365a990bcfe04262ff0f086da332bea6a | [
"MIT"
] | null | null | null | src/styles/App.css | playneko/playneko-firebase | d9397d7365a990bcfe04262ff0f086da332bea6a | [
"MIT"
] | null | null | null | button:focus {
outline: none;
}
.header > header {
width: 100%;
z-index: 9999;
max-width: 100%;
position: fixed;
box-shadow: unset;
color: #f1f1f1 !important;
background: #484848 !important;
}
.header-people_add {
flex: 1 1 auto;
text-align: right;
}
.header-people_back {
flex: 1 1 auto;
text-align: left;
}
.footer {
bottom: 0;
width: 100%;
z-index: 9999;
max-width: 100%;
position: fixed;
color: #f1f1f1 !important;
background: #484848 !important;
}
.footer > div > div > span {
height: 0px;
}
.footer-chat_room {
bottom: 0;
width: 100%;
height: 45px;
z-index: 9999;
max-width: 100%;
position: fixed;
}
.footer-chat_room > form > div {
padding-top: 0px;
margin-left: 0 !important;
background-color: unset !important;
}
.footer-chat_room > form > div > div {
color: #ffffff;
margin: unset !important;
padding: 8px 7px 9px !important;
}
.footer-chat_fieldset {
border: 0px;
}
.footer-chat_fieldset > fieldset {
border: 0px;
}
.footer-chat_input_open {
height: unset !important;
}
.footer-chat_room_emoji {
height: 180px;
margin: 0 auto;
}
.footer-chat_emoji_open {
display: block;
overflow: auto;
margin-top: 3px;
background: #545454;
}
.footer-chat_emoji_close {
display: none;
}
.footer-chat_room_emoji > div {
float: left;
}
.footer-chat_room_emoji > div > img {
width: 80px;
}
.footer_chat_room_emoji_pv_open {
opacity: 0.7;
height: 100px;
display: block;
text-align: center;
background: #545454;
}
.footer_chat_room_emoji_pv_open > img {
width: 100px;
opacity: unset;
}
.footer_chat_room_emoji_pv_close {
display: none;
}
.login-form {
width: calc(100vw);
width: -moz-calc(100vw);
width: -webkit-calc(100vw);
height: calc(100vh);
height: -moz-calc(100vh);
height: -webkit-calc(100vh);
max-width: 100%;
max-height: 100%;
background-color: #44beed;
background-size: contain;
background-repeat: no-repeat;
background-image: url('https://cocoatalk-41442.web.app/login.png');
}
.registry-form {
width: calc(100vw);
width: -moz-calc(100vw);
width: -webkit-calc(100vw);
height: calc(100vh);
height: -moz-calc(100vh);
height: -webkit-calc(100vh);
max-width: 100%;
max-height: 100%;
background-color: #44beed;
}
.login-form_group {
margin: 0 auto !important;
padding: calc(100vw - 84vw) !important;
padding-top: calc(100vh - 40vh) !important;
}
.registry-form_group {
margin: 0 auto !important;
padding: calc(100vw - 84vw) !important;
}
.login-form_show, .registry-form_show {
display: block;
padding-top: 10px;
text-align: center;
}
.login-form_hidden, .registry-form_hidden {
display: none;
}
.login-form > div.alert, .registry-form > div.alert {
margin-right: 25px;
margin-left: 25px;
}
.list-top {
padding-top: 60px !important;
}
.list-bottom {
padding-bottom: 50px !important;
}
.people-add_div {
display: flex;
/* margin-top: 15px; */
}
.people-add_div > form {
margin: 0 auto !important;
}
.people-add_div > form > div {
width: calc(80vw);
margin: 0 auto !important;
}
.chat-list_data {
font-size: 10px;
overflow: hidden;
display: -webkit-box;
-webkit-line-clamp: 1;
text-overflow: ellipsis;
-webkit-box-orient: vertical;
width: calc(100vw - 40vw);
}
.chat-list_date {
font-size: 13px;
}
.chat-room_bubble_avatar {
margin-bottom: auto;
min-width: 35px !important;
}
.chat-room_bubble_avatar > div {
width: 30px !important;
height: 30px !important;
}
.chat-room_bubble_left {
padding: 5px;
width: auto;
font-size: 10px;
color: #4c4c4c;
padding-left: 10px;
padding-right: 10px;
border-radius: 7px;
white-space: pre-line;
background: #e8e8e8;
border: 1px solid #e8e8e8;
border-top-left-radius: 0px;
}
.chat-room_bubble_right {
padding: 5px;
width: auto;
font-size: 10px;
padding-left: 10px;
padding-right: 10px;
border-radius: 7px;
white-space: pre-line;
background: #ffde3f;
border: 1px solid #ffde3f;
border-bottom-right-radius: 0px;
}
.chat-room_emoji_left, .chat-room_emoji_right {
width: auto;
}
.chat-room_emoji_left > img, .chat-room_emoji_right > img {
width: 100px;
}
.chat-room_bubble_name_left {
padding: 2px;
font-size: 9px;
}
.chat-room_bubble_time_left {
font-size: 9px;
margin-top: auto;
margin-bottom: 0;
padding-left: 5px;
}
.chat-room_bubble_time_right {
font-size: 9px;
margin-top: auto;
margin-left: auto;
margin-bottom: 0;
padding-right: 5px;
}
.other-avatar {
float: left;
padding: 15px;
min-width: 75px;
}
.other-avatar > div {
width: 75px;
height: 75px;
}
.other-name {
font-size: 20px;
padding-top: 15px;
}
.other-name > p {
white-space: nowrap;
}
.other-profile {
font-size: 12px;
padding-top: 10px;
}
.other-profile_list > div:first-child {
min-width: 60px;
max-width: 60px;
}
.other-progress > div {
color: #2196F3;
}
.other-progress > div, .other-progress > button {
margin-top: 12px;
}
.other-upload_success {
font-weight: bold;
color: #8BC34A !important;
}
.other-upload_error {
margin-top: 12px;
font-size: 12px !important;
margin: 10px !important;
color: #ffffff !important;
} | 17.428571 | 71 | 0.628233 |
c9b95c018570cab566199d405f170a24cd738e64 | 1,190 | ts | TypeScript | packages/explorer-for-endevor/src/endevor.ts | nickImbirev/che-che4z-explorer-for-endevor | 0b4616599b5d2212c31b5a99bda7aeb19ebfe445 | [
"Apache-2.0"
] | null | null | null | packages/explorer-for-endevor/src/endevor.ts | nickImbirev/che-che4z-explorer-for-endevor | 0b4616599b5d2212c31b5a99bda7aeb19ebfe445 | [
"Apache-2.0"
] | 1 | 2020-11-25T09:34:52.000Z | 2020-11-25T09:34:52.000Z | packages/explorer-for-endevor/src/endevor.ts | nickImbirev/che-che4z-explorer-for-endevor | 0b4616599b5d2212c31b5a99bda7aeb19ebfe445 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2020 Broadcom.
* The term "Broadcom" refers to Broadcom Inc. and/or its subsidiaries.
*
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* Broadcom, Inc. - initial API and implementation
*/
import { logger } from './globals';
import * as endevor from '@local/endevor/endevor';
export const getInstanceNames = endevor.getInstanceNames(logger);
export const searchForElements = endevor.searchForElements(logger);
export const viewElement = endevor.viewElement(logger);
export const retrieveElement = endevor.retrieveElement(logger);
export const generateElement = endevor.generateElement(logger);
export const retrieveElementWithDependencies = endevor.retrieveElementWithDependencies(
logger
);
export const retrieveElementWithFingerprint = endevor.retrieveElementWithFingerprint(
logger
);
export const printElement = endevor.printElement(logger);
export const printListing = endevor.printListing(logger);
export const updateElement = endevor.updateElement(logger);
| 37.1875 | 87 | 0.787395 |
6ba2954801d7d5501ce15f5e416668183e070596 | 60 | sql | SQL | src/test/resources/sql/fetch/b37caa18.sql | Shuttl-Tech/antlr_psql | fcf83192300abe723f3fd3709aff5b0c8118ad12 | [
"MIT"
] | 66 | 2018-06-15T11:34:03.000Z | 2022-03-16T09:24:49.000Z | src/test/resources/sql/fetch/b37caa18.sql | Shuttl-Tech/antlr_psql | fcf83192300abe723f3fd3709aff5b0c8118ad12 | [
"MIT"
] | 13 | 2019-03-19T11:56:28.000Z | 2020-08-05T04:20:50.000Z | src/test/resources/sql/fetch/b37caa18.sql | Shuttl-Tech/antlr_psql | fcf83192300abe723f3fd3709aff5b0c8118ad12 | [
"MIT"
] | 28 | 2019-01-05T19:59:02.000Z | 2022-03-24T11:55:50.000Z | -- file:rangefuncs.sql ln:54 expect:true
fetch all from foo
| 20 | 40 | 0.766667 |
d64015a5f99ccfcb04bf29f565961156fbdd8cb1 | 953 | cs | C# | Assets/Resources/Scripts/DebugHelper.cs | SchwiftyPython/PizzalikeRL | fbd4cdd5f7e6a519b9d85d401f7828c7c20d891f | [
"Apache-2.0"
] | null | null | null | Assets/Resources/Scripts/DebugHelper.cs | SchwiftyPython/PizzalikeRL | fbd4cdd5f7e6a519b9d85d401f7828c7c20d891f | [
"Apache-2.0"
] | null | null | null | Assets/Resources/Scripts/DebugHelper.cs | SchwiftyPython/PizzalikeRL | fbd4cdd5f7e6a519b9d85d401f7828c7c20d891f | [
"Apache-2.0"
] | null | null | null | using System;
using UnityEngine;
//<Summary>
// A class of functions to aid in debugging
//</Summary>
public class DebugHelper : MonoBehaviour, ISubscriber
{
public static DebugHelper Instance;
private void Start()
{
if (Instance == null)
{
Instance = this;
DontDestroyOnLoad(gameObject);
}
else if (Instance != this)
{
Destroy(gameObject);
}
EventMediator.Instance.SubscribeToEvent(GlobalHelper.KillPlayerEventName, this);
}
//<Summary>
// Sets player's current hp to zero
//</Summary>
public void KillPlayer()
{
GameManager.Instance.Player.CurrentHp = 0;
}
public void OnNotify(string eventName, object broadcaster, object parameter = null)
{
if (eventName.Equals(GlobalHelper.KillPlayerEventName, StringComparison.OrdinalIgnoreCase))
{
KillPlayer();
}
}
}
| 22.690476 | 99 | 0.610703 |
ae9a9d551fec2422b166eb814c1bf01b6d9f2068 | 2,569 | cs | C# | Editor/BrushSetEditor.cs | dimaswift/Decal2D | f61c9994340427f5ecf5b9c6347ac2023c174611 | [
"MIT"
] | null | null | null | Editor/BrushSetEditor.cs | dimaswift/Decal2D | f61c9994340427f5ecf5b9c6347ac2023c174611 | [
"MIT"
] | null | null | null | Editor/BrushSetEditor.cs | dimaswift/Decal2D | f61c9994340427f5ecf5b9c6347ac2023c174611 | [
"MIT"
] | null | null | null | using UnityEngine;
using System.Collections;
using UnityEditor;
using HandyUtilities;
using System.Collections.Generic;
namespace Decal2D
{
public abstract class BrushSetEditor<T> : ReordableList<IBrushBinding> where T : IBrushBinding
{
public abstract BrushSet<T> brushSet { get; }
protected override float elementHeight
{
get
{
return 50;
}
}
protected override string headerName
{
get
{
return "Brushes";
}
}
protected override IList list
{
get
{
return brushSet.brushes;
}
}
public override void OnInspectorGUI()
{
DoLayoutList();
if(reorderableList.index >= 0 && reorderableList.index < brushSet.brushes.Count && brushSet.brushes[reorderableList.index].brush != null)
{
SingleBrushEditor.DrawBrushLayout(brushSet.brushes[reorderableList.index].brush);
}
}
protected override IBrushBinding GetNewItem()
{
return brushSet.CreateBrush();
}
public void DrawIconInCorner(Rect rect, Brush brush)
{
if(brush)
{
var single = brush.GetBrushSafe();
if (single != null)
{
var brushIconAspect = single.iconPreview.width / single.iconPreview.height;
var w = brushIconAspect * (rect.height - 10);
var texRect = new Rect(rect.width - (w + 5), rect.y + 5,
w, rect.height - 10);
GUI.DrawTexture(texRect, single.iconPreview, ScaleMode.ScaleToFit);
}
}
}
protected override void OnDrawItem(Rect rect, int index, bool active, bool focused)
{
var bind = brushSet.brushes[index];
if(bind != null)
{
GUI.Label(new Rect(rect.x + 5, rect.y + 5, 40, 16), "Brush");
brushSet.brushes[index].brush = EditorGUI.ObjectField(new Rect(rect.x + 45, rect.y + 5, 200, 16),
brushSet.brushes[index].brush,
typeof(Brush),
false) as Brush;
DrawIconInCorner(rect, bind.brush);
if (GUI.changed)
EditorUtility.SetDirty(brushSet);
}
}
}
}
| 29.528736 | 149 | 0.498248 |
4b9f3cea2d12514a0b68770f7c965e39c90e1a91 | 2,838 | cpp | C++ | src/Adafruit_I2CRegister.cpp | nrobinson2000/Adafruit_VEML7700 | ad29bfb331ad08ed6e40de68abae6455f99760bf | [
"BSD-3-Clause"
] | 3 | 2019-07-19T23:47:53.000Z | 2019-07-22T03:45:10.000Z | src/Adafruit_I2CRegister.cpp | nrobinson2000/Adafruit_VEML7700 | ad29bfb331ad08ed6e40de68abae6455f99760bf | [
"BSD-3-Clause"
] | 1 | 2019-11-15T22:59:55.000Z | 2019-11-15T22:59:55.000Z | src/Adafruit_I2CRegister.cpp | nrobinson2000/Adafruit_VEML7700 | ad29bfb331ad08ed6e40de68abae6455f99760bf | [
"BSD-3-Clause"
] | null | null | null | #include "Adafruit_I2CRegister.h"
Adafruit_I2CRegister::Adafruit_I2CRegister(Adafruit_I2CDevice *device, uint16_t reg_addr, uint8_t width, uint8_t bitorder, uint8_t address_width) {
_device = device;
_addrwidth = address_width;
_address = reg_addr;
_bitorder = bitorder;
_width = width;
}
bool Adafruit_I2CRegister::write(uint8_t *buffer, uint8_t len) {
uint8_t addrbuffer[2] = {(uint8_t)(_address & 0xFF), (uint8_t)(_address>>8)};
if (! _device->write(buffer, len, true, addrbuffer, _addrwidth)) {
return false;
}
return true;
}
bool Adafruit_I2CRegister::write(uint32_t value, uint8_t numbytes) {
if (numbytes == 0) {
numbytes = _width;
}
if (numbytes > 4) {
return false;
}
for (int i=0; i<numbytes; i++) {
if (_bitorder == LSBFIRST) {
_buffer[i] = value & 0xFF;
} else {
_buffer[numbytes-i-1] = value & 0xFF;
}
value >>= 8;
}
return write(_buffer, numbytes);
}
// This does not do any error checking! returns 0xFFFFFFFF on failure
uint32_t Adafruit_I2CRegister::read(void) {
if (! read(_buffer, _width)) {
return -1;
}
uint32_t value = 0;
for (int i=0; i < _width; i++) {
value <<= 8;
if (_bitorder == LSBFIRST) {
value |= _buffer[_width-i-1];
} else {
value |= _buffer[i];
}
}
return value;
}
bool Adafruit_I2CRegister::read(uint8_t *buffer, uint8_t len) {
_buffer[0] = _address;
if (! _device->write_then_read(_buffer, 1, buffer, len)) {
return false;
}
return true;
}
bool Adafruit_I2CRegister::read(uint16_t *value) {
if (! read(_buffer, 2)) {
return false;
}
if (_bitorder == LSBFIRST) {
*value = _buffer[1];
*value <<= 8;
*value |= _buffer[0];
} else {
*value = _buffer[0];
*value <<= 8;
*value |= _buffer[1];
}
return true;
}
bool Adafruit_I2CRegister::read(uint8_t *value) {
if (! read(_buffer, 1)) {
return false;
}
*value = _buffer[0];
return true;
}
void Adafruit_I2CRegister::print(Stream *s) {
uint32_t val = read();
s->print("0x"); s->print(val, HEX);
}
void Adafruit_I2CRegister::println(Stream *s) {
print(s);
s->println();
}
Adafruit_I2CRegisterBits::Adafruit_I2CRegisterBits(Adafruit_I2CRegister *reg, uint8_t bits, uint8_t shift) {
_register = reg;
_bits = bits;
_shift = shift;
}
uint32_t Adafruit_I2CRegisterBits::read(void) {
uint32_t val = _register->read();
val >>= _shift;
return val & ((1 << (_bits+1)) - 1);
}
void Adafruit_I2CRegisterBits::write(uint32_t data) {
uint32_t val = _register->read();
// mask off the data before writing
uint32_t mask = (1 << (_bits+1)) - 1;
data &= mask;
mask <<= _shift;
val &= ~mask; // remove the current data at that spot
val |= data << _shift; // and add in the new data
_register->write(val, _register->width());
} | 22 | 147 | 0.634249 |
e255f4fbcf38cc3020404481db9cfe2d6c4be3c0 | 732 | py | Python | tests/unit/test_resources.py | LimaGuilherme/flask-boilerplate | 4053dd2d24937d405fedcd839e15d2cc45d87f01 | [
"MIT"
] | null | null | null | tests/unit/test_resources.py | LimaGuilherme/flask-boilerplate | 4053dd2d24937d405fedcd839e15d2cc45d87f01 | [
"MIT"
] | null | null | null | tests/unit/test_resources.py | LimaGuilherme/flask-boilerplate | 4053dd2d24937d405fedcd839e15d2cc45d87f01 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
from tests.unit import base
from app import resources
class CasingTest(base.TestCase):
def test_should_convert_camel_to_snake(self):
self.assertEqual(resources.ResourceBase.camel_to_snake('getThisSnaked'), 'get_this_snaked')
def test_should_convert_snake_to_camel(self):
self.assertEqual(resources.ResourceBase.snake_to_camel('get_this_camelled'), 'getThisCamelled')
def test_should_convert_snake_upper_to_camel(self):
self.assertEqual(resources.ResourceBase.snake_to_camel('GET_THIS_CAMELLED'), 'getThisCamelled')
def test_should_convert_pascal_to_snake(self):
self.assertEqual(resources.ResourceBase.camel_to_snake('GetThisSnaked'), 'get_this_snaked')
| 38.526316 | 103 | 0.782787 |
af4d9b52a5ba17b11d26e2f5d9631d64f888767d | 1,090 | py | Python | ML_and_DL/number_clacification_basic.py | AshfakYeafi/AI_practice_code | 3d8a0b9382f5903e840ce59218ebb95ca962ab01 | [
"MIT"
] | null | null | null | ML_and_DL/number_clacification_basic.py | AshfakYeafi/AI_practice_code | 3d8a0b9382f5903e840ce59218ebb95ca962ab01 | [
"MIT"
] | null | null | null | ML_and_DL/number_clacification_basic.py | AshfakYeafi/AI_practice_code | 3d8a0b9382f5903e840ce59218ebb95ca962ab01 | [
"MIT"
] | null | null | null | import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as np
from tensorflow import keras
import pickle
path="demo_model_1"
(X_train, y_train) , (X_test, y_test) =keras.datasets.mnist.load_data()
X_train_flat=X_train.reshape(X_train.shape[0],X_train.shape[1]*X_train.shape[1])
X_train_flat=X_train_flat/255
# print(y_train[0])
# print(X_train_flat[0])
# plt.matshow(X_train[0])
# plt.show()
# print(X_train_flat.shape)
model=keras.Sequential([
keras.layers.Dense(400,input_shape=(784,),activation="relu"),
keras.layers.Dense(200,activation="relu"),
keras.layers.Dense(100, activation="relu"),
keras.layers.Dense(50, activation="relu"),
keras.layers.Dense(10,activation="sigmoid")
]
)
model.compile(optimizer="Adam",
loss='sparse_categorical_crossentropy',
metrics="accuracy")
model.fit(X_train_flat,y_train,epochs=50)
model.save(path)
# new_model=keras.models.load_model(path)
# y_predict=new_model.predict(X_train_flat)
# print(y_predict[100])
# plt.matshow(X_train[100])
# plt.show()
# print(np.argmax(y_predict[100])) | 30.277778 | 80 | 0.734862 |
3ac999a6086879089cb73953085b4e91c8dd3c20 | 70 | lua | Lua | Mad City - New OP GUI.lua | xVoid-xyz/Roblox-Scripts | 7eb176fa654f2ea5fbc6bcccced1b15df7ed82c2 | [
"BSD-3-Clause"
] | 70 | 2021-02-09T17:21:32.000Z | 2022-03-28T12:41:42.000Z | Mad City - New OP GUI.lua | xVoid-xyz/Roblox-Scripts | 7eb176fa654f2ea5fbc6bcccced1b15df7ed82c2 | [
"BSD-3-Clause"
] | 4 | 2021-08-19T22:05:58.000Z | 2022-03-19T18:58:01.000Z | Mad City - New OP GUI.lua | xVoid-xyz/Roblox-Scripts | 7eb176fa654f2ea5fbc6bcccced1b15df7ed82c2 | [
"BSD-3-Clause"
] | 325 | 2021-02-26T22:23:41.000Z | 2022-03-31T19:36:12.000Z | loadstring(game:HttpGet(('https://pastebin.com/raw/9eUprNxz'),true))() | 70 | 70 | 0.742857 |
bd9b3951a37eeef5de29a8abc00f3c773473c911 | 1,511 | rb | Ruby | spec/support/helpers/vim.rb | eugen0329/vim-easy-search | d00e5b1f29288e0d884eb523558fea891a252631 | [
"Vim"
] | 358 | 2016-04-12T12:37:48.000Z | 2022-03-04T15:53:26.000Z | spec/support/helpers/vim.rb | eugen0329/vim-esearch | 02db26e593b80c2908b25ae558c2f0db7f135051 | [
"Vim"
] | 79 | 2016-06-08T16:56:47.000Z | 2022-02-28T20:06:48.000Z | spec/support/helpers/vim.rb | eugen0329/vim-easy-search | d00e5b1f29288e0d884eb523558fea891a252631 | [
"Vim"
] | 18 | 2016-09-01T21:12:26.000Z | 2022-01-01T13:26:51.000Z | # frozen_string_literal: true
module Helpers::Vim
extend RSpec::Matchers::DSL
include VimlValue::SerializationHelpers
shared_context 'set options' do |**options|
before do
editor.command! <<~TEXT
let g:save = #{VimlValue.dump(options.keys.zip(options.keys).to_h.transform_values { |v| var("&#{v}") })}
#{options.map { |k, v| "let &#{k} = #{VimlValue.dump(v)}" }.join("\n")}
TEXT
end
after do
editor.command! <<~TEXT
#{options.map { |k, _v| "let &#{k} = g:save.#{k}" }.join("\n")}
TEXT
end
end
# TODO: fix reusability
matcher :change_option do |option, timeout: 1|
include API::Mixins::BecomeTruthyWithinTimeout
supports_block_expectations
match do |block|
editor.with_ignore_cache do
@before = editor.echo(var(option))
block.call
@changed = became_truthy_within?(timeout) do
@after = editor.echo(var(option))
@before != @after
end
return false unless @changed
if @to
@changed_to_expected = became_truthy_within?(timeout) do
@after = editor.echo(var(option))
values_match?(@to, @after)
end
return false unless @changed_to_expected
end
end
true
end
chain :to do |to|
@to = to
end
failure_message do
msg = "expected to change #{@before.inspect}"
msg += " to #{@to.inspect}, got #{@after.inspect}" if @to
msg
end
end
end
| 23.984127 | 113 | 0.583719 |
2c3612fa5a5cdb10c96a1317f3f0dc4afb33ad89 | 166 | py | Python | simulator.py | AndreaKarlova/BLOX | f103c232009ebff61dcfb1de09a3f5df6c130877 | [
"MIT"
] | 19 | 2020-02-21T07:22:31.000Z | 2021-09-15T22:00:19.000Z | simulator.py | rob8718/BLOX | f103c232009ebff61dcfb1de09a3f5df6c130877 | [
"MIT"
] | null | null | null | simulator.py | rob8718/BLOX | f103c232009ebff61dcfb1de09a3f5df6c130877 | [
"MIT"
] | 4 | 2020-08-08T21:37:38.000Z | 2021-04-24T12:20:15.000Z | import csv
def simulation(parameter):
#Please call your simulation program with the input parameter
#and return its result
print('Simulation')
| 18.444444 | 65 | 0.698795 |
d633a9c553538df215bfc216b45e03292906d9ff | 1,366 | cs | C# | C#/Man/Division/Program.cs | Futupas/Man_1819 | 8316c02cb2b55612c4577742005c824e2017cbe6 | [
"MIT"
] | null | null | null | C#/Man/Division/Program.cs | Futupas/Man_1819 | 8316c02cb2b55612c4577742005c824e2017cbe6 | [
"MIT"
] | null | null | null | C#/Man/Division/Program.cs | Futupas/Man_1819 | 8316c02cb2b55612c4577742005c824e2017cbe6 | [
"MIT"
] | null | null | null | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace Division
{
class Program
{
static void Main(string[] args)
{
try
{
int a, b, d, ch, nac; //a/b=c
//dilene, chastka, numbers after comma
Console.WriteLine("a / b = c");
Console.Write("a = "); a = Int32.Parse(Console.ReadLine());
Console.Write("b = "); b = Int32.Parse(Console.ReadLine());
Console.Write("nac = "); nac = Int32.Parse(Console.ReadLine());
Console.Clear();
d = a / b;
ch = a % b;
Console.WriteLine(d);
Console.WriteLine(".");
a = ch * 10;
for (int i = 0; i < nac; i++)
{
d = a / b;
ch = a % b;
Console.WriteLine(d);
a = ch * 10;
Thread.Sleep(10);
}
Console.ReadLine();
}
catch (Exception ex)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(ex.Message);
Console.ReadLine();
}
}
}
}
| 29.06383 | 79 | 0.402635 |
4fa32342caade5fa70002a1b767e3c2bcd6cb713 | 61 | rb | Ruby | test/integration/server/serverspec/spec_helper.rb | oneconcern/openvpn | 24de3f1bd5ec95fe6b2788ae1c0a03e8414f6e49 | [
"Apache-2.0"
] | 1 | 2020-04-06T00:33:39.000Z | 2020-04-06T00:33:39.000Z | test/integration/server/serverspec/spec_helper.rb | oneconcern/openvpn | 24de3f1bd5ec95fe6b2788ae1c0a03e8414f6e49 | [
"Apache-2.0"
] | null | null | null | test/integration/server/serverspec/spec_helper.rb | oneconcern/openvpn | 24de3f1bd5ec95fe6b2788ae1c0a03e8414f6e49 | [
"Apache-2.0"
] | null | null | null | # encoding: UTF-8
require 'serverspec'
set :backend, :exec
| 10.166667 | 20 | 0.704918 |
2c7d20c6867cd77397de2a1ebf6c9cc0dffd8c7b | 133 | py | Python | tests/results/015_simple_hash09.py | CowboyTim/python-storable | f03cf0eae60eeb9c3345e9ddf3370a49a316e472 | [
"Zlib"
] | 8 | 2015-04-24T07:27:42.000Z | 2020-10-30T20:51:40.000Z | tests/results/015_simple_hash09.py | CowboyTim/python-storable | f03cf0eae60eeb9c3345e9ddf3370a49a316e472 | [
"Zlib"
] | 7 | 2015-09-08T01:40:12.000Z | 2021-09-29T15:19:46.000Z | tests/results/015_simple_hash09.py | CowboyTim/python-storable | f03cf0eae60eeb9c3345e9ddf3370a49a316e472 | [
"Zlib"
] | 10 | 2015-07-22T13:57:04.000Z | 2020-09-03T18:32:39.000Z | result = [
[0.6, 0.7],
{'a': 'b'},
None,
[
'uu',
'ii',
[None],
[7, 8, 9, {}]
]
]
| 11.083333 | 21 | 0.203008 |
e7042aa4998314586bab106ea621f3f82fc5c3fa | 1,430 | php | PHP | database/seeders/ProductElectronicsTableSeeder.php | s1110078/Time2Share | 338968c338687bb98bb0ea10de7bb1d2491e2ae3 | [
"MIT"
] | null | null | null | database/seeders/ProductElectronicsTableSeeder.php | s1110078/Time2Share | 338968c338687bb98bb0ea10de7bb1d2491e2ae3 | [
"MIT"
] | null | null | null | database/seeders/ProductElectronicsTableSeeder.php | s1110078/Time2Share | 338968c338687bb98bb0ea10de7bb1d2491e2ae3 | [
"MIT"
] | null | null | null | <?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use DB;
class ProductElectronicsTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$electronics_product_array = ["Drill", "Vacuum", "Charger"];
DB::table('product')->insert([
'name' => 'Chainsaw',
'category' => 'electronics',
'description' => 'A household chainsaw for assistance.',
'image' => '/img/'.'default_electronics.png',
'user_id' => 3,
'borrowed' => 5,
'review_id' => 2,
]);
foreach($electronics_product_array as $electronics) {
$rng_borrow = rand(0, 1);
$borrowed_user = rand(2, 6);
$rng_user = rand(1, 6);
if ($rng_borrow == 0){
if ($rng_user == $borrowed_user)
$borrowed_user--;
} else {
$borrowed_user = null;
}
DB::table('product')->insert([
'name' => $electronics,
'category' => 'electronics',
'description' => 'A household ' . $electronics . ' for assistance.',
'image' => '/img/' . 'default_electronics.png',
'user_id' => $rng_user,
'borrowed' => $borrowed_user,
]);
}
}
} | 28.039216 | 84 | 0.471329 |
384b3322a6aac4162a447774a4d4a7ed765314f1 | 1,078 | cs | C# | CodeGenerator/Config/EntitySchemaCollection.cs | conorjgallagher/Dynamics.ExtendedSvcUtil | d058ae8c97ce46c7c1f642b9ae24b822b50be1e6 | [
"MIT"
] | 4 | 2016-06-24T20:12:57.000Z | 2020-02-26T15:08:36.000Z | CodeGenerator/Config/EntitySchemaCollection.cs | conorjgallagher/Dynamics.ExtendedSvcUtil | d058ae8c97ce46c7c1f642b9ae24b822b50be1e6 | [
"MIT"
] | 3 | 2017-01-30T14:58:53.000Z | 2019-04-02T13:44:16.000Z | CodeGenerator/Config/EntitySchemaCollection.cs | conorjgallagher/Dynamics.ExtendedSvcUtil | d058ae8c97ce46c7c1f642b9ae24b822b50be1e6 | [
"MIT"
] | 1 | 2021-08-23T08:22:16.000Z | 2021-08-23T08:22:16.000Z | using System.Collections.Generic;
using System.Configuration;
using System.Linq;
namespace CodeGenerator.Config
{
[ConfigurationCollection(typeof(EntitySchema), AddItemName = "entity")]
public class EntitySchemaCollection : ConfigurationElementCollection, IEnumerable<EntitySchema>
{
protected override ConfigurationElement CreateNewElement()
{
return new EntitySchema();
}
protected override object GetElementKey(ConfigurationElement element)
{
var configElement = element as EntitySchema;
if (configElement != null)
return configElement.Name;
return null;
}
public EntitySchema this[int index]
{
get
{
return BaseGet(index) as EntitySchema;
}
}
IEnumerator<EntitySchema> IEnumerable<EntitySchema>.GetEnumerator()
{
return (from i in Enumerable.Range(0, Count)
select this[i])
.GetEnumerator();
}
}
} | 28.368421 | 99 | 0.601113 |
5865f3a594a40f3e9389f8f30e4c8f72a8444a48 | 826 | css | CSS | src/lib/reset.css | future-tech-learning-team/build-ssr-demo | d5b9e3e653ab6ee2380ace33667e0c7ceeec8031 | [
"MIT"
] | null | null | null | src/lib/reset.css | future-tech-learning-team/build-ssr-demo | d5b9e3e653ab6ee2380ace33667e0c7ceeec8031 | [
"MIT"
] | null | null | null | src/lib/reset.css | future-tech-learning-team/build-ssr-demo | d5b9e3e653ab6ee2380ace33667e0c7ceeec8031 | [
"MIT"
] | null | null | null |
html {
font-size: 62.5%;
}
body,
div,
h1,
h2,
h3,
h4,
h5,
h6,
p,
ul,
li,
dl,
dt,
dd,
textarea,
input,
button {
margin: 0;
padding: 0;
outline: none;
font-weight: normal;
}
body {
color: #333;
}
button,
input,
select,
textarea {
font-size: 100%;
outline: none;
line-height: 1.5;
}
textarea,
input {
resize: none;
-webkit-appearance: none;
border-radius: 0;
border: 0;
background-color: transparent;
}
ul,
ol {
list-style: none;
}
a {
color: #333;
text-decoration: none;
}
a:hover {
text-decoration: none;
}
del {
text-decoration: line-through;
}
input[type=number]::-webkit-inner-spin-button,
input[type=number]::-webkit-outer-spin-button {
-webkit-appearance: none;
margin: 0;
}
* {
-webkit-tap-highlight-color: transparent;
}
| 10.589744 | 47 | 0.599274 |
22e622606e586510d2679398553ad6450f493335 | 233 | lua | Lua | MMOCoreORB/bin/scripts/loot/custom_loot/groups/wearables/g_nightsister_bicep.lua | V-Fib/FlurryClone | 40e0ca7245ec31b3815eb6459329fd9e70f88936 | [
"Zlib",
"OpenSSL"
] | 18 | 2017-02-09T15:36:05.000Z | 2021-12-21T04:22:15.000Z | MMOCoreORB/bin/scripts/loot/custom_loot/groups/wearables/g_nightsister_bicep.lua | V-Fib/FlurryClone | 40e0ca7245ec31b3815eb6459329fd9e70f88936 | [
"Zlib",
"OpenSSL"
] | 61 | 2016-12-30T21:51:10.000Z | 2021-12-10T20:25:56.000Z | MMOCoreORB/bin/scripts/loot/custom_loot/groups/wearables/g_nightsister_bicep.lua | V-Fib/FlurryClone | 40e0ca7245ec31b3815eb6459329fd9e70f88936 | [
"Zlib",
"OpenSSL"
] | 71 | 2017-01-01T05:34:38.000Z | 2022-03-29T01:04:00.000Z | g_nightsister_bicep = {
description = "",
minimumLevel = 0,
maximumLevel = 0,
lootItems = {
{itemTemplate = "armor_nightsister_bicep_r", weight = 10000000}
}
}
addLootGroupTemplate("g_nightsister_bicep", g_nightsister_bicep)
| 233 | 233 | 0.746781 |
7aaec64de64daef2c70f69a8370742257e673262 | 1,521 | cs | C# | ToMigrate/Raven.Tests.MailingList/TypeConverter.cs | ryanheath/ravendb | f32ee65b73912aa1532929164d004e027d266270 | [
"Linux-OpenIB"
] | 1 | 2017-03-02T13:05:14.000Z | 2017-03-02T13:05:14.000Z | ToMigrate/Raven.Tests.MailingList/TypeConverter.cs | ryanheath/ravendb | f32ee65b73912aa1532929164d004e027d266270 | [
"Linux-OpenIB"
] | 1 | 2019-03-12T12:10:52.000Z | 2019-03-12T12:10:52.000Z | ToMigrate/Raven.Tests.MailingList/TypeConverter.cs | aviv86/ravendb | 3ee33d576fecd2c47dc7a9f5b671a46731fed659 | [
"Linux-OpenIB"
] | null | null | null | // -----------------------------------------------------------------------
// <copyright file="TypeConverter.cs" company="Hibernating Rhinos LTD">
// Copyright (c) Hibernating Rhinos LTD. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
using System.ComponentModel;
using Raven.Client;
using Raven.Client.Document;
using Raven.Imports.Newtonsoft.Json;
using Raven.Tests.Common;
using Xunit;
namespace Raven.Tests.MailingList
{
public class TypeConverter : RavenTest
{
[Fact]
public void ShouldWork()
{
var test = new Test {Name = "Hello World"};
using (IDocumentStore documentStore = NewDocumentStore())
{
using (IDocumentSession session = documentStore.OpenSession())
{
session.Store(test);
session.SaveChanges();
}
}
}
[JsonObject]
[TypeConverter(typeof (ExpandableObjectConverter))]
public class Test
{
/// <summary>Gets or sets the Name.</summary>
public string Name { get; set; }
/// <summary>The to string.</summary>
/// <returns>
/// The <see cref="string" />Name.
/// </returns>
public override string ToString()
{
return Name;
}
}
}
}
| 28.698113 | 79 | 0.464168 |
ccd3d2170b541006497bef51730d2010e58195fb | 1,353 | rb | Ruby | spec/models/course_template_spec.rb | jayshaffer/bridge_cache | 077aa5c6336f0af916eb54fa092eb902b3988782 | [
"MIT"
] | null | null | null | spec/models/course_template_spec.rb | jayshaffer/bridge_cache | 077aa5c6336f0af916eb54fa092eb902b3988782 | [
"MIT"
] | null | null | null | spec/models/course_template_spec.rb | jayshaffer/bridge_cache | 077aa5c6336f0af916eb54fa092eb902b3988782 | [
"MIT"
] | null | null | null | require 'spec_helper'
describe BridgeCache::CourseTemplate, type: :model do
describe 'import_from_csv' do
it 'should be able to take a csv dump into a table' do
BridgeCache::CourseTemplate.import_from_csv(get_fixture_path('course_templates.csv'))
expect(BridgeCache::CourseTemplate.all.count).to(eq(10))
end
end
describe 'check associations' do
it 'should be able to pull associations from its parent' do
BridgeCache::CourseTemplate.import_from_csv(get_fixture_path('course_templates.csv'))
BridgeCache::Domain.import_from_csv(get_fixture_path('domains.csv'))
BridgeCache::User.import_from_csv(get_fixture_path('users.csv'))
expect(BridgeCache::CourseTemplate.first.domain).to(eq(BridgeCache::Domain.first))
expect(BridgeCache::CourseTemplate.first.user).to(eq(BridgeCache::User.first))
end
it { should have_many(:affiliated_sub_accounts) }
it { should have_many(:domains) }
end
describe 'check scope' do
it 'should scope to domain by affilicated accounts' do
BridgeCache::CourseTemplate.import_from_csv(get_fixture_path('course_templates.csv'))
BridgeCache::AffiliatedSubAccount.import_from_csv(get_fixture_path('affiliated_sub_accounts.csv'))
rows = BridgeCache::CourseTemplate.in_domain(50).all
expect(rows.count).to(eq(1))
end
end
end
| 41 | 104 | 0.750185 |
36acdd54b92a33a235fc3e4435a94c5177ceea53 | 1,368 | dart | Dart | system_metrics_widget/lib/src/widgets/metrics/usage_indicator/usage_indicator_widget.dart | DisDis/dslideshow | 58e9b2afbcd43c7c7f99a2382dd109bcef5c4185 | [
"MIT"
] | 1 | 2021-04-29T14:49:00.000Z | 2021-04-29T14:49:00.000Z | system_metrics_widget/lib/src/widgets/metrics/usage_indicator/usage_indicator_widget.dart | DisDis/dslideshow | 58e9b2afbcd43c7c7f99a2382dd109bcef5c4185 | [
"MIT"
] | null | null | null | system_metrics_widget/lib/src/widgets/metrics/usage_indicator/usage_indicator_widget.dart | DisDis/dslideshow | 58e9b2afbcd43c7c7f99a2382dd109bcef5c4185 | [
"MIT"
] | 1 | 2021-07-15T18:34:22.000Z | 2021-07-15T18:34:22.000Z | import 'dart:math';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:system_metrics_widget/src/environment/settings.dart';
import 'package:system_metrics_widget/src/widgets/metrics/usage_indicator/usage_bar.dart';
abstract class UsageIndicatorWidget extends StatelessWidget {
final String title;
final String total;
final String free;
final String used;
final int? usagePercent;
UsageIndicatorWidget({
required this.title,
required this.total,
required this.free,
required this.used,
required this.usagePercent,
});
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'$title: $total, used: $used, free: $free, usage $usagePercent %',
style: Settings.metricsDetailsTextStyle,
),
Padding(
padding: EdgeInsets.only(top: 4),
child: UsageBar(
usagePercent: usagePercent,
),
),
],
);
}
static String formatBytes(int bytes, int decimals) {
if (bytes <= 0) return '0 B';
const suffixes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
var i = (log(bytes) / log(1024)).floor();
return ((bytes / pow(1024, i)).toStringAsFixed(decimals)) + ' ' + suffixes[i];
}
}
| 27.918367 | 90 | 0.642544 |
e757532b5c3675f95132dd20a4012873a2c5e6be | 419 | php | PHP | src/Command/FlipHorizontalCommand.php | fcomby4/ImageMerge | f528dbd5796a7ec129fd3085938843576517e088 | [
"MIT"
] | 3 | 2019-11-25T15:58:40.000Z | 2021-03-29T15:36:44.000Z | src/Command/FlipHorizontalCommand.php | fcomby4/ImageMerge | f528dbd5796a7ec129fd3085938843576517e088 | [
"MIT"
] | 2 | 2018-11-29T18:46:38.000Z | 2020-05-06T07:56:18.000Z | src/Command/FlipHorizontalCommand.php | fcomby4/ImageMerge | f528dbd5796a7ec129fd3085938843576517e088 | [
"MIT"
] | 1 | 2018-04-03T21:27:51.000Z | 2018-04-03T21:27:51.000Z | <?php
namespace Jackal\ImageMerge\Command;
use Jackal\ImageMerge\Model\Image;
/**
* Class FlipHorizontalCommand
* @package Jackal\ImageMerge\Command
*/
class FlipHorizontalCommand extends AbstractCommand
{
/**
* @param Image $image
* @return Image
*/
public function execute(Image $image)
{
imageflip($image->getResource(), IMG_FLIP_HORIZONTAL);
return $image;
}
}
| 17.458333 | 62 | 0.668258 |
8e7baf6a35f59e02babf7d7f1b9d81bfce3d40f8 | 795 | js | JavaScript | diskreet-blockchain/ts/session/messages/outgoing/controlMessage/group/ClosedGroupEncryptionPairRequestMessage.js | woflydev/general-projects | 4ab637fabd2b8ff563ec1637eccefed780bce163 | [
"MIT"
] | 1 | 2022-03-13T22:46:43.000Z | 2022-03-13T22:46:43.000Z | diskreet-blockchain/ts/session/messages/outgoing/controlMessage/group/ClosedGroupEncryptionPairRequestMessage.js | woflydev/general-projects | 4ab637fabd2b8ff563ec1637eccefed780bce163 | [
"MIT"
] | null | null | null | diskreet-blockchain/ts/session/messages/outgoing/controlMessage/group/ClosedGroupEncryptionPairRequestMessage.js | woflydev/general-projects | 4ab637fabd2b8ff563ec1637eccefed780bce163 | [
"MIT"
] | null | null | null | "use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ClosedGroupEncryptionPairRequestMessage = void 0;
const protobuf_1 = require("../../../../../protobuf");
const ClosedGroupMessage_1 = require("./ClosedGroupMessage");
class ClosedGroupEncryptionPairRequestMessage extends ClosedGroupMessage_1.ClosedGroupMessage {
dataProto() {
throw new Error('ClosedGroupEncryptionPairRequestMessage: This is unused for now ');
const dataMessage = super.dataProto();
dataMessage.closedGroupControlMessage.type =
protobuf_1.SignalService.DataMessage.ClosedGroupControlMessage.Type.ENCRYPTION_KEY_PAIR_REQUEST;
return dataMessage;
}
}
exports.ClosedGroupEncryptionPairRequestMessage = ClosedGroupEncryptionPairRequestMessage;
| 49.6875 | 108 | 0.774843 |
5da4c4c25c5180de10e006f11ebaa79e2b4777e8 | 4,925 | cpp | C++ | Crowny/Source/Crowny/Scripting/Mono/MonoMethod.cpp | bojosos/Nworc | a59cb18412a45a101f877caedf6ed0025a9e44a9 | [
"MIT"
] | 2 | 2021-05-13T17:57:04.000Z | 2021-10-04T07:07:01.000Z | Crowny/Source/Crowny/Scripting/Mono/MonoMethod.cpp | bojosos/Crowny | 5aef056d2c95e04870d2372a87257ad9dccf168a | [
"MIT"
] | null | null | null | Crowny/Source/Crowny/Scripting/Mono/MonoMethod.cpp | bojosos/Crowny | 5aef056d2c95e04870d2372a87257ad9dccf168a | [
"MIT"
] | null | null | null | #include "cwpch.h"
#include "Crowny/Scripting/Mono/MonoClass.h"
#include "Crowny/Scripting/Mono/MonoManager.h"
#include "Crowny/Scripting/Mono/MonoMethod.h"
#include "Crowny/Scripting/Mono/MonoUtils.h"
#include <mono/metadata/attrdefs.h>
#include <mono/metadata/debug-helpers.h>
#include <mono/metadata/loader.h>
#include <mono/metadata/object.h>
#include <mono/metadata/reflection.h>
namespace Crowny
{
MonoMethod::MonoMethod(::MonoMethod* method)
: m_Method(method), m_CachedParams(nullptr), m_CachedReturnType(nullptr), m_HasCachedSignature(false),
m_CachedNumParams(0)
{
m_Name = mono_method_get_name(m_Method);
m_FullDeclName = CrownyMonoVisibilityToString(GetVisibility()) + (IsStatic() ? " static " : " ") +
mono_method_full_name(m_Method, true);
}
MonoClass* MonoMethod::GetParameterType(uint32_t idx) const
{
if (!m_HasCachedSignature)
CacheSignature();
if (idx >= m_CachedNumParams)
{
CW_ENGINE_ERROR("Param index out of range.");
return nullptr;
}
return m_CachedParams[idx];
}
MonoObject* MonoMethod::Invoke(MonoObject* instance, void** params)
{
MonoObject* exception = nullptr;
MonoObject* ret = mono_runtime_invoke(m_Method, instance, params, &exception);
MonoUtils::CheckException(exception);
return ret;
}
void* MonoMethod::GetThunk() const { return mono_method_get_unmanaged_thunk(m_Method); }
bool MonoMethod::HasAttribute(MonoClass* monoClass) const
{
MonoCustomAttrInfo* info = mono_custom_attrs_from_method(m_Method);
if (info == nullptr)
return false;
bool hasAttrs = mono_custom_attrs_has_attr(info, monoClass->GetInternalPtr()) != 0;
mono_custom_attrs_free(info);
return hasAttrs;
}
MonoObject* MonoMethod::GetAttribute(MonoClass* monoClass) const
{
MonoCustomAttrInfo* info = mono_custom_attrs_from_method(m_Method);
if (info == nullptr)
return nullptr;
MonoObject* attrs = nullptr;
if (mono_custom_attrs_has_attr(info, monoClass->GetInternalPtr()))
{
attrs = mono_custom_attrs_get_attr(info, monoClass->GetInternalPtr());
}
mono_custom_attrs_free(info);
return attrs;
}
bool MonoMethod::IsStatic() const
{
if (!m_HasCachedSignature)
CacheSignature();
return m_IsStatic;
}
MonoClass* MonoMethod::GetReturnType() const
{
if (!m_HasCachedSignature)
CacheSignature();
return m_CachedReturnType;
}
void MonoMethod::CacheSignature() const
{
MonoMethodSignature* signature = mono_method_signature(m_Method);
MonoType* returnType = mono_signature_get_return_type(signature);
if (returnType != nullptr)
{
::MonoClass* returnTypeClass = mono_class_from_mono_type(returnType);
if (returnTypeClass != nullptr)
m_CachedReturnType = MonoManager::Get().FindClass(returnTypeClass);
}
m_CachedNumParams = (uint32_t)mono_signature_get_param_count(signature);
if (m_CachedParams != nullptr)
{
delete[] m_CachedParams;
m_CachedParams = nullptr;
}
if (m_CachedNumParams > 0)
{
m_CachedParams = new MonoClass*[m_CachedNumParams];
void* iter = nullptr;
for (uint32_t i = 0; i < m_CachedNumParams; i++)
{
MonoType* curParamType = mono_signature_get_params(signature, &iter);
::MonoClass* returnTypeClass = mono_class_from_mono_type(curParamType);
m_CachedParams[i] = MonoManager::Get().FindClass(returnTypeClass);
}
}
m_IsStatic = !mono_signature_is_instance(signature);
m_HasCachedSignature = true;
}
uint32_t MonoMethod::GetNumParams() const
{
if (!m_HasCachedSignature)
CacheSignature();
return m_CachedNumParams;
}
CrownyMonoVisibility MonoMethod::GetVisibility()
{
uint32_t flags = mono_method_get_flags(m_Method, nullptr) & MONO_METHOD_ATTR_ACCESS_MASK;
switch (flags)
{
case (MONO_METHOD_ATTR_PRIVATE):
return CrownyMonoVisibility::Private;
case (MONO_METHOD_ATTR_FAM_AND_ASSEM):
return CrownyMonoVisibility::ProtectedInternal;
case (MONO_METHOD_ATTR_ASSEM):
return CrownyMonoVisibility::Internal;
case (MONO_METHOD_ATTR_FAMILY):
return CrownyMonoVisibility::Protected;
case (MONO_METHOD_ATTR_PUBLIC):
return CrownyMonoVisibility::Public;
}
CW_ENGINE_ASSERT(false, "Unknown visibility.");
return CrownyMonoVisibility::Private;
}
} // namespace Crowny | 32.615894 | 108 | 0.643249 |
f4150d3f87fa6a55d8888e91c88b7b94104e26d5 | 496 | cs | C# | 15. DESIGN PATTERNS/03. Behavioral Patterns/11. Visitor/VisitorDemo.cs | pirocorp/Databases-Advanced---Entity-Framework | c2be979fa9a35a184bbcac87458524ad5e5f7fea | [
"MIT"
] | null | null | null | 15. DESIGN PATTERNS/03. Behavioral Patterns/11. Visitor/VisitorDemo.cs | pirocorp/Databases-Advanced---Entity-Framework | c2be979fa9a35a184bbcac87458524ad5e5f7fea | [
"MIT"
] | null | null | null | 15. DESIGN PATTERNS/03. Behavioral Patterns/11. Visitor/VisitorDemo.cs | pirocorp/Databases-Advanced---Entity-Framework | c2be979fa9a35a184bbcac87458524ad5e5f7fea | [
"MIT"
] | null | null | null | namespace _11._Visitor
{
public static class VisitorDemo
{
public static void Main()
{
// Setup employee collection
var employees = new Employees();
employees.Attach(new Clerk());
employees.Attach(new Director());
employees.Attach(new President());
// Employees are 'visited'
employees.Accept(new IncomeVisitor());
employees.Accept(new VacationVisitor());
}
}
}
| 26.105263 | 52 | 0.552419 |
a35633fbaaf562d9b6354a1d5855a43f1fe56bbd | 3,733 | tsx | TypeScript | front/components/menu/accessibility.component.tsx | OMoukoko/1000jours | 1ca613176993016a2b1797e2f038d018b28bce2e | [
"Apache-2.0"
] | 8 | 2021-02-11T17:05:16.000Z | 2021-10-09T09:09:05.000Z | front/components/menu/accessibility.component.tsx | OMoukoko/1000jours | 1ca613176993016a2b1797e2f038d018b28bce2e | [
"Apache-2.0"
] | 993 | 2021-02-16T10:08:34.000Z | 2022-03-31T16:35:50.000Z | front/components/menu/accessibility.component.tsx | OMoukoko/1000jours | 1ca613176993016a2b1797e2f038d018b28bce2e | [
"Apache-2.0"
] | 6 | 2021-02-11T17:05:20.000Z | 2021-12-07T16:53:55.000Z | import type { FC } from "react";
import * as React from "react";
import { StyleSheet, View } from "react-native";
import { Paddings } from "../../constants";
import ModalHtmlContent from "../base/modalHtmlContent.component";
import A from "../html/a.component";
import H1 from "../html/h1.component";
import H2 from "../html/h2.component";
import Li from "../html/li.component";
import P from "../html/p.component";
interface Props {
setIsVisible: (showMenu: boolean) => void;
}
const Accessibility: FC<Props> = ({ setIsVisible }) => {
const content = (
<View>
<H1>Accessibilité</H1>
<H2>Déclaration d’accessibilité</H2>
<P>
Le Ministère du travail, de l’emploi et de l’insertion s’engage à rendre
son service accessible conformément à l’article 47 de la loi n° 2005-102
du 11 février 2005.
</P>
<P>
À cette fin, il met en œuvre la stratégie et l’action suivante :
réalisation d’un audit de conformité à l'été de l’année 2021.
</P>
<P>
Cette déclaration d’accessibilité s’applique à l'application "1000
premiers jours".
</P>
<H2>État de conformité</H2>
<P>
l'application "1000 premiers jours" n’est pas encore en conformité avec
le référentiel général d’amélioration de l’accessibilité (RGAA). Le site
n’a pas encore été audité.
</P>
<P>
Nous tâchons de rendre dès la conception, ce site accessible à toutes et
à tous.
</P>
<H2>Résultat des tests</H2>
<P>
L’audit de conformité est en attente de réalisation (été de l’année
2021).
</P>
<H2>Établissement de cette déclaration d’accessibilité</H2>
<P>Cette déclaration a été établie le 1er juin 2021.</P>
<H2>Amélioration et contact</H2>
<P>
Si vous n’arrivez pas à accéder à un contenu ou à un service, vous
pouvez contacter le responsable du site Internet
index-egapro.travail.gouv.fr pour être orienté vers une alternative
accessible ou obtenir le contenu sous une autre forme.
</P>
<P>E-mail :</P>
<A url="mailto:[email protected]">
[email protected]
</A>
<P>Nous essayons de répondre le plus rapidement possible.</P>
<H2>Voies de recours</H2>
<P>Cette procédure est à utiliser dans le cas suivant.</P>
<P>
Vous avez signalé au responsable du site internet un défaut
d’accessibilité qui vous empêche d’accéder à un contenu ou à un des
services du portail et vous n’avez pas obtenu de réponse satisfaisante.
</P>
<P>Vous pouvez :</P>
<View style={styles.ul}>
<Li>Écrire un message au Défenseur des droits</Li>
<Li>Contacter le délégué du Défenseur des droits dans votre région</Li>
<Li>
Envoyer un courrier par la poste (gratuit, ne pas mettre de timbre) :
</Li>
<View style={styles.ul}>
<Li>Défenseur des droits</Li>
<Li>Libre réponse</Li>
<Li>71120 75342 Paris CEDEX 07</Li>
</View>
</View>
<H2>En savoir plus sur l’accessibilité</H2>
<P>
Pour en savoir plus sur la politique d’accessibilité numérique de l’État
:
</P>
<A url="http://references.modernisation.gouv.fr/accessibilite-numerique">
Référentiel général d'amélioration de l'accessibilité
</A>
</View>
);
return <ModalHtmlContent setIsVisible={setIsVisible} content={content} />;
};
const styles = StyleSheet.create({
ul: {
paddingLeft: Paddings.light,
paddingTop: Paddings.light,
},
});
export default Accessibility;
| 33.330357 | 80 | 0.633539 |
74696dbb9cfa26e948106005a5db8b4e5781bfa6 | 506 | css | CSS | stylesheet/css/css.css | alfaben12/kprpllasttask | d47e9c9e6e1fbde5f66203fcacb3ad27fa45b062 | [
"Apache-2.0"
] | null | null | null | stylesheet/css/css.css | alfaben12/kprpllasttask | d47e9c9e6e1fbde5f66203fcacb3ad27fa45b062 | [
"Apache-2.0"
] | null | null | null | stylesheet/css/css.css | alfaben12/kprpllasttask | d47e9c9e6e1fbde5f66203fcacb3ad27fa45b062 | [
"Apache-2.0"
] | null | null | null | <head>
<style type="text/css">
* {
box-sizing:border-box;
}
.clearfix:after {
content: "";
display: table;
clear: both;
}
.divide1{
float: left;
width:50%;
padding-right: 10px;
}
.divide2{
float: left;
width:50%;
padding-left: 10px;
}
@media screen and (max-width: 900px){
.divide1{
float: none;
width:100%;
padding:0 0 10px 0;
}
.divide2{
float: none;
width:100%;
padding: 0 0 10px 0;
}
}
</style>
</head> | 14.457143 | 39 | 0.529644 |
f14325e7f99b05a8d9812fd7c1f0d9dd311edaea | 1,650 | rb | Ruby | db/schema.rb | vovka/echocat--ruby-kata-1 | fd70715c49271b106d2e7c8d5d0ff941535adde2 | [
"MIT"
] | null | null | null | db/schema.rb | vovka/echocat--ruby-kata-1 | fd70715c49271b106d2e7c8d5d0ff941535adde2 | [
"MIT"
] | null | null | null | db/schema.rb | vovka/echocat--ruby-kata-1 | fd70715c49271b106d2e7c8d5d0ff941535adde2 | [
"MIT"
] | null | null | null | # This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# This file is the source Rails uses to define your schema when running `rails
# db:schema:load`. When creating a new database, `rails db:schema:load` tends to
# be faster and is potentially less error prone than running all of your
# migrations from scratch. Old migrations may fail to apply correctly if those
# migrations use external dependencies or application code.
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 2020_12_02_113048) do
create_table "authors", force: :cascade do |t|
t.string "email"
t.string "firstname"
t.string "lastname"
end
create_table "authors_books", force: :cascade do |t|
t.integer "author_id"
t.integer "book_id"
t.index ["author_id"], name: "index_authors_books_on_author_id"
t.index ["book_id"], name: "index_authors_books_on_book_id"
end
create_table "authors_magazines", force: :cascade do |t|
t.integer "author_id"
t.integer "magazine_id"
t.index ["author_id"], name: "index_authors_magazines_on_author_id"
t.index ["magazine_id"], name: "index_authors_magazines_on_magazine_id"
end
create_table "books", force: :cascade do |t|
t.string "title"
t.string "isbn"
t.string "description"
end
create_table "magazines", force: :cascade do |t|
t.string "title"
t.string "isbn"
t.date "publishedAt"
end
end
| 34.375 | 86 | 0.735152 |
b02d364fad492b49625b2e4436c0c11396e28860 | 787 | py | Python | algorithm/greedy/luck_balance/solution.py | delaanthonio/hackerrank | b1f2e1e93b3260be90eb3b8cb8e86e9a700acf27 | [
"MIT"
] | 1 | 2017-07-02T01:35:39.000Z | 2017-07-02T01:35:39.000Z | algorithm/greedy/luck_balance/solution.py | delaanthonio/hackerrank | b1f2e1e93b3260be90eb3b8cb8e86e9a700acf27 | [
"MIT"
] | null | null | null | algorithm/greedy/luck_balance/solution.py | delaanthonio/hackerrank | b1f2e1e93b3260be90eb3b8cb8e86e9a700acf27 | [
"MIT"
] | 1 | 2018-04-03T15:11:56.000Z | 2018-04-03T15:11:56.000Z | #!/usr/bin/env python3
"""
Luck Balance
:author: Dela Anthonio
:hackerrank: https://hackerrank.com/delaanthonio
:problem: https://www.hackerrank.com/challenges/luck-balance
"""
import sys
from typing import List, Tuple
def luck_balance(contests: List[Tuple[int, int]], important) -> int:
important_contests = sorted((l for l, i in contests if i), reverse=True)
luck = 0
luck += sum(important_contests[:important])
luck -= sum(important_contests[important:])
luck += sum(l for l, i in contests if not i)
return luck
def main():
_, important = [int(x) for x in input().split()]
contests = [tuple(int(x) for x in line.split()) for line in sys.stdin]
luck = luck_balance(contests, important)
print(luck)
if __name__ == '__main__':
main()
| 23.848485 | 76 | 0.678526 |
256e798c8115dcca363698389835221d6d074609 | 217 | cs | C# | 3-Data/Source/GameAccess_BlobStorage/GameAccess_BlobStorage/Config.cs | msimecek/Azure-Gaming-Workshop | 31ab13675392f5c2e3f07ac7dd516c784c270757 | [
"MIT"
] | null | null | null | 3-Data/Source/GameAccess_BlobStorage/GameAccess_BlobStorage/Config.cs | msimecek/Azure-Gaming-Workshop | 31ab13675392f5c2e3f07ac7dd516c784c270757 | [
"MIT"
] | null | null | null | 3-Data/Source/GameAccess_BlobStorage/GameAccess_BlobStorage/Config.cs | msimecek/Azure-Gaming-Workshop | 31ab13675392f5c2e3f07ac7dd516c784c270757 | [
"MIT"
] | null | null | null | using System;
using System.Collections.Generic;
using System.Text;
namespace GameAccess_BlobStorage
{
public static class Config
{
public static string ApiUrl = "http://localhost:43551/api";
}
}
| 18.083333 | 67 | 0.709677 |
d66323862f1643a862d1c82fcb1f2fd54c83b7cf | 2,822 | cs | C# | DefaultApplicationBuilderFactory.cs | amh1979/AspNetCore.FileLog | 6f9aadd1929dae6aa0117a652db3f1329edd3834 | [
"MIT"
] | 5 | 2019-01-25T05:03:14.000Z | 2019-12-11T02:31:10.000Z | DefaultApplicationBuilderFactory.cs | amh1979/AspNetCore.FileLog | 6f9aadd1929dae6aa0117a652db3f1329edd3834 | [
"MIT"
] | null | null | null | DefaultApplicationBuilderFactory.cs | amh1979/AspNetCore.FileLog | 6f9aadd1929dae6aa0117a652db3f1329edd3834 | [
"MIT"
] | 3 | 2019-01-03T13:08:27.000Z | 2020-12-17T10:14:49.000Z | /* ===============================================
* 功能描述:AspNetCore.Extensions.Internal.ApplicationBuilderFactory
* 创 建 者:WeiGe
* 创建日期:10/16/2018 6:19:08 PM
* ===============================================*/
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Builder.Internal;
using Microsoft.AspNetCore.Hosting.Builder;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Text;
namespace Microsoft.AspNetCore.Builder
{
internal class DefaultApplicationBuilderFactory : IApplicationBuilderFactory
{
static private ConcurrentBag<BuilderAction> _builderActions
= new ConcurrentBag<BuilderAction>();
private readonly IServiceProvider _serviceProvider;
public DefaultApplicationBuilderFactory(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
//Func<IServiceProvider, List<ServiceDescriptor>> GetDescriptors;
public IApplicationBuilder CreateBuilder(IFeatureCollection serverFeatures)
{
var builder = new ApplicationBuilder(_serviceProvider, serverFeatures);
while (_builderActions!=null&&!_builderActions.IsEmpty)
{
BuilderAction action;
if (_builderActions.TryTake(out action))
{
action.Action?.Invoke(builder);
action.ActionWithState?.Invoke(builder, action.State);
}
else {
throw new Exception("TryTake");
}
}
_builderActions = null;
return builder;
}
public static void OnCreateBuilder(Action<IApplicationBuilder> builderAction)
{
if (builderAction != null)
{
_builderActions.Add(new BuilderAction { Action = builderAction });
}
}
public static void OnCreateBuilder(Action<IApplicationBuilder, object> builderAction, object state)
{
if (state == null)
{
throw new ArgumentNullException(nameof(state), "Please use OnCreateBuilder(Action<IApplicationBuilder> builderAction).");
}
if (builderAction != null)
{
_builderActions.Add(new BuilderAction { ActionWithState = builderAction, State = state });
}
}
class BuilderAction
{
public object State { get; set; }
public Action<IApplicationBuilder, object> ActionWithState { get; set; }
public Action<IApplicationBuilder> Action { get; set; }
}
}
}
| 37.131579 | 137 | 0.60489 |
0a8b2c067fab7ffe6c41f188250f1bf03498abba | 630 | cs | C# | src/Jimu.Client/ApiGateway/Core/JimuQueryStringModelBinderProvider.cs | tianweimol/jimu | e9a1651bb3ad4d98682e4a4c9f43a52f511a66b0 | [
"MIT"
] | null | null | null | src/Jimu.Client/ApiGateway/Core/JimuQueryStringModelBinderProvider.cs | tianweimol/jimu | e9a1651bb3ad4d98682e4a4c9f43a52f511a66b0 | [
"MIT"
] | null | null | null | src/Jimu.Client/ApiGateway/Core/JimuQueryStringModelBinderProvider.cs | tianweimol/jimu | e9a1651bb3ad4d98682e4a4c9f43a52f511a66b0 | [
"MIT"
] | null | null | null | using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ModelBinding.Binders;
using Microsoft.Extensions.Logging.Abstractions;
namespace Jimu.Client.ApiGateway.Core
{
public class JimuQueryStringModelBinderProvider : IModelBinderProvider
{
private readonly IModelBinder _modelBinder = new JimuQueryStringModelBinder(new SimpleTypeModelBinder(typeof(JimuQueryString), new NullLoggerFactory()));
public IModelBinder GetBinder(ModelBinderProviderContext context)
{
return context.Metadata.ModelType == typeof(JimuQueryString) ? _modelBinder : null;
}
}
}
| 39.375 | 161 | 0.771429 |
23cbf7afb2fbea8a740a21a63d20bf5eff431e3a | 1,345 | js | JavaScript | pages/index.js | adeb6600/VoterQ | 67320fdaa210b3c1911922b0f495e7f9dd03b255 | [
"MIT"
] | null | null | null | pages/index.js | adeb6600/VoterQ | 67320fdaa210b3c1911922b0f495e7f9dd03b255 | [
"MIT"
] | null | null | null | pages/index.js | adeb6600/VoterQ | 67320fdaa210b3c1911922b0f495e7f9dd03b255 | [
"MIT"
] | null | null | null | import React from 'react';
import {geolocated} from 'react-geolocated'
import {Query } from 'react-apollo'
import { RegCenterList, allRegCenterQueryVars } from '../data';
import { Index } from '../containers';
const loadData = (props)=>(<Query query = {RegCenterList}
variables ={allRegCenterQueryVars}>
{({loading ,error, data, fetchMore})=>(
<Index
loading ={loading}
error = {error}
allCenters = {data.allRegCenters || []}
loadMorePosts= {()=>fetchMore({
variables: {
skip: data.allRegCenters.length
},
updateQuery : (previousResult, {fetchMoreResult})=>{
if (!fetchMoreResult) {
return previousResult
}
return Object.assign({}, previousResult, {
// Append the new posts results to the old one
allRegCenters: [...previousResult.allRegCenters, ...fetchMoreResult.allRegCenters]
})
}
})
}
/>
)
}
</Query>)
export default geolocated({
positionOptions: {
enableHighAccuracy: false,
},
userDecisionTimeout: 5000,
})(loadData)
| 26.9 | 106 | 0.500372 |
15bc4f36a6c60c26755ab63c3981cf776d6ad024 | 549 | rb | Ruby | lib/terraforming.rb | aloyzio/Terraform-Granular | 5be0161fdd8d982e5869a70dd28f54b480dc77a5 | [
"MIT"
] | null | null | null | lib/terraforming.rb | aloyzio/Terraform-Granular | 5be0161fdd8d982e5869a70dd28f54b480dc77a5 | [
"MIT"
] | null | null | null | lib/terraforming.rb | aloyzio/Terraform-Granular | 5be0161fdd8d982e5869a70dd28f54b480dc77a5 | [
"MIT"
] | null | null | null | require "aws-sdk-core"
require "erb"
require "json"
require "thor"
require "zlib"
require "terraforming/version"
require "terraforming/cli"
require "terraforming/resource"
require "terraforming/resource/db_parameter_group"
require "terraforming/resource/db_security_group"
require "terraforming/resource/db_subnet_group"
require "terraforming/resource/ec2"
require "terraforming/resource/elb"
require "terraforming/resource/rds"
require "terraforming/resource/s3"
require "terraforming/resource/security_group"
require "terraforming/resource/vpc"
| 27.45 | 50 | 0.830601 |
a005a6cd25bb1a159c0d4dc8cea11c6414d4aff5 | 404 | ts | TypeScript | src/utils/filter-unique.rxjs-pipe.ts | justerest/multi-replace | 76624112de8ff3075d2e27e3398c9c7475fb911c | [
"MIT"
] | 2 | 2020-03-10T19:41:59.000Z | 2020-05-30T09:23:23.000Z | src/utils/filter-unique.rxjs-pipe.ts | justerest/multi-replace-vsix | e181321ef3c599ec6c41cd126ee97f3895dd3947 | [
"MIT"
] | 6 | 2020-05-22T18:44:18.000Z | 2021-06-13T08:47:59.000Z | src/utils/filter-unique.rxjs-pipe.ts | justerest/multi-replace-vsix | e181321ef3c599ec6c41cd126ee97f3895dd3947 | [
"MIT"
] | 1 | 2021-08-22T19:23:01.000Z | 2021-08-22T19:23:01.000Z | import { MonoTypeOperatorFunction } from 'rxjs';
import { filter } from 'rxjs/operators';
/**
* RxJs pipable operator.
*/
export function filterUnique<T>(fn: (arg: T) => any = (data) => data): MonoTypeOperatorFunction<T> {
const cache = new Set<string>();
return filter((data) => {
const value = fn(data);
if (!cache.has(value)) {
cache.add(value);
return true;
}
return false;
});
}
| 22.444444 | 100 | 0.638614 |
a183da5d58dba8b8f2378d0ee15225c0f620e53f | 202 | ts | TypeScript | src/types/globals.d.ts | mergemocha/remotr-backend | b94574d1ff10980ac9f05aec5c4ff1ea2e023443 | [
"MIT"
] | null | null | null | src/types/globals.d.ts | mergemocha/remotr-backend | b94574d1ff10980ac9f05aec5c4ff1ea2e023443 | [
"MIT"
] | 34 | 2021-04-26T10:11:02.000Z | 2021-05-25T08:21:52.000Z | src/types/globals.d.ts | mergemocha/remotr-backend | b94574d1ff10980ac9f05aec5c4ff1ea2e023443 | [
"MIT"
] | null | null | null | import winston from 'winston'
declare global {
// eslint-disable-next-line no-var
var logger: winston.Logger
}
declare module 'express-session' {
interface SessionData {
token: string
}
}
| 15.538462 | 36 | 0.707921 |
c6eed6d420f7564a7ea79b8560b3487f4057b0a3 | 2,685 | py | Python | main.py | georgiyermakov/mtrxpcnc | 5e697a0c968a0ca0b5dde7b60daa0c9be7511007 | [
"Apache-2.0"
] | null | null | null | main.py | georgiyermakov/mtrxpcnc | 5e697a0c968a0ca0b5dde7b60daa0c9be7511007 | [
"Apache-2.0"
] | null | null | null | main.py | georgiyermakov/mtrxpcnc | 5e697a0c968a0ca0b5dde7b60daa0c9be7511007 | [
"Apache-2.0"
] | null | null | null |
import telebot
from telebot import types
TOKEN = '403760552:AAH6R0EAKTYAvjsOX1noscBStd7XG1WSnw0'
bot = telebot.TeleBot(TOKEN)
@bot.message_handler(commands=['start'])
def start(m):
"""Отвечаем на команду /start
"""
keyboard = types.InlineKeyboardMarkup()
keyboard.row(*[types.InlineKeyboardButton(text=name, callback_data=name) for name in ['СДЕЛАТЬ КРУТЫЕ БРЭЙДЫ']])
keyboard.row(*[types.InlineKeyboardButton(text=name, callback_data=name) for name in ['СФОТАТЬСЯ В ЗЕЛЕНОМ АВТОБУСЕ']])
keyboard.row(*[types.InlineKeyboardButton(text=name, callback_data=name) for name in ['ПОЛУЧИТЬ СЕКРЕТНУЮ СКИДКУ']])
keyboard.row(*[types.InlineKeyboardButton(text=name, callback_data=name) for name in ['СОХРАНИТЬ МОДНЫЙ СТИКЕРПАК']])
keyboard.row(*[types.InlineKeyboardButton(text=name, callback_data=name) for name in ['СТАТЬ АМБАССАДОРОМ']])
bot.send_message(m.chat.id, "Привет, я чат-бот MATRIX, который будет сегодня жужжать пчелой для всех гостей ПИКНИКА АФИШИ! Давай расскажу, что мы приготовили для тебя сегодня:", reply_markup=keyboard)
@bot.callback_query_handler(func= lambda c: True)
def inline(c):
if c.data == 'СДЕЛАТЬ КРУТЫЕ БРЭЙДЫ':
bot.send_message(chat_id=c.message.chat.id, text="Какой фестиваль можно представить без кос? Команда стилистов MATRIX целый день будет плести яркие брэйды с канекалоном всем желающим абсолютно бесплатно! Для того чтобы записаться, подойди на стойку ресепшн в бьюти-баре MATRIX. Торопись, желающих очень много!")
elif c.data == 'СФОТАТЬСЯ В ЗЕЛЕНОМ АВТОБУСЕ':
bot.send_message(chat_id=c.message.chat.id, text="В нашем зеленом фотобасе можно сделать крутые фото, которые сразу можно отправить себе на почту или распечатать прямо на месте. А если выложить фото в соцсети с #liveRAW и показать нашему промоутеру, то можно получить набор крутых наклеек BIOLAGE RAW. Торопись, количество наклеек ограничено")
elif c.data == 'ПОЛУЧИТЬ СЕКРЕТНУЮ СКИДКУ':
bot.send_message(chat_id=c.message.chat.id, text="Крутые продукты профессионального ухода за волосами MATRIX со скидкой 30% на www.matrix.ru. До конца лета для всех гостей ПИКНИКА по кодовому слову PICNICMATRIX. Ура!")
elif c.data == 'СОХРАНИТЬ МОДНЫЙ СТИКЕРПАК':
bot.send_message(chat_id=c.message.chat.id, text="Лови набор стикеров!")
elif c.data == 'СТАТЬ АМБАССАДОРОМ':
bot.send_message(chat_id=c.message.chat.id, text="Этой осенью запустится профессиональная эко-гамма по уходу за волосами Biolage RAW. Это не просто продукты, это манифест иного образа жизни. Хочешь узнать первым и стать лидером мнений новой гаммы? Оставляй свой e-mail, и мы отправим тебе инструкцию. #liveRAW")
bot.polling() | 78.970588 | 351 | 0.766108 |
9d1ef2f0ab36a21a4ea6b6e3b0cc847d349ec616 | 3,704 | h | C | examples/MobileNetV2/MobileNetV2.h | miaobin/webnn-native | a0aa73dcbc7277d31fefb2a20322d11a88678fae | [
"Apache-2.0"
] | null | null | null | examples/MobileNetV2/MobileNetV2.h | miaobin/webnn-native | a0aa73dcbc7277d31fefb2a20322d11a88678fae | [
"Apache-2.0"
] | null | null | null | examples/MobileNetV2/MobileNetV2.h | miaobin/webnn-native | a0aa73dcbc7277d31fefb2a20322d11a88678fae | [
"Apache-2.0"
] | null | null | null | // Copyright 2021 The WebNN-native Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <webnn/webnn.h>
#include <webnn/webnn_cpp.h>
#include "examples/SampleUtils.h"
class MobileNetV2 {
public:
MobileNetV2(bool nchw);
~MobileNetV2() = default;
bool LoadNCHW(const std::string& weightsPath, bool softmax = true);
bool LoadBatchNormNCHW(const std::string& weightsPath, bool softmax = true);
bool LoadNHWC(const std::string& weightsPath, bool softmax = true);
ml::Result Compute(const void* inputData, size_t inputLength);
const ml::Operand BuildConstantFromNpy(const ml::GraphBuilder& builder,
const std::string& path);
const ml::Operand BuildConv(const ml::GraphBuilder& builder,
const ml::Operand& input,
int32_t convIndex,
bool fused,
utils::Conv2dOptions* options = nullptr,
const std::string& biasName = "");
const ml::Operand BuildConvBatchNorm(const ml::GraphBuilder& builder,
const ml::Operand& input,
int32_t nameIndex,
utils::Conv2dOptions* options = nullptr,
int32_t subNameIndex = -1);
const ml::Operand BuildFire(const ml::GraphBuilder& builder,
const ml::Operand& input,
const std::vector<int32_t>& convIndexes,
int32_t groups,
bool strides = false,
bool shouldAdd = true);
const ml::Operand BuildBatchNormFire(const ml::GraphBuilder& builder,
const ml::Operand& input,
int32_t subNameIndex,
utils::Conv2dOptions* options);
const ml::Operand BuildLinearBottleneck(const ml::GraphBuilder& builder,
const ml::Operand& input,
const std::vector<int32_t>& convIndexes,
int32_t biasIndex,
utils::Conv2dOptions* dwiseOptions,
bool shouldAdd = true);
const ml::Operand BuildFireMore(const ml::GraphBuilder& builder,
const ml::Operand& input,
const std::vector<int32_t>& convIndexes,
const std::vector<int32_t> groups,
bool strides = true);
const ml::Operand BuildGemm(const ml::GraphBuilder& builder,
const ml::Operand& input,
int32_t gemmIndex);
private:
ml::Context mContext;
ml::Graph mGraph;
ml::NamedResults mResults;
bool mNCHW = true;
std::vector<SHARED_DATA_TYPE> mConstants;
std::string mDataPath;
};
| 49.386667 | 84 | 0.528618 |
2cbb88239d05ecb172bf155a8c4485a6b8e67a30 | 1,687 | py | Python | JsonCodeTools/objects_common/enumType.py | kamlam/EAGLE-Open-Model-Profile-and-Tools-1 | 42690535de136251d8a464ad254ac0ea344d383a | [
"Apache-2.0"
] | null | null | null | JsonCodeTools/objects_common/enumType.py | kamlam/EAGLE-Open-Model-Profile-and-Tools-1 | 42690535de136251d8a464ad254ac0ea344d383a | [
"Apache-2.0"
] | null | null | null | JsonCodeTools/objects_common/enumType.py | kamlam/EAGLE-Open-Model-Profile-and-Tools-1 | 42690535de136251d8a464ad254ac0ea344d383a | [
"Apache-2.0"
] | null | null | null | class EnumType(object):
# Internal data storage uses integer running from 0 to range_end
# range_end is set to the number of possible values that the Enum can take on
# External representation of Enum starts at 1 and goes to range_end + 1
def __init__(self, initial_value):
self.set(initial_value)
def load_json(self, json_struct):
self.set(json_struct)
def json_serializer(self):
# Returns a string
# This could be changed to encode enums as integers when transmitting messages
if self.value < 0:
return None
else:
return type(self).possible_values[self.value]
def __str__(self):
return str(self.json_serializer())
def get(self):
# Returns an integer, using the external representation
return self.value + 1
def set(self, value):
# The value to set can be either a string or an integer
if type(value) is str:
# This will raise ValueError for wrong assignments
try:
self.value = type(self).possible_values.index(value)
except ValueError:
raise ValueError('', value, type(self).possible_values)
elif type(value) is int:
if value >= 0 and value <= type(self).range_end:
# External representation of Enum starts at 1, internal at 0. External value 0 by default
# to indicate empty object.
value = value - 1
self.value = value
else:
raise ValueError('', value, type(self).range_end)
else:
raise TypeError('', value, 'string or integer')
| 37.488889 | 105 | 0.608773 |
79a470cd187188312100f9ca493e1a0281186a9e | 243 | php | PHP | app/Commands/ToggleRentalActivationCommand.php | olsfinest/rentgorilla | d02a201e746b316f5cff788a6b1161ceea62e7e3 | [
"MIT"
] | null | null | null | app/Commands/ToggleRentalActivationCommand.php | olsfinest/rentgorilla | d02a201e746b316f5cff788a6b1161ceea62e7e3 | [
"MIT"
] | null | null | null | app/Commands/ToggleRentalActivationCommand.php | olsfinest/rentgorilla | d02a201e746b316f5cff788a6b1161ceea62e7e3 | [
"MIT"
] | null | null | null | <?php namespace RentGorilla\Commands;
use RentGorilla\Commands\Command;
class ToggleRentalActivationCommand extends Command
{
public $rental_id;
function __construct($rental_id)
{
$this->rental_id = $rental_id;
}
}
| 16.2 | 51 | 0.711934 |
b90469d036de6fbbe6fa1b2050fae07ce7076b0f | 2,063 | swift | Swift | IDPDesign/UIKit/Generated/Lens+UINavigationItemGenerated.swift | idapgroup/IDPDesign | a4d5813f77fc000dc8fbe784de473072b487ae37 | [
"BSD-3-Clause"
] | 4 | 2017-10-15T13:27:35.000Z | 2017-12-05T11:32:47.000Z | IDPDesign/UIKit/Generated/Lens+UINavigationItemGenerated.swift | idapgroup/IDPDesign | a4d5813f77fc000dc8fbe784de473072b487ae37 | [
"BSD-3-Clause"
] | null | null | null | IDPDesign/UIKit/Generated/Lens+UINavigationItemGenerated.swift | idapgroup/IDPDesign | a4d5813f77fc000dc8fbe784de473072b487ae37 | [
"BSD-3-Clause"
] | 3 | 2017-09-27T22:07:58.000Z | 2019-03-04T13:00:22.000Z | // Generated using Sourcery 0.9.0 — https://github.com/krzysztofzablocki/Sourcery
// DO NOT EDIT
import UIKit
public func title<Object: UINavigationItem>() -> Lens<Object, String?> {
return Lens(
get: { $0.title },
setter: { $0.title = $1 }
)
}
public func titleView<Object: UINavigationItem>() -> Lens<Object, UIView?> {
return Lens(
get: { $0.titleView },
setter: { $0.titleView = $1 }
)
}
public func prompt<Object: UINavigationItem>() -> Lens<Object, String?> {
return Lens(
get: { $0.prompt },
setter: { $0.prompt = $1 }
)
}
public func backBarButtonItem<Object: UINavigationItem>() -> Lens<Object, UIBarButtonItem?> {
return Lens(
get: { $0.backBarButtonItem },
setter: { $0.backBarButtonItem = $1 }
)
}
public func hidesBackButton<Object: UINavigationItem>() -> Lens<Object, Bool> {
return Lens(
get: { $0.hidesBackButton },
setter: { $0.hidesBackButton = $1 }
)
}
public func leftBarButtonItems<Object: UINavigationItem>() -> Lens<Object, [UIBarButtonItem]?> {
return Lens(
get: { $0.leftBarButtonItems },
setter: { $0.leftBarButtonItems = $1 }
)
}
public func rightBarButtonItems<Object: UINavigationItem>() -> Lens<Object, [UIBarButtonItem]?> {
return Lens(
get: { $0.rightBarButtonItems },
setter: { $0.rightBarButtonItems = $1 }
)
}
public func leftItemsSupplementBackButton<Object: UINavigationItem>() -> Lens<Object, Bool> {
return Lens(
get: { $0.leftItemsSupplementBackButton },
setter: { $0.leftItemsSupplementBackButton = $1 }
)
}
public func leftBarButtonItem<Object: UINavigationItem>() -> Lens<Object, UIBarButtonItem?> {
return Lens(
get: { $0.leftBarButtonItem },
setter: { $0.leftBarButtonItem = $1 }
)
}
public func rightBarButtonItem<Object: UINavigationItem>() -> Lens<Object, UIBarButtonItem?> {
return Lens(
get: { $0.rightBarButtonItem },
setter: { $0.rightBarButtonItem = $1 }
)
}
| 27.506667 | 97 | 0.622395 |
0512dc238af505281388cdb767546c95a3ea138b | 1,010 | rb | Ruby | lib/procon_bypass_man/remote_pbm_action.rb | splaspla-hacker/procon_bypass_man | 473c03847eb4ea33a08f897cfbe933fd78a674eb | [
"MIT"
] | 6 | 2022-01-05T11:01:53.000Z | 2022-02-18T03:54:46.000Z | lib/procon_bypass_man/remote_pbm_action.rb | splaspla-hacker/procon_bypass_man | 473c03847eb4ea33a08f897cfbe933fd78a674eb | [
"MIT"
] | 20 | 2021-11-28T11:18:44.000Z | 2022-03-04T11:40:38.000Z | lib/procon_bypass_man/remote_pbm_action.rb | splaspla-hacker/procon_bypass_man | 473c03847eb4ea33a08f897cfbe933fd78a674eb | [
"MIT"
] | null | null | null | module ProconBypassMan
module RemotePbmAction
require "procon_bypass_man/remote_pbm_action/base_action"
require "procon_bypass_man/remote_pbm_action/change_pbm_version_action"
require "procon_bypass_man/remote_pbm_action/reboot_os_action"
require "procon_bypass_man/remote_pbm_action/stop_pbm_action"
require "procon_bypass_man/remote_pbm_action/restore_pbm_setting.rb"
require "procon_bypass_man/remote_pbm_action/commands/update_remote_pbm_action_status_command"
ACTION_CHANGE_PBM_VERSION = "change_pbm_version"
ACTION_REBOOT_OS = "reboot_os"
ACTION_STOP_PBM = "stop_pbm"
ACTION_RESTORE_SETTING = "restore_pbm_setting"
ACTIONS = [
ACTION_CHANGE_PBM_VERSION,
ACTION_REBOOT_OS,
ACTION_STOP_PBM,
ACTION_RESTORE_SETTING,
]
STATUS_FAILED = :failed
STATUS_IN_PROGRESS = :in_progress
STATUS_PROCESSED = :processed
ACTION_STATUSES = [
STATUS_FAILED,
STATUS_IN_PROGRESS,
STATUS_PROCESSED,
]
end
end
| 30.606061 | 98 | 0.773267 |
82391e9cca087717cd0b9a00c0a25aa968ffc2b9 | 13,261 | hxx | C++ | rutil/SharedPtr.hxx | dulton/reSipServer | ac4241df81c1e3eef2e678271ffef4dda1fc6747 | [
"Apache-2.0"
] | 1 | 2019-04-15T14:10:58.000Z | 2019-04-15T14:10:58.000Z | rutil/SharedPtr.hxx | dulton/reSipServer | ac4241df81c1e3eef2e678271ffef4dda1fc6747 | [
"Apache-2.0"
] | null | null | null | rutil/SharedPtr.hxx | dulton/reSipServer | ac4241df81c1e3eef2e678271ffef4dda1fc6747 | [
"Apache-2.0"
] | 2 | 2019-10-31T09:11:09.000Z | 2021-09-17T01:00:49.000Z | #if !defined(RESIP_SHAREDPTR_HXX)
#define RESIP_SHAREDPTR_HXX
/**
@file
@brief Defines a reference-counted pointer class.
@note This implementation is a modified version of shared_ptr from
Boost.org. License text is below.
http://www.boost.org/libs/smart_ptr/shared_ptr.htm
*/
#include "rutil/SharedCount.hxx"
#include <memory> // for std::auto_ptr
#include <algorithm> // for std::swap
#include <functional> // for std::less
#include <typeinfo> // for std::bad_cast
#include <iosfwd> // for std::basic_ostream
#include <cassert>
namespace resip
{
template<class T> class enable_shared_from_this;
struct static_cast_tag {};
struct const_cast_tag {};
struct dynamic_cast_tag {};
struct polymorphic_cast_tag {};
template<class T> struct SharedPtr_traits
{
typedef T & reference;
};
template<> struct SharedPtr_traits<void>
{
typedef void reference;
};
template<> struct SharedPtr_traits<void const>
{
typedef void reference;
};
template<> struct SharedPtr_traits<void volatile>
{
typedef void reference;
};
template<> struct SharedPtr_traits<void const volatile>
{
typedef void reference;
};
// enable_shared_from_this support
template<class T, class Y> void sp_enable_shared_from_this( shared_count const & pn, resip::enable_shared_from_this<T> const * pe, Y const * px )
{
if(pe != 0) pe->_internal_weak_this._internal_assign(const_cast<Y*>(px), pn);
}
inline void sp_enable_shared_from_this( shared_count const & /*pn*/, ... )
{
}
/**
@brief Implements reference counted copy semantics for a class T.
The object pointed to is deleted when the last SharedPtr pointing to it
is destroyed or reset.
*/
template<class T> class SharedPtr
{
private:
// Borland 5.5.1 specific workaround
typedef SharedPtr<T> this_type;
public:
typedef T element_type;
typedef T value_type;
typedef T * pointer;
typedef typename SharedPtr_traits<T>::reference reference;
SharedPtr(): px(0), pn() // never throws in 1.30+
{
}
template<class Y>
explicit SharedPtr(Y * p): px(p), pn(p, checked_deleter<Y>()) // Y must be complete
{
sp_enable_shared_from_this( pn, p, p );
}
//
// Requirements: D's copy constructor must not throw
//
// SharedPtr will release p by calling d(p)
//
template<class Y, class D> SharedPtr(Y * p, D d): px(p), pn(p, d)
{
sp_enable_shared_from_this( pn, p, p );
}
// generated copy constructor, assignment, destructor are fine...
// except that Borland C++ has a bug, and g++ with -Wsynth warns
#if defined(__BORLANDC__) || defined(__GNUC__)
SharedPtr & operator=(SharedPtr const & r) // never throws
{
px = r.px;
pn = r.pn; // shared_count::op= doesn't throw
return *this;
}
#endif
template<class Y>
SharedPtr(SharedPtr<Y> const & r): px(r.px), pn(r.pn) // never throws
{
}
template<class Y>
SharedPtr(SharedPtr<Y> const & r, static_cast_tag): px(static_cast<element_type *>(r.px)), pn(r.pn)
{
}
template<class Y>
SharedPtr(SharedPtr<Y> const & r, const_cast_tag): px(const_cast<element_type *>(r.px)), pn(r.pn)
{
}
template<class Y>
SharedPtr(SharedPtr<Y> const & r, dynamic_cast_tag): px(dynamic_cast<element_type *>(r.px)), pn(r.pn)
{
if(px == 0) // need to allocate new counter -- the cast failed
{
pn = resip::shared_count();
}
}
template<class Y>
SharedPtr(SharedPtr<Y> const & r, polymorphic_cast_tag): px(dynamic_cast<element_type *>(r.px)), pn(r.pn)
{
if(px == 0)
{
throw std::bad_cast();
}
}
template<class Y>
explicit SharedPtr(std::auto_ptr<Y> & r): px(r.get()), pn()
{
Y * tmp = r.get();
pn = shared_count(r);
sp_enable_shared_from_this( pn, tmp, tmp );
}
template<class Y>
SharedPtr & operator=(SharedPtr<Y> const & r) // never throws
{
px = r.px;
pn = r.pn; // shared_count::op= doesn't throw
return *this;
}
template<class Y>
SharedPtr & operator=(std::auto_ptr<Y> & r)
{
this_type(r).swap(*this);
return *this;
}
void reset() // never throws in 1.30+
{
this_type().swap(*this);
}
template<class Y> void reset(Y * p) // Y must be complete
{
assert(p == 0 || p != px); // catch self-reset errors
this_type(p).swap(*this);
}
template<class Y, class D> void reset(Y * p, D d)
{
this_type(p, d).swap(*this);
}
reference operator* () const // never throws
{
assert(px != 0);
return *px;
}
T * operator-> () const // never throws
{
assert(px != 0);
return px;
}
T * get() const // never throws
{
return px;
}
// implicit conversion to "bool"
#if defined(__SUNPRO_CC) // BOOST_WORKAROUND(__SUNPRO_CC, <= 0x530)
operator bool () const
{
return px != 0;
}
#elif defined(__MWERKS__) // BOOST_WORKAROUND(__MWERKS__, BOOST_TESTED_AT(0x3003))
typedef T * (this_type::*unspecified_bool_type)() const;
operator unspecified_bool_type() const // never throws
{
return px == 0? 0: &this_type::get;
}
#else
typedef T * this_type::*unspecified_bool_type;
operator unspecified_bool_type() const // never throws
{
return px == 0? 0: &this_type::px;
}
#endif
// operator! is redundant, but some compilers need it
bool operator! () const // never throws
{
return px == 0;
}
bool unique() const // never throws
{
return pn.unique();
}
long use_count() const // never throws
{
return pn.use_count();
}
void swap(SharedPtr<T> & other) // never throws
{
std::swap(px, other.px);
pn.swap(other.pn);
}
template<class Y> bool _internal_less(SharedPtr<Y> const & rhs) const
{
return pn < rhs.pn;
}
void * _internal_get_deleter(std::type_info const & ti) const
{
return pn.get_deleter(ti);
}
// Tasteless as this may seem, making all members public allows member templates
// to work in the absence of member template friends. (Matthew Langston)
private:
template<class Y> friend class SharedPtr;
T * px; // contained pointer
shared_count pn; // reference counter
}; // SharedPtr
template<class T, class U> inline bool operator==(SharedPtr<T> const & a, SharedPtr<U> const & b)
{
return a.get() == b.get();
}
template<class T, class U> inline bool operator!=(SharedPtr<T> const & a, SharedPtr<U> const & b)
{
return a.get() != b.get();
}
#if __GNUC__ == 2 && __GNUC_MINOR__ <= 96
// Resolve the ambiguity between our op!= and the one in rel_ops
template<class T> inline bool operator!=(SharedPtr<T> const & a, SharedPtr<T> const & b)
{
return a.get() != b.get();
}
#endif
template<class T, class U> inline bool operator<(SharedPtr<T> const & a, SharedPtr<U> const & b)
{
return a._internal_less(b);
}
template<class T> inline void swap(SharedPtr<T> & a, SharedPtr<T> & b)
{
a.swap(b);
}
template<class T, class U> SharedPtr<T> static_pointer_cast(SharedPtr<U> const & r)
{
return SharedPtr<T>(r, static_cast_tag());
}
template<class T, class U> SharedPtr<T> const_pointer_cast(SharedPtr<U> const & r)
{
return SharedPtr<T>(r, const_cast_tag());
}
template<class T, class U> SharedPtr<T> dynamic_pointer_cast(SharedPtr<U> const & r)
{
return SharedPtr<T>(r, dynamic_cast_tag());
}
// shared_*_cast names are deprecated. Use *_pointer_cast instead.
template<class T, class U> SharedPtr<T> shared_static_cast(SharedPtr<U> const & r)
{
return SharedPtr<T>(r, static_cast_tag());
}
template<class T, class U> SharedPtr<T> shared_dynamic_cast(SharedPtr<U> const & r)
{
return SharedPtr<T>(r, dynamic_cast_tag());
}
template<class T, class U> SharedPtr<T> shared_polymorphic_cast(SharedPtr<U> const & r)
{
return SharedPtr<T>(r, polymorphic_cast_tag());
}
template<class T, class U> SharedPtr<T> shared_polymorphic_downcast(SharedPtr<U> const & r)
{
assert(dynamic_cast<T *>(r.get()) == r.get());
return shared_static_cast<T>(r);
}
template<class T> inline T * get_pointer(SharedPtr<T> const & p)
{
return p.get();
}
// operator<<
#if defined(__GNUC__) && (__GNUC__ < 3)
template<class Y> EncodeStream & operator<< (EncodeStream & os, SharedPtr<Y> const & p)
{
os << p.get();
return os;
}
#else
template<class E, class T, class Y> std::basic_ostream<E, T> & operator<< (std::basic_ostream<E, T> & os, SharedPtr<Y> const & p)
{
os << p.get();
return os;
}
#endif
// get_deleter (experimental)
#if (defined(__GNUC__) && (__GNUC__ < 3)) || (defined(__EDG_VERSION__) && (__EDG_VERSION__ <= 238))
// g++ 2.9x doesn't allow static_cast<X const *>(void *)
// apparently EDG 2.38 also doesn't accept it
template<class D, class T> D * get_deleter(SharedPtr<T> const & p)
{
void const * q = p._internal_get_deleter(typeid(D));
return const_cast<D *>(static_cast<D const *>(q));
}
#else
template<class D, class T> D * get_deleter(SharedPtr<T> const & p)
{
return static_cast<D *>(p._internal_get_deleter(typeid(D)));
}
#endif
} // namespace resip
#endif
// Note: This implementation is a modified version of shared_ptr from
// Boost.org
//
// http://www.boost.org/libs/smart_ptr/shared_ptr.htm
//
/* ====================================================================
*
* Boost Software License - Version 1.0 - August 17th, 2003
*
* Permission is hereby granted, free of charge, to any person or organization
* obtaining a copy of the software and accompanying documentation covered by
* this license (the "Software") to use, reproduce, display, distribute,
* execute, and transmit the Software, and to prepare derivative works of the
* Software, and to permit third-parties to whom the Software is furnished to
* do so, all subject to the following:
*
* The copyright notices in the Software and this entire statement, including
* the above license grant, this restriction and the following disclaimer,
* must be included in all copies of the Software, in whole or in part, and
* all derivative works of the Software, unless such copies or derivative
* works are solely in the form of machine-executable object code generated by
* a source language processor.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
* SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
* FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* ====================================================================
*/
/* ====================================================================
* The Vovida Software License, Version 1.0
*
* Copyright (c) 2000 Vovida Networks, Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The names "VOCAL", "Vovida Open Communication Application Library",
* and "Vovida Open Communication Application Library (VOCAL)" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact [email protected].
*
* 4. Products derived from this software may not be called "VOCAL", nor
* may "VOCAL" appear in their name, without prior written
* permission of Vovida Networks, Inc.
*
* THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND
* NON-INFRINGEMENT ARE DISCLAIMED. IN NO EVENT SHALL VOVIDA
* NETWORKS, INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT DAMAGES
* IN EXCESS OF $1,000, NOR FOR ANY INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*
* ====================================================================
*
* This software consists of voluntary contributions made by Vovida
* Networks, Inc. and many individuals on behalf of Vovida Networks,
* Inc. For more information on Vovida Networks, Inc., please see
* <http://www.vovida.org/>.
*
*/
| 28.396146 | 145 | 0.660131 |
dda2b90a2bd4a911ebb325dfb5248e19d573fae1 | 1,602 | py | Python | src/network_state_graph.py | RoseBay-Consulting/BlockSim | 95dcf2fde05877bdcf59610fd3c3a3314b892f6c | [
"MIT"
] | 13 | 2019-03-14T09:01:51.000Z | 2020-11-21T18:46:59.000Z | src/network_state_graph.py | RoseBay-Consulting/BlockSim | 95dcf2fde05877bdcf59610fd3c3a3314b892f6c | [
"MIT"
] | null | null | null | src/network_state_graph.py | RoseBay-Consulting/BlockSim | 95dcf2fde05877bdcf59610fd3c3a3314b892f6c | [
"MIT"
] | 12 | 2019-03-14T07:54:29.000Z | 2021-04-13T16:57:23.000Z | #import matplotlib.pyplot as plt
import networkx as nx
import numpy as np
import pandas as pd
import random
# use graphviz
def show_network(data,labels):
pass
def csv_loader():
data = pd.read_csv("config/network_model.csv")
data.set_index('node',inplace=True)
nodes=data.columns.tolist()
nodeID=[int(i) for i in nodes]
network_df = pd.DataFrame(data.values,columns=nodeID,index=nodeID)
print(network_df)
graph = nx.from_numpy_matrix(network_df.values)
#nx.draw(graph)
#plt.show()
return network_df,nodeID
def network_creator(nodeID,max_latency):
'''
Arguments:
1. nodeID : List of nodes ID
2. max_latency: Maximum latency to be asserted in communication between nodes
For future improvements, make sure to handle an unconnected node.
'''
dimension= len(nodeID)
# Generate a random adjency matrix of size dimension * dimension for lookup table
np.random.seed(7)
x=np.random.randint(2, size=(dimension, dimension))
# Fill diagonal value with 0 for representing 0 latency for self communication.
np.fill_diagonal(x,0)
# Generate a graph
graph = nx.from_numpy_matrix(x)
# Add latency randomly
for (u, v) in graph.edges():
np.random.seed(7)
graph[u][v]['weight'] = random.randint(1,max_latency)
network_df= pd.DataFrame(nx.to_numpy_array(graph),columns=nodeID,index=nodeID)
print("Printing network")
network_df.to_csv('20_nodes.csv',index=False)
# print(network_df)
# nx.draw(graph)
#nx.draw(nx.from_numpy_array(network_df.values))
return network_df | 32.04 | 85 | 0.704744 |
029f7862c89879897231d107e993919270bfa276 | 1,241 | hpp | C++ | src/Event/KeyboardEvent.hpp | billy4479/BillyEngine | df7d519f740d5862c4743872dbf89b3654eeb423 | [
"MIT"
] | 1 | 2021-09-05T20:50:59.000Z | 2021-09-05T20:50:59.000Z | src/Event/KeyboardEvent.hpp | billy4479/sdl-tests | df7d519f740d5862c4743872dbf89b3654eeb423 | [
"MIT"
] | null | null | null | src/Event/KeyboardEvent.hpp | billy4479/sdl-tests | df7d519f740d5862c4743872dbf89b3654eeb423 | [
"MIT"
] | null | null | null | #pragma once
#include "Event.hpp"
#include "KeyCodes.hpp"
namespace BillyEngine {
class KeyboardEvent : public Event {
public:
KeyboardEvent(Key::KeyCode keyCode, Key::Mods::Mods mods)
: m_Key(keyCode), m_Mods(mods) {}
EVENT_CLASS_CATEGORY(EventCategory::Input | EventCategory::Keyboard)
Key::KeyCode GetKeyCode() { return m_Key; }
Key::Mods::Mods GetKeyMods() { return m_Mods; }
protected:
Key::KeyCode m_Key;
Key::Mods::Mods m_Mods;
};
class KeyPressedEvent : public KeyboardEvent {
public:
KeyPressedEvent(const Key::KeyCode keycode, const Key::Mods::Mods mods)
: KeyboardEvent(keycode, mods) {}
std::string ToString() const override {
std::stringstream ss;
ss << "KeyPressedEvent: " << m_Key;
return ss.str();
}
EVENT_CLASS_TYPE(KeyPressed)
};
class KeyReleasedEvent : public KeyboardEvent {
public:
KeyReleasedEvent(const Key::KeyCode keycode, const Key::Mods::Mods mods)
: KeyboardEvent(keycode, mods) {}
std::string ToString() const override {
std::stringstream ss;
ss << "KeyReleasedEvent: " << m_Key;
return ss.str();
}
EVENT_CLASS_TYPE(KeyReleased)
};
} // namespace BillyEngine | 24.82 | 76 | 0.65834 |
7ac1761e47a1ef5a82e37613ca5e23a15e04eacf | 666 | cs | C# | ForoshGahe Mobile/admin/AdminManageSells.aspx.cs | tebyaniyan/ForoshGahe-Mobile | f9b8ec3f0bab5e52420e158907dc9c1c92b21634 | [
"MIT"
] | null | null | null | ForoshGahe Mobile/admin/AdminManageSells.aspx.cs | tebyaniyan/ForoshGahe-Mobile | f9b8ec3f0bab5e52420e158907dc9c1c92b21634 | [
"MIT"
] | null | null | null | ForoshGahe Mobile/admin/AdminManageSells.aspx.cs | tebyaniyan/ForoshGahe-Mobile | f9b8ec3f0bab5e52420e158907dc9c1c92b21634 | [
"MIT"
] | null | null | null | using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class AdminManageSells : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void dg_SelectedIndexChanged(object sender, EventArgs e)
{
SqlDataSource2.DeleteCommand = "DELETE FROM tSells WHERE (fCode = '"+dg.SelectedValue.ToString()+"')";
SqlDataSource2.Delete();
dg.SelectedIndex = -1;
}
}
| 25.615385 | 110 | 0.716216 |
a5755593cdc656f8d04f194f8972fb2ecaa192d2 | 1,686 | dart | Dart | lib/src/repositories/employer_repository/employer_provider.dart | IAmRealPoca/cvideo-employer-mobile | aab821dc66d2eca9c80532c4acbafbd542031fb8 | [
"MIT"
] | null | null | null | lib/src/repositories/employer_repository/employer_provider.dart | IAmRealPoca/cvideo-employer-mobile | aab821dc66d2eca9c80532c4acbafbd542031fb8 | [
"MIT"
] | null | null | null | lib/src/repositories/employer_repository/employer_provider.dart | IAmRealPoca/cvideo-employer-mobile | aab821dc66d2eca9c80532c4acbafbd542031fb8 | [
"MIT"
] | null | null | null | import 'dart:convert';
import 'package:cvideo_employer_mobile/src/app_components/app_components.dart';
import 'package:cvideo_employer_mobile/src/models/models.dart';
class EmployerProvider {
static const successCode = 200;
static final EmployerProvider _instance = EmployerProvider._internal();
EmployerProvider._internal();
factory EmployerProvider() {
return _instance;
}
Future<StatisticsModel> fetchStatistics() async {
String apiToken = await AppStorage.instance.readSecureApiToken();
final response = await AppHttpClient.get(
"/employers/current-employer/statistics",
headers: {"Authorization": "bearer $apiToken"});
if (response.statusCode != successCode) {
throw Exception("Failed to loading!");
}
final dynamic json = jsonDecode(Utf8Decoder().convert(response.bodyBytes));
return StatisticsModel.fromJson(json);
// final response = await rootBundle.loadString("assets/json/statistics.json");
// dynamic json = jsonDecode(response);
// return StatisticsModel.fromJson(json);
}
Future<List<RecruitmentModel>> fetchRecruitments() async {
String apiToken = await AppStorage.instance.readSecureApiToken();
final response = await AppHttpClient.get(
"/employers/current-employer/recruitment-posts",
headers: {"Authorization": "bearer $apiToken"});
if (response.statusCode != successCode) {
throw Exception("Failed to loading!");
}
final List<dynamic> json =
jsonDecode(Utf8Decoder().convert(response.bodyBytes));
return json.map((e) => RecruitmentModel.fromJson(e)).toList();
}
}
| 31.222222 | 84 | 0.692764 |
f3f97eb86f00e4480557299d4653265a5aab66fb | 2,125 | ts | TypeScript | packages/util/src/tailwind-get-classes.ts | twstyled/twstyled-contrib | 7b427c9fe6054b248ab1d0fe3583b24fb36a911e | [
"MIT"
] | 39 | 2021-02-11T15:06:19.000Z | 2022-03-25T23:27:24.000Z | packages/util/src/tailwind-get-classes.ts | twstyled/twstyled-contrib | 7b427c9fe6054b248ab1d0fe3583b24fb36a911e | [
"MIT"
] | 2 | 2021-03-10T10:31:20.000Z | 2021-05-02T05:29:49.000Z | packages/util/src/tailwind-get-classes.ts | twstyled/twstyled-contrib | 7b427c9fe6054b248ab1d0fe3583b24fb36a911e | [
"MIT"
] | 3 | 2021-08-17T13:54:31.000Z | 2021-11-25T01:57:55.000Z | import tailwindData, { createTwClassDictionary } from '@xwind/core'
import { getTwConfigCache, getTwConfigPath } from '.'
function splitAtLastOccurence(src: string, char: string) {
const pos = src.lastIndexOf(char)
return [src.substring(0, pos), src.substring(pos + 1)]
}
function splitAtLastTwoOccurences(src: string, char: string) {
const pos2 = src.lastIndexOf(char)
const pos1 = src.substring(0, pos2 - 1).lastIndexOf(char)
return [
src.substring(0, pos1),
src.substring(pos1 + 1, pos2),
src.substring(pos2 + 1)
]
}
let $twAttributes: string[]
let $twVariants: string[]
export default function getTailwindAttributesAndVariants(options: {
configPath: string
}): [string[], string[]] {
const twConfigPath = getTwConfigPath(options.configPath)
const { twConfig, isNewTwConfig } = getTwConfigCache(twConfigPath)
if (!$twAttributes || isNewTwConfig) {
const { utilitiesRoot, componentsRoot, screens, variants } = tailwindData(
twConfig
)
const twObjectMap = createTwClassDictionary(utilitiesRoot, componentsRoot)
const TW_COLORS = /^(divide|bg|from|via|to|border|placeholder|ring-offset|ring|text)\-/
const tw: Record<string, true> = Object.keys(twObjectMap)
.filter((key) => !key.startsWith('-') && !key.startsWith('XWIND'))
.sort()
.reduce((accum, el) => {
accum[el] = true
if (TW_COLORS.test(el)) {
const components = splitAtLastTwoOccurences(el, '-')
if (components[0]) {
accum[components[0]] = accum[components[0]] || true
} else {
accum[components[1]] = accum[components[1]] || true
}
} else {
const components = splitAtLastOccurence(el, '-')
if (components[0]) {
accum[components[0]] = accum[components[0]] || true
} else {
accum[components[1]] = accum[components[1]] || true
}
}
return accum
}, {} as any)
$twAttributes = Object.keys(tw)
$twVariants = ([] as string[]).concat(...screens, ...variants, 'tw')
}
return [$twAttributes, $twVariants]
}
| 32.692308 | 91 | 0.631529 |
e72e6548b80611c47189080f3619da9a38742cd6 | 22,545 | php | PHP | application/views/v_pilih_kamar.php | akhmadarief/sistem-penyewaan-rusunawa-ci | 58faa50982fb45d10797ef506fa2b77338547071 | [
"MIT"
] | null | null | null | application/views/v_pilih_kamar.php | akhmadarief/sistem-penyewaan-rusunawa-ci | 58faa50982fb45d10797ef506fa2b77338547071 | [
"MIT"
] | null | null | null | application/views/v_pilih_kamar.php | akhmadarief/sistem-penyewaan-rusunawa-ci | 58faa50982fb45d10797ef506fa2b77338547071 | [
"MIT"
] | null | null | null | <!-- START PAGE CONTENT-->
<div class="page-content fade-in-up">
<div class="row">
<div class="col-md-12">
<div class="ibox">
<div class="ibox-head">
<div class="ibox-title">Denah Kamar</div>
<div class="ibox-tools">
<a class="ibox-collapse"><i class="fa fa-minus"></i></a>
</div>
</div>
<div class="ibox-body">
<ul class="nav nav-tabs tabs-line">
<li class="nav-item">
<a class="nav-link active" href="#A" data-toggle="tab">Gedung A</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#B" data-toggle="tab">Gedung B</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#C" data-toggle="tab">Gedung C</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#D" data-toggle="tab">Gedung D</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#E" data-toggle="tab">Gedung E</a>
</li>
</ul>
<div class="tab-content">
<div class="tab-pane fade show active" id="A">
<form class="form-horizontal">
<div class="form-group row" style="margin-top: 25px;">
<label class="col-sm-2 col-form-label" style="flex: 0 0 10%; min-width: 110px !important;">Pilih Lantai</label>
<div class="col-sm-2" style="min-width: 170px">
<select id="gedung_A" class="form-control">
<option value="A">Semua Lantai</option>
<option value="A2">Lantai 2</option>
<option value="A3">Lantai 3</option>
<option value="A4">Lantai 4</option>
</select>
</div>
</div>
</form>
<div id="lantai_A" style="margin-top: 25px;">
</div>
</div>
<div class="tab-pane fade" id="B">
<form class="form-horizontal">
<div class="form-group row" style="margin-top: 25px;">
<label class="col-sm-2 col-form-label" style="flex: 0 0 10%; min-width: 110px !important;">Pilih Lantai</label>
<div class="col-sm-2" style="min-width: 170px">
<select id="gedung_B" class="form-control">
<option value="B">Semua Lantai</option>
<option value="B1">Lantai 1</option>
<option value="B2">Lantai 2</option>
<option value="B3">Lantai 3</option>
<option value="B4">Lantai 4</option>
</select>
</div>
</div>
</form>
<div id="lantai_B" style="margin-top: 25px;">
</div>
</div>
<div class="tab-pane fade" id="C">
<form class="form-horizontal">
<div class="form-group row" style="margin-top: 25px;">
<label class="col-sm-2 col-form-label" style="flex: 0 0 10%; min-width: 110px !important;">Pilih Lantai</label>
<div class="col-sm-2" style="min-width: 170px">
<select id="gedung_C" class="form-control">
<option value="C">Semua Lantai</option>
<option value="C2">Lantai 2</option>
<option value="C3">Lantai 3</option>
<option value="C4">Lantai 4</option>
</select>
</div>
</div>
</form>
<div id="lantai_C" style="margin-top: 25px;">
</div>
</div>
<div class="tab-pane fade" id="D">
<form class="form-horizontal">
<div class="form-group row" style="margin-top: 25px;">
<label class="col-sm-2 col-form-label" style="flex: 0 0 10%; min-width: 110px !important;">Pilih Lantai</label>
<div class="col-sm-2" style="min-width: 170px">
<select id="gedung_D" class="form-control">
<option value="D">Semua Lantai</option>
<option value="D1">Lantai 1</option>
<option value="D2">Lantai 2</option>
<option value="D3">Lantai 3</option>
<option value="D4">Lantai 4</option>
</select>
</div>
</div>
</form>
<div id="lantai_D" style="margin-top: 25px;">
</div>
</div>
<div class="tab-pane fade" id="E">
<form class="form-horizontal">
<div class="form-group row" style="margin-top: 25px;">
<label class="col-sm-2 col-form-label" style="flex: 0 0 10%; min-width: 110px !important;">Pilih Lantai</label>
<div class="col-sm-2" style="min-width: 170px">
<select id="gedung_E" class="form-control">
<option value="E">Semua Lantai</option>
<option value="E1">Lantai 1</option>
<option value="E2">Lantai 2</option>
<option value="E3">Lantai 3</option>
<option value="E4">Lantai 4</option>
</select>
</div>
</div>
</form>
<div id="lantai_E" style="margin-top: 25px;">
</div>
</div>
</div>
</div>
<div class="ibox-body text-center bg-light">
<div class="legenda">
<div class="satu-legenda">
<div class="kotak-l kosong"></div>
<span>Belum Berpenghuni</span>
</div>
<div class="satu-legenda">
<div class="kotak-l terisi1"></div>
<span>1 Penghuni</span>
</div>
<div class="satu-legenda">
<div class="kotak-l terisi2"></div>
<span>2 Penghuni</span>
</div>
<div class="satu-legenda">
<div class="kotak-l sendiri"></div>
<span>Sendiri</span>
</div>
<div class="satu-legenda">
<div class="kotak-l piutang"></div>
<span>Piutang</span>
</div>
<div class="satu-legenda">
<div class="kotak-l terpilih"></div>
<span>Sedang Dipilih</span>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6" id="penghuni1" style="display: none;">
<div class="ibox">
<div class="ibox-head">
<div class="ibox-title">Data Penghuni I</div>
<div class="btn-group">
<a class="btn btn-dark btn-sm" id="tambah_penghuni" data-toggle="tooltip" data-placement="top" title="" data-original-title="Tambah Penghuni">
<i class="fa fa-plus"></i>
</a>
<a class="btn btn-dark btn-sm" id="edit_penghuni" data-toggle="tooltip" data-placement="top" title="" data-original-title="Ubah Data">
<i class="fa fa-pencil"></i>
</a>
<button class="btn btn-dark btn-sm perpanjang" data-toggle="tooltip" data-placement="top" title="" data-original-title="Perpanjang">
<i class="fa fa-arrows-h"></i>
</button>
<button class="btn btn-dark btn-sm eks_penghuni" data-toggle="tooltip" data-placement="top" title="" data-original-title="Selesai Menghuni">
<i class="fa fa-window-close"></i>
</button>
</div>
</div>
<div class="ibox-body">
<form class="form-horizontal">
<div class="form-group row">
<label class="col-sm-3 col-form-label">No. Kamar</label>
<div class="col-sm-9">
<input class="form-control" type="text" id="no_kamar" disabled>
</div>
</div>
<div class="form-group row">
<label class="col-sm-3 col-form-label">Nama</label>
<div class="col-sm-9">
<input class="form-control" type="text" id="nama" disabled>
</div>
</div>
<div class="form-group row">
<label class="col-sm-3 col-form-label">No. HP</label>
<div class="col-sm-9">
<input class="form-control" type="text" id="no" disabled>
</div>
</div>
<div class="form-group row">
<label class="col-sm-3 col-form-label">Prodi</label>
<div class="col-sm-9">
<input class="form-control" type="text" id="prodi" disabled>
</div>
</div>
<div class="form-group row">
<label class="col-sm-3 col-form-label">Fakultas</label>
<div class="col-sm-9">
<input class="form-control" type="text" id="fakultas" disabled>
</div>
</div>
<div class="form-group row">
<label class="col-sm-3 col-form-label">Masa Huni</label>
<div class="col-sm-9 input-daterange input-group" id="datepicker">
<input class="input-sm form-control" type="text" id="tgl_masuk" disabled>
<span class="input-group-addon p-l-10 p-r-10">s.d.</span>
<input class="input-sm form-control" type="text" id="tgl_keluar" disabled>
</div>
</div>
<div class="form-group row">
<label class="col-sm-3 col-form-label">Jumlah Harus Dibayar</label>
<div class="col-sm-9">
<input class="form-control" type="text" id="biaya" disabled>
</div>
</div>
<div class="form-group row">
<label class="col-sm-3 col-form-label">Jumlah Telah Dibayar</label>
<div class="col-sm-9">
<input class="form-control" type="text" id="bayar" disabled>
</div>
</div>
<div class="form-group row">
<label class="col-sm-3 col-form-label">Piutang</label>
<div class="col-sm-9">
<input class="form-control" type="text" id="piutang" disabled>
</div>
</div>
</form>
</div>
</div>
</div>
<div class="col-md-6" id="penghuni2" style="display: none;">
<div class="ibox">
<div class="ibox-head">
<div class="ibox-title">Data Penghuni II</div>
<div class="btn-group">
<a class="btn btn-dark btn-sm" id="tambah_penghuni2" data-toggle="tooltip" data-placement="top" title="" data-original-title="Tambah Penghuni">
<i class="fa fa-plus"></i>
</a>
<a class="btn btn-dark btn-sm" id="edit_penghuni2" data-toggle="tooltip" data-placement="top" title="" data-original-title="Ubah Data">
<i class="fa fa-pencil"></i>
</a>
<button class="btn btn-dark btn-sm perpanjang2" data-toggle="tooltip" data-placement="top" title="" data-original-title="Perpanjang">
<i class="fa fa-arrows-h"></i>
</button>
<button class="btn btn-dark btn-sm eks_penghuni2" data-toggle="tooltip" data-placement="top" title="" data-original-title="Selesai Menghuni">
<i class="fa fa-window-close"></i>
</button>
</div>
</div>
<div class="ibox-body">
<form class="form-horizontal">
<div class="form-group row">
<label class="col-sm-3 col-form-label">No. Kamar</label>
<div class="col-sm-9">
<input class="form-control" type="text" id="no_kamar2" disabled>
</div>
</div>
<div class="form-group row">
<label class="col-sm-3 col-form-label">Nama</label>
<div class="col-sm-9">
<input class="form-control" type="text" id="nama2" disabled>
</div>
</div>
<div class="form-group row">
<label class="col-sm-3 col-form-label">No. HP</label>
<div class="col-sm-9">
<input class="form-control" type="text" id="no2" disabled>
</div>
</div>
<div class="form-group row">
<label class="col-sm-3 col-form-label">Prodi</label>
<div class="col-sm-9">
<input class="form-control" type="text" id="prodi2" disabled>
</div>
</div>
<div class="form-group row">
<label class="col-sm-3 col-form-label">Fakultas</label>
<div class="col-sm-9">
<input class="form-control" type="text" id="fakultas2" disabled>
</div>
</div>
<div class="form-group row">
<label class="col-sm-3 col-form-label">Masa Huni</label>
<div class="col-sm-9 input-daterange input-group" id="datepicker">
<input class="input-sm form-control" type="text" id="tgl_masuk2" disabled>
<span class="input-group-addon p-l-10 p-r-10">s.d.</span>
<input class="input-sm form-control" type="text" id="tgl_keluar2" disabled>
</div>
</div>
<div class="form-group row">
<label class="col-sm-3 col-form-label">Jumlah Harus Dibayar</label>
<div class="col-sm-9">
<input class="form-control" type="text" id="biaya2" disabled>
</div>
</div>
<div class="form-group row">
<label class="col-sm-3 col-form-label">Jumlah Telah Dibayar</label>
<div class="col-sm-9">
<input class="form-control" type="text" id="bayar2" disabled>
</div>
</div>
<div class="form-group row">
<label class="col-sm-3 col-form-label">Piutang</label>
<div class="col-sm-9">
<input class="form-control" type="text" id="piutang2" disabled>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<!-- END PAGE CONTENT--> | 71.119874 | 179 | 0.308405 |
496a326d665c5974fc1de7d72c8292ef23d83c0e | 35,701 | py | Python | text_adventure/example_games/mini_knightmare.py | TomMonks/text-adventure-engine | 9af9ea2a0fca92ffc981760f6907702822b47ae8 | [
"MIT"
] | null | null | null | text_adventure/example_games/mini_knightmare.py | TomMonks/text-adventure-engine | 9af9ea2a0fca92ffc981760f6907702822b47ae8 | [
"MIT"
] | null | null | null | text_adventure/example_games/mini_knightmare.py | TomMonks/text-adventure-engine | 9af9ea2a0fca92ffc981760f6907702822b47ae8 | [
"MIT"
] | null | null | null | '''
A mini Knightmare text adventure game.
--------------------------------------
Knightmare was a popular TV programme in the early to mid 1990s
shown on ITV in UK. This game is a text adventure version
of a mini Knightmare quest. As a text adventure the mechanics
are different from the TV show and it is intended as a fun tribute.
Credits:
-------
The puzzles in this game are partially based on the first episode of
Knightmare.
Rooms in the game:
------------------
* antechamer - the start room where the quest begins
* puzzle1 - where a player must solve an anagram
* puzzle2 - where a player must answer riddles
* puzzle3 - where a player must find a way across a chasm
* puzzle4 - where a player must choose their fate.
'''
from text_adventure.commands import (
AddActionToInventoryItem,
AddInventoryItemtoHolder,
AddLinkToLocation,
AppendToRoomDescription,
ChangeLocationDescription,
ClearInventoryItemActions,
NullCommand,
PlayerDeath,
QuitGame,
RemoveInventoryItem,
SetCurrentRoom
)
from text_adventure.constants import (
DEFAULT_VERBS,
EAST, GIVE, NORTH,
QUIT_COMMAND, SOUTH, WEST)
from text_adventure.world import TextWorld, Room, InventoryItem
from text_adventure.actions import (
BasicInventoryItemAction,
ChoiceInventoryItemAction,
ConditionalInventoryItemAction,
RestrictedInventoryItemAction,
RoomSpecificInventoryItemAction
)
# Constants ##################################################################
START_INDEX = 0
GAME_NAME = 'Mini Knightmare'
OPENING_DESC = "[yellow]Welcome watcher of illusion to the " \
+ "castle of confusion for this is the time of adventure..." \
+ "\n\nI Treguard issue the challenge. Beyond this portal lies" \
+ " the Dungeon of Deceit which I alone have mastered. " \
+ " But you who have crossed time must master it also..." \
+ "\n\nEnter stranger... [/yellow]"
SPELLCASTING = 'spellcasting'
ANSWER = 'answer'
ENTER = 'enter'
TOUCH = 'touch'
LIGHT = 'light'
# Procedures to create game logic ############################################
def load_adventure():
'''
Return a mini knightmare text world adventure.
Returns:
-------
TextWorld
The adventure to play.
'''
# STEP 1: CREATE ROOMS AND LINKS #########################################
# Let's instantiate some Room objects to represent our network of rooms
# start fo the game = antechamber within Castle Knightmare
antechamber = Room(name="Throne room")
antechamber.description = "You are stood in an antechamber within Castle" \
+ " Knightmare. Candles scattered around the casts a room dull light" \
+ ", and a large fireplace brings warmth. [green]Treguard[/ green]" \
+ " sits in a great chair. In the corner of the room is a portal."
puzzle1 = Room(name='puzzle1')
puzzle1.description = """You are in a brightly lit room. There is a door to
at the far end barred by a portcullis. There are letters scratched into
ground. """
puzzle2 = Room(name='puzzle2')
puzzle2.description = "You are in room with all stone walls." \
+ " There is an exit to the south. On the north wall is a " \
+ "huge carving of a face."
puzzle3 = Room(name='chasm')
puzzle3.description = "You are standing in a large cavern to the south" \
+ " of a deep chasm. On the north side the cavern can be exited via" \
+ " an entrance to a tunnel in the shape of a serpent's head." \
+ " a dark figure stands on the other side of the chasm."
puzzle4 = Room(name='tunnel')
puzzle4.first_enter_msg = "(Treguard's voice whispers in your ears):" \
+ " [italic green]'Caution stranger your time in " \
+ "the dungeon of deceit draws to an end. But danger is still close" \
+ ". Choose your fate. But choose wisely'[/italic green]"
puzzle4.description = "\n\nYou are standing in a long tunnel." \
+ " To the west a door has two crosses engraved above it." \
+ " To the east is a door with two upside down crosses engraved" \
+ " above it. Another exit leads South."
dark_room = Room(name='dark room')
dark_room.description = "[bold]It is very dark.[/ bold]\n" \
+ "There is a single beam of light penetrating the ceiling" \
+ " and shining in the centre of the chamber. "\
+ "You sense an evil presence in this room."
light_room = Room(name='light room')
light_room.description = "[bold]The room is filled with a pure " \
+ "almost blinding white light[/ bold]. In the centre of room "\
+ "the light dims revealing a dark nebulous portal."
# store rooms in a list
rooms_collection = [antechamber, puzzle1, puzzle2, puzzle3, puzzle4,
dark_room, light_room]
# link rooms
puzzle2.add_exit(puzzle1, SOUTH)
puzzle3.add_exit(puzzle2, EAST)
puzzle4.add_exit(dark_room, EAST)
puzzle4.add_exit(light_room, WEST)
puzzle4.add_exit(light_room, SOUTH)
# STEP 2. CREATE INVENTORY ###############################################
# Create all the inventory to be used in the game. Not all of it will be
# added to the game immediately.
# 2.1 Antechamber inventory ##############################################
helmet, closed_portal, open_portal, treguard, treguard2 = \
create_antechamber_inventory()
# dungeoneer must wear the helmet
antechamber.add_inventory(helmet)
# initially the portal is closed.
antechamber.add_inventory(closed_portal)
antechamber.add_inventory(treguard)
# 2.2 Puzzle 1 inventory #################################################
# letters on the ground
letters, letter_o, letter_p, letter_e, letter_n = \
create_puzzle1_inventory()
puzzle1.add_inventory(letters)
puzzle1.add_inventory(letter_o)
puzzle1.add_inventory(letter_p)
puzzle1.add_inventory(letter_e)
puzzle1.add_inventory(letter_n)
# 2.2 Puzzle 2 inventory: olgarth of legend ##############################
olgarth, olgarth2a, olgarth2b = create_puzzle2_inventory()
puzzle2.add_inventory(olgarth)
# 2.3 Puzzle 3 inventory: Lilith #########################################
lilith = create_puzzle_3_inventory()
puzzle3.add_inventory(lilith)
# 2.4 Puzzle 4: beam of light and dark portal
light_beam, dark_portal = create_puzzle_4_inventory()
dark_room.add_inventory(light_beam)
light_room.add_inventory(dark_portal)
# 2.5 MISC Inventory #####################################################
# spell
spell, ruby, lamp = create_misc_inventory()
# STEP 3. SETUP ADVRENTURE OBJECT + COMMANDS #############################
adventure = setup_adventure(rooms_collection)
# 3.1 ANTECHAMBER ACTIONS ################################################
# wear helment (if in inventory)
# enter portal (if wearing helmet)
create_antechamber_actions(antechamber, puzzle1, helmet, closed_portal,
open_portal, adventure)
# talk to treguard
# 'answer' treguard and choose either a lamp or ruby
create_treguard_actions(antechamber, treguard, treguard2, ruby,
lamp, adventure)
# 3.2 PUZZLE 1: letters ##################################################
# Player must 'touch' the letters in the correct order.
create_puzzle1_actions(puzzle1, puzzle2, letter_o, letter_p, letter_e,
letter_n)
# 3.4 PUZZLE 2: olgarth of legend ########################################
# Olgarth asks 2 riddles
# 0 correct - death
# 1 correct - open way ahead (puzzle 3)
# 2 correct - open + bridge spell.
# 'answer olgarth <answer>'
create_puzzle2_actions(puzzle2, puzzle3, olgarth, olgarth2a, olgarth2b,
spell, adventure)
# 3.5 PUZZLE 3: LILITH & THE CHASM #######################################
# Lilith and the chasm
# Cast Bridge spell by-passes lilith
# Give Lilith ruby - she creates bridge.
create_puzzle3_actions(puzzle3, puzzle4, lilith, spell, ruby, adventure)
# 3.6 PUZZLE 5: Choose your fate.#########################################
# If the dungeoneer chooses the dark room they must have the lamp
# The other room is the 'light' room and they suvive no matter what.
create_dark_room_actions(dark_room, light_room, light_beam, lamp,
adventure)
create_light_room_actions(dark_portal, adventure)
return adventure
def create_light_room_actions(dark_portal, adventure):
ENTER_PORTAL = 'You step forward into the darkness ...'
ENDING = '\n\nYou find yourself once again in a warm antechamber of ' \
+ 'Castle Knightmare. Treguard stands before you and as he lifts ' \
+ 'the Helmet of Justice from your head you realise he is smiling.' \
+ "\n\n[italic green]'Well stranger, you have remained true to your "\
+ "quest and survived the Dungeon of Deceit. This in itself is your " \
+ "reward. As for me I have only one remaining task...'" \
+ "\n\n'Spellcasting D.I.M.I.S.S.' [/ italic green]"
GAME_OVER_MSG = "Well done adventurer. You have completed Knightmare."
end_cmd = QuitGame(adventure, quit_msg=ENTER_PORTAL + ENDING,
game_over_msg=GAME_OVER_MSG)
touch_portal_action = BasicInventoryItemAction(end_cmd, ENTER)
dark_portal.add_action(touch_portal_action)
def create_dark_room_actions(dark_room, light_room, light_beam, lamp, adventure):
TOUCH_BEAM_MSG = "In the corner of your eye you catch a brief"\
+ " glimpse of a many legs rushing towards you before a great pain "\
+ "fills your chest..."
TREGUARD_BAD_END = "\n\nAs the final light fades from your eyes you " \
+ "hear Treguard speak for one last time:\n[italic green]'Oooh "\
+ "NASTY. I thought the symbol might provide you a clue. " \
+ "But fear not stranger your time is not"\
+ " yet at an end. You have many centuries of time to ponder your " \
+ "mistakes in your after-life service of Shelob...[/ italic green]"
LIGHT_LAMP_MSG = "Light from the lamp floods the room and reveals a " \
+ "monsterous spider like creature looming down on you. Centuries old"\
+ " eyes peer down at you revealing the beast's hidden thirst, but"\
+ " the creature cowers away from the light. A solitary exit lies to" \
+ " the north."
TREGUARD_LAMP = "\n\nTreguard speaks: [italic green]'Caution.. you have "\
+ "entered the domain of Shelob the Enslaver. You were wise to "\
+ "light your lamp. But do not linger adventurer, make your escape "\
+ "quickly' [/italic green]"
# enter light beam
player_death = PlayerDeath(TOUCH_BEAM_MSG + TREGUARD_BAD_END,
QuitGame(adventure))
death_action = BasicInventoryItemAction(player_death, command_text=ENTER)
light_beam.add_action(death_action)
# light lamp
remove_lamp = RemoveInventoryItem(adventure, lamp)
room_desc = ChangeLocationDescription(dark_room, LIGHT_LAMP_MSG)
add_link = AddLinkToLocation(dark_room, light_room, NORTH)
tre_warning = NullCommand('\n' + LIGHT_LAMP_MSG + TREGUARD_LAMP)
cmds = [remove_lamp, room_desc, add_link, tre_warning]
light_action = RestrictedInventoryItemAction(adventure, cmds, [lamp],
'', LIGHT)
lamp.add_action(light_action)
def create_puzzle_4_inventory():
light_beam = InventoryItem('A beam of light', fixed=True, background=True)
light_beam.long_description = "A singlular thin beam of light penetrates "\
+ " the ceiling of the chamber from an unknown source. The beam "\
+ "illuminates the centre of the room and is just wide enough " \
+ "to step into"
light_beam.add_alias("light")
light_beam.add_alias("beam")
# the dark portal (final item to end the game)
dark_portal = InventoryItem('dark portal', fixed=True, background=True)
dark_portal.long_description = "Treguard speaks [italic green]'"\
+ "This portal is the end of your journey adventurer. Don't give up" \
+ " now; take the final step.' [/italic green]"
dark_portal.add_alias('dark')
dark_portal.add_alias('portal')
return light_beam, dark_portal
def create_misc_inventory():
'''
Create misc inventory that is used within the game. These might
be relevant (or obtained and then used across) multiple puzzles
'''
spell = InventoryItem('The bridge spell')
spell.long_description = "Cast me if you wish to avoid the depths"
spell.add_alias("bridge")
# ruby
ruby = InventoryItem('ruby')
ruby.long_description = "A beautiful and valuable ruby. " \
+ "It might come in useful!"
ruby.add_alias('ruby')
# lamp
lamp = InventoryItem('lamp')
lamp.long_description = "The lamp has two crosses engraved on it." \
+ " It might come in useful!"
lamp.add_alias('lamp')
return spell, ruby, lamp
def create_antechamber_inventory():
'''
The antechamber is the beginning of the game and is where
Treguard resides.
Returns:
-------
tuple: (helmet, closed_portal, open_portal, treguard, treguard2)
'''
helmet = InventoryItem('The Helmet of Justice')
helmet.long_description = """The fabled helmet of justice!
The helmet protects a dungeoneer just like a standard helmet, but also
protects them from Dungeon of Deciet's potent illusions."""
helmet.add_alias('helmet')
helmet.add_alias('justice')
# portal - this is fixed to the inventory of the room. (can't be picked up)
closed_portal = InventoryItem('portal', fixed=True, background=True)
closed_portal.long_description = """The portal to the Dungeon of Deceit.
It has a dull glow. Enter at your own risk!"""
closed_portal.add_alias('portal')
open_portal = InventoryItem('portal', fixed=True, background=True)
open_portal.long_description = """The portal to the Dungeon of Deceit.
It is glowing brightly. Enter at your own risk!"""
open_portal.add_alias('portal')
# treguard offers the player a ruby or lantern
treguard = InventoryItem('treguard', fixed=True, background=True)
treguard.long_description = "Treguard of Dunshelm, the dungeon master." \
+ "He stars unflinchingly at you. His eyes feel like they pierce" \
+ " your very soul."
treguard.add_alias("treguard")
treguard.add_alias("tre")
# treguard after choosing the item.
treguard2 = InventoryItem('treguard', fixed=True, background=True)
treguard2.long_description = "Treguard of Dunshelm, the dungeon master." \
+ "He stars unflinchingly at you. His eyes feel like they pierce" \
+ " your very soul."
treguard2.add_alias("treguard")
treguard.add_alias("tre")
return helmet, closed_portal, open_portal, treguard, treguard2
def create_puzzle1_inventory():
'''
Puzzle 1 is a simple anagrame. Players need to spell open by touching
the letters in the correct order. There is also a general letters item
that describes the scene.
Returns:
-------
tuple: (letters, letter_o, letter_p, letter_e, letter_n)
'''
letters = InventoryItem('letters', fixed=True, background=True)
letters.long_description = "The letters N, P, E, and O are engraved in" \
+ " ground."
letters.add_alias('letters')
letters.add_alias('letter')
letters.add_alias('ground')
HIDE_LETTERS = True
letter_o = InventoryItem('the letter o', fixed=True,
background=HIDE_LETTERS)
letter_o.long_description = "The letter O as used in Oscar."
letter_o.add_alias('the letter o')
letter_o.add_alias('o')
letter_o.add_alias('O')
letter_p = InventoryItem('the letter p', fixed=True,
background=HIDE_LETTERS)
letter_p.long_description = "The letter P as used in Papa."
letter_p.add_alias('p')
letter_p.add_alias('P')
letter_p.add_alias('the letter p')
letter_e = InventoryItem('the letter e', fixed=True,
background=HIDE_LETTERS)
letter_e.long_description = "The letter E as used in Echo"
letter_e.add_alias('e')
letter_e.add_alias('E')
letter_e.add_alias('the letter e')
letter_n = InventoryItem('the letter n', fixed=True,
background=HIDE_LETTERS)
letter_n.long_description = "The letter N as used in November"
letter_n.add_alias('n')
letter_n.add_alias('N')
letter_n.add_alias('the letter n')
return letters, letter_o, letter_p, letter_e, letter_n
def create_puzzle2_inventory():
'''
Puzzle 2 inventory.
Olgarth of legends.
There are three olgarth objects. olgarth is replaced either by
olgarth2a (correct answer) or olgarth2b (incorrect answer)
Returns:
-------
Tuple (olgarth, olgarth2a, olgarth2b)
'''
olgarth = InventoryItem("Olgarth", fixed=True, background=True)
olgarth.long_description = "A creature appears to live within the wall" \
+ " itself and is manifested as a giant face."
olgarth.add_alias("olgarth")
olgarth.add_alias("face")
olgarth.add_alias("creature")
olgarth.add_alias("carving")
# olgarth for second riddle... first answer correct.
olgarth2a = InventoryItem("Olgarth", fixed=True, background=True)
olgarth2a.long_description = "A creature appears to live within the wall" \
+ " itself and is manifested as a giant face."
olgarth2a.add_alias("olgarth")
olgarth2a.add_alias("face")
olgarth2a.add_alias("creature")
olgarth2a.add_alias("carving")
# olgarth for second riddle... first answer correct incorrect.
olgarth2b = InventoryItem("Olgarth", fixed=True, background=True)
olgarth2b.long_description = "A creature appears to live within the wall" \
+ " itself and is manifested as a giant face."
olgarth2b.add_alias("olgarth")
olgarth2b.add_alias("face")
olgarth2b.add_alias("creature")
olgarth2b.add_alias("carving")
return olgarth, olgarth2a, olgarth2b
def create_puzzle_3_inventory():
'''
Puzzle 3 inventory. Lilith.
Returns:
-------
InventoryItem (lilith)
'''
lilith = InventoryItem("Lilith", fixed=True, background=True)
lilith.long_description = "A mysterious figure in a dark hood."
lilith.add_alias('lilith')
lilith.add_alias('figure')
return lilith
def setup_adventure(rooms_collection):
'''
create adventure object and setup command interface.
'''
# customise the command verb set
knightmare_verb_mapping = DEFAULT_VERBS
# = ['look', 'inv', 'get', 'drop', 'ex', 'quit']
# create the game room
adventure = TextWorld(name=GAME_NAME, rooms=rooms_collection,
start_index=START_INDEX,
command_verb_mapping=knightmare_verb_mapping,
use_aliases='classic')
# custom game over message
adventure.game_over_message = 'Your adventure ends here stranger.'
# add additional alisas for the word 'use' - classic knightmare spellcast
adventure.add_use_command_alias(SPELLCASTING)
# enter portal
adventure.add_use_command_alias(ENTER)
# touch letters
adventure.add_use_command_alias(TOUCH)
# answer riddles or choices
adventure.add_use_command_alias(ANSWER)
# light lamp
adventure.add_use_command_alias(LIGHT)
# Adventure opening line.
adventure.opening = OPENING_DESC
return adventure
def create_antechamber_actions(antechamber, puzzle1, helmet, closed_portal,
open_portal, adventure):
'''
Antechamber actions
The dungeoneer must posess the helmet and wear it. This activates
portal to the Dungeon of Deciet.
Wear helmet
1. Remove the helmet from the players inventory
2. Output a fun message to the player.
3. Replace the closed_portal object with open_portal.
The open portal can be entered. This moves the player to puzzle 1.
'''
# WEAR THE HELMET ########################################################
remove_helmet = RemoveInventoryItem(adventure, helmet)
wear_message = NullCommand("You place the Helmet of Justice on your head.")
remove_closed_portal = RemoveInventoryItem(antechamber, closed_portal)
add_open_portal = AddInventoryItemtoHolder([open_portal], antechamber)
wear_cmds = [remove_helmet, wear_message, remove_closed_portal,
add_open_portal]
# The player only needs to be holding the helmet
action_requirements = helmet
# a message if the player is in a room with the grapes, but not holding!
need_to_pick_up = "You aren't holding a helmet."
wear_helmet = RestrictedInventoryItemAction(adventure, wear_cmds,
action_requirements,
need_to_pick_up,
'wear')
# finally add the action to the grapes InventoryItem.
helmet.add_action(wear_helmet)
# attempt to enter the closed portal
failed_entry_msg = NullCommand("It is not safe to enter yet.")
fail_entry = BasicInventoryItemAction(failed_entry_msg,
command_text='enter')
closed_portal.add_action(fail_entry)
# ENTER the open portal
enter_message = NullCommand("[red]You step into the bright light of the "
+ "portal...\n\n[/ red]")
move_room = SetCurrentRoom(adventure, puzzle1)
enter_action = BasicInventoryItemAction([enter_message, move_room],
command_text='enter')
open_portal.add_action(enter_action)
def create_treguard_actions(antechamber, treguard, treguard2, ruby, lamp,
adventure):
'''
TALK TO TREGUARD and CHOOSE a ruby or lamp
'''
TRE_SPEACH = "[italic green]'Welcome stranger...To help you on " \
+ "your quest I can offer you a precious 'ruby' or the 'lamp of the" \
+ " cross' \nAnswer me...which do you choose?'[/ italic green]"
TRE2_SPEACH = "[italic green]'The dungeon awaits you.'[/ italic green]"
TRE_UNIMPRESSED = 'Treguard looks unimpressed with your choice.'
CHOOSE_RUBY = "Treguard hands you a ruby." \
+ "[italic green]\n'A rare and precious gem." \
+ " Let us hope its value is of value in the dungeon'" \
+ "[/ italic green]"
CHOOSE_LAMP = "Treguard hands you a lamp." \
+ "[italic green]\n'The dungeon is a dark place" \
+ " Let this lamp light your path in your darkest hour.'" \
+ "[/ italic green]"
talk_tre = BasicInventoryItemAction(NullCommand(TRE_SPEACH),
command_text="talk")
treguard.add_action(talk_tre)
# answer treguard lamp or answer tregaurd ruby
add_ruby = AddInventoryItemtoHolder(ruby, adventure)
tre_talk2 = NullCommand(CHOOSE_RUBY)
remove_tre = RemoveInventoryItem(antechamber, treguard)
add_tre2 = AddInventoryItemtoHolder(treguard2, antechamber)
cmds1 = [add_ruby, tre_talk2, remove_tre, add_tre2]
ruby_action = BasicInventoryItemAction(cmds1, command_text='answer')
add_lamp = AddInventoryItemtoHolder(lamp, adventure)
tre_talk2 = NullCommand(CHOOSE_LAMP)
cmds2 = [add_lamp, tre_talk2, remove_tre, add_tre2]
lamp_action = BasicInventoryItemAction(cmds2, command_text='answer')
action_choices = {'ruby': ruby_action,
'lamp': lamp_action}
tre_choice = ChoiceInventoryItemAction(action_choices, 'answer',
TRE_UNIMPRESSED)
treguard.add_action(tre_choice)
talk_tre2 = BasicInventoryItemAction(NullCommand(TRE2_SPEACH), 'talk')
treguard2.add_action(talk_tre2)
def create_puzzle2_actions(puzzle2, puzzle3, olgarth, olgarth2a, olgarth2b,
spell, adventure):
'''
Answer Olgarth of legends riddles.
'''
CORRECT_ANSWER = "[bold italic red]'Truth accepted'[/ bold italic red]"
ONE_INCORRECT_ANSWER = 'You do not speak the truth.'
DEATH_MSG = "[bold red]'I FEED UPON YOU.'[/ bold red]" \
+ "\nAs the world fades to black Treguard speaks:"\
+ "\n[italic green]'Oohh nasty! Your soul has been consumed" \
+ " by Olgarth. Your bones will remain" \
+ " in the dungeon of deciet for all eternity.'"
SPELL_MSG = "[italic green] I grant you the spell " \
+ "BRIDGE. [/ italic green]"
ANSWER_1 = 'stone'
ANSWER_2 = 'arthur'
RIDDLE_1 = "\nRiddle: 1 [italic yellow]'Of earth I was born. Deep fires" \
+ " tempered me. Mountains slept on me. My father was younger" \
+ " than I and a sculptor gave me my face. " \
+ " What am I made of?'[/ italic yellow]"
RIDDLE_2 = "\nRiddle 2: [italic yellow]'Once by magic I was cleft." \
+ " Deep in my chest a sword was left. 10 years of pain" \
+ " I endured. then came a prince who pulled it forth. " \
+ " Name him now and gain reward.'[/ italic yellow]"
OLGARTH_INTRO = "[italic green]'I am Olgarth of legend. " \
+ " I have riddles of different times of different legends." \
+ " Two riddles I have and seek answers. Answer one correctly" \
+ " and the way ahead is opened. Answer two correctly and" \
+ " help I shall provide. Fail both and I feed upon you.'" \
+ "[/italic green]"
# OLGARTH: RIDDLE 2 ######################################################
# response to talk olgarth
riddle_text = NullCommand(RIDDLE_2)
talk_olgarth2 = BasicInventoryItemAction(riddle_text, command_text='talk')
olgarth2a.add_action(talk_olgarth2)
# These command issued no matter what with 2a
# Link to puzzle 3
link_puz3 = AddLinkToLocation(puzzle2, puzzle3, WEST)
# Add the link as descriptive text
extra_desc = \
AppendToRoomDescription(puzzle2, " The way forward is to the West.")
# 2a CORRECRT answer 2
# action = remove olgarth, give player spell, show text, link p3
remove_o2 = RemoveInventoryItem(puzzle2, olgarth2a)
add_spell = AddInventoryItemtoHolder([spell], adventure)
response_txt = NullCommand(CORRECT_ANSWER)
spell_output = NullCommand(SPELL_MSG)
correct_action = BasicInventoryItemAction([remove_o2, add_spell,
response_txt,
spell_output,
link_puz3, extra_desc],
'answer')
# 2a INCORRECT answer.
# remove olgarth, show text, link p3, add link as txt
incorrect_txt = NullCommand(ONE_INCORRECT_ANSWER)
incorrect_action = \
BasicInventoryItemAction([incorrect_txt, link_puz3, extra_desc],
'answer')
olgarth_qa = ConditionalInventoryItemAction(ANSWER_2,
correct_action,
incorrect_action,
command_text='answer')
olgarth2a.add_action(olgarth_qa)
# OLGARTH ACTIONS - AFTER 1 INCORRECT ANSWER #############################
# add riddle - command word 'talk'
olgarth2b.add_action(talk_olgarth2)
# correct answer action = remove, output text, link p3, add desc to room.
correct_action = BasicInventoryItemAction([remove_o2, response_txt,
link_puz3, extra_desc],
'answer')
# incorrect answer = Death and game over ...
player_death = PlayerDeath(DEATH_MSG,
QuitGame(adventure, quit_msg='Game over'))
incorrect_action = \
BasicInventoryItemAction(player_death, 'answer')
olgarth_qa = ConditionalInventoryItemAction(ANSWER_2,
correct_action,
incorrect_action,
command_text='answer')
olgarth2b.add_action(olgarth_qa)
# OLGARTH RIDDLE 1 ACTIONS ###############################################
olgarth_response = NullCommand(OLGARTH_INTRO + RIDDLE_1)
talk_olgarth = BasicInventoryItemAction(olgarth_response,
command_text='talk')
olgarth.add_action(talk_olgarth)
remove_o1 = RemoveInventoryItem(puzzle2, olgarth)
add_o2a = AddInventoryItemtoHolder([olgarth2a], puzzle2)
output = NullCommand(CORRECT_ANSWER)
correct_action = BasicInventoryItemAction([remove_o1, add_o2a, output],
'answer')
add_o2b = AddInventoryItemtoHolder([olgarth2b], puzzle2)
output = NullCommand(ONE_INCORRECT_ANSWER)
incorrect_action = \
BasicInventoryItemAction([remove_o1, add_o2b, output], 'answer')
olgarth_qa = ConditionalInventoryItemAction(ANSWER_1,
correct_action,
incorrect_action,
command_text='answer')
olgarth.add_action(olgarth_qa)
def create_puzzle1_actions(puzzle1, puzzle2, letter_o, letter_p, letter_e,
letter_n):
'''
PUZZLE 1: touch letters in correct order
and manage response when letters touched out of order
'''
wrong_order = BasicInventoryItemAction(NullCommand("Nothing happens."),
command_text="touch")
letter_p.add_action(wrong_order)
letter_e.add_action(wrong_order)
letter_n.add_action(wrong_order)
# 'touch o'. This will add an action to 'p' and so on. 'n' opens
# the portculia and adds a exit.
# Tip - create the final action first and work backwards when coding...
execute_msg = 'The letter [yellow]glows[/ yellow] briefly and disappears.'
remove_n = RemoveInventoryItem(puzzle1, letter_n)
open_message = 'The portcullis O.P.E.Ns!'
p1_solved = """You are in a brightly lit room. There is an open door to
to the north."""
new_description = ChangeLocationDescription(puzzle1, p1_solved,
open_message)
open_portcullis = AddLinkToLocation(puzzle1, puzzle2, NORTH)
letter_n_action = BasicInventoryItemAction([remove_n, new_description,
open_portcullis],
command_text='touch')
clear_n = ClearInventoryItemActions(letter_n)
remove_e = RemoveInventoryItem(puzzle1, letter_e)
add_n_action = AddActionToInventoryItem(letter_n_action, letter_n,
execute_msg)
letter_e_action = BasicInventoryItemAction([clear_n, remove_e,
add_n_action],
command_text='touch')
clear_e = ClearInventoryItemActions(letter_e)
remove_p = RemoveInventoryItem(puzzle1, letter_p)
add_e_action = AddActionToInventoryItem(letter_e_action, letter_e,
execute_msg)
letter_p_action = BasicInventoryItemAction([clear_e, remove_p,
add_e_action],
command_text='touch')
clear_p = ClearInventoryItemActions(letter_p)
remove_o = RemoveInventoryItem(puzzle1, letter_o)
add_p_action = AddActionToInventoryItem(letter_p_action, letter_p,
execute_msg)
letter_o_action = BasicInventoryItemAction([clear_p, remove_o,
add_p_action],
command_text='touch')
# only the first letter has its action added on load...
letter_o.add_action(letter_o_action)
def create_puzzle3_actions(puzzle3, puzzle4, lilith, spell, ruby, adventure):
'''
Puzzle 3: Lilith and the Chasm
Either use B.R.I.D.G.E spell or give ruby to Lilith to cross the chasm.
'''
LIL_SPEAK = "[italic yellow]'No master, but a mistress rules here. " \
+ "I am called Lilith and this is my domain. " \
+ "The only way beyond is through the serpent's mouth." \
+ "You must leave. Kindly use the alternative exit. " \
+ "For some small consideration I might just spare you " \
+ "and allow you to leave through the serpent's mouth. " \
+ "Have you anything that might interest me?'[/ italic yellow] :snake:"
SPELLCAST = "[italic pink] spellcasting: B.R.I.D.G.E [/ italic pink]"
BRIDGE_APPEAR = "\nA bridge magically appears across the chasm."
LIL_ACCEPT = "[italic yellow]'I accept your offering'[/ italic yellow]"\
+ ":snake:"
LIL_LEAVE = "\n(Lilith fades into nothingness)"
UPDATE_DESC = "You are standing in a large cavern on the south side" \
+ " of a [bold]bridge[/bold] crossing a deep chasm. On the north" \
+ " side the cavern can be exited via an entrance to a tunnel" \
+ " in the shape of a serpent's head."
NO_RUBY = "Its probably best not to offer her something you don't have."
NO_SPELL = "you don't have a spell"
# Talk to lilith #########################################################
talk_lil = BasicInventoryItemAction(NullCommand(LIL_SPEAK),
command_text="talk")
lilith.add_action(talk_lil)
# SPELLCASTING ###########################################################
spellcast_cmd = NullCommand(SPELLCAST)
remove_spell = RemoveInventoryItem(adventure, spell)
remove_lil = RemoveInventoryItem(puzzle3, lilith)
add_tunnel = AddLinkToLocation(puzzle3, puzzle4, 'n')
new_desc = \
ChangeLocationDescription(puzzle3, UPDATE_DESC,
BRIDGE_APPEAR + "\n" + LIL_LEAVE)
cmds = [spellcast_cmd, remove_spell, remove_lil, add_tunnel, new_desc]
reqs = [spell]
command_txt = 'spellcasting'
spell_action = RestrictedInventoryItemAction(adventure, cmds, reqs,
NO_SPELL,
command_txt=command_txt)
spell_p3_action = RoomSpecificInventoryItemAction(adventure, puzzle3,
spell_action,
command_text=command_txt)
spell.add_action(spell_p3_action)
# Give ruby to lilith ####################################################
remove_ruby = RemoveInventoryItem(adventure, ruby)
lil_give_txt = NullCommand(LIL_ACCEPT)
cmds = [remove_ruby, remove_lil, lil_give_txt, add_tunnel, new_desc]
reqs = [ruby]
ruby_action = RestrictedInventoryItemAction(adventure, cmds, reqs,
NO_RUBY,
command_txt=GIVE)
ruby_p3_action = RoomSpecificInventoryItemAction(adventure, puzzle3,
ruby_action,
command_text=GIVE)
ruby.add_action(ruby_p3_action)
| 42.755689 | 104 | 0.625529 |
2d4132d973c95349293f642504e84e266d593da3 | 170 | dart | Dart | taste_cloud_functions/functions/test/toolbox/import_mailchimp.dart | tasteapp/taste_public | b2d884b405224dd1e74b4462fac2c1f59c1f6ca2 | [
"MIT"
] | null | null | null | taste_cloud_functions/functions/test/toolbox/import_mailchimp.dart | tasteapp/taste_public | b2d884b405224dd1e74b4462fac2c1f59c1f6ca2 | [
"MIT"
] | null | null | null | taste_cloud_functions/functions/test/toolbox/import_mailchimp.dart | tasteapp/taste_public | b2d884b405224dd1e74b4462fac2c1f59c1f6ca2 | [
"MIT"
] | 1 | 2021-02-06T07:44:39.000Z | 2021-02-06T07:44:39.000Z | import '../utilities.dart';
Future importMailchimp() async => mailchimp.batch((await TasteUsers.get())
.map((u) => u.updateMailchimpUserRequest)
.withoutNulls);
| 28.333333 | 74 | 0.705882 |
05d721857319cb7f32220a3666d9ce4de8d3c451 | 228 | py | Python | python/examples/websocket/main.py | fission/environment-registry | 1ed158f60be08a597272b5e9f7466553fad53e81 | [
"Apache-2.0"
] | null | null | null | python/examples/websocket/main.py | fission/environment-registry | 1ed158f60be08a597272b5e9f7466553fad53e81 | [
"Apache-2.0"
] | null | null | null | python/examples/websocket/main.py | fission/environment-registry | 1ed158f60be08a597272b5e9f7466553fad53e81 | [
"Apache-2.0"
] | null | null | null | def main(ws, clients):
print("The number of clients is: {}".format(len(clients)))
count = 0
while not ws.closed and count < 5:
message = ws.receive()
ws.send(message)
count += 1
ws.close() | 28.5 | 62 | 0.570175 |
74e1b52bd19d40a63838e87cfb10392cf9250489 | 2,595 | go | Go | go/vt/vtgate/engine/session_primitive.go | tokikanno/vitess | 5860897b8fc91d30c480f1adb3f8dcc7d9c002ec | [
"Apache-2.0"
] | 13 | 2018-09-27T14:16:05.000Z | 2022-01-30T09:02:49.000Z | go/vt/vtgate/engine/session_primitive.go | tokikanno/vitess | 5860897b8fc91d30c480f1adb3f8dcc7d9c002ec | [
"Apache-2.0"
] | 17 | 2018-10-18T06:50:05.000Z | 2022-01-20T18:18:34.000Z | go/vt/vtgate/engine/session_primitive.go | tokikanno/vitess | 5860897b8fc91d30c480f1adb3f8dcc7d9c002ec | [
"Apache-2.0"
] | 8 | 2019-10-21T17:45:17.000Z | 2021-09-07T06:47:49.000Z | /*
Copyright 2021 The Vitess Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package engine
import (
"vitess.io/vitess/go/sqltypes"
querypb "vitess.io/vitess/go/vt/proto/query"
vtrpcpb "vitess.io/vitess/go/vt/proto/vtrpc"
"vitess.io/vitess/go/vt/vterrors"
)
// SessionPrimitive the session primitive is a very small primitive used
// when we have simple engine code that needs to interact with the Session
type SessionPrimitive struct {
action func(sa SessionActions) (*sqltypes.Result, error)
name string
noInputs
noTxNeeded
}
var _ Primitive = (*SessionPrimitive)(nil)
// NewSessionPrimitive creates a SessionPrimitive
func NewSessionPrimitive(name string, action func(sa SessionActions) (*sqltypes.Result, error)) *SessionPrimitive {
return &SessionPrimitive{
action: action,
name: name,
}
}
// RouteType implements the Primitive interface
func (s *SessionPrimitive) RouteType() string {
return "SHOW"
}
// GetKeyspaceName implements the Primitive interface
func (s *SessionPrimitive) GetKeyspaceName() string {
return ""
}
// GetTableName implements the Primitive interface
func (s *SessionPrimitive) GetTableName() string {
return ""
}
// Execute implements the Primitive interface
func (s *SessionPrimitive) TryExecute(vcursor VCursor, _ map[string]*querypb.BindVariable, _ bool) (*sqltypes.Result, error) {
return s.action(vcursor.Session())
}
// StreamExecute implements the Primitive interface
func (s *SessionPrimitive) TryStreamExecute(vcursor VCursor, _ map[string]*querypb.BindVariable, _ bool, callback func(*sqltypes.Result) error) error {
qr, err := s.action(vcursor.Session())
if err != nil {
return err
}
return callback(qr)
}
// GetFields implements the Primitive interface
func (s *SessionPrimitive) GetFields(_ VCursor, _ map[string]*querypb.BindVariable) (*sqltypes.Result, error) {
return nil, vterrors.New(vtrpcpb.Code_INTERNAL, "not supported for this primitive")
}
// description implements the Primitive interface
func (s *SessionPrimitive) description() PrimitiveDescription {
return PrimitiveDescription{
OperatorType: s.name,
}
}
| 30.174419 | 151 | 0.770328 |
bd824df2a4f27a28119567722de705560bbc276a | 202 | cs | C# | Programming Basics/2016 June/CSharpProgrammingBasicDemo/Playsound/PlaySound.cs | andreykata/SoftUni | f96d6ee7df5a2ab8c688fb281e3198d132f3c1bd | [
"MIT"
] | null | null | null | Programming Basics/2016 June/CSharpProgrammingBasicDemo/Playsound/PlaySound.cs | andreykata/SoftUni | f96d6ee7df5a2ab8c688fb281e3198d132f3c1bd | [
"MIT"
] | null | null | null | Programming Basics/2016 June/CSharpProgrammingBasicDemo/Playsound/PlaySound.cs | andreykata/SoftUni | f96d6ee7df5a2ab8c688fb281e3198d132f3c1bd | [
"MIT"
] | null | null | null | using System;
class PlaySound
{
static void Main(string[] args)
{
var leva = int.Parse(Console.ReadLine());
var euro = leva / 1.95583;
Console.WriteLine(euro);
}
}
| 16.833333 | 49 | 0.574257 |
0878b7d2bea18bced93318b706eb3214038b06d4 | 222 | sql | SQL | primeri_sa_vezbi/pbp.trocas5/pbp.trocas5.zadaci/zadatak4.sql | ivana-matf-bg-ac-rs/projektovanje-baza-podataka | f9dcfc84dea7b3bbb991f7991843fda37b144f54 | [
"MIT"
] | null | null | null | primeri_sa_vezbi/pbp.trocas5/pbp.trocas5.zadaci/zadatak4.sql | ivana-matf-bg-ac-rs/projektovanje-baza-podataka | f9dcfc84dea7b3bbb991f7991843fda37b144f54 | [
"MIT"
] | null | null | null | primeri_sa_vezbi/pbp.trocas5/pbp.trocas5.zadaci/zadatak4.sql | ivana-matf-bg-ac-rs/projektovanje-baza-podataka | f9dcfc84dea7b3bbb991f7991843fda37b144f54 | [
"MIT"
] | null | null | null | /*
4. Kreirati SQL iskaz kojim se briše prethodno dodata kolona iz
zadatka 3.
*/
USE poslovanje;
-- Brise se kolona
ALTER TABLE fakture
DROP COLUMN primio;
-- Ispisuje se definicija tabele
SHOW CREATE TABLE fakture; | 14.8 | 64 | 0.752252 |
3913bf312b61dd7c1877057e91cc74c284bdbe7b | 2,514 | py | Python | producer/producer/__main__.py | HelenMel/WebsiteStatusesAggregators | 787283121b3eff3fbaf201106facf3d0f167ca8e | [
"MIT"
] | 1 | 2020-04-07T12:03:38.000Z | 2020-04-07T12:03:38.000Z | producer/producer/__main__.py | HelenMel/WebsiteStatusesAggregators | 787283121b3eff3fbaf201106facf3d0f167ca8e | [
"MIT"
] | null | null | null | producer/producer/__main__.py | HelenMel/WebsiteStatusesAggregators | 787283121b3eff3fbaf201106facf3d0f167ca8e | [
"MIT"
] | null | null | null | from producer.checkers.website_checker import WebsiteChecker
from producer.repositories.kafka import KafkaWriter
from producer.utilities.json_serializer import JsonSerializer
from producer.config.app_config import AppConfig
import schedule
from concurrent.futures import ThreadPoolExecutor
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
WEBSITES = [
"https://www.verkkokauppa.com/fi/catalog/59a/Lemmikit",
"https://www.coursera.org/professional-certificates/google-it-support"
]
class WebsiteStatusProducer():
"""This class accept list of websites as a parameter,
check websites statuses and store statuses to kafka
:param websites: list of websites to query
:param request_every: request frequency in seconds
"""
def __init__(self, websites = WEBSITES, request_every = 5):
self.websites = websites
self.request_every = request_every
self.is_running = False
self._publisher = None
self._app_config = None
@property
def app_config(self):
if self._app_config is None:
self._app_config = AppConfig()
return self._app_config
@property
def publisher(self):
if self._publisher is None:
self._publisher = KafkaWriter(self.app_config.kafka_config(), JsonSerializer.dataclass_to_json)
return self._publisher
def run(self):
checkers = [WebsiteChecker(url) for url in self.websites]
executor = ThreadPoolExecutor(max_workers=2)
self.is_running = True
for checker in checkers:
schedule.every(self.request_every).seconds.do(self._main_job_async, executor, checker, self.publisher)
while self.is_running:
try:
schedule.run_pending()
except KeyboardInterrupt as _:
break
except Exception as err:
logger.error(f"Job will be finished because of an error: {err}")
break
executor.shutdown(wait=True)
schedule.clear()
self.publisher.close()
def _main_job(self, checker, publisher):
status = checker.check_get()
if status is not None:
publisher.send_sync(status)
logger.info(f"send {status}")
def _main_job_async(self, executor, checker, publisher):
executor.submit(self._main_job, checker, publisher)
if __name__ == "__main__":
producer = WebsiteStatusProducer()
producer.run() | 33.972973 | 114 | 0.678202 |
3cf56ec09d117b2f65dca124ee52ec858f73ea81 | 6,648 | go | Go | test/postgres/dao/goma_date_types_gen.go | kyokomi/goma | 688904cf12b4caf16e37ebe92c8a15ee8b86ce6e | [
"Apache-2.0"
] | 25 | 2015-02-15T10:39:50.000Z | 2020-07-30T18:46:36.000Z | test/postgres/dao/goma_date_types_gen.go | kyokomi/goma | 688904cf12b4caf16e37ebe92c8a15ee8b86ce6e | [
"Apache-2.0"
] | 55 | 2015-02-16T15:04:27.000Z | 2016-02-25T08:41:24.000Z | test/postgres/dao/goma_date_types_gen.go | kyokomi/goma | 688904cf12b4caf16e37ebe92c8a15ee8b86ce6e | [
"Apache-2.0"
] | 3 | 2015-02-23T11:22:22.000Z | 2020-06-03T02:29:50.000Z | package dao
// NOTE: THIS FILE WAS PRODUCED BY THE
// GOMA CODE GENERATION TOOL (github.com/kyokomi/goma)
// DO NOT EDIT
import (
"log"
"database/sql"
"github.com/kyokomi/goma/test/postgres/entity"
)
var tableGomaDateTypes = "goma_date_types"
var columnsGomaDateTypes = []string{
"id",
"timestamp_columns",
"nil_timestamp_columns",
}
// GomaDateTypesTableName goma_date_types table name
func GomaDateTypesTableName() string {
return tableGomaDateTypes
}
// GomaDateTypesTableColumns goma_date_types table columns
func GomaDateTypesTableColumns() []string {
return columnsGomaDateTypes
}
// GomaDateTypesDaoQueryer is interface
type GomaDateTypesDaoQueryer interface {
Query(query string, args ...interface{}) (*sql.Rows, error)
Exec(query string, args ...interface{}) (sql.Result, error)
}
// GomaDateTypesDao is generated goma_date_types table.
type GomaDateTypesDao struct {
*sql.DB
TableName string
Columns []string
}
// Query GomaDateTypesDao query
func (g GomaDateTypesDao) Query(query string, args ...interface{}) (*sql.Rows, error) {
return g.DB.Query(query, args...)
}
// Exec GomaDateTypesDao exec
func (g GomaDateTypesDao) Exec(query string, args ...interface{}) (sql.Result, error) {
return g.DB.Exec(query, args...)
}
var _ GomaDateTypesDaoQueryer = (*GomaDateTypesDao)(nil)
// GomaDateTypes is GomaDateTypesDao.
func GomaDateTypes(db *sql.DB) GomaDateTypesDao {
tblDao := GomaDateTypesDao{}
tblDao.DB = db
tblDao.TableName = tableGomaDateTypes
tblDao.Columns = columnsGomaDateTypes
return tblDao
}
// TxGomaDateTypesDao is generated goma_date_types table transaction.
type TxGomaDateTypesDao struct {
*sql.Tx
TableName string
Columns []string
}
// Query TxGomaDateTypesDao query
func (g TxGomaDateTypesDao) Query(query string, args ...interface{}) (*sql.Rows, error) {
return g.Tx.Query(query, args...)
}
// Exec TxGomaDateTypesDao exec
func (g TxGomaDateTypesDao) Exec(query string, args ...interface{}) (sql.Result, error) {
return g.Tx.Exec(query, args...)
}
var _ GomaDateTypesDaoQueryer = (*TxGomaDateTypesDao)(nil)
// TxGomaDateTypes is GomaDateTypesDao.
func TxGomaDateTypes(tx *sql.Tx) TxGomaDateTypesDao {
tblDao := TxGomaDateTypesDao{}
tblDao.Tx = tx
tblDao.TableName = tableGomaDateTypes
tblDao.Columns = columnsGomaDateTypes
return tblDao
}
// SelectAll select goma_date_types table all recode.
func (g GomaDateTypesDao) SelectAll() ([]entity.GomaDateTypes, error) {
return _GomaDateTypesSelectAll(g)
}
// SelectAll transaction select goma_date_types table all recode.
func (g TxGomaDateTypesDao) SelectAll() ([]entity.GomaDateTypes, error) {
return _GomaDateTypesSelectAll(g)
}
func _GomaDateTypesSelectAll(g GomaDateTypesDaoQueryer) ([]entity.GomaDateTypes, error) {
queryString, args, err := queryArgs("goma_date_types", "selectAll", nil)
if err != nil {
return nil, err
}
var es []entity.GomaDateTypes
rows, err := g.Query(queryString, args...)
if err != nil {
return nil, err
}
defer rows.Close()
for rows.Next() {
var e entity.GomaDateTypes
if err := e.Scan(rows); err != nil {
break
}
es = append(es, e)
}
if err != nil {
log.Println(err, queryString)
return nil, err
}
return es, nil
}
// SelectByID select goma_date_types table by primaryKey.
func (g GomaDateTypesDao) SelectByID(id int64) (entity.GomaDateTypes, error) {
return _GomaDateTypesSelectByID(g, id)
}
// SelectByID transaction select goma_date_types table by primaryKey.
func (g TxGomaDateTypesDao) SelectByID(id int64) (entity.GomaDateTypes, error) {
return _GomaDateTypesSelectByID(g, id)
}
func _GomaDateTypesSelectByID(g GomaDateTypesDaoQueryer, id int64) (entity.GomaDateTypes, error) {
argsMap := map[string]interface{}{
"id": id,
}
queryString, args, err := queryArgs("goma_date_types", "selectByID", argsMap)
if err != nil {
return entity.GomaDateTypes{}, err
}
rows, err := g.Query(queryString, args...)
if err != nil {
return entity.GomaDateTypes{}, err
}
defer rows.Close()
if !rows.Next() {
return entity.GomaDateTypes{}, sql.ErrNoRows
}
var e entity.GomaDateTypes
if err := e.Scan(rows); err != nil {
log.Println(err, queryString)
return entity.GomaDateTypes{}, err
}
return e, nil
}
// Insert insert goma_date_types table.
func (g GomaDateTypesDao) Insert(e entity.GomaDateTypes) (sql.Result, error) {
return _GomaDateTypesInsert(g, e)
}
// Insert transaction insert goma_date_types table.
func (g TxGomaDateTypesDao) Insert(e entity.GomaDateTypes) (sql.Result, error) {
return _GomaDateTypesInsert(g, e)
}
func _GomaDateTypesInsert(g GomaDateTypesDaoQueryer, e entity.GomaDateTypes) (sql.Result, error) {
argsMap := map[string]interface{}{
"id": e.ID,
"timestamp_columns": e.TimestampColumns,
"nil_timestamp_columns": e.NilTimestampColumns,
}
queryString, args, err := queryArgs("goma_date_types", "insert", argsMap)
if err != nil {
return nil, err
}
result, err := g.Exec(queryString, args...)
if err != nil {
log.Println(err, queryString)
}
return result, err
}
// Update update goma_date_types table.
func (g GomaDateTypesDao) Update(e entity.GomaDateTypes) (sql.Result, error) {
return _GomaDateTypesUpdate(g, e)
}
// Update transaction update goma_date_types table.
func (g TxGomaDateTypesDao) Update(e entity.GomaDateTypes) (sql.Result, error) {
return _GomaDateTypesUpdate(g, e)
}
// Update update goma_date_types table.
func _GomaDateTypesUpdate(g GomaDateTypesDaoQueryer, e entity.GomaDateTypes) (sql.Result, error) {
argsMap := map[string]interface{}{
"id": e.ID,
"timestamp_columns": e.TimestampColumns,
"nil_timestamp_columns": e.NilTimestampColumns,
}
queryString, args, err := queryArgs("goma_date_types", "update", argsMap)
if err != nil {
return nil, err
}
result, err := g.Exec(queryString, args...)
if err != nil {
log.Println(err, queryString)
}
return result, err
}
// Delete delete goma_date_types table.
func (g GomaDateTypesDao) Delete(id int64) (sql.Result, error) {
return _GomaDateTypesDelete(g, id)
}
// Delete transaction delete goma_date_types table.
func (g TxGomaDateTypesDao) Delete(id int64) (sql.Result, error) {
return _GomaDateTypesDelete(g, id)
}
// Delete delete goma_date_types table by primaryKey.
func _GomaDateTypesDelete(g GomaDateTypesDaoQueryer, id int64) (sql.Result, error) {
argsMap := map[string]interface{}{
"id": id,
}
queryString, args, err := queryArgs("goma_date_types", "delete", argsMap)
if err != nil {
return nil, err
}
result, err := g.Exec(queryString, args...)
if err != nil {
log.Println(err, queryString)
}
return result, err
}
| 26.173228 | 98 | 0.731949 |
06d3d3fcbfb72b630cfccde711744699d4c5e431 | 2,274 | py | Python | maestro/container.py | kstaken/maestro | 5f7537acece4612ef0c9a5b8f59f060aa980468e | [
"MIT"
] | 113 | 2015-01-02T20:42:06.000Z | 2022-02-06T09:48:13.000Z | maestro/container.py | kstaken/maestro | 5f7537acece4612ef0c9a5b8f59f060aa980468e | [
"MIT"
] | 3 | 2015-06-12T10:25:51.000Z | 2020-11-25T04:46:37.000Z | maestro/container.py | toscanini/maestro | 5f7537acece4612ef0c9a5b8f59f060aa980468e | [
"MIT"
] | 15 | 2015-01-30T06:20:23.000Z | 2022-02-06T22:28:50.000Z | import os, sys
from exceptions import ContainerError
import utils, StringIO, logging
import py_backend
class Container:
def __init__(self, name, state, config, mounts=None):
self.log = logging.getLogger('maestro')
self.state = state
self.config = config
self.name = name
self.mounts = mounts
if 'hostname' not in self.config:
self.config['hostname'] = name
#if 'command' not in self.config:
# self.log.error("Error: No command specified for container " + name + "\n")
# raise ContainerError('No command specified in configuration')
self.backend = py_backend.PyBackend()
def create(self):
self._start_container(False)
def run(self):
self._start_container()
def rerun(self):
# Commit the current container and then use that image_id to restart.
self.state['image_id'] = self.backend.commit_container(self.state['container_id'])['Id']
self._start_container()
def start(self):
utils.status("Starting container %s - %s" % (self.name, self.state['container_id']))
self.backend.start_container(self.state['container_id'], self.mounts)
def stop(self, timeout=10):
utils.status("Stopping container %s - %s" % (self.name, self.state['container_id']))
self.backend.stop_container(self.state['container_id'], timeout=timeout)
def destroy(self, timeout=None):
self.stop(timeout)
utils.status("Destroying container %s - %s" % (self.name, self.state['container_id']))
self.backend.remove_container(self.state['container_id'])
def get_ip_address(self):
return self.backend.get_ip_address(self.state['container_id'])
def inspect(self):
return self.backend.inspect_container(self.state['container_id'])
def attach(self):
# should probably catch ctrl-c here so that the process doesn't abort
for line in self.backend.attach_container(self.state['container_id']):
sys.stdout.write(line)
def _start_container(self, start=True):
# Start the container
self.state['container_id'] = self.backend.create_container(self.state['image_id'], self.config)
if (start):
self.start()
self.log.info('Container started: %s %s', self.name, self.state['container_id'])
| 33.940299 | 99 | 0.684257 |
ff6a4aca4dba8e9a2d73153671c922968adad77c | 4,423 | py | Python | tracklets/utils/utils.py | yoyomimi/TNT_pytorch | 165c5da0bc66baf84bb1ddc5fe0cf6a101555c59 | [
"Apache-2.0"
] | 20 | 2020-03-08T14:47:04.000Z | 2021-11-14T12:55:28.000Z | tracklets/utils/utils.py | Mauriyin/TNT_pytorch | fed7e182a45e5cf74d827f090d72251eedbd7cc1 | [
"Apache-2.0"
] | 13 | 2020-03-08T14:39:01.000Z | 2022-03-12T00:18:08.000Z | tracklets/utils/utils.py | Mauriyin/TNT_pytorch | fed7e182a45e5cf74d827f090d72251eedbd7cc1 | [
"Apache-2.0"
] | 6 | 2020-03-08T14:47:11.000Z | 2021-05-21T10:33:05.000Z | # -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
# Created by Mingfei Chen ([email protected])
# Created On: 2020-2-25
# ------------------------------------------------------------------------------
import numpy as np
import pandas as pd
import torch
def get_embeddings(model, frame_feat, max_emb_bs=16):
"""use appearance inference model to get embeddings from frames in fram_list.
Args:
model: pretrained appearance model, eval mode for inference.
frame_feat: (frame_num, 3, size, size).
max_emb_bs: the maximun of the frames fed to the appearance model one time as a batch.
Return:
img_emb_output: (frame_num, emb_dim).
"""
img_bs = frame_feat.shape[0]
p_frame = 0
img_emb = []
while img_bs > max_emb_bs:
img_input = frame_feat[p_frame:p_frame+max_emb_bs]
img_emb.append(model(img_input))
p_frame += max_emb_bs
img_bs -= max_emb_bs
img_input = frame_feat[p_frame:p_frame+img_bs]
if img_bs == 1:
new_input = torch.stack([img_input[0], img_input[0]])
img_emb.append(model(new_input)[-1].view(1, -1))
else:
img_emb.append(model(img_input))
img_emb_output = torch.cat(img_emb)
return img_emb_output
def get_tracklet_pair_input_features(model, img_1, img_2, loc_mat, tracklet_mask_1, tracklet_mask_2, real_window_len, tracklet_pair_features):
"""Reference to the paper "https://arxiv.org/pdf/1811.07258.pdf" Section 4.2 Multi-Scale TrackletNet.
Args:
model: pretrained appearance model, eval mode for inference.
img_1: one batch of tracklet_1_frames, <list>, len eqs batchsize; for each item, <torch.Tensor>, (frame_num, 3, size, size)
img_2: one batch of tracklet_2_frames, <list>, len eqs batchsize; for each item, <torch.Tensor>, (frame_num, 3, size, size)
loc_mat: (bs, window_len, 4), interpolated in the dataset file, indicates the location for each tracklet.
tracklet_mask_1: (bs, window_len, 1), detection status, 1 when there is an object detected.
tracklet_mask_2: (bs, window_len, 1), detection status, 1 when there is an object detected.
tracklet_pair_features: (bs, window_len, emb_dim)
Return:
tracklet_pair_input: (bs, 4+emb_dim, window_len, 3)
"""
assert len(img_1) == len(img_2) == len(tracklet_pair_features)
bs, window_len, emb_dim = tracklet_pair_features.shape
# extract embedding using pretrained appearance model
for i in range(bs):
real_win_len_now = real_window_len[i]
emb_1 = get_embeddings(model, img_1[i])
frame_len_1 = len(emb_1)
emb_2 = get_embeddings(model, img_2[i])
frame_len_2 = len(emb_2)
tracklet_pair_features[i][:frame_len_1] = emb_1.detach()
tracklet_pair_features[i][real_win_len_now-frame_len_2:real_win_len_now] = emb_2.detach()
tracklet_pair_features_np = tracklet_pair_features.cpu().numpy()
# interpolate the embeddings
for i in range(bs):
real_win_len_now = real_window_len[i]
feat_np = tracklet_pair_features_np[i]
feat_np[0][np.where(feat_np[0]==0)] = 1e-5
feat_np[-1][np.where(feat_np[-1]==0)] = 1e-5
feat_pd = pd.DataFrame(data=feat_np).replace(0, np.nan, inplace=False)
feat_pd_np = np.array(feat_pd.interpolate()).astype(np.float32)
if real_win_len_now < window_len:
feat_pd_np[real_win_len_now:] = np.zeros((window_len-real_win_len_now, emb_dim)).astype(np.float32)
tracklet_pair_features[i] = torch.from_numpy(feat_pd_np)
tracklet_pair_features = tracklet_pair_features.cuda(non_blocking=True) # (bs, window_len, emb_dim)
# cat loc_mat (bs, window_len, emb_dim+4, 1)
tracklet_pair_features_with_loc = torch.cat([loc_mat, tracklet_pair_features], dim=-1).unsqueeze(-1)
# expand det mask (bs, window_len, emb_dim+4, 1)
tracklet_mask_1_input = tracklet_mask_1.expand(-1, -1, emb_dim+4).unsqueeze(-1)
tracklet_mask_2_input = tracklet_mask_2.expand(-1, -1, emb_dim+4).unsqueeze(-1)
# cat pair_input (bs, window_len, emb_dim+4, 3)
tracklet_pair_input = torch.cat([tracklet_pair_features_with_loc, tracklet_mask_1_input, tracklet_mask_2_input], dim=-1)
return tracklet_pair_input
| 42.528846 | 142 | 0.656116 |
2d1b18b5cccbc3c410b8a5fc12905b781bd1d43f | 533 | css | CSS | src/components/Welcome/components/WelcomeDevelopers/WelcomeDevelopers.css | archanaserver/ChRIS_store_ui | fa5c31cd6a4b78aa0cfd46cef0e24f4b0336bc83 | [
"MIT"
] | 1 | 2022-01-14T08:19:15.000Z | 2022-01-14T08:19:15.000Z | src/components/Welcome/components/WelcomeDevelopers/WelcomeDevelopers.css | archanaserver/ChRIS_store_ui | fa5c31cd6a4b78aa0cfd46cef0e24f4b0336bc83 | [
"MIT"
] | null | null | null | src/components/Welcome/components/WelcomeDevelopers/WelcomeDevelopers.css | archanaserver/ChRIS_store_ui | fa5c31cd6a4b78aa0cfd46cef0e24f4b0336bc83 | [
"MIT"
] | 1 | 2021-04-13T00:10:15.000Z | 2021-04-13T00:10:15.000Z | .welcome-developers {
/* display */
display:flex;
flex-direction:column;
width:70%;
padding: 6em 2em;
/* font */
font-size: 1.4em;
}
.welcome-developers-header{
/* display */
margin-bottom: 0.5em;
/* font */
font-size: 2em;
line-height: 1.3;
}
.callToAction-btn{
width: max-content;
margin:0 auto;
width: 208.5px;
}
/* ============================== */
/* ---------- RESPONSIVE -------- */
/* ============================== */
@media (min-width: 768px) {
.welcome-developers{
width: 70%;
}
} | 16.151515 | 36 | 0.500938 |
cf3109af0d5fe0227a51b0120e380723f6b6ec82 | 1,908 | php | PHP | resources/views/home.blade.php | jahidul2018/liratextilebd | 9092a02171ce8b57dd535dae0bea18ceb4e4aa0c | [
"MIT"
] | null | null | null | resources/views/home.blade.php | jahidul2018/liratextilebd | 9092a02171ce8b57dd535dae0bea18ceb4e4aa0c | [
"MIT"
] | null | null | null | resources/views/home.blade.php | jahidul2018/liratextilebd | 9092a02171ce8b57dd535dae0bea18ceb4e4aa0c | [
"MIT"
] | null | null | null | @extends('layouts.app')
@section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header"> {{ Auth::user()->name }} {{ __('Admin login Dashboard') }}</div>
<div class="card-body">
@if (session('status'))
<div class="alert alert-success" role="alert">
{{ session('status') }}
</div>
@endif
{{ __('You are logged in! ') }}
<nav class="pcoded-navbar">
<div class="pcoded-inner-navbar main-menu">
<div class="pcoded-navigatio-lavel">Site Navigation</div>
<ul class="pcoded-item pcoded-left-item">
<li class="pcoded-hasmenu">
<a href="{{ url('/admin', []) }}">
<span class="pcoded-micon"><i class="feather icon-home"></i></span>
<span class="pcoded-mtext">Dashboard</span>
</a>
<ul class="pcoded-submenu">
<li class="">
<a href="{{ url('/admin', []) }}">
<span class="pcoded-mtext">Home</span>
</a>
</li>
</ul>
</li>
</ul>
</div>
</nav>
</div>
</div>
</div>
</div>
</div>
@endsection
| 39.75 | 107 | 0.320231 |
f1816e68272d5e0844bfa41322a778ba59ba9ebd | 2,421 | rb | Ruby | spec/hidemyass/proxy/base_spec.rb | appPlant/hidemyass | 0df05187fc11bce4e0a44883b458716f5c1d2fcb | [
"MIT"
] | 3 | 2016-12-24T04:54:35.000Z | 2016-12-24T04:55:02.000Z | spec/hidemyass/proxy/base_spec.rb | appPlant/hidemyass | 0df05187fc11bce4e0a44883b458716f5c1d2fcb | [
"MIT"
] | 1 | 2016-07-14T12:21:05.000Z | 2016-07-19T13:14:59.000Z | spec/hidemyass/proxy/base_spec.rb | appPlant/hidemyass | 0df05187fc11bce4e0a44883b458716f5c1d2fcb | [
"MIT"
] | 1 | 2017-04-07T12:23:45.000Z | 2017-04-07T12:23:45.000Z |
describe HideMyAss::Proxy::Base do
let!(:proxy) { described_class.new(nil) }
describe 'SSL support' do
context 'when protocol is http' do
before { allow(proxy).to receive(:protocol).and_return 'http' }
it('is not supported') { expect(proxy.ssl?).to be false }
end
context 'when protocol is https' do
before { allow(proxy).to receive(:protocol).and_return 'https' }
it('is supported') { expect(proxy.ssl?).to be true }
end
context 'when protocol is socks' do
before { allow(proxy).to receive(:protocol).and_return 'socks4/5' }
it('is supported') { expect(proxy.ssl?).to be true }
end
end
describe 'anonymity' do
before { allow(proxy).to receive(:anonymity).and_return anonymity }
context 'low' do
let(:anonymity) { 0 }
it('is not anonym') { expect(proxy.anonym?).to be false }
end
context 'medium' do
let(:anonymity) { 1 }
it('is anonym') { expect(proxy.anonym?).to be true }
end
context 'high' do
let(:anonymity) { 2 }
it('is anonym') { expect(proxy.anonym?).to be true }
end
end
describe 'security' do
before { allow(proxy).to receive(:anonymity).and_return 1 }
context 'when protocol is HTTP' do
before { allow(proxy).to receive(:protocol).and_return 'http' }
it('is not secure') { expect(proxy.secure?).to be false }
end
context 'when network is not anonym' do
before { allow(proxy).to receive(:anonym?).and_return false }
it('is not secure') { expect(proxy.secure?).to be false }
end
context 'when network is anonym and protocol supports SSL' do
before do
allow(proxy).to receive(:anonym?).and_return true
allow(proxy).to receive(:ssl?).and_return true
end
it('is secure') { expect(proxy.secure?).to be true }
end
end
describe '#url' do
context 'when ip = 1.0.0.1 and port = 80' do
before do
allow(proxy).to receive(:ip).and_return '1.0.0.1'
allow(proxy).to receive(:port).and_return 80
end
it('relative url is 1.0.0.1:80') do
expect(proxy.rel_url).to eq('1.0.0.1:80')
end
context 'and protocol is http' do
before { allow(proxy).to receive(:protocol).and_return 'http' }
it('url is http://1.0.0.1:80') do
expect(proxy.url).to eq('http://1.0.0.1:80')
end
end
end
end
end
| 28.482353 | 73 | 0.61297 |
5c178d0653f13283901f8a3a4b52c8d3f7354951 | 2,088 | kt | Kotlin | sample/src/main/java/com/github/terrakok/cicerone/sample/ui/start/StartActivity.kt | Gaket/Cicerone | e210e45c3633ed04940c5c65ddc4711b1d0e575c | [
"MIT"
] | 2,594 | 2016-10-04T20:11:07.000Z | 2022-03-31T05:39:40.000Z | sample/src/main/java/com/github/terrakok/cicerone/sample/ui/start/StartActivity.kt | JonerGod/Cicerone | e210e45c3633ed04940c5c65ddc4711b1d0e575c | [
"MIT"
] | 136 | 2016-10-13T05:59:46.000Z | 2022-03-29T12:31:39.000Z | sample/src/main/java/com/github/terrakok/cicerone/sample/ui/start/StartActivity.kt | JonerGod/Cicerone | e210e45c3633ed04940c5c65ddc4711b1d0e575c | [
"MIT"
] | 281 | 2016-10-10T21:14:47.000Z | 2022-03-01T19:09:31.000Z | package com.github.terrakok.cicerone.sample.ui.start
import android.os.Bundle
import android.view.View
import com.github.terrakok.cicerone.Navigator
import com.github.terrakok.cicerone.NavigatorHolder
import com.github.terrakok.cicerone.Router
import com.github.terrakok.cicerone.androidx.AppNavigator
import com.github.terrakok.cicerone.sample.R
import com.github.terrakok.cicerone.sample.SampleApplication
import com.github.terrakok.cicerone.sample.mvp.start.StartActivityPresenter
import com.github.terrakok.cicerone.sample.mvp.start.StartActivityView
import moxy.MvpAppCompatActivity
import moxy.presenter.InjectPresenter
import moxy.presenter.ProvidePresenter
import javax.inject.Inject
/**
* Created by terrakok 21.11.16
*/
class StartActivity : MvpAppCompatActivity(), StartActivityView {
@Inject
lateinit var router: Router
@Inject
lateinit var navigatorHolder: NavigatorHolder
@InjectPresenter
lateinit var presenter: StartActivityPresenter
private val navigator: Navigator = AppNavigator(this, -1)
@ProvidePresenter
fun createStartActivityPresenter() = StartActivityPresenter(router)
override fun onCreate(savedInstanceState: Bundle?) {
SampleApplication.INSTANCE.appComponent.inject(this)
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_start)
initViews()
}
private fun initViews() {
findViewById<View>(R.id.ordinary_nav_button).setOnClickListener {
presenter.onOrdinaryPressed()
}
findViewById<View>(R.id.multi_nav_button).setOnClickListener {
presenter.onMultiPressed()
}
findViewById<View>(R.id.result_and_anim_button).setOnClickListener {
presenter.onResultWithAnimationPressed()
}
}
override fun onResume() {
super.onResume()
navigatorHolder.setNavigator(navigator)
}
override fun onPause() {
navigatorHolder.removeNavigator()
super.onPause()
}
override fun onBackPressed() {
presenter.onBackPressed()
}
} | 29.828571 | 76 | 0.7409 |
e7787334357093ef00c920cf8beb07e23ba85498 | 474 | php | PHP | database/factories/TekstopisacFactory.php | milicaVidic/ItehLaravel | 2fdd60112b029e32cf0e66d773797cd8a022909e | [
"MIT"
] | null | null | null | database/factories/TekstopisacFactory.php | milicaVidic/ItehLaravel | 2fdd60112b029e32cf0e66d773797cd8a022909e | [
"MIT"
] | null | null | null | database/factories/TekstopisacFactory.php | milicaVidic/ItehLaravel | 2fdd60112b029e32cf0e66d773797cd8a022909e | [
"MIT"
] | null | null | null | <?php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
class TekstopisacFactory extends Factory
{
/**
* Define the model's default state.
*
* @return array
*/
public function definition()
{
return [
'ime' => $this->faker->firstName(),
'prezime' => $this->faker->lastName(),
'broj_pesama' => $this->faker->numberBetween($min = 1, $max = 500),
];
}
}
| 20.608696 | 80 | 0.563291 |
682ffcba06364510665a75114de068b934b667ac | 1,653 | php | PHP | tests/Helpers.php | MonkDev/monkcms-php | 4ccc8124b1a328a09fc157096cfe72de92935798 | [
"MIT"
] | 1 | 2021-01-18T16:37:22.000Z | 2021-01-18T16:37:22.000Z | tests/Helpers.php | MonkDev/monkcms-php | 4ccc8124b1a328a09fc157096cfe72de92935798 | [
"MIT"
] | 14 | 2017-01-16T20:38:37.000Z | 2019-08-26T01:37:24.000Z | tests/Helpers.php | MonkDev/monkcms-php | 4ccc8124b1a328a09fc157096cfe72de92935798 | [
"MIT"
] | 2 | 2017-06-14T23:53:36.000Z | 2017-09-25T02:32:55.000Z | <?php
namespace Tests;
use PHPUnit\Framework\TestCase;
use Requests_Session;
use Requests_Response;
class Helpers
{
public static function mockRequest(TestCase $testCase)
{
return $testCase->getMockBuilder(Requests_Session::class)
->setMethods(['get'])
->getMock();
}
public static function mockSuccessfulRequest(TestCase $testCase)
{
$request = self::mockRequest($testCase);
$request->method('get')
->willReturn(self::successfulResponse());
return $request;
}
public static function expectSuccessfulRequestToQueryString(TestCase $testCase, $queryString)
{
$request = self::mockSuccessfulRequest($testCase);
$request->expects($testCase->once())
->method('get')
->with($testCase->stringEndsWith($queryString));
return $request;
}
public static function mockFailureRequest(TestCase $testCase)
{
$request = self::mockRequest($testCase);
$request->method('get')
->willReturn(self::failureResponse());
return $request;
}
private static function successfulResponse()
{
$response = new Requests_Response();
$response->body = ' 1{"show":{"title":"Church of Monk"}}';
$response->status_code = 200;
$response->success = true;
return $response;
}
private static function failureResponse()
{
$response = new Requests_Response();
$response->status_code = 400;
$response->success = false;
return $response;
}
}
| 25.828125 | 97 | 0.595886 |
ecdf998723117ccd73624307b65e9d26f9a56032 | 123 | rb | Ruby | db/migrate/20160119043142_add_mpaa_rating_to_movies.rb | alexwilkinson/immedialist-backend | bf00e2ab74159c92449cc59876b663d0edb86846 | [
"MIT"
] | null | null | null | db/migrate/20160119043142_add_mpaa_rating_to_movies.rb | alexwilkinson/immedialist-backend | bf00e2ab74159c92449cc59876b663d0edb86846 | [
"MIT"
] | null | null | null | db/migrate/20160119043142_add_mpaa_rating_to_movies.rb | alexwilkinson/immedialist-backend | bf00e2ab74159c92449cc59876b663d0edb86846 | [
"MIT"
] | null | null | null | class AddMpaaRatingToMovies < ActiveRecord::Migration
def change
add_column :movies, :mpaa_rating, :string
end
end
| 20.5 | 53 | 0.772358 |
e8982291cb5c8c9fee8e88ba78621982dafec74a | 850 | lua | Lua | src/program/lwaftr/alarms.lua | peahonen/snabb | 4b0c18beb86223414fcdbf0dc9e9f5fa5aaa2179 | [
"Apache-2.0"
] | 1,657 | 2016-04-01T09:04:47.000Z | 2022-03-31T18:25:24.000Z | src/program/lwaftr/alarms.lua | peahonen/snabb | 4b0c18beb86223414fcdbf0dc9e9f5fa5aaa2179 | [
"Apache-2.0"
] | 700 | 2016-04-19T17:59:51.000Z | 2020-01-13T13:03:35.000Z | src/program/lwaftr/alarms.lua | peahonen/snabb | 4b0c18beb86223414fcdbf0dc9e9f5fa5aaa2179 | [
"Apache-2.0"
] | 180 | 2016-04-04T15:04:23.000Z | 2022-02-16T23:15:33.000Z | module(..., package.seeall)
alarms = {
[{alarm_type_id='arp-resolution'}] = {
perceived_severity = 'critical',
alarm_text =
'Make sure you can resolve external-interface.next-hop.ip address '..
'manually. If it cannot be resolved, consider setting the MAC '..
'address of the next-hop directly. To do it so, set '..
'external-interface.next-hop.mac to the value of the MAC address.',
},
[{alarm_type_id='ndp-resolution'}] = {
perceived_severity = 'critical',
alarm_text =
'Make sure you can resolve internal-interface.next-hop.ip address '..
'manually. If it cannot be resolved, consider setting the MAC '..
'address of the next-hop directly. To do it so, set '..
'internal-interface.next-hop.mac to the value of the MAC address.',
},
}
| 40.47619 | 78 | 0.629412 |
25e516256f783873445467430704d0415390734c | 1,706 | cs | C# | VisualStudio/Sources/CentralUnitService/LevelModifier/Mapper/ControllerMapperNullObject.cs | Heinzman/DigiRcMan | a81d31871aca8c34914815ca780d2b9b4296b8ad | [
"MIT"
] | null | null | null | VisualStudio/Sources/CentralUnitService/LevelModifier/Mapper/ControllerMapperNullObject.cs | Heinzman/DigiRcMan | a81d31871aca8c34914815ca780d2b9b4296b8ad | [
"MIT"
] | null | null | null | VisualStudio/Sources/CentralUnitService/LevelModifier/Mapper/ControllerMapperNullObject.cs | Heinzman/DigiRcMan | a81d31871aca8c34914815ca780d2b9b4296b8ad | [
"MIT"
] | null | null | null | using System.Collections.Generic;
using Heinzman.BusinessObjects;
namespace Heinzman.CentralUnitService.LevelModifier.Mapper
{
public class ControllerMapperNullObject : IControllerMapper
{
public ControllerMapperNullObject()
{
CreateMapperTable();
}
public Dictionary<ControllerLevel, int> MapperTable { get; private set; }
public ControllerLevel DoWork(ControllerLevel controllerLevel)
{
return controllerLevel;
}
private void CreateMapperTable()
{
MapperTable = new Dictionary<ControllerLevel, int>
{
{ControllerLevel.L0, 0},
{ControllerLevel.L1, 1},
{ControllerLevel.L2, 2},
{ControllerLevel.L3, 3},
{ControllerLevel.L4, 4},
{ControllerLevel.L5, 5},
{ControllerLevel.L6, 6},
{ControllerLevel.L7, 7},
{ControllerLevel.L8, 8},
{ControllerLevel.L9, 9},
{ControllerLevel.L10, 10},
{ControllerLevel.L11, 11},
{ControllerLevel.L12, 12},
{ControllerLevel.L13, 13},
{ControllerLevel.L14, 14},
{ControllerLevel.L15, 15},
};
}
}
}
| 38.772727 | 82 | 0.42204 |
bfc1193dafa07faae4737db9683a3756c577b281 | 1,778 | kt | Kotlin | backend/src/main/kotlin/es/guillermoorellana/keynotedex/backend/api/conference/GetConference.kt | wiyarmir/keynotedex | ec6d7e50d5c7285e6d26f06caaca03a279af38c6 | [
"Apache-2.0"
] | 54 | 2018-06-13T09:47:28.000Z | 2021-11-09T09:34:38.000Z | backend/src/main/kotlin/es/guillermoorellana/keynotedex/backend/api/conference/GetConference.kt | wiyarmir/keynotedex | ec6d7e50d5c7285e6d26f06caaca03a279af38c6 | [
"Apache-2.0"
] | 2 | 2019-02-12T17:20:03.000Z | 2020-12-05T22:07:33.000Z | backend/src/main/kotlin/es/guillermoorellana/keynotedex/backend/api/conference/GetConference.kt | wiyarmir/keynotedex | ec6d7e50d5c7285e6d26f06caaca03a279af38c6 | [
"Apache-2.0"
] | 5 | 2018-09-18T07:08:12.000Z | 2021-05-06T10:53:37.000Z | package es.guillermoorellana.keynotedex.backend.api.conference
import es.guillermoorellana.keynotedex.backend.JsonSerializableConverter
import es.guillermoorellana.keynotedex.backend.data.conferences.ConferenceStorage
import es.guillermoorellana.keynotedex.backend.data.conferences.toDto
import es.guillermoorellana.keynotedex.backend.data.hashids
import es.guillermoorellana.keynotedex.datasource.responses.ConferenceResponse
import es.guillermoorellana.keynotedex.datasource.responses.ConferencesResponse
import es.guillermoorellana.keynotedex.datasource.responses.ErrorResponse
import io.ktor.application.call
import io.ktor.http.ContentType
import io.ktor.http.HttpStatusCode
import io.ktor.locations.KtorExperimentalLocationsAPI
import io.ktor.locations.get
import io.ktor.response.respond
import io.ktor.routing.Route
import io.ktor.routing.accept
@UseExperimental(KtorExperimentalLocationsAPI::class)
fun Route.getConference(conferenceStorage: ConferenceStorage) {
JsonSerializableConverter.register(ConferenceResponse.serializer())
JsonSerializableConverter.register(ConferencesResponse.serializer())
accept(ContentType.Application.Json) {
get<ConferenceEndpoint> { (conferenceId) ->
if (conferenceId == null) {
call.respond(ConferencesResponse(conferenceStorage.conferences().toDto()))
return@get
}
val conference = conferenceId
.let { hashids.decode(it).firstOrNull() }
?.let { conferenceStorage.conference(it) }
when (conference) {
null -> call.respond(HttpStatusCode.NotFound, ErrorResponse("Not found"))
else -> call.respond(ConferenceResponse(conference.toDto()))
}
}
}
}
| 43.365854 | 90 | 0.755906 |
da9916fd7be9d7bc64cb34d30ed0c5ec6a50ccf1 | 1,481 | php | PHP | resources/views/publicidad/modal.blade.php | AdrianPalacios04/adminthormegait | 099508e145baa59ebc2865f74dc9e3d4fbaabd91 | [
"MIT"
] | null | null | null | resources/views/publicidad/modal.blade.php | AdrianPalacios04/adminthormegait | 099508e145baa59ebc2865f74dc9e3d4fbaabd91 | [
"MIT"
] | null | null | null | resources/views/publicidad/modal.blade.php | AdrianPalacios04/adminthormegait | 099508e145baa59ebc2865f74dc9e3d4fbaabd91 | [
"MIT"
] | null | null | null |
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Nueva Marca</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form action="{{url('marca')}}" method="post">
<div class="modal-body">
<input type="text" class="form-control" name="marcas" id="marcas">
</div>
</form>
<div class="modal-footer">
<button type="button" class="btn btn-primary" id="addCode">Save changes</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<script>
// $('body').on('click','#addCode',function(event) {
// // var marcas = $(this).data('marcas');
// var marcas = $('#marcas').val();
// $.ajax({
// type:"POST",
// url:"{{url('marca')}}",
// data:{
// "_token": "{{ csrf_token() }}", // toquen para el metodo POST
// 'marca':marcas // variable que se necesita
// },
// success:function(res){
// window.location.reload(); //refrescar la página
// }
// })
// })
</script>
| 31.510638 | 125 | 0.534774 |
34044d74a5bba51555cad2916901d043660d2d2e | 289 | swift | Swift | Sources/Protocols/Identifiable.swift | useeless37/FinniversKit | 2773784238904d7013e02205ff82f42f988d737f | [
"Apache-2.0"
] | 1 | 2020-12-07T21:42:03.000Z | 2020-12-07T21:42:03.000Z | Sources/Protocols/Identifiable.swift | useeless37/FinniversKit | 2773784238904d7013e02205ff82f42f988d737f | [
"Apache-2.0"
] | null | null | null | Sources/Protocols/Identifiable.swift | useeless37/FinniversKit | 2773784238904d7013e02205ff82f42f988d737f | [
"Apache-2.0"
] | null | null | null | //
// Copyright © FINN.no AS, Inc. All rights reserved.
//
import Foundation
public protocol Identifiable {
static var reuseIdentifier: String { get }
}
public extension Identifiable {
public static var reuseIdentifier: String {
return String(describing: self)
}
}
| 18.0625 | 53 | 0.695502 |
bec0181232768205a97eb29a75a876b4e67f2174 | 1,154 | sql | SQL | db/seed.sql | SleepyJake18/Employee-Management-System | 6817be673026b9a13d54cfbc0e5fc3f33d94fb94 | [
"MIT"
] | null | null | null | db/seed.sql | SleepyJake18/Employee-Management-System | 6817be673026b9a13d54cfbc0e5fc3f33d94fb94 | [
"MIT"
] | null | null | null | db/seed.sql | SleepyJake18/Employee-Management-System | 6817be673026b9a13d54cfbc0e5fc3f33d94fb94 | [
"MIT"
] | null | null | null | USE employees_db;
INSERT INTO department (department_name) VALUES ("Sales");
INSERT INTO department (department_name) VALUES ("Hardware Development");
INSERT INTO department (department_name) VALUES ("Software Development");
INSERT INTO department (department_name) VALUES ("Recruiting");
INSERT INTO roles (title, salary, department_id) VALUES ("Senior Sotware Developer", 70, 3);
INSERT INTO roles (title, salary, department_id) VALUES ("Junior Software Developer", 50, 3);
INSERT INTO roles (title, salary, department_id) VALUES ("Engineer", 50, 2);
INSERT INTO roles (title, salary, department_id) VALUES ("Director", 100, 1);
INSERT INTO roles (title, salary, department_id) VALUES ("Talent Acquisition Specialist", 100, 4);
INSERT INTO employee (first_name, last_name, role_id) VALUES ("Nate", "Russel", 2);
INSERT INTO employee (first_name, last_name, role_id) VALUES ("Jack", "Parker", 1);
INSERT INTO employee (first_name, last_name, role_id) VALUES ("Ben", "Ben", 3);
INSERT INTO employee (first_name, last_name, role_id) VALUES ("Rachel", "Thiim", 4);
INSERT INTO employee (first_name, last_name, role_id) VALUES ("Israel", "Molestina", 5); | 64.111111 | 98 | 0.753033 |
74eecd61093081a45bc80ce1d2b90d4b50c38d2d | 113 | go | Go | echo-server/common/configs.go | LaCumbancha/backup-server | 24df104ae858deb8c6bd564f619299353125ce8c | [
"MIT"
] | null | null | null | echo-server/common/configs.go | LaCumbancha/backup-server | 24df104ae858deb8c6bd564f619299353125ce8c | [
"MIT"
] | null | null | null | echo-server/common/configs.go | LaCumbancha/backup-server | 24df104ae858deb8c6bd564f619299353125ce8c | [
"MIT"
] | null | null | null | package common
type ServerConfig struct {
Port string
StoragePath string
}
const PADDING_CHARACTER = "|"
| 12.555556 | 29 | 0.743363 |
5d088baa36d8e56c9e85b240aeed3993c1dff95c | 3,138 | dart | Dart | lib/src/external/universal_http_client.dart | EdsonMello-code/uno | 636669e8ffa6d389002b2ab41e76907fd84c412d | [
"MIT"
] | 38 | 2021-11-14T10:36:41.000Z | 2022-03-12T22:14:22.000Z | lib/src/external/universal_http_client.dart | EdsonMello-code/uno | 636669e8ffa6d389002b2ab41e76907fd84c412d | [
"MIT"
] | 3 | 2021-11-15T02:56:55.000Z | 2022-01-19T19:44:06.000Z | lib/src/external/universal_http_client.dart | EdsonMello-code/uno | 636669e8ffa6d389002b2ab41e76907fd84c412d | [
"MIT"
] | 3 | 2021-11-15T07:08:26.000Z | 2021-11-16T20:12:30.000Z | import 'dart:convert';
import '../infra/infra.dart';
import 'package:universal_io/io.dart';
class UniversalHttpClient implements HttpDatasource {
final HttpClient client;
const UniversalHttpClient(this.client);
@override
Future<Response> fetch(Request unoRequest) async {
client.connectionTimeout = unoRequest.timeout;
try {
final request = await client.openUrl(unoRequest.method, unoRequest.uri);
for (var key in unoRequest.headers.keys) {
request.headers.set(key, unoRequest.headers[key]!);
}
request.add(unoRequest.bodyBytes);
final response = await request.close();
unoRequest.onDownloadProgress?.call(response.contentLength, 0);
var totalbytes = 0;
final mainStream = response.transform<List<int>>(
StreamTransformer.fromHandlers(
handleData: (value, sink) {
totalbytes += value.length;
unoRequest.onDownloadProgress
?.call(response.contentLength, totalbytes);
sink.add(value);
},
),
);
var data = await _convertResponseData(
mainStream, unoRequest.responseType, unoRequest);
final headers = <String, String>{};
response.headers.forEach((key, values) {
headers[key] = values.join(',');
});
final unoResponse = Response(
request: unoRequest,
status: response.statusCode,
data: data,
headers: headers,
);
return unoResponse;
} on SocketException catch (e, s) {
throw UnoError<SocketException>(
e.toString().replaceFirst('SocketException', ''),
stackTrace: s,
request: unoRequest,
data: e,
);
}
}
dynamic _convertResponseData(Stream<List<int>> mainStream,
ResponseType responseType, Request request) async {
if (responseType == ResponseType.json) {
try {
final buffer = StringBuffer();
await for (var item in mainStream.transform(utf8.decoder)) {
buffer.write(item);
}
return jsonDecode(buffer.toString());
} on FormatException catch (e, s) {
throw UnoError<FormatException>(
'Data body isn`t a json. Please, use other [ResponseType] in request.',
data: e,
request: request,
stackTrace: s,
);
}
} else if (responseType == ResponseType.plain) {
try {
final buffer = StringBuffer();
await for (var item in mainStream.transform(utf8.decoder)) {
buffer.write(item);
}
return buffer.toString();
} on FormatException catch (e, s) {
throw UnoError<FormatException>(
'Data body isn`t a plain text (String). Please, use other [ResponseType] in request.',
data: e,
request: request,
stackTrace: s,
);
}
} else if (responseType == ResponseType.arraybuffer) {
var bytes = <int>[];
await for (var b in mainStream) {
bytes.addAll(b);
}
return bytes;
} else if (responseType == ResponseType.stream) {
return mainStream;
}
}
}
| 29.327103 | 96 | 0.602932 |
20b5a3837d98800d6af3db1760c1887348c065b8 | 9,262 | py | Python | functions/socketio/video.py | VMAJSTER/openstreamingplatform | f002246db922dab9a3f019f46001f3901326feaf | [
"MIT"
] | null | null | null | functions/socketio/video.py | VMAJSTER/openstreamingplatform | f002246db922dab9a3f019f46001f3901326feaf | [
"MIT"
] | null | null | null | functions/socketio/video.py | VMAJSTER/openstreamingplatform | f002246db922dab9a3f019f46001f3901326feaf | [
"MIT"
] | null | null | null | from flask import abort
from flask_security import current_user
from classes.shared import db, socketio
from classes import RecordedVideo
from classes import settings
from classes import notifications
from classes import subscriptions
from functions import system
from functions import webhookFunc
from functions import templateFilters
from functions import videoFunc
from functions import subsFunc
from app import r
@socketio.on('deleteVideo')
def deleteVideoSocketIO(message):
if current_user.is_authenticated:
videoID = int(message['videoID'])
result = videoFunc.deleteVideo(videoID)
if result is True:
db.session.commit()
db.session.close()
return 'OK'
else:
db.session.commit()
db.session.close()
return abort(500)
else:
db.session.commit()
db.session.close()
return abort(401)
@socketio.on('editVideo')
def editVideoSocketIO(message):
if current_user.is_authenticated:
videoID = int(message['videoID'])
videoName = system.strip_html(message['videoName'])
videoTopic = int(message['videoTopic'])
videoDescription = message['videoDescription']
videoAllowComments = False
if message['videoAllowComments'] == "True" or message['videoAllowComments'] == True:
videoAllowComments = True
result = videoFunc.changeVideoMetadata(videoID, videoName, videoTopic, videoDescription, videoAllowComments)
if result is True:
db.session.commit()
db.session.close()
return 'OK'
else:
db.session.commit()
db.session.close()
return abort(500)
else:
db.session.commit()
db.session.close()
return abort(401)
@socketio.on('createClip')
def createclipSocketIO(message):
if current_user.is_authenticated:
videoID = int(message['videoID'])
clipName = system.strip_html(message['clipName'])
clipDescription = message['clipDescription']
startTime = float(message['clipStart'])
stopTime = float(message['clipStop'])
result = videoFunc.createClip(videoID, startTime, stopTime, clipName, clipDescription)
if result[0] is True:
db.session.commit()
db.session.close()
return 'OK'
else:
db.session.commit()
db.session.close()
return abort(500)
else:
db.session.commit()
db.session.close()
return abort(401)
@socketio.on('moveVideo')
def moveVideoSocketIO(message):
if current_user.is_authenticated:
videoID = int(message['videoID'])
newChannel = int(message['destinationChannel'])
result = videoFunc.moveVideo(videoID, newChannel)
if result is True:
db.session.commit()
db.session.close()
return 'OK'
else:
db.session.commit()
db.session.close()
return abort(500)
else:
db.session.commit()
db.session.close()
return abort(401)
@socketio.on('togglePublished')
def togglePublishedSocketIO(message):
sysSettings = settings.settings.query.first()
if current_user.is_authenticated:
videoID = int(message['videoID'])
videoQuery = RecordedVideo.RecordedVideo.query.filter_by(owningUser=current_user.id, id=videoID).first()
if videoQuery is not None:
newState = not videoQuery.published
videoQuery.published = newState
if videoQuery.channel.imageLocation is None:
channelImage = (sysSettings.siteProtocol + sysSettings.siteAddress + "/static/img/video-placeholder.jpg")
else:
channelImage = (sysSettings.siteProtocol + sysSettings.siteAddress + "/images/" + videoQuery.channel.imageLocation)
if newState is True:
webhookFunc.runWebhook(videoQuery.channel.id, 6, channelname=videoQuery.channel.channelName,
channelurl=(sysSettings.siteProtocol + sysSettings.siteAddress + "/channel/" + str(videoQuery.channel.id)),
channeltopic=templateFilters.get_topicName(videoQuery.channel.topic),
channelimage=channelImage, streamer=templateFilters.get_userName(videoQuery.channel.owningUser),
channeldescription=str(videoQuery.channel.description), videoname=videoQuery.channelName,
videodate=videoQuery.videoDate, videodescription=str(videoQuery.description),
videotopic=templateFilters.get_topicName(videoQuery.topic),
videourl=(sysSettings.siteProtocol + sysSettings.siteAddress + '/play/' + str(videoQuery.id)),
videothumbnail=(sysSettings.siteProtocol + sysSettings.siteAddress + '/videos/' + str(videoQuery.thumbnailLocation)))
subscriptionQuery = subscriptions.channelSubs.query.filter_by(channelID=videoQuery.channel.id).all()
for sub in subscriptionQuery:
# Create Notification for Channel Subs
newNotification = notifications.userNotification(templateFilters.get_userName(videoQuery.channel.owningUser) + " has posted a new video to " + videoQuery.channel.channelName + " titled " + videoQuery.channelName, '/play/' + str(videoQuery.id), "/images/" + str(videoQuery.channel.owner.pictureLocation), sub.userID)
db.session.add(newNotification)
db.session.commit()
subsFunc.processSubscriptions(videoQuery.channel.id, sysSettings.siteName + " - " + videoQuery.channel.channelName + " has posted a new video", "<html><body><img src='" +
sysSettings.siteProtocol + sysSettings.siteAddress + sysSettings.systemLogo + "'><p>Channel " + videoQuery.channel.channelName + " has posted a new video titled <u>" +
videoQuery.channelName + "</u> to the channel.</p><p>Click this link to watch<br><a href='" + sysSettings.siteProtocol + sysSettings.siteAddress + "/play/" +
str(videoQuery.id) + "'>" + videoQuery.channelName + "</a></p>")
db.session.commit()
db.session.close()
return 'OK'
else:
db.session.commit()
db.session.close()
return abort(500)
else:
db.session.commit()
db.session.close()
return abort(401)
@socketio.on('togglePublishedClip')
def togglePublishedClipSocketIO(message):
if current_user.is_authenticated:
clipID = int(message['clipID'])
clipQuery = RecordedVideo.Clips.query.filter_by(id=clipID).first()
if clipQuery is not None and current_user.id == clipQuery.recordedVideo.owningUser:
newState = not clipQuery.published
clipQuery.published = newState
if newState is True:
subscriptionQuery = subscriptions.channelSubs.query.filter_by(channelID=clipQuery.recordedVideo.channel.id).all()
for sub in subscriptionQuery:
# Create Notification for Channel Subs
newNotification = notifications.userNotification(templateFilters.get_userName(clipQuery.recordedVideo.owningUser) + " has posted a new clip to " +
clipQuery.recordedVideo.channel.channelName + " titled " + clipQuery.clipName,'/clip/' +
str(clipQuery.id),"/images/" + str(clipQuery.recordedVideo.channel.owner.pictureLocation), sub.userID)
db.session.add(newNotification)
db.session.commit()
db.session.close()
return 'OK'
else:
db.session.commit()
db.session.close()
return abort(500)
else:
db.session.commit()
db.session.close()
return abort(401)
@socketio.on('editClip')
def changeClipMetadataSocketIO(message):
if current_user.is_authenticated:
clipID = int(message['clipID'])
clipName = message['clipName']
clipDescription = message['clipDescription']
result = videoFunc.changeClipMetadata(clipID, clipName, clipDescription)
if result is True:
db.session.commit()
db.session.close()
return 'OK'
else:
db.session.commit()
db.session.close()
return abort(500)
else:
db.session.commit()
db.session.close()
return abort(401)
@socketio.on('deleteClip')
def deleteClipSocketIO(message):
if current_user.is_authenticated:
clipID = int(message['clipID'])
result = videoFunc.deleteClip(clipID)
if result is True:
db.session.commit()
db.session.close()
return 'OK'
else:
db.session.commit()
db.session.close()
return abort(500)
else:
db.session.commit()
db.session.close()
return abort(401) | 41.164444 | 335 | 0.617361 |
c3505840fa0bc4b40a2801adea31678f4873e3c3 | 2,993 | cs | C# | EWKT.Tests/Parsers/EWKTParserTests.cs | 0xRCE/EWKT | a6d4fa0303421675d4e7ae8f51098e60496b4259 | [
"MIT"
] | null | null | null | EWKT.Tests/Parsers/EWKTParserTests.cs | 0xRCE/EWKT | a6d4fa0303421675d4e7ae8f51098e60496b4259 | [
"MIT"
] | null | null | null | EWKT.Tests/Parsers/EWKTParserTests.cs | 0xRCE/EWKT | a6d4fa0303421675d4e7ae8f51098e60496b4259 | [
"MIT"
] | null | null | null | using EWKT.Parsers;
using EWKT.Primitives;
using Microsoft.VisualStudio.TestTools.UnitTesting;
//using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace EWKT.Tests.Parsers
{
[TestClass]
public class EWKTParserTests
{
[TestMethod]
public void Test_EWKTParser_RootGeometry()
{
var ewkt = "POINT (10 20)";
var root = EWKTParser.Convert(ewkt);
Assert.IsNotNull(root);
Assert.IsInstanceOfType(root, typeof(PointZ));
}
[TestMethod]
public void Test_EWKTParser_Point_Negative_Coordinate()
{
var ewkt = "POINT(-1 2.0)";
var parser = EWKTParser.CreateParser(ewkt);
var geom = parser.Parse();
Assert.AreEqual("POINT", geom.Name);
Assert.IsNotNull(geom);
var coordinates = geom.Coordinates.ToList();
Assert.AreEqual(1, coordinates.Count);
Assert.AreEqual("-1 2.0", coordinates[0].Set);
}
[TestMethod]
public void Test_EWKTParser_PointGeometry_Negative_Coordinate()
{
var ewkt = "POINT(-1 2.0)";
var geom = EWKTParser.Convert(ewkt) as PointZ;
Assert.IsNotNull(geom);
var point = geom.Coordinate;
Assert.AreEqual(-1, point.X);
Assert.AreEqual(2.0d, point.Y);
}
[TestMethod]
public void Test_EWKTParser_Null()
{
var ewkt = (string)null;
var geom = EWKTParser.Convert(ewkt);
Assert.IsNull(geom);
}
[TestMethod]
public void Test_EWKTParser_Simple_Polygon()
{
var ewkt = "POLYGON Z((30 10 1,40 40 1,20 40 1,10 20 1,30 10 1))";
var parser = EWKTParser.CreateParser(ewkt);
var geom = parser.Parse();
Assert.AreEqual("POLYGON Z", geom.Name);
Assert.IsNotNull(geom);
var coordinates = geom.Children.First().Coordinates.ToList();
Assert.AreEqual(1, coordinates.Count);
Assert.AreEqual("30 10 1, 40 40 1, 20 40 1, 10 20 1, 30 10 1", coordinates[0].Set);
}
[TestMethod]
public void Test_EWKTParser_Complex_CurvePolygon()
{
var ewkt = "CURVEPOLYGON(CIRCULARSTRING(1 3, 3 5, 4 7, 7 3, 1 3))";
var parser = EWKTParser.CreateParser(ewkt);
var geom = parser.Parse();
Assert.AreEqual("CURVEPOLYGON", geom.Name);
Assert.IsNotNull(geom);
var coordinates = geom.Coordinates.ToList();
Assert.AreEqual(0, coordinates.Count);
var child = geom.Children.FirstOrDefault();
Assert.IsNotNull(child);
coordinates = child.Coordinates.ToList();
Assert.AreEqual(1, coordinates.Count);
Assert.AreEqual("1 3, 3 5, 4 7, 7 3, 1 3", coordinates[0].Set);
}
}
}
| 29.93 | 95 | 0.571667 |
a36ba66972024885edbfbbd4ae3259b213918026 | 2,902 | java | Java | chapter_005_junior_001/src/test/java/ru/job4j/map/CustomHashMapTest.java | andrebatist/job4j | cb8ad39eb6642d4d4ce9f3be4d77eadf6d8bb538 | [
"Apache-2.0"
] | 1 | 2018-11-30T19:03:44.000Z | 2018-11-30T19:03:44.000Z | chapter_005_junior_001/src/test/java/ru/job4j/map/CustomHashMapTest.java | andrebatist/job4j | cb8ad39eb6642d4d4ce9f3be4d77eadf6d8bb538 | [
"Apache-2.0"
] | 1 | 2020-10-13T10:19:40.000Z | 2020-10-13T10:19:40.000Z | chapter_005_junior_001/src/test/java/ru/job4j/map/CustomHashMapTest.java | andrebatist/job4j | cb8ad39eb6642d4d4ce9f3be4d77eadf6d8bb538 | [
"Apache-2.0"
] | null | null | null | package ru.job4j.map;
import org.junit.Test;
import java.util.Iterator;
import static org.hamcrest.core.Is.*;
import static org.junit.Assert.*;
/**
* Test.
*
* @author Plaksin Arseniy ([email protected])
* @version $Id$
* @since 23.04.2019
*/
public class CustomHashMapTest {
@Test
public void whenInsertThenGetByKey() {
CustomHashMap<Integer, String> map = new CustomHashMap<>(2);
assertThat(map.insert(1, "1"), is(true));
assertThat(map.insert(-2, "2"), is(true));
assertThat(map.insert(3, "3"), is(true));
assertThat(map.get(1), is("1"));
assertThat(map.get(-2), is("2"));
assertThat(map.get(3), is("3"));
}
@Test
public void whenInsertExistingKeyThenNewValue() {
CustomHashMap<Integer, String> map = new CustomHashMap<>(2);
assertThat(map.insert(1, "prev"), is(true));
assertThat(map.insert(1, "new"), is(true));
assertThat(map.get(1), is("new"));
}
@Test
public void whenInsertThenContainsAll() {
CustomHashMap<Integer, String> map = new CustomHashMap<>(0);
map.insert(1, "1");
map.insert(2, "2");
map.insert(3, "3");
map.insert(4, "4");
map.insert(5, "5");
assertThat(map.get(1), is("1"));
assertThat(map.get(2), is("2"));
assertThat(map.get(3), is("3"));
assertThat(map.get(4), is("4"));
assertThat(map.get(5), is("5"));
}
@Test
public void whenDeleteThenDoesNotContain() {
CustomHashMap<Integer, String> map = new CustomHashMap<>(2);
map.insert(1, "1");
map.insert(2, "2");
assertThat(map.get(1), is("1"));
assertThat(map.get(2), is("2"));
assertThat(map.delete(1), is(true));
assertThat(map.delete(1), is(false));
assertNull(map.get(1));
assertThat(map.get(2), is("2"));
assertThat(map.delete(2), is(true));
assertThat(map.delete(2), is(false));
assertNull(map.get(2));
}
@Test
public void whenDeleteNonExistingElementThenFalse() {
CustomHashMap<Integer, String> map = new CustomHashMap<>(2);
map.insert(1, "1");
assertThat(map.delete(2), is(false));
}
@Test
public void whenIterateThenGetAllEntries() {
CustomHashMap<Integer, String> map = new CustomHashMap<>(23);
map.insert(1, "1");
map.insert(33, "33");
Iterator it = map.iterator();
assertThat(it.hasNext(), is(true));
CustomHashMap.Entry<Integer, String> entry = (CustomHashMap.Entry<Integer, String>) it.next();
assertThat(entry.getKey(), is(1));
assertThat(entry.getValue(), is("1"));
entry = (CustomHashMap.Entry<Integer, String>) it.next();
assertThat(entry.getKey(), is(33));
assertThat(entry.getValue(), is("33"));
assertThat(it.hasNext(), is(false));
}
} | 32.244444 | 102 | 0.5796 |
2f4be795ebad8a78dd5fbd11b22652cf605782a0 | 594 | js | JavaScript | cmd/mailslurper/www/mailslurper/templates/helpers/pageSelector.js | aidenjude/mailslurper | 9db722857672e7192640ecfeec8923b89308f022 | [
"MIT"
] | 1,135 | 2015-05-13T04:28:10.000Z | 2022-03-30T09:43:22.000Z | cmd/mailslurper/www/mailslurper/templates/helpers/pageSelector.js | aidenjude/mailslurper | 9db722857672e7192640ecfeec8923b89308f022 | [
"MIT"
] | 141 | 2015-08-04T18:16:19.000Z | 2022-02-02T00:20:33.000Z | cmd/mailslurper/www/mailslurper/templates/helpers/pageSelector.js | aidenjude/mailslurper | 9db722857672e7192640ecfeec8923b89308f022 | [
"MIT"
] | 173 | 2015-08-23T07:30:25.000Z | 2022-02-24T03:38:49.000Z | // Copyright 2013-2018 Adam Presley. All rights reserved
// Use of this source code is governed by the MIT license
// that can be found in the LICENSE file.
"use strict";
Handlebars.registerHelper("pageSelector", function (elementName, totalPages, currentPage) {
var html = "<select id=\"" + elementName + "\" class=\"form-control\">";
for (var index = 1; index <= totalPages; index++) {
html += "<option value=\"" + index + "\"";
html += (currentPage == index) ? " selected=\"selected\"" : "";
html += ">" + index;
html += "</option>";
}
html += "</select>";
return html;
});
| 29.7 | 91 | 0.627946 |
40f4cc8679c0f1ae76d2475c39fa51bd5ebba8b6 | 672 | rb | Ruby | app/models/submission.rb | sirsean/skynet | 21089bc5c12368ec4fec568d0c75e4ccde67f8c4 | [
"Apache-2.0"
] | 1 | 2016-11-21T01:49:12.000Z | 2016-11-21T01:49:12.000Z | app/models/submission.rb | sirsean/skynet | 21089bc5c12368ec4fec568d0c75e4ccde67f8c4 | [
"Apache-2.0"
] | null | null | null | app/models/submission.rb | sirsean/skynet | 21089bc5c12368ec4fec568d0c75e4ccde67f8c4 | [
"Apache-2.0"
] | null | null | null | class Submission < ActiveRecord::Base
self.per_page = 10
mount_uploader :photo, PhotoUploader
belongs_to :user
has_many :votes
def can_delete?(u)
!u.nil? && (u == self.user || u.admin?)
end
def self.nearby(lat, long, miles)
find_by_sql ["SELECT *,
SQRT(
POW(69.1 * (latitude - ?), 2) +
POW(69.1 * (? - longitude) * COS(latitude / 57.3), 2)) AS distance
FROM #{table_name} GROUP BY id HAVING (
SQRT(
POW(69.1 * (latitude - ?), 2) +
POW(69.1 * (? - longitude) * COS(latitude / 57.3), 2))
)< ? ORDER BY distance ASC LIMIT 20", lat, long, lat, long, miles]
end
end
| 29.217391 | 78 | 0.549107 |
a7eaf398134428d28a7a0f6ce1d94fb6b2cba4b0 | 238 | h | C | viewController/homeController/QuanXianViewController.h | zccdy/XBHEBProject | 62a62b9c74aa3975e15c20f821817864e81dcd04 | [
"MIT"
] | null | null | null | viewController/homeController/QuanXianViewController.h | zccdy/XBHEBProject | 62a62b9c74aa3975e15c20f821817864e81dcd04 | [
"MIT"
] | null | null | null | viewController/homeController/QuanXianViewController.h | zccdy/XBHEBProject | 62a62b9c74aa3975e15c20f821817864e81dcd04 | [
"MIT"
] | null | null | null | //
// QuanXianViewController.h
// XBHEBProject
//
// Created by xubh-note on 15/5/8.
// Copyright (c) 2015年 xu banghui. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface QuanXianViewController : UITableViewController
@end
| 17 | 57 | 0.718487 |
f46e4ecb59fec9bec762e2ac163cdcaaaa6758e3 | 1,126 | cs | C# | Scripts/Functions/Math.cs | M-T-Asagi/ScriptsUnityUtil | 52d5897486d62ed3ed235f87053904c62d80e44a | [
"MIT"
] | null | null | null | Scripts/Functions/Math.cs | M-T-Asagi/ScriptsUnityUtil | 52d5897486d62ed3ed235f87053904c62d80e44a | [
"MIT"
] | null | null | null | Scripts/Functions/Math.cs | M-T-Asagi/ScriptsUnityUtil | 52d5897486d62ed3ed235f87053904c62d80e44a | [
"MIT"
] | null | null | null | using UnityEngine;
namespace AsagiHandyScripts
{
static public class Math
{
static public Vector2Int GreatestCommonResolution(int maxOfPixels, Vector2Int originalResolution)
{
int gcd = GetGreatestCommonDivisor(originalResolution.x, originalResolution.y);
Vector2Int aspect = originalResolution;
aspect.x /= gcd;
aspect.y /= gcd;
float magni = Mathf.Sqrt((float)maxOfPixels / (float)(aspect.x * aspect.y));
return new Vector2Int(Mathf.CeilToInt(aspect.x * magni), Mathf.CeilToInt(aspect.y * magni));
}
static public int GetGreatestCommonDivisor(int a, int b)
{
int big = Mathf.Max(a, b);
int small = Mathf.Min(a, b);
if (small == 0)
return big;
return GetGreatestCommonDivisor(small, big % small);
}
static public int PowInt(int x, int y)
{
int result = 1;
for (int i = 0; i < y; i++)
{
result *= x;
}
return result;
}
}
} | 28.15 | 105 | 0.539964 |
e2f5e9c8a09680181641113cfaa9943a094941ba | 2,609 | py | Python | test/generate_tones.py | merlinran/acorn-precision-farming-rover | 228bbeb537550df79ae57985c427975ffa828bcd | [
"Apache-2.0"
] | 143 | 2021-02-23T16:17:32.000Z | 2022-03-30T09:42:27.000Z | test/generate_tones.py | Twisted-Fields/acorn-precision-farming-rover | 228bbeb537550df79ae57985c427975ffa828bcd | [
"Apache-2.0"
] | 19 | 2021-05-13T19:03:21.000Z | 2022-03-25T08:46:44.000Z | test/generate_tones.py | merlinran/acorn-precision-farming-rover | 228bbeb537550df79ae57985c427975ffa828bcd | [
"Apache-2.0"
] | 17 | 2021-02-23T22:02:24.000Z | 2022-03-20T15:12:20.000Z | from tones import SINE_WAVE, SAWTOOTH_WAVE
from tones.mixer import Mixer
# Create mixer, set sample rate and amplitude
mixer = Mixer(44100, 0.5)
# Create two monophonic tracks that will play simultaneously, and set
# initial values for note attack, decay and vibrato frequency (these can
# be changed again at any time, see documentation for tones.Mixer
mixer.create_track(0, SAWTOOTH_WAVE, vibrato_frequency=20.0,
vibrato_variance=30.0, attack=0.01, decay=0.1)
#mixer.create_track(1, SINE_WAVE, attack=0.01, decay=0.1)
# Add a 1-second tone on track 0, slide pitch from c# to f#)
mixer.add_note(0, note='c#', octave=5, duration=1.0, endnote='f#')
# Add a 1-second tone on track 1, slide pitch from f# to g#)
# mixer.add_note(0, note='f#', octave=5, duration=1.0, endnote='g#')
# Mix all tracks into a single list of samples and write to .wav file
mixer.write_wav('complete.wav')
# Create mixer, set sample rate and amplitude
mixer = Mixer(44100, 0.5)
# Create two monophonic tracks that will play simultaneously, and set
# initial values for note attack, decay and vibrato frequency (these can
# be changed again at any time, see documentation for tones.Mixer
#mixer.create_track(0, SAWTOOTH_WAVE, vibrato_frequency=7.0, vibrato_variance=30.0, attack=0.01, decay=0.1)
mixer.create_track(0, SINE_WAVE, attack=0.01, decay=0.1)
# Add a 1-second tone on track 0, slide pitch from c# to f#)
mixer.add_note(0, note='a', octave=5, duration=0.25,
endnote='a', vibrato_frequency=7.0)
# Add a 1-second tone on track 1, slide pitch from f# to g#)
# mixer.add_note(0, note='c', octave=5, duration=1.0, endnote='a')
# Mix all tracks into a single list of samples and write to .wav file
mixer.write_wav('wait.wav')
# Create mixer, set sample rate and amplitude
mixer = Mixer(44100, 0.5)
# Create two monophonic tracks that will play simultaneously, and set
# initial values for note attack, decay and vibrato frequency (these can
# be changed again at any time, see documentation for tones.Mixer
mixer.create_track(0, SAWTOOTH_WAVE, vibrato_frequency=7.0,
vibrato_variance=30.0, attack=0.01, decay=0.1)
#mixer.create_track(0, SINE_WAVE, attack=0.01, decay=0.1)
# Add a 1-second tone on track 0, slide pitch from c# to f#)
mixer.add_note(0, note='f', octave=5, duration=4.0,
endnote='g', vibrato_frequency=2.0)
# Add a 1-second tone on track 1, slide pitch from f# to g#)
# mixer.add_note(0, note='c', octave=5, duration=1.0, endnote='a')
# Mix all tracks into a single list of samples and write to .wav file
mixer.write_wav('error.wav')
| 41.412698 | 107 | 0.721732 |
d64527b69329b479e82f2e4cfec20b40ea75c0a1 | 718 | cs | C# | mcs/tests/test-var-02.cs | lefb766/mono | 4f458a4ff72bc6c5e07f82aec9040d355cbb8f5c | [
"Apache-2.0"
] | 469 | 2019-01-23T12:21:59.000Z | 2022-03-10T15:50:42.000Z | mcs/tests/test-var-02.cs | lefb766/mono | 4f458a4ff72bc6c5e07f82aec9040d355cbb8f5c | [
"Apache-2.0"
] | 83 | 2015-07-16T01:31:41.000Z | 2016-01-13T02:15:47.000Z | mcs/tests/test-var-02.cs | lefb766/mono | 4f458a4ff72bc6c5e07f82aec9040d355cbb8f5c | [
"Apache-2.0"
] | 36 | 2019-01-23T22:17:09.000Z | 2022-01-20T15:41:34.000Z |
// Tests variable type inference with the var keyword when assigning to user-defined types
using System;
public class Class1
{
public bool Method()
{
return true;
}
public int Property = 16;
}
public class Test
{
private class Class2
{
public bool Method()
{
return true;
}
public int Property = 42;
}
public static int Main ()
{
var class1 = new Class1 ();
if (class1.GetType () != typeof (Class1))
return 1;
if (!class1.Method ())
return 2;
if (class1.Property != 16)
return 3;
var class2 = new Class2();
if (class2.GetType () != typeof (Class2))
return 4;
if (!class2.Method ())
return 5;
if (class2.Property != 42)
return 6;
return 0;
}
}
| 15.276596 | 90 | 0.622563 |
25ef47d3ca65836b091c44f369ae3380435c1732 | 449 | cs | C# | Assets/Scripts/UI/UI_Item.cs | InFaNsO/CorperateSim | bb312bf11b9cecd3aee8de2f3d7a8ea92f2d5409 | [
"MIT"
] | null | null | null | Assets/Scripts/UI/UI_Item.cs | InFaNsO/CorperateSim | bb312bf11b9cecd3aee8de2f3d7a8ea92f2d5409 | [
"MIT"
] | null | null | null | Assets/Scripts/UI/UI_Item.cs | InFaNsO/CorperateSim | bb312bf11b9cecd3aee8de2f3d7a8ea92f2d5409 | [
"MIT"
] | null | null | null | using Michsky.UI.ModernUIPack;
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
public class UI_Item : MonoBehaviour
{
[SerializeField] public Image myImage;
[SerializeField] public TMP_Text myText;
[SerializeField] public Item myItem;
[SerializeField] public ButtonManagerBasic myButton;
public void Logger()
{
Debug.Log("Button Pressed");
}
}
| 22.45 | 56 | 0.737194 |
218690c6ea0e0fc00cdf2a744c5d9e2521be9247 | 22,917 | js | JavaScript | shop/public/order/pay/header_7e581c3.js | anxuefei/anxuefeithinkphp | 05329b8c8e48743d0409e63d5ab4eb2e8e9591a6 | [
"Apache-2.0"
] | null | null | null | shop/public/order/pay/header_7e581c3.js | anxuefei/anxuefeithinkphp | 05329b8c8e48743d0409e63d5ab4eb2e8e9591a6 | [
"Apache-2.0"
] | null | null | null | shop/public/order/pay/header_7e581c3.js | anxuefei/anxuefeithinkphp | 05329b8c8e48743d0409e63d5ab4eb2e8e9591a6 | [
"Apache-2.0"
] | null | null | null | function ContentBuildFun(e,t,i,s){for(var n="<dl><dt>"+e+"(<span>"+i+"</span>)</dt>",a=0;a<t.length;a++){var o=0;switch(e){case"手机":o=1;break;case"配件":o=2;break;case"服务":o=3;break;default:o=4}var r='{cfrom:9103, name:"'+t[a].name+'", keyword: "'+s+'",result_type:'+o+", search_page:1}",l=$('<dd><a href="'+t[a].url+'">'+t[a].name+"</a></dd>");l.find("a").attr("data-track",r),n+=l.prop("outerHTML")}return n+="</dl>"}function SearchKeyEvent(e){this.$searchWrap=$(e.wrap),this.$searchInput=this.$searchWrap.find(e.input),this.$searchlist=this.$searchWrap.find(e.list).children("dl"),this.special=e.special||null,this.mutil=this.check_mutil(),this.limitHeight=0,this.check_elements(e.list),this.addkey_press()}function getKeyName(e){switch(e.which){case 38:return"up";case 40:return"down";case 13:return"enter"}}function initHomeLogin(e){if(!(e.length<=0)){var t=$("#J_topCartNum");$.ajax({url:webCtx+"/tool/cookie?t="+(new Date).getTime(),type:"get",dataType:"json",success:function(i){e[0]._isLogin=!!i.vivo_account_cookie_iqoo_openid,e[0]._isLogin?(e.find("span").html("账号中心"),t.show()):(e.find("span").html("登录/注册"),t.hide()),e.on("click",function(){this._isLogin?location.href="//passport.vivo.com.cn/":LoginConfirm.redirect()})}})}}!function(e){function t(){var e=v.round;this.isplay=!1,this.rounds=[],this.box=new createjs.Container,this.handle=null,p.addChild(this.box);for(var t=0;t<e.offsetArr.length;t++)this.rounds.push(new i(t)),this.box.addChild(this.rounds[t].ele)}function i(e){var t=v.round,i=t.offsetArr[e].split(",");this.color=t.color,this.speed=t.speed+d(.008,.006),this.isParent=!!parseInt(i[0]),this.isDot=!!parseInt(i[1]),this.width=6*parseFloat(i[2]),this.radius=parseFloat(i[3])*u/2,this.alpha=parseFloat(i[4]),this.x=u*parseFloat(i[5]),this.y=u*parseFloat(i[6]),this.angle=d(1,-1)*f,this.direct=this.angle>f/2?-1:1,this.vector=this.isParent?new a(this.x,this.y,0,0):new a(this.x,this.y,this.radius,this.angle),this.draw()}function s(){var e=v.planet;this.planets=[],this.connector=new createjs.Container,this.box=new createjs.Container,this.handle=null,this.isplay=!1,p.addChild(this.connector,this.box);for(var t=0;t<e.size;t++)this.planets.push(new n(e)),this.box.addChild(this.planets[t].ele)}function n(e){this.planet=e,this.x=d(1.2*u,u),this.y=d(.6*u,.3*u),this.length=d(.4*u,.2*u),this.angle=d(1,-1)*f,this.alpha=d(1,.1),this.direct=this.angle>f/2?-1:1,this.speed=this.planet.speed+d(.008,.001),this.vector=new a(this.x,this.y,this.length,this.angle*this.direct,this.alpha),this.draw()}function a(e,t,i,s,n){this.startX=e,this.startY=t,this.alpha=n,this.angle=s,this.setX=function(e){tihs.startX=e},this.setY=function(e){this.startY=e},this.getAngle=function(){return this.angle},this.setAngle=function(e){this.angle=e,this.x=this.startX+Math.cos(this.angle)*this.length,this.y=this.startY+Math.sin(this.angle)*this.length},this.getLength=function(){return this.length},this.setLength=function(e){this.length=e,this.x=Math.cos(this.angle)*this.length,this.Y=Math.sin(this.angle)*this.length},this.getDistance=function(e){var t=e.x-this.x,i=e.y-this.y;return Math.sqrt(t*t+i*i)},this.setLength(i),this.setAngle(s)}function o(){var e=v.circle;this.circles=[],this.isplay=!1,this.box=new createjs.Container,this.handle=null,p.addChild(this.box);for(var t=0;t<e.offsetArr.length;t++)this.circles.push(new r(t,e)),this.box.addChild(this.circles[t].ele)}function r(e,t){var i=t.offsetArr[e].split(","),s=i[0],n=i[1];this.playend=!1,this.index=e,this.direct=i[2],this.ele=new createjs.Container,this.ele.alpha=i[3],this.x=c+s*this.direct,this.y=c/2+n*this.direct,this.ele.x=this.xcache=this.x,this.ele.y=this.ycache=this.y,this.r=.7*c*i[5],this.color=t.color,this.angle=d(2*Math.PI,0),this.width=i[4],this.dotWidth=this.width*(this.width>3?1.5:2),this.box=new createjs.Container,this.box.x=this.x,this.box.y=this.y,this.box.regX=this.x,this.box.regY=this.y,this.duration=this.r/l*10,this.block=0,this.ele.addChild(this.box),this.draw()}var l,h,c,u,p,d=function(e,t,i){var e=e||0===e?e:1,t=t||0,s=t+(e-t)*Math.random();return i?Math.round(s):s},f=2*Math.PI,v=(Math.PI/180,180*Math.PI,{circle:{offsetArr:["5,0,1,0.3,2,0.6","-10,20,-1,0.5,1,0.8","-15,-10,-1,0.8,2,0.9","5,-5,1,1,4,1"],color:"#008cd6"},planet:{size:50,speed:.005,color:"#008cd6"},round:{offsetArr:["1,0,0.4,0.6,0.3,1,0.5","0,1,0.4,0.6,0.3,1,0.5","0,0,0.4,0.6,0.3,1,0.5","1,0,0.5,0.35,0.5,1.05,0.3","0,1,0.5,0.35,0.5,1.05,0.3","1,0,0.7,0.2,0.7,0.83,0.65","0,1,0.7,0.2,0.7,0.83,0.65","1,0,0.7,0.1,1,1,0.8","0,1,0.7,0.1,1,1,0.8"],color:"#008cd6",speed:.008}});t.prototype.loop=function(){for(var e=this.rounds,t=0;t<e.length;t++)e[t].update();this.handle=requestAnimationFrame(this.loop.bind(this))},t.prototype.play=function(){!this.isplay&&(this.loop(),this.isplay=!0)},t.prototype.stop=function(){this.handle&&this.isplay&&(cancelAnimationFrame(this.handle),this.handle=null,this.isplay=!1)},i.prototype.draw=function(){this.ele=new createjs.Shape;var e;this.isDot?(e=6,this.ele.graphics.f(this.color).dc(this.vector.x,this.vector.y,e)):(e=this.isParent?this.radius:this.radius*d(.15,.08),this.ele.graphics.s(this.color).ss(this.width).dc(this.vector.x,this.vector.y,e)),this.ele.alpha=this.alpha,this.ele.x=this.vector.x,this.ele.y=this.vector.y,this.ele.regX=this.vector.x,this.ele.regY=this.vector.y},i.prototype.update=function(){var e=this.vector;e.setAngle(this.speed*this.direct+e.getAngle()),this.ele.x=e.x,this.ele.y=e.y},s.prototype.drawLine=function(e,t){var i=new createjs.Shape;i.graphics.ss(4*t.alpha).s("#008cd6").mt(e.x,e.y).lt(t.x,t.y),i.alpha=t.alpha,this.connector.addChild(i)},s.prototype.loop=function(){for(var e=this.planets,t=0;t<e.length;t++)e[t].update();this.connector.removeAllChildren();for(var t=0;t<e.length;t++)for(var i=e[t],s=0;s<e.length;s++){var n=e[s],a=n.vector.getDistance(i.vector);i!=n&&.3*c>a&&this.drawLine(i.vector,n.vector)}this.handle=requestAnimationFrame(this.loop.bind(this))},s.prototype.play=function(){!this.isplay&&(this.loop(),this.isplay=!0)},s.prototype.stop=function(){this.handle&&this.isplay&&(cancelAnimationFrame(this.handle),this.handle=null,this.isplay=!1)},n.prototype.draw=function(){this.ele=new createjs.Shape,this.ele.graphics.f(this.planet.color).dc(this.vector.x,this.vector.y,6),this.ele.x=this.vector.x,this.ele.alpha=this.vector.alpha,this.ele.y=this.vector.y,this.ele.regX=this.vector.x,this.ele.regY=this.vector.y},n.prototype.update=function(){var e=this.vector;e.setAngle(this.speed*this.direct+e.getAngle()),this.ele.x=e.x,this.ele.y=e.y},o.prototype.loop=function(){for(var e=this.circles,t=0;t<e.length;t++)e[t].update();this.handle=requestAnimationFrame(this.loop.bind(this))},o.prototype.play=function(){!this.isplay&&(this.loop(),this.isplay=!0)},o.prototype.stop=function(){this.handle&&this.isplay&&(cancelAnimationFrame(this.handle),this.handle=null,this.isplay=!1)},r.prototype.draw=function(){var e=new createjs.Shape;e.graphics.s(this.color).ss(this.width).dc(this.x,this.y,this.r),this.dot=new createjs.Shape,this.dx=this.x+this.r*Math.cos(this.angle),this.dy=this.y+this.r*Math.sin(this.angle),this.dot.graphics.f(this.color).dc(this.dx,this.dy,this.dotWidth),this.box.addChild(e,this.dot)},r.prototype.update=function(){var e=f/this.duration*this.direct;this.box.rotation=this.box.rotation+e,this.block+=d(.01*Math.PI,.001*Math.PI),this.box.x=this.box.x+.2*Math.sin(this.block*this.direct),this.box.y=this.box.y+.2*Math.cos(this.block*this.direct)},e.Emitter=function(e,t){this.type=t||"circle",this.wrap=document.getElementById(e),this._canvas=document.createElement("canvas"),this.wrap.appendChild(this._canvas),p=null,this.init()},Emitter.prototype.init=function(){this._stage=new createjs.Stage(this._canvas),p=this.container=new createjs.Container,this.ant=null,this._stage.addChild(p),this.resize(),this.create(this.type),this.containx=this.container.x=c,this.container.alpha=0,this._canvas.width=2*l,this._canvas.height=2*c,e.addEventListener("resize",this.resize.bind(this)),createjs.Ticker.setFPS(30),createjs.Ticker.addEventListener("tick",this._stage)},Emitter.prototype.create=function(){switch(this.type){case"round":this.ant=new t;break;case"planet":this.ant=new s;break;default:this.ant=new o}},Emitter.prototype.in=function(e){var e=e||function(){};TweenMax.killTweensOf(this.container),TweenMax.to(this.container,.8,{x:this.containx-c,alpha:1,delay:.02,ease:Ease.easeIn,onComplete:e})},Emitter.prototype.out=function(e){var e=e||function(){};TweenMax.killTweensOf(this.container),TweenMax.to(this.container,.5,{x:this.containx+c,alpha:0,delay:.02,ease:Back.easeInOut,onComplete:e})},Emitter.prototype.play=function(){this.ant&&this.ant.play(),this.ant&&this.in()},Emitter.prototype.stop=function(){var e=this;this.ant&&this.out(function(){e.ant.stop()})},Emitter.prototype.resize=function(){var e=this.wrap.getBoundingClientRect();l=e.width,c=e.height,h=2*l,u=2*c,this._canvas.style.width=l+"px",this._canvas.style.height=c+"px"};for(var $=0,m=["ms","moz","webkit","o"],y=0;y<m.length&&!e.requestAnimationFrame;++y)e.requestAnimationFrame=e[m[y]+"RequestAnimationFrame"],e.cancelAnimationFrame=e[m[y]+"CancelAnimationFrame"]||e[m[y]+"CancelRequestAnimationFrame"];e.requestAnimationFrame||(e.requestAnimationFrame=function(t){var i=(new Date).getTime(),s=Math.max(0,16-(i-$)),n=e.setTimeout(function(){t(i+s)},s);return $=i+s,n}),e.cancelAnimationFrame||(e.cancelAnimationFrame=function(e){clearTimeout(e)})}(window);var Menu=function(){function e(){for(var e=0;e<a.size();e++)TweenMax.set(a.eq(e),{x:s.eq(e).offset().left})}var t=$(window),i=$("#vivo-head-wrap"),s=i.find(".series"),n=i.find(".gb-vivo-menu-series"),a=n.find("ul");e();var o=new TimelineMax({paused:!0}),r=!1;self.menuOpen=r;var l,h;o.from(n,.5,{height:0}),s.each(function(){this.handle=new TimelineMax({paused:!0}),this.handle.staggerFrom(a.eq($(this).index()).find("li"),.45,{y:-25,autoAlpha:0,ease:Ease.easeIn},.1,"+=.5").from(a.eq($(this).index()),.6,{height:0},.3),TweenMax.set(n,{autoAlpha:1}),$(this).hover(function(){clearTimeout(l,h);var e=this;e.wrap=e.wrap||$(e).data("wrap"),e.type=e.type||$(e).data("type"),r=!0,!e.c&&Modernizr.canvas&&e.wrap&&$("#"+e.wrap).size()>0&&(e.c=new Emitter(e.wrap,e.type)),$(this).siblings(".series").mouseleave(),h=setTimeout(function(){o.timeScale(1.5).play(),e.handle.timeScale(1.5).play(),e.c&&e.c.play()},100)},function(){r=!1;var e=this;l=setTimeout(function(){r||(o.timeScale(1.5).reverse(),e.handle.timeScale(4).reverse(),e.c&&e.c.stop())},100)})}),n.hover(function(){r=!0},function(){r=!1,s.mouseleave()}),t.on({resize:e})}(),searchUrlConfig={getKeyWords:HOMEURL+"/search/ajax/recWords",getAssciate:HOMEURL+"/search/ajax/assResult",globalSearch:HOMEURL+"/search"};!function(e){e.setSearchUrl=function(e,t){searchUrlConfig[e]&&(searchUrlConfig[e]=t.toString())},e.curl=function(e,t,i){var s=""==e?1==t?i:!1:e,n=searchUrlConfig.globalSearch+"?q="+s;s&&Vtrack.clickStats({cfrom:9102,keyword:s,search_page:1}),s&&(window.location.href=n)}}(window);var $box=$("#vivo-head-wrap .gb-vivo-head"),$title=$box.find(".nav-gb"),$searchBox=$box.find(".v_h_search"),$searchOpen=$box.find(".nav-t-search"),$searchClose=$searchBox.find(".search-close"),$searchResults=$searchBox.find(".results"),$input=$searchBox.find("input"),$contentBox=$searchBox.find(".search-content"),$link=$contentBox.find(".link"),$userBtn=$(".nav-t-user"),$msearchBox=$(".gb-vivo-s-nav"),$mresults=$msearchBox.find(".results"),$mmenulist=$msearchBox.find("li"),SearchBuild={LinkBuild:function(e){for(var t='<dt><a href="#">全局搜索</a></dt>',i=0;i<e.length;i++)t+='<dd><a href="'+e[i].linkUrl+'">'+e[i].word+"</a></dd>";return t},ContentBuild:function(e){var t=e.keyword;delete e.keyword;var i="";for(var s in e){var n=e[s].name,a=e[s].value,o=e[s].number;i+=ContentBuildFun(n,a,o,t)}return i}};SearchKeyEvent.prototype.addkey_press=function(){var e=this;return e.$searchlist.children("dd").size()<1?!1:void $(document).on({keyup:function(t){if(!e.isvisible())return!1;var i=getKeyName(t),s=e.islast(),n=e.isfirst();if("up"==i&&!n){var a=e.$searchlist.eq(0).children("dd");if(a.first().hasClass("current"))a.first().removeClass("current"),e.$searchInput.focus();else{var o=e.$searchlist.children(".current");if(o.index()===e.$searchlist.children("dt").index()+1){var r=o.parent().index(),l=e.check_elements(r,"up");return o.removeClass("current"),l||0===l?(e.$searchlist.eq(l).children("dd").last().addClass("current"),!1):(e.$searchInput.focus(),!1)}o.prev("dd").addClass("current").siblings().removeClass("current")}}if("down"==i&&!s)if(n)e.$searchlist.children("dd").first().addClass("current"),e.$searchInput.blur();else{var o=e.$searchlist.children(".current");if(o.index()===o.parent().children().last().index()){var r=o.parent().index(),l=e.check_elements(r);return l?(o.removeClass("current"),e.$searchlist.eq(l).children("dd").first().addClass("current"),!1):!1}o.next("dd").addClass("current").siblings().removeClass("current")}if("enter"==i&&!n){var h=e.$searchlist.find(".current a").attr("href");location.href=h}t.preventDefault()}})},SearchKeyEvent.prototype.check_mutil=function(){return this.$searchlist.size()>1?!0:!1},SearchKeyEvent.prototype.isvisible=function(){return this.$searchlist.first().is(":visible")},SearchKeyEvent.prototype.isfirst=function(){return this.$searchlist.children().hasClass("current")?!1:!0},SearchKeyEvent.prototype.islast=function(){return this.$searchlist.last().children().last().hasClass("current")?!0:!1},SearchKeyEvent.prototype.check_elements=function(e,t){if("up"===t)for(;e--;){if(this.$searchlist.eq(e).children("dd").size()>0)return e;if(0==e)return!1}else for(;++e;){if(this.$searchlist.eq(e).children("dd").size()>0)return e;if(e>=this.$searchlist.size())return!1}},SearchKeyEvent.prototype.enbleWheel=function(){$(window).scrollTop(this.limitHeight),$("html").removeClass("limit-content"),$("#vivo-head-wrap").next().css({marginTop:""})},SearchKeyEvent.prototype.unenbleWheel=function(){this.limitHeight=$(window).scrollTop(),$("html").addClass("limit-content"),$("#vivo-head-wrap").next().css({marginTop:-this.limitHeight})};var searchkeyevent=new SearchKeyEvent({wrap:"#vivo-head-wrap .v_h_search",input:".search-top input",list:".search-content"}),Search={getKey:function(){$.ajax({type:"get",url:searchUrlConfig.getKeyWords,dataType:"jsonp",jsonp:"jsoncallback",success:function(e){e.keyWord&&($input.attr("placeholder",e.keyWord),$input.attr("data-keydata","true"))}})}(),init:function(){function e(e){if(!$box.hasClass("openSearch"))return!1;e=window.event||e;var i=$(e.srcElement||e.target);$(i).is($input)||$(i).parents("dl").is($link)||$(i).parent().is(r)||$(i).is($searchOpen)||$(i).parents("section").is($searchResults)||t.close()}var t=this,i=new TimelineMax({paused:!0}),s=new TimelineMax({paused:!0});s.staggerFrom($link.children(),.45,{y:-25,autoAlpha:0,ease:Ease.easeInOut},.1,"+=.3"),i.from($searchBox,.7,{autoAlpha:0},0).to($searchOpen,.5,{x:"-=50"},.2).to($searchClose,.3,{scale:1,rotation:180},.2).to($userBtn,.1,{autoAlpha:0},0).from($input,.2,{x:0,autoAlpha:0},.6);for(var n=$title.size(),a=n;a>=0;a--)i.add(TweenMax.to($title.eq(a).find("a"),.2,{scale:0}),.04*(n-a));$mresults.hide();var o=$("#gb-mask-layer");TweenMax.set($searchBox,{display:"block"}),TweenMax.set(o,{display:"none",autoAlpha:0}),t.play=!1;var r=$("#vivo-high-switch");$searchOpen.mouseleave(function(){$searchOpen.removeClass("leave")}),$searchOpen.click(function(){if($searchOpen.addClass("leave"),searchkeyevent.unenbleWheel(),$box.hasClass("openSearch"))return curl($input.val(),$input.data("keydata"),$input.attr("placeholder")),!1;var n=$box.find(".vivo-head").hasClass("openUser");n&&UserControl(n),t.play=!0,i.timeScale(1.5).play(),TweenMax.to(o,.2,{display:"block",autoAlpha:1},0),setTimeout(function(){$box.addClass("openSearch"),$input.focus(),$(document).on("click",function(t){$box.hasClass("openSearch")&&e(t)})},500),$link.find("dd").size()>0&&(TweenMax.set($contentBox,{display:"block"}),TweenMax.to($contentBox,.3,{autoAlpha:1,ease:Ease.easeIn},.4),s.seek(0).timeScale(1.5).play())}),$searchClose.click(function(){$searchOpen.removeClass("leave"),searchkeyevent.enbleWheel(),$(document).off("click"),i.timeScale(1.5).reverse(),TweenMax.to($contentBox,.3,{autoAlpha:0,onComplete:function(){TweenMax.set($contentBox,{display:"none"}),t.SearchControl(!1,self.ismobile)}}),TweenMax.to(o,.2,{display:"none",autoAlpha:0},0),t.play=!1,$(document).off("click"),$box.removeClass("openSearch Searching"),$mresults.hide()})},SearchPlay:function(){function e(){$input.keyup(function(e){var s="37"==e.which||"38"==e.which||"39"==e.which;if(s)return!1;var n=$(this).val(),a=n.replace(/(^\s+)|(\s+$)/g,"")?n.replace(/\s/g,""):n,o=a.indexOf(" ")>-1;"13"==e.which||"108"==e.which?!o&&curl(a,$input.data("keydata"),$input.attr("placeholder")):"40"!=e.which&&(""==a?i.SearchControl(!1,self.ismobile):o?i.SearchControl(!1,self.ismobile):t(a))})}function t(e){return e?void $.ajax({type:"get",url:searchUrlConfig.getAssciate+"?query="+e,dataType:"jsonp",jsonp:"jsoncallback",success:function(t){t.result.keyword=e;var s=SearchBuild.ContentBuild(t.result);s&&i.SearchControl(s,self.ismobile)}}):!1}var i=this;$input.on({compositionstart:function(){$input.off("keyup")},compositionend:function(){t($(this).val()),e()}}),e()},SearchControl:function(e,t){if(e)if(t)$mmenulist.hide(),$mresults.empty().html(e).show();else{$link.hide(),$box.addClass("Searching"),$searchResults.empty().html(e).show();{new SearchKeyEvent({wrap:"#vivo-head-wrap .v_h_search",input:".search-top input",list:".search-content .results"})}}else t?($mresults.empty().html(e).hide(),$mmenulist.show(),$input.val("")):($searchResults.empty().html(e).hide(),$link.show())},MobileFun:function(){var e=this;e.Recovery()},open:function(){$searchOpen.click()},close:function(){$searchClose.click()},Recovery:function(){var e=this;e.SearchControl(!1,self.ismobile),$input.attr("style",""),$searchClose.click(),$searchOpen.off("click"),$searchClose.off("click"),$(document).off("click")}};Search.init();var $headDom=$("#vivo-head-wrap"),$stage=$headDom.find(".gb-vivo-head"),$userBtn=$(".nav-t-user"),$userList=$(".v_h_usercenter"),$muenBtn=$(".gb-vivo-h-menu"),listAnt=new TimelineMax({paused:!0});listAnt.staggerFrom($userList.find("li"),.45,{y:-25,autoAlpha:0,ease:Ease.easeInOut},.1,"+=0.6");var isplay=!0,Header={init:function(){$navList=$(".gb-vivo-h-nav");var e=$("#vivo-head-wrap"),t='<i id="gb-mask-layer"></i>';e.parent().append(t);var i=this;Search.SearchPlay(),$userList.mouseenter(function(){isplay=!1,isplay&&i.UserControl(!1),clearTimeout(i._userTime)}),$userList.mouseleave(function(){i.UserControl(!0),isplay=!1,i._userTime=setTimeout(function(){isplay=!0},400)}),i.AddEvent()},AddEvent:function(){var e=this;$userBtn.mouseenter(function(){return $stage.hasClass("openMenu openSearch")?!1:($stage.removeClass("openMenu"),clearTimeout(e._userTime),isplay=!0,void e.UserControl(!1))}),$userBtn.mouseleave(function(){e._userTime=setTimeout(function(){e.UserControl(!0)},300)})},UserControl:function(e,t){var i=this,s=$("#gb-mask-layer");e?($userBtn.removeClass("current"),$stage.removeClass("openUser"),TweenMax.to(s,.3,{autoAlpha:0,onComplete:function(){TweenMax.set(s,{display:"none"})}},.1),TweenMax.to($userList,.3,{autoAlpha:0,onComplete:function(){TweenMax.set($userList,{display:"none"})}}),i._tmout=setTimeout(function(){listAnt.seek(0).pause()},300),$("html").removeClass("limit-content")):(self.ismobile&&($("html").addClass("limit-content"),$userBtn.addClass("current")),self.mMuenOpen&&$muenBtn.click(),clearTimeout(i._tmout),$stage.addClass("openUser"),t?(TweenMax.set(s,{display:"block",autoAlpha:1}),TweenMax.set($userList,{display:"block",autoAlpha:1}),listAnt.seek(2)):(TweenMax.to(s,.3,{display:"block",autoAlpha:1},.1),TweenMax.to($userList,.3,{display:"block",autoAlpha:1,ease:Ease.easeIn}),listAnt.seek(0).timeScale(1.5).play()))},Recovery:function(){$userBtn.off("mouseenter mouseleave")}};Header.init(),initHomeLogin($("#J_login_home_head"));var $followBox=$(".gb-foot-copyright"),$followList=$followBox.find(".follow-list"),$followDom=$followList.find("li"),$followBtn=$followBox.find(".follow_btn"),$langBtn=$followBox.find(".lang_btn"),$langList=$followBox.find(".lang-list"),$langDom=$langList.find("li"),$wechatBtn=$(".wechat-follow"),$aliBtn=$(".ali-follow"),$follow_box=$(".vivo-follow-toast"),Foot={init:function(){var e=this;e.followAnt=new TimelineMax({paused:!0}),e.followAnt.staggerFrom($followDom,.1,{y:50,autoAlpha:0,ease:Ease.easeOut},.02,"-=0.01"),e.langAnt=new TimelineMax({paused:!0}),e.langAnt.staggerFrom($langDom,.1,{y:50,autoAlpha:0,ease:Ease.easeOut},.02,"-=0.01"),e.AddEvent()},AddEvent:function(){var e=this;$followBtn.mouseenter(function(){e.FollowAntControl(!1)}),$followBtn.mouseleave(function(){e.FollowAntControl(!0)}),$followList.mouseleave(function(){e.FollowAntControl(!0)}),$langBtn.mouseenter(function(){e.LangAntControl(!1)}),$langBtn.mouseleave(function(){e.LangAntControl(!0)}),$langList.mouseleave(function(){e.LangAntControl(!0)}),$wechatBtn.click(function(e){e.preventDefault()}),$aliBtn.click(function(e){e.preventDefault()}),$wechatBtn.mouseenter(function(){$follow_box.removeClass("openAli").addClass("openWechat"),TweenMax.to($follow_box,.2,{autoAlpha:1,ease:Ease.easeOut})}),$wechatBtn.mouseleave(function(){TweenMax.to($follow_box,.1,{autoAlpha:0,ease:Ease.easeOut})}),$aliBtn.mouseenter(function(){$follow_box.removeClass("openWechat").addClass("openAli"),TweenMax.to($follow_box,.2,{autoAlpha:1,ease:Ease.easeOut})}),$aliBtn.mouseleave(function(){TweenMax.to($follow_box,.1,{autoAlpha:0,ease:Ease.easeOut})})},FollowAntControl:function(e){var t=this;e?(TweenMax.to($followList,.1,{autoAlpha:0,ease:Ease.easeOut,onComplete:function(){$followList.hide(),$follow_box.removeClass("openAli openWechat")}}),TweenMax.to($followList.siblings(".vivo-f-triangle"),.1,{autoAlpha:0,ease:Ease.easeOut}),t.followAnt.reverse()):(TweenMax.to($followList,.1,{display:"block",autoAlpha:1,ease:Ease.easeOut}),TweenMax.to($followList.siblings(".vivo-f-triangle"),.1,{autoAlpha:1,ease:Ease.easeOut}),t.followAnt.play())},LangAntControl:function(e){var t=this;e?(TweenMax.to($langList,.1,{autoAlpha:0,ease:Ease.easeOut,onComplete:function(){$langList.hide()}}),TweenMax.to($langList.siblings(".vivo-f-triangle"),.1,{autoAlpha:0,ease:Ease.easeOut}),t.langAnt.reverse()):(TweenMax.to($langList,.1,{display:"block",autoAlpha:1,ease:Ease.easeOut}),TweenMax.to($langList.siblings(".vivo-f-triangle"),.1,{autoAlpha:1,ease:Ease.easeOut}),t.langAnt.play())},Recovery:function(){$followBtn.off("mouseenter"),$langBtn.off("mouseenter"),$wechatBtn.off("mouseenter mouseleave click"),$aliBtn.off("mouseenter mouseleave click")}};Foot.init(),$("a[burying]").each(function(){var e=$(this),t={},i=e.attr("burying"),s=i.split("&");if(i){for(var n=0;n<s.length;n++){var a=s[n].split("=");t[a[0]]=a[1]}e.on("click",function(){t.pageview="官网首页",Vtrack.clickStats(t)})}e.removeAttr("burying")}); | 22,917 | 22,917 | 0.716499 |
29b15538836cb22ef802320a5f54e324d55a6b34 | 17,394 | rs | Rust | src/glb/gpio_cfgctl11.rs | andelf/bl702-pac | c5a7791d304c0d7d4c665a8f92ad22e00a09db7c | [
"Apache-2.0",
"MIT"
] | 4 | 2021-06-29T05:22:00.000Z | 2021-11-06T23:45:55.000Z | src/glb/gpio_cfgctl11.rs | andelf/bl702-pac | c5a7791d304c0d7d4c665a8f92ad22e00a09db7c | [
"Apache-2.0",
"MIT"
] | null | null | null | src/glb/gpio_cfgctl11.rs | andelf/bl702-pac | c5a7791d304c0d7d4c665a8f92ad22e00a09db7c | [
"Apache-2.0",
"MIT"
] | 3 | 2021-06-29T05:22:03.000Z | 2022-03-23T12:42:47.000Z | #[doc = "Register `GPIO_CFGCTL11` reader"]
pub struct R(crate::R<GPIO_CFGCTL11_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<GPIO_CFGCTL11_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<GPIO_CFGCTL11_SPEC>> for R {
#[inline(always)]
fn from(reader: crate::R<GPIO_CFGCTL11_SPEC>) -> Self {
R(reader)
}
}
#[doc = "Register `GPIO_CFGCTL11` writer"]
pub struct W(crate::W<GPIO_CFGCTL11_SPEC>);
impl core::ops::Deref for W {
type Target = crate::W<GPIO_CFGCTL11_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl core::ops::DerefMut for W {
#[inline(always)]
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl From<crate::W<GPIO_CFGCTL11_SPEC>> for W {
#[inline(always)]
fn from(writer: crate::W<GPIO_CFGCTL11_SPEC>) -> Self {
W(writer)
}
}
#[doc = "Field `reg_gpio_23_func_sel` reader - "]
pub struct REG_GPIO_23_FUNC_SEL_R(crate::FieldReader<u8, u8>);
impl REG_GPIO_23_FUNC_SEL_R {
pub(crate) fn new(bits: u8) -> Self {
REG_GPIO_23_FUNC_SEL_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for REG_GPIO_23_FUNC_SEL_R {
type Target = crate::FieldReader<u8, u8>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `reg_gpio_23_func_sel` writer - "]
pub struct REG_GPIO_23_FUNC_SEL_W<'a> {
w: &'a mut W,
}
impl<'a> REG_GPIO_23_FUNC_SEL_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x1f << 24)) | ((value as u32 & 0x1f) << 24);
self.w
}
}
#[doc = "Field `reg_gpio_23_pd` reader - "]
pub struct REG_GPIO_23_PD_R(crate::FieldReader<bool, bool>);
impl REG_GPIO_23_PD_R {
pub(crate) fn new(bits: bool) -> Self {
REG_GPIO_23_PD_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for REG_GPIO_23_PD_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `reg_gpio_23_pd` writer - "]
pub struct REG_GPIO_23_PD_W<'a> {
w: &'a mut W,
}
impl<'a> REG_GPIO_23_PD_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 21)) | ((value as u32 & 0x01) << 21);
self.w
}
}
#[doc = "Field `reg_gpio_23_pu` reader - "]
pub struct REG_GPIO_23_PU_R(crate::FieldReader<bool, bool>);
impl REG_GPIO_23_PU_R {
pub(crate) fn new(bits: bool) -> Self {
REG_GPIO_23_PU_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for REG_GPIO_23_PU_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `reg_gpio_23_pu` writer - "]
pub struct REG_GPIO_23_PU_W<'a> {
w: &'a mut W,
}
impl<'a> REG_GPIO_23_PU_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 20)) | ((value as u32 & 0x01) << 20);
self.w
}
}
#[doc = "Field `reg_gpio_23_drv` reader - "]
pub struct REG_GPIO_23_DRV_R(crate::FieldReader<u8, u8>);
impl REG_GPIO_23_DRV_R {
pub(crate) fn new(bits: u8) -> Self {
REG_GPIO_23_DRV_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for REG_GPIO_23_DRV_R {
type Target = crate::FieldReader<u8, u8>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `reg_gpio_23_drv` writer - "]
pub struct REG_GPIO_23_DRV_W<'a> {
w: &'a mut W,
}
impl<'a> REG_GPIO_23_DRV_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x03 << 18)) | ((value as u32 & 0x03) << 18);
self.w
}
}
#[doc = "Field `reg_gpio_23_smt` reader - "]
pub struct REG_GPIO_23_SMT_R(crate::FieldReader<bool, bool>);
impl REG_GPIO_23_SMT_R {
pub(crate) fn new(bits: bool) -> Self {
REG_GPIO_23_SMT_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for REG_GPIO_23_SMT_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `reg_gpio_23_smt` writer - "]
pub struct REG_GPIO_23_SMT_W<'a> {
w: &'a mut W,
}
impl<'a> REG_GPIO_23_SMT_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 17)) | ((value as u32 & 0x01) << 17);
self.w
}
}
#[doc = "Field `reg_gpio_23_ie` reader - "]
pub struct REG_GPIO_23_IE_R(crate::FieldReader<bool, bool>);
impl REG_GPIO_23_IE_R {
pub(crate) fn new(bits: bool) -> Self {
REG_GPIO_23_IE_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for REG_GPIO_23_IE_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `reg_gpio_23_ie` writer - "]
pub struct REG_GPIO_23_IE_W<'a> {
w: &'a mut W,
}
impl<'a> REG_GPIO_23_IE_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 16)) | ((value as u32 & 0x01) << 16);
self.w
}
}
#[doc = "Field `reg_gpio_22_func_sel` reader - "]
pub struct REG_GPIO_22_FUNC_SEL_R(crate::FieldReader<u8, u8>);
impl REG_GPIO_22_FUNC_SEL_R {
pub(crate) fn new(bits: u8) -> Self {
REG_GPIO_22_FUNC_SEL_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for REG_GPIO_22_FUNC_SEL_R {
type Target = crate::FieldReader<u8, u8>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `reg_gpio_22_func_sel` writer - "]
pub struct REG_GPIO_22_FUNC_SEL_W<'a> {
w: &'a mut W,
}
impl<'a> REG_GPIO_22_FUNC_SEL_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x1f << 8)) | ((value as u32 & 0x1f) << 8);
self.w
}
}
#[doc = "Field `reg_gpio_22_pd` reader - "]
pub struct REG_GPIO_22_PD_R(crate::FieldReader<bool, bool>);
impl REG_GPIO_22_PD_R {
pub(crate) fn new(bits: bool) -> Self {
REG_GPIO_22_PD_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for REG_GPIO_22_PD_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `reg_gpio_22_pd` writer - "]
pub struct REG_GPIO_22_PD_W<'a> {
w: &'a mut W,
}
impl<'a> REG_GPIO_22_PD_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 5)) | ((value as u32 & 0x01) << 5);
self.w
}
}
#[doc = "Field `reg_gpio_22_pu` reader - "]
pub struct REG_GPIO_22_PU_R(crate::FieldReader<bool, bool>);
impl REG_GPIO_22_PU_R {
pub(crate) fn new(bits: bool) -> Self {
REG_GPIO_22_PU_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for REG_GPIO_22_PU_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `reg_gpio_22_pu` writer - "]
pub struct REG_GPIO_22_PU_W<'a> {
w: &'a mut W,
}
impl<'a> REG_GPIO_22_PU_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 4)) | ((value as u32 & 0x01) << 4);
self.w
}
}
#[doc = "Field `reg_gpio_22_drv` reader - "]
pub struct REG_GPIO_22_DRV_R(crate::FieldReader<u8, u8>);
impl REG_GPIO_22_DRV_R {
pub(crate) fn new(bits: u8) -> Self {
REG_GPIO_22_DRV_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for REG_GPIO_22_DRV_R {
type Target = crate::FieldReader<u8, u8>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `reg_gpio_22_drv` writer - "]
pub struct REG_GPIO_22_DRV_W<'a> {
w: &'a mut W,
}
impl<'a> REG_GPIO_22_DRV_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x03 << 2)) | ((value as u32 & 0x03) << 2);
self.w
}
}
#[doc = "Field `reg_gpio_22_smt` reader - "]
pub struct REG_GPIO_22_SMT_R(crate::FieldReader<bool, bool>);
impl REG_GPIO_22_SMT_R {
pub(crate) fn new(bits: bool) -> Self {
REG_GPIO_22_SMT_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for REG_GPIO_22_SMT_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `reg_gpio_22_smt` writer - "]
pub struct REG_GPIO_22_SMT_W<'a> {
w: &'a mut W,
}
impl<'a> REG_GPIO_22_SMT_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 1)) | ((value as u32 & 0x01) << 1);
self.w
}
}
#[doc = "Field `reg_gpio_22_ie` reader - "]
pub struct REG_GPIO_22_IE_R(crate::FieldReader<bool, bool>);
impl REG_GPIO_22_IE_R {
pub(crate) fn new(bits: bool) -> Self {
REG_GPIO_22_IE_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for REG_GPIO_22_IE_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `reg_gpio_22_ie` writer - "]
pub struct REG_GPIO_22_IE_W<'a> {
w: &'a mut W,
}
impl<'a> REG_GPIO_22_IE_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !0x01) | (value as u32 & 0x01);
self.w
}
}
impl R {
#[doc = "Bits 24:28"]
#[inline(always)]
pub fn reg_gpio_23_func_sel(&self) -> REG_GPIO_23_FUNC_SEL_R {
REG_GPIO_23_FUNC_SEL_R::new(((self.bits >> 24) & 0x1f) as u8)
}
#[doc = "Bit 21"]
#[inline(always)]
pub fn reg_gpio_23_pd(&self) -> REG_GPIO_23_PD_R {
REG_GPIO_23_PD_R::new(((self.bits >> 21) & 0x01) != 0)
}
#[doc = "Bit 20"]
#[inline(always)]
pub fn reg_gpio_23_pu(&self) -> REG_GPIO_23_PU_R {
REG_GPIO_23_PU_R::new(((self.bits >> 20) & 0x01) != 0)
}
#[doc = "Bits 18:19"]
#[inline(always)]
pub fn reg_gpio_23_drv(&self) -> REG_GPIO_23_DRV_R {
REG_GPIO_23_DRV_R::new(((self.bits >> 18) & 0x03) as u8)
}
#[doc = "Bit 17"]
#[inline(always)]
pub fn reg_gpio_23_smt(&self) -> REG_GPIO_23_SMT_R {
REG_GPIO_23_SMT_R::new(((self.bits >> 17) & 0x01) != 0)
}
#[doc = "Bit 16"]
#[inline(always)]
pub fn reg_gpio_23_ie(&self) -> REG_GPIO_23_IE_R {
REG_GPIO_23_IE_R::new(((self.bits >> 16) & 0x01) != 0)
}
#[doc = "Bits 8:12"]
#[inline(always)]
pub fn reg_gpio_22_func_sel(&self) -> REG_GPIO_22_FUNC_SEL_R {
REG_GPIO_22_FUNC_SEL_R::new(((self.bits >> 8) & 0x1f) as u8)
}
#[doc = "Bit 5"]
#[inline(always)]
pub fn reg_gpio_22_pd(&self) -> REG_GPIO_22_PD_R {
REG_GPIO_22_PD_R::new(((self.bits >> 5) & 0x01) != 0)
}
#[doc = "Bit 4"]
#[inline(always)]
pub fn reg_gpio_22_pu(&self) -> REG_GPIO_22_PU_R {
REG_GPIO_22_PU_R::new(((self.bits >> 4) & 0x01) != 0)
}
#[doc = "Bits 2:3"]
#[inline(always)]
pub fn reg_gpio_22_drv(&self) -> REG_GPIO_22_DRV_R {
REG_GPIO_22_DRV_R::new(((self.bits >> 2) & 0x03) as u8)
}
#[doc = "Bit 1"]
#[inline(always)]
pub fn reg_gpio_22_smt(&self) -> REG_GPIO_22_SMT_R {
REG_GPIO_22_SMT_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 0"]
#[inline(always)]
pub fn reg_gpio_22_ie(&self) -> REG_GPIO_22_IE_R {
REG_GPIO_22_IE_R::new((self.bits & 0x01) != 0)
}
}
impl W {
#[doc = "Bits 24:28"]
#[inline(always)]
pub fn reg_gpio_23_func_sel(&mut self) -> REG_GPIO_23_FUNC_SEL_W {
REG_GPIO_23_FUNC_SEL_W { w: self }
}
#[doc = "Bit 21"]
#[inline(always)]
pub fn reg_gpio_23_pd(&mut self) -> REG_GPIO_23_PD_W {
REG_GPIO_23_PD_W { w: self }
}
#[doc = "Bit 20"]
#[inline(always)]
pub fn reg_gpio_23_pu(&mut self) -> REG_GPIO_23_PU_W {
REG_GPIO_23_PU_W { w: self }
}
#[doc = "Bits 18:19"]
#[inline(always)]
pub fn reg_gpio_23_drv(&mut self) -> REG_GPIO_23_DRV_W {
REG_GPIO_23_DRV_W { w: self }
}
#[doc = "Bit 17"]
#[inline(always)]
pub fn reg_gpio_23_smt(&mut self) -> REG_GPIO_23_SMT_W {
REG_GPIO_23_SMT_W { w: self }
}
#[doc = "Bit 16"]
#[inline(always)]
pub fn reg_gpio_23_ie(&mut self) -> REG_GPIO_23_IE_W {
REG_GPIO_23_IE_W { w: self }
}
#[doc = "Bits 8:12"]
#[inline(always)]
pub fn reg_gpio_22_func_sel(&mut self) -> REG_GPIO_22_FUNC_SEL_W {
REG_GPIO_22_FUNC_SEL_W { w: self }
}
#[doc = "Bit 5"]
#[inline(always)]
pub fn reg_gpio_22_pd(&mut self) -> REG_GPIO_22_PD_W {
REG_GPIO_22_PD_W { w: self }
}
#[doc = "Bit 4"]
#[inline(always)]
pub fn reg_gpio_22_pu(&mut self) -> REG_GPIO_22_PU_W {
REG_GPIO_22_PU_W { w: self }
}
#[doc = "Bits 2:3"]
#[inline(always)]
pub fn reg_gpio_22_drv(&mut self) -> REG_GPIO_22_DRV_W {
REG_GPIO_22_DRV_W { w: self }
}
#[doc = "Bit 1"]
#[inline(always)]
pub fn reg_gpio_22_smt(&mut self) -> REG_GPIO_22_SMT_W {
REG_GPIO_22_SMT_W { w: self }
}
#[doc = "Bit 0"]
#[inline(always)]
pub fn reg_gpio_22_ie(&mut self) -> REG_GPIO_22_IE_W {
REG_GPIO_22_IE_W { w: self }
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.0.bits(bits);
self
}
}
#[doc = "GPIO_CFGCTL11.\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [gpio_cfgctl11](index.html) module"]
pub struct GPIO_CFGCTL11_SPEC;
impl crate::RegisterSpec for GPIO_CFGCTL11_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [gpio_cfgctl11::R](R) reader structure"]
impl crate::Readable for GPIO_CFGCTL11_SPEC {
type Reader = R;
}
#[doc = "`write(|w| ..)` method takes [gpio_cfgctl11::W](W) writer structure"]
impl crate::Writable for GPIO_CFGCTL11_SPEC {
type Writer = W;
}
#[doc = "`reset()` method sets GPIO_CFGCTL11 to value 0"]
impl crate::Resettable for GPIO_CFGCTL11_SPEC {
#[inline(always)]
fn reset_value() -> Self::Ux {
0
}
}
| 30.041451 | 408 | 0.588881 |
e7470435519be6b2ba075d750215feb35a7943ef | 9,466 | php | PHP | vistas/registrar/pedido-1.php | Pheetbag/CDA | 7b753dbaee26f7fd59f0b56fd161ee7ac8436ef0 | [
"MIT"
] | 1 | 2018-07-25T20:30:33.000Z | 2018-07-25T20:30:33.000Z | vistas/registrar/pedido-1.php | Pheetbag/CDA | 7b753dbaee26f7fd59f0b56fd161ee7ac8436ef0 | [
"MIT"
] | null | null | null | vistas/registrar/pedido-1.php | Pheetbag/CDA | 7b753dbaee26f7fd59f0b56fd161ee7ac8436ef0 | [
"MIT"
] | null | null | null | <?php include_head('CDA - Registrar'); ?>
<link rel="stylesheet" href="<?php echo HTTP ?>/vistas/registrar/style.css?v=0.5">
</head>
<body>
<?php include_header('registrar', 'Registrar', 'Pedido'); ?>
<!-- <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#agregar-proveedor">
Launch demo modal
</button> -->
<div class="modal fade" tabindex="-1" id="agregar-proveedor">
<div class="modal-dialog modal-dialog-centered">
<form method="POST" action="<?php echo HTTP ?>/registrar/pedido/registrar-proveedor?<?php echo datos_url($datos); ?>" class="modal-content validar" novalidate>
<div class="modal-header">
<h5 class="modal-title">Proveedor nuevo</h5>
</div>
<div class="modal-body">
<div class="alert alert-warning" role="alert">
El rif <b><?php
$rif_div = explode('-', $datos['rif']);
$rif = $rif_div[0] . '-' . number_format( $rif_div[1] ,0, ',','.');
echo $rif ?></b> no pertenece a ningún proveedor registrado. Inserta los datos del proveedor para continuar.
</div>
<div class="row">
<div class="form-group col">
<label required for="proveedor-nombre">Nombre</label>
<input type="text" class="form-control" id="proveedor-nombre" name="nombre" placeholder="Nombre">
<div class="invalid-feedback">
Ingrese un nombre válido.
</div>
<div class="valid-feedback">
¡Perfecto!
</div>
</div>
<div class="form-group col">
<label for="proveedor-tlf">Teléfono</label>
<input type="number" class="form-control" id="proveedor-tlf" name="tlf" placeholder="Teléfono">
<div class="invalid-feedback">
Ingrese un número de teléfono válido.
</div>
<div class="valid-feedback">
¡Perfecto!
</div>
</div>
</div>
<div class="form-group">
<label required for="cliente-dir">Dirección</label>
<input type="text" class="form-control" id="cliente-dir" name="dir" placeholder="Dirección">
<div class="invalid-feedback">
Ingrese una dirección válida.
</div>
<div class="valid-feedback">
¡Perfecto!
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancelar</button>
<button type="submit" class="btn btn-primary">Agregar</button>
</div>
</form>
</div>
</div>
<main class="container-fluid nav-spaced full-screen" id="navPush">
<div class="row">
<div class="col-sm-6">
<form class="container-fluid validar" method="POST" action="<?php echo HTTP ?>/registrar/pedido/validar-proveedor?<?php echo datos_url($datos); ?>" novalidate>
<div class="row">
<div class="col-md-12 col-lg-8">
<div class="card mb-3">
<h6 class="card-header">Fecha</h6>
<div class="card-body">
<input required type="date" class="form-control bg-light" name="fecha" value="<?php echo $datos['fecha'] ?>">
<div class="invalid-feedback">
Ingrese una fecha válida.
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12 col-lg-8">
<div class="card mb-3">
<h6 class="card-header">Fecha de llegada</h6>
<div class="card-body">
<input required type="date" class="form-control bg-light" name="llegada" value="<?php echo $datos['llegada'] ?>">
<div class="invalid-feedback">
Ingrese una fecha de llegada válida.
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12 col-lg-8">
<div class="card mb-3">
<h6 class="card-header">Seleccionar proveedor</h6>
<div class="card-body input-group">
<div class="input-group-prepend">
<span class="input-group-text">J-</span>
</div>
<input required type="number" class="form-control" name="rif" placeholder="Rif" value="<?php echo $datos['rif-numero'] ?>">
<div class="invalid-feedback">
Ingrese un rif válido.
</div>
<div class="valid-feedback">
¡Perfecto!
</div>
</div>
</div>
</div>
</div>
<div class="row mb-4">
<div class="col-md-12 col-lg-8">
<button type="submit" name="nuevo-producto" class="btn btn-primary btn-block py-2">
Continuar
</button>
</div>
</div>
</form>
</div>
<div class="col-sm-6 col-lg-5 container-fluid">
<div class="row mb-4">
<div class="col-sm-12">
<div class="progress" style="height: 25px;">
<div class="progress-bar progress-bar-striped progress-bar-animated
bg-success font-weight-bold" style="width:33.3%;">Paso 1</div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="card">
<h6 class="card-header text-center px-5">
<?php
if($datos['proveedor'] != null){
$rif_div = explode('-', $datos['proveedor']['rif']);
$rif = $rif_div[0] . '-' . number_format( $rif_div[1] ,0, ',','.');
echo
$datos['proveedor']['nombre_empresa'] .
' | ' . $rif . '
<br><br>' .
$datos['proveedor']['direccion'] .
' <br>' .
$datos['proveedor']['telefono']
;
}else{
echo '
Sin cliente asociado
<br><br>
No hay datos disponible. Debes asociar un cliente a la factura para continuar';
}
?>
</h6>
<h6 class="card-header text-muted text-center">
<?php
echo(date('d/m/Y',strtotime($datos['fecha'])))
?>
</h6>
<ul class="list-group list-group-flush">
<?php
if($datos['productos'] == null){
echo'
<div class="p-5"></div>
';
}else{
$cantidad_productos = count($datos['productos']);
for ($i=0; $i < $cantidad_productos; $i++) {
$producto = $consultar->get('producto', $datos['productos'][$i]);
$cantidad = number_format( $datos['cantidades'][$i] ,0,',', ' ');
$costo = $datos['costos'][$i];
$subtotal = number_format( $costo * $cantidad ,2,',', '.');
echo '
<li class="list-group-item list-group-item-action container-fluid">
<div class="row">
<div class="col-sm-6 text-left">
<p class="mb-0 font-weight-bold">'. $producto['nombre_producto'] .'</p>
<p class="mb-0">Codigo: '. $producto['codigo_producto'] .'</p>
</div>
<div class="col-sm-6 text-right">
<p class="font-weight-bold mb-0 text-success ">Bs.S '. $subtotal .'</p>
<p class="mb-0">x'. $cantidad .'</p>
</div>
</div>
</li>
';
}
}
?>
</ul>
<?php
$subtotal = 0;
for ($i=0; $i < count($datos['productos']); $i++) {
$subtotal += $datos['costos'][$i] * $datos['cantidades'][$i];
}
echo '<div class="card-footer text-muted text-right">';
echo 'SUBTOTAL Bs.S ' . number_format( $subtotal ,2,',', '.') . '</div>';
echo '<div class="card-footer text-center font-weight-bold">';
echo 'TOTAL Bs.S ' . number_format( $subtotal,2,',', '.'). '</div>';
?>
</div>
</div>
</div>
</div>
</div>
</main>
<?php
if(isset($_GET['error'])){
include_footer("
<script type=' text/javascript' >
$(window).on('load',function(){
$('#agregar-proveedor').modal('show');
});
</script>");
}else{
include_footer();
}
?>
| 34.929889 | 172 | 0.440735 |
759f53c3bb24cd43bd85c0415a3ef3b787507377 | 451 | css | CSS | styles/Loader.module.css | RomainGuarinoni/Osu-dashboard | f2e44de3e3dd116b96ecf4801e3658b017fb9d46 | [
"MIT"
] | null | null | null | styles/Loader.module.css | RomainGuarinoni/Osu-dashboard | f2e44de3e3dd116b96ecf4801e3658b017fb9d46 | [
"MIT"
] | 12 | 2021-05-13T15:09:52.000Z | 2021-11-24T16:44:35.000Z | styles/Loader.module.css | RomainGuarinoni/Osu-dashboard | f2e44de3e3dd116b96ecf4801e3658b017fb9d46 | [
"MIT"
] | null | null | null | .ldsDualRing {
display: inline-block;
width: 70px;
height: 70px;
}
.ldsDualRing:after {
content: " ";
display: block;
width: 54px;
height: 54px;
margin: 8px;
border-radius: 50%;
border: 6px solid #fff;
border-color: var(--hover) transparent var(--hover) transparent;
animation: lds-dual-ring 1.2s ease infinite;
}
@keyframes lds-dual-ring {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
| 18.04 | 66 | 0.643016 |
5f28cac591f79cb6c958a298126f5920bfc0b568 | 207 | rb | Ruby | lib/errors.rb | skh/toycity3 | 7f880499ea5f1755cd6722c68c7b0528a8662e8a | [
"MIT"
] | null | null | null | lib/errors.rb | skh/toycity3 | 7f880499ea5f1755cd6722c68c7b0528a8662e8a | [
"MIT"
] | null | null | null | lib/errors.rb | skh/toycity3 | 7f880499ea5f1755cd6722c68c7b0528a8662e8a | [
"MIT"
] | null | null | null | # lib/errors.rb
class DuplicateProductError < StandardError
end
class DuplicateCustomerError < StandardError
end
class OutOfStockError < StandardError
end
class NoSuchTransactionError < StandardError
end | 15.923077 | 44 | 0.845411 |
43c59e1bf87ba6b6449c3c09fcefa167e8f12370 | 961 | tsx | TypeScript | src/components/FilterForm/index.tsx | caroldartdigital/SharedModules | 63762fcd6208be15998a5a483fefeb31097eec02 | [
"MIT"
] | null | null | null | src/components/FilterForm/index.tsx | caroldartdigital/SharedModules | 63762fcd6208be15998a5a483fefeb31097eec02 | [
"MIT"
] | null | null | null | src/components/FilterForm/index.tsx | caroldartdigital/SharedModules | 63762fcd6208be15998a5a483fefeb31097eec02 | [
"MIT"
] | null | null | null | import React from 'react'
import { useIntl } from 'react-intl'
import { Tooltip } from 'antd'
import { RedoOutlined, SearchOutlined } from '@ant-design/icons'
import Button from '../Button'
import { Wrapper } from '../Form/styles'
export type FilterFormProps = {
resetFilter: () => void
}
function FilterFormComponent({ resetFilter }: FilterFormProps) {
const intl = useIntl()
const { messages } = intl
return (
<Wrapper media="true">
<Tooltip title={messages['search']}>
<Button
htmlType="submit"
type="primary"
icon={<SearchOutlined />}
description={messages['search']}
/>
</Tooltip>
<Tooltip title={messages['resetFilters']}>
<Button
type="primary"
icon={<RedoOutlined />}
description={messages['resetFilters']}
onClick={resetFilter}
/>
</Tooltip>
</Wrapper>
)
}
export default FilterFormComponent
| 23.439024 | 64 | 0.604579 |
c9ecff4ce3e6e6ccb56a3e1d89c70686bfa7f045 | 268 | ts | TypeScript | src/app/api/models/currency-amount-summary.ts | Kcire6/CyclosInfoUGT | 073be5c76808dc56ede015579fbc11961d573873 | [
"MIT"
] | null | null | null | src/app/api/models/currency-amount-summary.ts | Kcire6/CyclosInfoUGT | 073be5c76808dc56ede015579fbc11961d573873 | [
"MIT"
] | null | null | null | src/app/api/models/currency-amount-summary.ts | Kcire6/CyclosInfoUGT | 073be5c76808dc56ede015579fbc11961d573873 | [
"MIT"
] | null | null | null | /* tslint:disable */
import { AmountSummary } from './amount-summary';
import { Currency } from './currency';
/**
* Contains summarized statistics over amounts of a currency
*/
export interface CurrencyAmountSummary extends AmountSummary {
currency?: Currency;
}
| 24.363636 | 62 | 0.735075 |
e2da828e91dc9f0d6b0dadf185a42c8037de7454 | 4,888 | py | Python | preprocessing/functions/data_formatter.py | andygubser/data_visualisation | 406b595025f29e48bac7effdb9e9dfb19809f371 | [
"MIT"
] | null | null | null | preprocessing/functions/data_formatter.py | andygubser/data_visualisation | 406b595025f29e48bac7effdb9e9dfb19809f371 | [
"MIT"
] | null | null | null | preprocessing/functions/data_formatter.py | andygubser/data_visualisation | 406b595025f29e48bac7effdb9e9dfb19809f371 | [
"MIT"
] | null | null | null | import pandas as pd
import numpy as np
pd.options.display.max_rows = 500
class DataFormatter:
@classmethod
def format_data(cls, df):
df = cls._format_columns(df)
df = cls._format_booleans(df)
df = cls._format_numericals(df)
df = cls._format_rows(df)
df = cls._format_datetimes(df)
df = cls._format_age(df)
# df = cls._format_type(df)
df = cls._format_fatal(df)
return df.reset_index(drop=True)
@classmethod
def _format_columns(cls, df):
df.dropna(how="all", axis="columns", inplace=True)
df.columns = map(cls._camel_to_snake, df.columns)
unnamed_cols = df.columns[df.columns.str.contains('unnamed')].tolist()
df.drop(unnamed_cols, axis="columns", inplace=True)
df.rename(columns={"fatal(y/n)": "fatal"}, inplace=True)
# df = df.reindex(sorted(df.columns), axis="columns")
return df
@classmethod
def _format_rows(cls, df):
df["case_number"] = df["case_number"].replace(0, np.nan)
df = df[~df["case_number"].isna()]
return df
@classmethod
def _camel_to_snake(cls, single_column_name):
import re
single_column_name = single_column_name.replace(" ", "").replace(".", "_")
single_column_name = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', single_column_name)
single_column_name = re.sub('([a-z0-9])([A-Z])', r'\1_\2', single_column_name).lower()
return single_column_name
@classmethod
def _format_booleans(cls, df):
return df.replace(["false", "true"], [False, True])
@classmethod
def _format_numericals(cls, df):
params = list([df.columns[df.columns.str.startswith("param_")],
df.columns[df.columns.str.startswith("kpi_")],
df.columns[df.columns.str.startswith("recipe_")]
])
params = [item for sublist in params for item in sublist]
params = [x for x in params if 'timestamp' not in x]
df[params] = df[params].apply(pd.to_numeric, downcast="signed", errors="ignore")
return df
@classmethod
def _format_date(cls, df):
df["date_prep"] = df["date"].str.lower()
df["date_prep"] = df["date_prep"].str.strip()
df["date_prep"] = df["date_prep"].str.replace("reported", "")
df["date_prep"] = df["date_prep"].str.replace("before", "")
df["date_prep"] = pd.to_datetime(df["date_prep"], errors="ignore")
return df
@classmethod
def _format_year(cls, df):
df["year_prep"] = df["year"].replace(0.0, np.nan)
df["year_from_casenumber"] = df["case_number"].str.findall('\d{4}').str[0]
df["year_from_casenumber"] = pd.to_numeric(df["year_from_casenumber"])
df["year_from_casenumber"] = df["year_from_casenumber"].mask(df["year_from_casenumber"] < 1000)
df["year_from_date"] = df["date"].str.findall('\d{4}').str[-1]
df["year_from_date"] = pd.to_numeric(df["year_from_date"])
df.loc[df["year_prep"].isna(), 'year_prep'] = df["year_from_date"]
df.loc[df["year_prep"].isna(), 'year_prep'] = df["year_from_casenumber"]
return df
@classmethod
def _format_datetimes(cls, df):
df = cls._format_date(df)
df = cls._format_year(df)
return df
@classmethod
def _format_age(cls, df):
df["age_prep"] = df["age"].astype(str).str.findall('\d+').str[0]
df["age_prep"] = pd.to_numeric(df["age_prep"], errors="ignore")
# df.loc[df["age_prep"].str.len() == 0, "age_prep"]
return df
@classmethod
def _format_type(cls, df):
type_dict = dict(zip(["Unprovoked", "Provoked"], [0, 1]))
df["type_cat"] = df["type"].replace(type_dict)
return df
@classmethod
def _format_fatal(cls, df):
df["fatal_cat"] = df["fatal"].str.strip().str.lower().str.replace("m", "n").replace(["n", "y"], [0, 1])
return df
# @classmethod
# def _unstack_list(cls, df, col_to_concatenate):
# cols_all = set(df.columns)
# cols_to_repeat = cols_all.difference(col_to_concatenate)
# number_of_lists_per_row = df[col_to_concatenate].str.len().fillna(1)
#
# df_unstacked = pd.DataFrame({
# col: np.repeat(df[col].values, number_of_lists_per_row) for col in cols_to_repeat
# }).assign(**{col_to_concatenate: np.concatenate(df[col_to_concatenate].values)})[df.columns.tolist()]
#
# # df = pd.DataFrame({cols_to_repeat:
# # np.repeat(
# # df[cols_to_repeat].values,
# # df[col_to_concatenate].str.len()),
# # col_to_concatenate:
# # np.concatenate(df[col_to_concatenate].values)})
# return df
| 38.488189 | 111 | 0.588175 |
ebd0369a451aef5dbdab2247f74ca926def9cab8 | 23,837 | css | CSS | public/css/main.css | AngelSanz1/quieroundocv1 | 788e21a2d9fb3dc6f2222a6b5272f295876e8856 | [
"MIT"
] | null | null | null | public/css/main.css | AngelSanz1/quieroundocv1 | 788e21a2d9fb3dc6f2222a6b5272f295876e8856 | [
"MIT"
] | 2 | 2016-04-11T23:18:34.000Z | 2016-04-11T23:18:53.000Z | public/css/main.css | AngelSanz1/quieroundocv1 | 788e21a2d9fb3dc6f2222a6b5272f295876e8856 | [
"MIT"
] | null | null | null | /* FONTS */
@font-face {
font-family: Montserrat_Light ;
src : url('../fonts/Montserrat-Light.otf')format('opentype');
}
@font-face {
font-family: Raleway_Medium ;
src : url('../fonts/Raleway-Medium.ttf')format('truetype');
}
@font-face {
font-family: Raleway_Bold ;
src: url('../fonts/Raleway-Bold.ttf')format('truetype');
}
@font-face {
font-family: Raleway_Regular ;
src: url('../fonts/Raleway-Regular.ttf')format('truetype');
}
@font-face {
font-family: BebasNeue_Regular;
src : url('../fonts/BebasNeue-Regular.otf')format('opentype');
}
@font-face {
font-family: BebasNeue_Bold;
src : url('../fonts/BebasNeue-Bold.otf')format('opentype');
}
@font-face {
font-family: Raleway_Light;
src : url('../fonts/Raleway-Light.ttf')format('truetype');
}
@font-face {
font-family: Raleway_ExtraLight;
src : url('../fonts/Raleway-ExtraLight.ttf')format('truetype');
}
/* MEDIA QUERIES */
@media (min-width: 320px) {
header nav .activo {
border-bottom: none; /*ESTO ES PARA LA OPCION ACTIVE*/
}
.right-text {
text-align: center;
}
.left-text {
text-align: center;
}
.cover-img {
margin-top: -5%;
}
.health-ad img {
margin-top: 30px;
margin-bottom: 20px;
}
.right-block {
margin-right: auto;
margin-left: auto;
}
.left-block {
margin-right: auto;
margin-left: auto;
}
.banner2-index {
height:500px;
z-index: 0;
}
.banner2-index .item h3{
margin-top: 50px;
}
.banner2-index .item img {
width: 80%;
}
/*footer*/
footer .description p {
padding : 30px 35px;
}
footer .slogan p {
margin-top: 0;
}
footer .contact {
padding: 50px 40px;
}
footer .contact .social_net{
padding: 20px 0;
}
.doc-banner2 p:nth-child(4) {
margin: 60px 5px;
}
.doc-banner3 {
/*background-image: url('../img/imagen-testimonios.png');
background-repeat:no-repeat;
background-size:cover;*/
width:100%;
height:500px;
}
.doc-banner3 .item h1 {
font-size: 40pt;
}
.owl-theme .owl-controls {
/*margin-left: 50%;*/
}
.doc-banner3 .item {
margin-top: 230px;
margin-left: 0;
}
.pa-banner2-index .item .right {
padding-top: 20px;
margin-bottom: 50px;
}
}
@media (min-width: 480px) {
.right-text {
text-align: center;
}
.left-text {
text-align: center;
}
}
@media (min-width: 600px) {
.right-text {
text-align: center;
}
.left-text {
text-align: center;
}
footer .description p {
padding : 30px 90px;
}
footer .slogan p {
padding: 0 100px;
}
footer .contact {
padding: 50px 120px;
}
}
@media (min-width: 768px) {
.right-text {
text-align: center;
}
.left-text {
text-align: center;
}
.cover-img {
margin-top: -15%;
}
.banner2-index {
height:550px;
z-index: 0;
}
.banner2-index .item h3{
margin-top: 170px;
}
.banner2-index .item img {
width: 100%;
}
.banner2-index .image {
margin-top: -5px;
}
footer .description p {
padding : 30px 120px;
}
.doc-banner2 p:nth-child(4) {
margin: 60px 50px;
}
.doc-banner3 {
/*background-image: url('../img/imagen-testimonios.png');
background-repeat:no-repeat;
background-size:cover;*/
width:100%;
height:550px;
}
.doc-banner3 .item h1 {
font-size: 40pt;
padding: 0 50px;
}
.owl-theme .owl-controls {
/*margin-left: 50%;*/
}
.doc-banner3 .item {
margin-top: 200px;
margin-left: 0;
}
}
@media (min-width: 1024px) {
header nav .activo {
border-bottom: 6px solid #CFF0FE; /*ESTO ES PARA LA OPCION ACTIVE*/
}
.right-text {
text-align: center;
}
.left-text {
text-align: center;
}
.cover-img {
margin-top: 0;
}
.health-ad img {
margin-top: 200px;
margin-bottom: 20px;
}
.right-block {
margin-right: 0;
margin-left: auto;
}
.left-block {
margin-right: auto;
margin-left: 0;
}
footer .description p {
padding : 30px 0;
}
footer .slogan p {
margin-top: 70px;
padding: 0 20px;
}
footer .contact {
padding: 50px 20px;
}
.pa-banner2-index .item .right {
padding-top: 190px;
margin-bottom: 0;
}
.banner2-index {
height:660px;
z-index: -1;
}
}
@media (min-width: 1280px) {
.right-text {
text-align: right;
}
.left-text {
text-align: left;
}
.banner2-index {
height:550px;
z-index: -1;
}
.banner2-index .item h3{
margin-top: 250px;
}
.banner2-index .item img {
width: 40%;
}
footer .description p {
padding : 30px 50px;
}
footer .contact {
margin-top: 30px;
}
footer .slogan p {
margin-top: 80px;
}
.doc-banner2 p:nth-child(4) {
margin: 60px 300px;
}
.doc-banner3 {
/*background-image: url('../img/imagen-testimonios.png');
background-repeat:no-repeat;
background-size:cover;*/
width:100%;
height:600px;
}
.doc-banner3 .item h1 {
font-size: 40pt;
padding: 0 50px;
}
.owl-theme .owl-controls {
margin-left: 50%;
}
.doc-banner3 .item {
margin-top: 200px;
margin-left: 50%;
}
.banner2-index {
height:660px;
z-index: -1;
}
.banner2-index .image {
margin-top: 90px;
}
}
@media (min-width: 1600px) {
footer .description p {
padding : 30px 90px;
}
footer .contact {
margin-top: 30px;
padding: 50px 90px;
}
footer .slogan p {
margin-top: 80px;
}
.doc-banner2 p:nth-child(4) {
margin: 60px 500px;
}
.doc-banner3 .item h1 {
font-size: 50pt;
padding: 0 10px;
}
}
/* GENERAL */
body {
background-color: #35353F;
}
.text-blue {
color: #178FEB;
}
a:link {
text-decoration: none;
color: #ffffff;
}
/* visited link */
a:visited {
text-decoration: none;
color: #ffffff;
}
/* mouse over link */
a:hover {
text-decoration: none;
color: #ffffff;
}
/* selected link */
a:active {
text-decoration: none;
color: #ffffff;
}
header nav {
background-color: #178FEB;
font-family: 'Raleway_Regular';
text-transform: uppercase;
text-decoration: none;
position: fixed;
top: 0;
width: 100%;
z-index: 999;
height: 124px;
}
header nav ul {
text-decoration: none;
padding: 0;
margin: 43px 0;
}
header nav li {
display: inline;
}
header nav li a {
text-decoration: none;
color: #ffffff;
font-size: 13pt;
}
header nav li a:hover {
background-color: #ffffff;
text-decoration: none;
color: #178FEB;
transition: all .1s ease-in-out;
padding-top: 53px;
padding-bottom: 56px;
}
.nav-left img{
padding: 15px 0;
}
.nav-center li a {
padding: 50px 5%;
}
.nav .mhome {
margin-top: -3px;
}
.nav-right li a {
padding: 50px 3%;
}
.nav-right li a:hover {
padding-bottom: 59px;
}
.nav-right a{
text-transform: uppercase;
color: #ffffff;
font-size: 13pt;
padding: 50px 3%;
/*border-bottom: 6px solid #fff;*/ /*ESTO ES PARA LA OPCION ACTIVE*/
}
.nav-right a:hover {
background-color: #ffffff;
text-decoration: none;
color: #178FEB;
transition: all .1s ease-in-out;
padding-top: 53px;
padding-bottom: 56px;
}
.nav-right .dropdown {
position: relative;
display: inline-block;
}
.right-text {
/*text-align: right;*/
margin-top: 46px;
}
.left-text {
/*text-align: left;*/
margin-top: 46px;
}
.nav-right .dropdown-content {
display: none;
position: absolute;
background-color: #35353F;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
padding: 12px 16px;
color: #fff;
margin-top: 54px;
font-size: 13pt;
}
.nav-right .dropdown:hover .dropdown-content {
display: block;
}
.nav-right img {
height: 20px;
width: 20px;
}
.menu_bar a {
color: white;
}
@media screen and (max-width: 991px) {
header {
position: fixed;
z-index: 9999;
width: 100%;
padding: 0;
margin: 0;
}
.container-fluid {
padding: 0;
margin: 0;
}
header nav {
width: 70%;
height: 100%;
margin: 0;
padding: 0;
z-index: 999;
background: #178FEB;
left: -100%;
margin-top: 55px;
overflow: scroll;
}
header nav ul li {
display: block;
float: none;
border-bottom: 1px solid rgba(255, 255, 255, .3);
margin: 0;
padding: 20px 0;
}
header nav ul li a {
margin: 0;
padding: 0;
}
header nav li a:hover {
background-color: #008BC4;
padding-top: 22px;
padding-bottom: 22px;
text-decoration: none;
color: #fff;
}
.menu_bar {
display: block;
margin: 0;
padding: 0;
/*position: fixed;*/
z-index: 9999;
width: 100%;
background: #178FEB;
}
.menu_bar .btn-menu {
display: block;
padding: 20px;
margin: 0;
text-decoration: none;
width: 100%;
}
.nav-right li a:hover {
padding-bottom: 22px;
}
}
.banner1 {
padding:0;
}
.banner2 {
background-color: #ffffff;
text-align: center;
}
.banner2 p:first-child {
font-family: 'Raleway_Regular';
font-size: 33pt;
margin-top: 100px;
margin-bottom: 80px;
}
.banner2 p:nth-child(3) {
text-transform: uppercase;
font-family: 'Raleway_Bold';
font-size: 25pt;
color: #393939;
margin-top: 80px;
}
.banner2 p:nth-child(3) span{
color: #142444;
}
.banner2 .button {
margin-bottom: 320px;
}
.banner2 .button img {
margin-top: 30px;
transition: all .2s ease-in-out;
}
.banner2 .button img:hover {
transform: scale(1.05);
}
.right-block {
display: block;
/*margin-right: 0;
margin-left: auto;*/
}
.left-block {
display: block;
/*margin-right: auto;
margin-left: 0;*/
}
/* HEALTH_AD */
.health-ad {
color: #ffffff;
text-align: center;
min-height: 590px;
}
.health-ad .slogan {
margin-top: 90px;
}
.health-ad .slogan p:first-child {
text-transform: uppercase;
font-family: 'BebasNeue_Bold';
font-size: 60pt;
}
.health-ad .slogan p:nth-child(2) {
font-family: 'Raleway_Bold';
font-size: 25pt;
}
/* HOW WORKS */
.h-work {
background-color: #ffffff;
text-align: center;
}
.h-work .title h2 {
text-align: center;
color: #393939;
font-family:'Raleway_Bold';
margin-top: 100px;
font-size: 20pt;
padding: 0;
text-transform: uppercase;
padding-bottom: 20px;
}
.h-work .blue_pleca {
padding: 0;
border: none;
border-top: 6px solid #178FEB;
width: 45px;
}
.h-work p {
font-family: 'Raleway_Regular';
font-size: 10pt;
margin-bottom: 30px;
color: #000000;
padding: 0 40px;
}
.h-work .content .description:hover {
background-color: #178FEB;
border: 2px solid #ffffff;
transition: background .25s ease-in-out;
}
.h-work .content .description:hover p {
color: #ffffff;
}
.h-work .content .description:hover hr:after {
color: #ffffff;
background: #178FEB;
transition: background .25s ease-in-out;
}
.h-work .content .description:hover hr {
border-top: solid #ffffff;
}
.h-work .content .description:hover h4 {
color: #ffffff;
}
.h-work .content .description {
background-color: #ffffff;
border: 2px solid #D7D7D7;
border-radius: 12px;
height: 310px;
width: 260px;
margin-top: 25px;
margin-bottom: 50px;
}
.h-work .content .description img {
margin-top: 30px;
width: 88px;
height: 88px;
}
.h-work h4 {
font-family: 'BebasNeue_Regular';
color: #178FEB;
font-size: 25pt;
}
.h-work .content .description .localiza {
background: url('../img/localiza.png');
background-repeat:no-repeat;
background-size:100%;
margin-top: 30px;
width:100px;
height:100px;
}
.h-work .content .description .confirma {
background: url('../img/confirma.png');
background-repeat:no-repeat;
background-size:100%;
margin-top: 25px;
width:100px;
height:100px;
}
.h-work .content .description .recibe {
background: url('../img/recibe.png');
background-repeat:no-repeat;
background-size:100%;
margin-top: 30px;
width:100px;
height:100px;
}
.h-work .content .description .evalua {
background: url('../img/evalua.png');
background-repeat:no-repeat;
background-size:100%;
margin-top: 30px;
width:100px;
height:100px;
}
.h-work .content hr {
padding: 0;
border: none;
border-top: solid #178FEB;
width: 50px;
}
.h-work .content hr:after {
display: inline-block;
position: relative;
top: -0.7em;
font-size: 18pt;
color: #178FEB;
font-family: 'BebasNeue_Regular';
padding: 0 0.25em;
background: white;
}
.h-work .content .hr0h {
border: none;
border-top: solid #D7D7D7;
width:75%;
position:absolute;
margin-top:170px;
margin-left:15%;
}
.h-work .content .hr0v {
border: none;
border-left: solid #D7D7D7;
height:1070px;
position:absolute;
margin-top:170px;
margin-left:48%;
}
.h-work .hr1:after {
content: "1";
}
.h-work .hr2:after {
content: "2";
}
.h-work .hr3:after {
content: "3";
}
.h-work .hr4:after {
content: "4";
}
.banner2-index {
background-image: url('../img/banner_web.png');
background-repeat:no-repeat;
background-size:cover;
width:100%;
/*height:600px;
z-index: -1;*/
}
.banner2-index .item h3{
font-family: 'Raleway_Bold';
font-size: 25pt;
color: #ffffff;
letter-spacing: 1px;
/*margin-top: 250px;*/
text-transform: uppercase;
}
.banner2-index .item p{
font-size: 16pt;
color: #fff;
}
.banner2-index .item .ques {
font-family: 'Raleway_Bold';
margin-top: 50px;
text-align: center;
}
.banner2-index .item .answ {
font-family: 'Raleway_Regular';
text-align: center;
}
.banner2-index .item .img-size {
width:300px;
height:auto;
}
.banner2-pag {
background: #ffffff;
height: 230px;
}
.banner2-pag hr {
margin-top:30px;
width: 830px;
border-top: solid #D7D7D7;
}
#custom-pagination-container {
padding: 6px;
background-color: transparent;
z-index: 9999;
margin-top: -130px;
}
#custom-pagination-container .owl-page {
display: inline-block;
zoom: 1;
cursor: pointer;
}
#custom-pagination-container .owl-page span {
display: block;
margin: 5px 47px;
width:144px;
height:144px;
}
#custom-pagination-container .owl-page span p {
color: #939598;
font-family: 'Raleway_Regular';
font-size: 13pt;
padding: 150px 0;
}
#custom-pagination-container .owl-page .bg-img-0 {
background: url('../img/primeros-auxilios2.png');
background-repeat:no-repeat;
background-size:100%;
margin-top: 30px;
transition: background .25s ease-in-out;
z-index: 9999;
}
#custom-pagination-container .owl-page .bg-img-1 {
background: url('../img/medicina_general_2.png');
background-repeat:no-repeat;
background-size:100%;
margin-top: 30px;
transition: background .25s ease-in-out;
}
#custom-pagination-container .owl-page .bg-img-2 {
background: url('../img/especialistas-2.png');
background-repeat:no-repeat;
background-size:100%;
margin-top: 30px;
transition: background .25s ease-in-out;
}
#custom-pagination-container .owl-page .bg-img-3 {
background: url('../img/premium-2.png');
background-repeat:no-repeat;
background-size:100%;
margin-top: 30px;
transition: background .25s ease-in-out;
}
#custom-pagination-container .owl-page.active span p, #custom-pagination-container .owl-page:hover span p {
color: #142444;
}
#custom-pagination-container .owl-page.active .bg-img-0, #custom-pagination-container .owl-page:hover .bg-img-0 {
background: url('../img/primeros-auxilios.png');
background-repeat:no-repeat;
background-size:100%;
margin-top: 30px;
transition: background .25s ease-in-out;
}
#custom-pagination-container .owl-page.active .bg-img-1, #custom-pagination-container .owl-page:hover .bg-img-1 {
background: url('../img/medicina-general.png');
background-repeat:no-repeat;
background-size:100%;
margin-top: 30px;
transition: background .25s ease-in-out;
}
#custom-pagination-container .owl-page.active .bg-img-2, #custom-pagination-container .owl-page:hover .bg-img-2 {
background: url('../img/especialistas.png');
background-repeat:no-repeat;
background-size:100%;
margin-top: 30px;
transition: background .25s ease-in-out;
}
#custom-pagination-container .owl-page.active .bg-img-3, #custom-pagination-container .owl-page:hover .bg-img-3 {
background: url('../img/premium.png');
background-repeat:no-repeat;
background-size:100%;
margin-top: 30px;
transition: background .25s ease-in-out;
}
/* footer */
footer {
background-color: #35353F;
color : #ffffff;
font-family : 'Montserrat_Light';
}
footer .description {
margin: 30px 0;
}
footer .description p {
font-size : 10pt;
text-align: justify;
}
footer .slogan p {
font-family: 'Raleway_Regular';
font-size: 33pt;
text-align: center;
}
footer .contact {
font-size: 12pt;
}
footer .contact .social_net {
margin: 0;
}
footer .contact .social_net a {
padding: 0 20px;
}
/***************************/
/* MEDICOS */
/***************************/
.doc-banner2 {
text-align: center;
background-color: #ffffff;
}
.doc-banner2 img {
margin-top: 90px;
width: 80px;
height: 80px;
}
.doc-banner2 p:nth-child(2) {
text-transform: uppercase;
font-family: 'Raleway_Bold';
font-size: 27pt;
color: #393939;
margin-top: 20px;
}
.doc-banner2 hr:nth-child(3) {
padding: 0;
border: none;
border-top: 6px solid #178FEB;
width: 45px;
}
.doc-banner2 p:nth-child(4) {
font-family: 'Raleway_Regular';
font-size: 20pt;
color: #707070;
/*margin: 60px 500px;*/
text-align: center;
margin-bottom: 100px;
}
.doc-banner3 {
background-image: url('../img/fondo_testimonios.png');
background-repeat:no-repeat;
background-size:cover;
width:100%;
/*height:655px;*/
}
.doc-banner3 .item {
/*margin-top: 15%;
margin-left: 50%;*/
color: #178FEB;
text-transform: uppercase;
font-family: 'BebasNeue_Bold';
}
.doc-banner3 .item h1 {
/*font-size: 50pt;*/
}
.doc-banner3 .owl-theme .owl-controls .owl-page span {
background: url('../img/pacientes.png');
background-repeat:no-repeat;
background-size:100%;
margin-top: 30px;
width:100px;
height:100px;
}
.owl-theme .owl-controls {
/*margin-left: 50%;*/
}
.owl-theme .owl-controls .owl-page{
display: inline-block;
zoom: 1;
*display: inline;/*IE7 life-saver */
}
.owl-theme .owl-controls .owl-page span{
display: block;
width: 12px;
height: 12px;
margin: 5px 7px;
filter: Alpha(Opacity=50);/*IE7 fix*/
opacity: 0.5;
-webkit-border-radius: 20px;
-moz-border-radius: 20px;
border-radius: 20px;
background: #ffffff;
margin-top: 100px;
}
.owl-theme .owl-controls .owl-page.active span,
.owl-theme .owl-controls.clickable .owl-page:hover span{
filter: Alpha(Opacity=100);/*IE7 fix*/
opacity: 1;
}
.doc-banner4 {
background-color: #ffffff;
text-align: center;
padding: 100px 0;
}
.doc-banner4 h2 {
text-transform: uppercase;
font-family: 'Raleway_Bold';
font-size: 27pt;
color: #393939;
margin-top: 60px;
}
.doc-banner4 hr{
padding: 0;
border: none;
border-top: 6px solid #178FEB;
width: 45px;
}
.doc-banner4 p {
font-family: 'Raleway_Regular';
font-size: 10pt;
margin-bottom: 30px;
color: #000000;
padding: 0 40px;
}
.doc-banner4 .content .description:hover {
background-color: #178FEB;
border: 2px solid #ffffff;
transition: background .25s ease-in-out;
}
.doc-banner4 .content .description:hover p {
color: #ffffff;
}
.doc-banner4 .content .description:hover h4 {
color: #ffffff;
}
.doc-banner4 .content .description {
background-color: #ffffff;
border: 2px solid #D7D7D7;
border-radius: 12px;
height: 310px;
width: 260px;
margin-top: 25px;
margin-bottom: 50px;
}
.doc-banner4 h4 {
font-family: 'BebasNeue_Regular';
color: #178FEB;
font-size: 25pt;
}
.doc-banner4 .content .description .paciente {
background: url('../img/pacientes.png');
background-repeat:no-repeat;
background-size:100%;
margin-top: 30px;
width:100px;
height:100px;
}
.doc-banner4 .content .description .tiempo {
background: url('../img/tiempo.png');
background-repeat:no-repeat;
background-size:100%;
margin-top: 30px;
width:100px;
height:100px;
}
.doc-banner4 .content .description .ingresos{
background: url('../img/ingresos.png');
background-repeat:no-repeat;
background-size:100%;
margin-top: 30px;
width:100px;
height:100px;
}
.doc-banner4 .static h3{
font-family: 'BebasNeue_Bold';
font-size: 40pt;
}
.doc-banner4 .static p {
font-size: 20pt;
}
.doc-banner4 .static span {
font-family: 'BebasNeue_Bold';
font-size: 45pt;
}
.doc-health-ad {
color: #fff;
text-align: center;
min-height: 390px;
}
.doc-health-ad .slogan {
margin-top: 90px;
text-transform: uppercase;
font-family: 'BebasNeue_Regular';
font-size: 70pt;
}
.doc-health-ad button {
text-transform: uppercase;
font-family: 'Raleway_Bold';
font-size: 20pt;
background-color: transparent;
padding: 20px 35px;
border: 3px solid #fff;
margin-bottom: 50px;
}
.doc-health-ad button:hover {
text-transform: uppercase;
font-family: 'Raleway_Bold';
font-size: 20pt;
background-color: transparent;
padding: 20px 35px;
border: 3px solid #ffffff;
color: #ffffff;
}
/*************/
.pa-banner2 {
background: #fff;
}
.pa-banner2 .pa-left {
margin-top: 90px;
}
.pa-banner2 .pa-left h2 {
color: #178FEB;
text-transform: uppercase;
font-family: 'BebasNeue_Regular';
font-size: 30pt;
}
.pa-banner2 .pa-left .pleca {
margin-bottom: 50px;
}
.pa-banner2 .pa-left .dina-img {
padding: 1% 0;
}
.pa-banner2 .pa-left .dina-text {
font-family: 'Raleway_Regular';
font-size: 14pt;
padding: 5% 0;
text-align: center;
padding-left: 20px;
}
.pa-banner2 .pa-right {
margin-top: 90px;
margin-bottom: 90px;
}
.pa-banner2 .pa-right img {
margin-bottom: 20px;
}
.pa-banner2 .pa-right .title {
background: #178FEB;
color: #ffffff;
font-family: 'BebasNeue_Regular';
height: 90px;
border: 1px solid #A1A1A1;
}
.pa-banner2 .pa-right .title h3 {
font-size: 30pt;
margin-top: 25px;
}
.pa-banner2 .pa-right .description {
background: #ffffff;
border: 1px solid #A1A1A1;
}
.pa-banner2 .pa-right .description .question {
font-family: 'BebasNeue_Regular';
font-size: 20pt;
margin-top: 40px;
margin-bottom: 30px;
}
.pa-banner2 .pa-right .description .answer {
font-family: 'Raleway_Regular';
font-size: 14pt;
}
.pa-banner2 .btn-med button{
margin-top: 100px;
margin-bottom: 100px;
background: #178FEB;
color: #ffffff;
text-transform: uppercase;
font-size: 25pt;
font-family: 'BebasNeue_Regular';
padding: 40px 50px;
border: 1px solid #178FEB;
border-radius: 15px;
}
.text-black {
color: #35353F;
}
.upper {
text-transform: uppercase;
}
.pa-banner2-index {
background: #178FEB;
}
.pa-banner2-index .item .left h3 {
font-family: 'Raleway_Bold';
font-size: 22pt;
color: #ffffff;
margin-bottom: 20px;
}
.pa-banner2-index .item .left img {
margin-top: 15px;
margin-bottom: 15px;
}
.pa-banner2-index .item .left p {
font-family: 'Raleway_Light';
font-size: 16pt;
}
.pa-banner2-index .item .center {
font-family: 'Raleway_Light';
color: #fff;
font-size: 15pt;
padding-top: 170px;
}
.pa-banner2-index .item .center p {
margin-top: 20px;
margin-bottom: 30px;
padding: 0 20px;
}
.pa-banner2-index .item .right {
font-family: 'Raleway_Bold';
font-size: 13pt;
color: #ffffff;
text-align: center;
/*padding-top: 190px;*/
}
.pa-banner2-index .item .right hr {
border: none;
border-top: 2px solid #ffffff;
width: 90px;
}
.tarifa {
font-family: 'BebasNeue_Regular';
font-size: 23pt;
}
.font-x {
font-family: 'Raleway_Light';
}
.btn-banner {
background: transparent;
color: white;
font-family: 'Raleway_Light';
text-transform: uppercase;
font-size: 20pt;
text-align: center;
margin-top: -150px;
padding: 20px 30px;
border: 2px solid white;
}
/***/
.politic {
background: #ffffff;
margin-top: 90px;
font-size: 12pt;
font-family: 'Raleway_Regular';
}
.politic img {
margin-top: 50px;
margin-bottom: 100px;
}
.politic h2 {
font-family: 'Raleway_Bold';
font-size: 20pt;
margin-bottom: 30px;
text-align: center;
}
.politic hr {
margin-top:30px;
width: 50px;
border-top: 4px solid #178FEB;
}
.content{
/*Checar si hace falta*/
/*display: none;*/
}
div.loader{
position: absolute;
width: 100%;
height: 100%;
background-color: #ffffff;
}
div.loader img{
position: absolute;
top: 50%;
left: 50%;
margin-left: -72px;
margin-top: -72px;
} | 19.554553 | 113 | 0.65499 |
a3787eddc4a14cbc4e39de93dacc70eb9823025a | 5,239 | java | Java | src/mod/gcewing/sg/SGInterfaceTE.java | liachmodded/SGCraft | f092b9ce8d046e3f64099c7c83ccebb7a65d5c78 | [
"MIT"
] | 12 | 2016-01-09T11:51:36.000Z | 2021-09-24T09:52:57.000Z | src/mod/gcewing/sg/SGInterfaceTE.java | liachmodded/SGCraft | f092b9ce8d046e3f64099c7c83ccebb7a65d5c78 | [
"MIT"
] | 53 | 2016-04-16T22:06:03.000Z | 2021-08-16T18:02:26.000Z | src/mod/gcewing/sg/SGInterfaceTE.java | liachmodded/SGCraft | f092b9ce8d046e3f64099c7c83ccebb7a65d5c78 | [
"MIT"
] | 25 | 2016-01-16T08:25:25.000Z | 2022-01-24T18:30:20.000Z | //------------------------------------------------------------------------------------------------
//
// SG Craft - Base class for stargate computer interface tile entities
//
//------------------------------------------------------------------------------------------------
package gcewing.sg;
import net.minecraft.tileentity.*;
import gcewing.sg.SGAddressing.AddressingError;
import static gcewing.sg.BaseBlockUtils.*;
public class SGInterfaceTE extends BaseTileEntity {
public SGBaseTE getBaseTE() {
return SGBaseTE.get(worldObj, getPos().add(0, 1, 0));
}
// Signature is really prependArgs(Object..., Object[])
public static Object[] prependArgs(Object... args) {
int preLength = args.length - 1;
Object[] post = (Object[])args[preLength];
Object[] xargs = new Object[preLength + post.length];
for (int i = 0; i < preLength; i++)
xargs[i] = args[i];
for (int i = 0; i < post.length; i++)
xargs[preLength + i] = post[i];
return xargs;
}
public void rebroadcastNetworkPacket(Object packet) {
}
public static class CIStargateState {
public String state;
public int chevrons;
public String direction;
public CIStargateState(String state, int chevrons, String direction) {
this.state = state;
this.chevrons = chevrons;
this.direction = direction;
}
}
public SGBaseTE requireBaseTE() {
SGBaseTE te = getBaseTE();
if (te != null && te.isMerged)
return te;
throw new IllegalArgumentException("No stargate connected to interface");
}
public SGBaseTE requireIrisTE() {
SGBaseTE te = requireBaseTE();
if (te != null && te.hasIrisUpgrade)
return te;
else
throw new IllegalArgumentException("No iris fitted to stargate");
}
String directionDescription(SGBaseTE te) {
if (te.isConnected()) {
if (te.isInitiator)
return "Outgoing";
else
return "Incoming";
}
else
return "";
}
public CIStargateState ciStargateState() {
SGBaseTE te = getBaseTE();
if (te != null)
return new CIStargateState(te.sgStateDescription(), te.numEngagedChevrons, directionDescription(te));
else
return new CIStargateState("Offline", 0, "");
}
public double ciEnergyAvailable() {
SGBaseTE te = getBaseTE();
if (te != null)
return te.availableEnergy();
else
return 0;
}
public double ciEnergyToDial(String address) {
SGBaseTE te = requireBaseTE();
try {
address = SGAddressing.normalizeAddress(address);
SGBaseTE dte = SGAddressing.findAddressedStargate(address, getTileEntityWorld(te));
if (dte == null)
throw new IllegalArgumentException("No stargate at address " + address);
double distanceFactor = SGBaseTE.distanceFactorForCoordDifference(te, dte);
return SGBaseTE.energyToOpen * distanceFactor;
}
catch (AddressingError e) {
System.out.printf("SGBaseTE.ciEnergyToDial: caught %s\n", e);
throw new IllegalArgumentException(e.getMessage());
}
}
public String ciLocalAddress() {
SGBaseTE te = getBaseTE();
try {
if (te != null)
return te.getHomeAddress();
else
return "";
}
catch (AddressingError e) {
throw new IllegalArgumentException(e.getMessage());
}
}
public String ciRemoteAddress() {
SGBaseTE te = requireBaseTE();
try {
if (te.connectedLocation != null)
return SGAddressing.addressForLocation(te.connectedLocation);
else
return "";
}
catch (AddressingError e) {
throw new IllegalArgumentException(e.getMessage());
}
}
public void ciDial(String address) {
SGBaseTE te = requireBaseTE();
address = SGAddressing.normalizeAddress(address);
String error = te.connect(address, null);
if (error != null)
throw new IllegalArgumentException(error);
}
public void ciDisconnect() {
SGBaseTE te = requireBaseTE();
String error = te.attemptToDisconnect(null);
if (error != null)
throw new IllegalArgumentException(error);
}
public String ciIrisState() {
SGBaseTE te = getBaseTE();
if (te != null && te.hasIrisUpgrade)
return te.irisStateDescription();
else
return "Offline";
}
public void ciOpenIris() {
requireIrisTE().openIris();
}
public void ciCloseIris() {
requireIrisTE().closeIris();
}
public void ciSendMessage(Object[] args) {
SGBaseTE te = requireBaseTE();
String error = te.sendMessage(args);
if (error != null)
throw new IllegalArgumentException(error);
}
}
| 31 | 113 | 0.550678 |
a084240a7581c80947112e30d61feac78b67a4e3 | 1,128 | swift | Swift | KeyboardLayoutGuideSample/KeyboardLayoutGuideSample/MultipleForms/FormView.swift | Sab-swiftlin/KeyboardLayoutGuideSample | e4fb4b23654ea1f10f5426adf0df5d9e18d86aa8 | [
"MIT"
] | null | null | null | KeyboardLayoutGuideSample/KeyboardLayoutGuideSample/MultipleForms/FormView.swift | Sab-swiftlin/KeyboardLayoutGuideSample | e4fb4b23654ea1f10f5426adf0df5d9e18d86aa8 | [
"MIT"
] | null | null | null | KeyboardLayoutGuideSample/KeyboardLayoutGuideSample/MultipleForms/FormView.swift | Sab-swiftlin/KeyboardLayoutGuideSample | e4fb4b23654ea1f10f5426adf0df5d9e18d86aa8 | [
"MIT"
] | null | null | null | import UIKit
class FormView: UIView {
@IBOutlet private weak var titleLabel: UILabel!
@IBOutlet private weak var field: UITextField!
override init(frame: CGRect) {
super.init(frame: frame)
loadNib()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
loadNib()
}
func setTitle(title: String) {
titleLabel.text = title
}
private func loadNib() {
guard let formView = Bundle.main.loadNibNamed("Form", owner: self, options: nil)?.first as? UIView else { fatalError() }
addSubview(formView)
formView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
formView.topAnchor.constraint(equalTo: topAnchor),
formView.bottomAnchor.constraint(equalTo: bottomAnchor),
formView.leadingAnchor.constraint(equalTo: leadingAnchor),
formView.trailingAnchor.constraint(equalTo: trailingAnchor)
])
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
self.endEditing(true)
}
}
| 30.486486 | 128 | 0.641844 |
ed6f284ec220ee7f20c4fb717f8f78e48fb71170 | 207 | h | C | 52jianpan/jianpan/ViewController.h | P79N6A/demo | 0286a294b8f9f83b316e75e8d996e94fb6ab6a53 | [
"Apache-2.0"
] | 4 | 2019-08-14T03:06:51.000Z | 2021-11-15T03:02:09.000Z | 52jianpan/jianpan/ViewController.h | P79N6A/demo | 0286a294b8f9f83b316e75e8d996e94fb6ab6a53 | [
"Apache-2.0"
] | null | null | null | 52jianpan/jianpan/ViewController.h | P79N6A/demo | 0286a294b8f9f83b316e75e8d996e94fb6ab6a53 | [
"Apache-2.0"
] | 2 | 2019-09-17T06:50:12.000Z | 2021-11-15T03:02:11.000Z | //
// ViewController.h
// jianpan
//
// Created by Jay on 2018/3/22.
// Copyright © 2018年 Jay. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface ViewController : UITableViewController
@end
| 12.9375 | 49 | 0.681159 |
e1e95e2e1dd8c052db11208b9fc40342112923b1 | 796 | rb | Ruby | app/services/stored_file_zipper.rb | robstolarz/nucore-uconn | 7e0e80919d978fa73703e261ee9319b517e89004 | [
"MIT"
] | null | null | null | app/services/stored_file_zipper.rb | robstolarz/nucore-uconn | 7e0e80919d978fa73703e261ee9319b517e89004 | [
"MIT"
] | null | null | null | app/services/stored_file_zipper.rb | robstolarz/nucore-uconn | 7e0e80919d978fa73703e261ee9319b517e89004 | [
"MIT"
] | null | null | null | class StoredFileZipper
attr_reader :files
def initialize(files)
@files = files
end
def read
return @read if @read
zip_io = build_zip
zip_io.rewind
@read = zip_io.read
end
private
def build_zip
@filenames = {}
Zip::OutputStream.write_buffer do |stream|
files.each do |file|
stream.put_next_entry(filename(file))
stream << file.read
end
end
end
# If a filename has already been used, append a -X to the end of the name
# before the extension. E.g. 12345_B07.ab1 => 12345_B07-1.ab1
def filename(file)
if @filenames.key?(file.name)
@filenames[file.name] += 1
file.name.sub(/\.(\w+)\z/, "-#{@filenames[file.name]}.\\1")
else
@filenames[file.name] = 0
file.name
end
end
end
| 18.952381 | 75 | 0.61809 |
517e83be9aa1e2720023ebe4a9605576eba50eb7 | 1,071 | js | JavaScript | lib/helpers/injectCSS.js | zacharyz/react-modal-static-overlay | 1e1ec06f305f358472a975998678371a1af38ba5 | [
"MIT"
] | 2 | 2015-09-05T02:50:57.000Z | 2016-10-21T19:05:31.000Z | lib/helpers/injectCSS.js | zacharyz/react-modal-static-overlay | 1e1ec06f305f358472a975998678371a1af38ba5 | [
"MIT"
] | null | null | null | lib/helpers/injectCSS.js | zacharyz/react-modal-static-overlay | 1e1ec06f305f358472a975998678371a1af38ba5 | [
"MIT"
] | null | null | null | module.exports = function() {
injectStyle([
'.ReactModal__Overlay {',
' background-color: rgba(255, 255, 255, 0.75);',
'}',
'.ReactModal__Content {',
' position: absolute;',
' top: 40px;',
' left: 40px;',
' right: 40px;',
' bottom: 40px;',
' border: 1px solid #ccc;',
' background: #fff;',
' overflow: auto;',
' -webkit-overflow-scrolling: touch;',
' border-radius: 4px;',
' outline: none;',
' padding: 20px;',
'}',
'@media (max-width: 768px) {',
' .ReactModal__Content {',
' top: 10px;',
' left: 10px;',
' right: 10px;',
' bottom: 10px;',
' padding: 10px;',
' }',
'}'
].join('\n'));
};
function injectStyle(css) {
var style = document.getElementById('rackt-style');
if (!style) {
style = document.createElement('style');
style.setAttribute('id', 'rackt-style');
var head = document.getElementsByTagName('head')[0];
head.insertBefore(style, head.firstChild);
}
style.innerHTML = style.innerHTML+'\n'+css;
}
| 24.906977 | 56 | 0.542484 |
de7ae350140c32164b66b3ce4153ce54c2bce5b5 | 3,241 | rs | Rust | kernel-ewasm/cap9-std/examples/acl_bootstrap.rs | sambacha/cap9 | 05fe5451468679efa89e93e19614bedd7b4ca349 | [
"Apache-2.0"
] | 12 | 2019-07-02T14:59:42.000Z | 2021-09-27T03:00:45.000Z | kernel-ewasm/cap9-std/examples/acl_bootstrap.rs | Daolab/beakeros | 05fe5451468679efa89e93e19614bedd7b4ca349 | [
"Apache-2.0"
] | 74 | 2018-08-13T12:55:08.000Z | 2019-03-27T12:55:31.000Z | kernel-ewasm/cap9-std/examples/acl_bootstrap.rs | Daolab/beakeros | 05fe5451468679efa89e93e19614bedd7b4ca349 | [
"Apache-2.0"
] | 8 | 2019-07-02T13:33:24.000Z | 2022-01-09T22:25:19.000Z | #![no_std]
#![allow(non_snake_case)]
extern crate cap9_std;
extern crate pwasm_std;
extern crate pwasm_abi_derive;
// When we are compiling to WASM, unresolved references are left as (import)
// expressions. However, under any other target symbols will have to be linked
// for EVM functions (blocknumber, create, etc.). Therefore, when we are not
// compiling for WASM (be it test, realse, whatever) we want to link in dummy
// functions. pwasm_test provides all the builtins provided by parity, while
// cap9_test covers the few that we have implemented ourselves.
#[cfg(not(target_arch = "wasm32"))]
extern crate pwasm_test;
#[cfg(not(target_arch = "wasm32"))]
extern crate cap9_test;
fn main() {}
// struct CapIndex(pub u8);
pub mod ACL {
use pwasm_abi::types::*;
use pwasm_abi_derive::eth_abi;
use cap9_std;
#[eth_abi(ACLBootstrapEndpoint)]
pub trait ACLBootstrapInterface {
fn constructor(&mut self);
fn init(&mut self, entry_key: H256, entry_address: Address, entry_cap_list: Vec<H256>, admin_key: H256, admin_address: Address, admin_cap_list: Vec<H256>, admin_account: Address);
}
pub struct ACLContract;
impl ACLBootstrapInterface for ACLContract {
fn constructor(&mut self) {}
fn init(&mut self, entry_key: H256, entry_address: Address, entry_cap_list: Vec<H256>, admin_key: H256, admin_address: Address, admin_cap_list: Vec<H256>, admin_account: Address) {
// Register the admin procedure, uses RegCap 0
cap9_std::reg(0, admin_key.into(), admin_address, admin_cap_list).unwrap();
// Register the entry procedure
cap9_std::reg(1, entry_key.into(), entry_address, entry_cap_list).unwrap();
// Set the entry procedure
cap9_std::entry(0, entry_key.into()).unwrap();
// Add admin to the admin group (1)
let admin_group: u8 = 1;
let mut account_map: cap9_std::StorageEnumerableMap<Address, u8>
= cap9_std::StorageEnumerableMap::from(0).unwrap();
account_map.insert(admin_account, admin_group);
// Set the procedure of the admin group (1) to the admin procedure
let mut procedure_map: cap9_std::StorageEnumerableMap<u8,cap9_std::SysCallProcedureKey>
= cap9_std::StorageEnumerableMap::from(1).unwrap();
procedure_map.insert(admin_group, admin_key.into());
// Unregister this bootstrap procedure, note that the contract will
// not be reaped.
let current_proc = cap9_std::proc_table::get_current_proc_id();
cap9_std::delete(0, current_proc.into()).unwrap();
}
}
}
// Declares the dispatch and dispatch_ctor methods
use pwasm_abi::eth::EndpointInterface;
#[no_mangle]
pub fn call() {
let mut endpoint = ACL::ACLBootstrapEndpoint::new(ACL::ACLContract {});
// Read http://solidity.readthedocs.io/en/develop/abi-spec.html#formal-specification-of-the-encoding for details
pwasm_ethereum::ret(&endpoint.dispatch(&pwasm_ethereum::input()));
}
#[no_mangle]
pub fn deploy() {
let mut endpoint = ACL::ACLBootstrapEndpoint::new(ACL::ACLContract {});
endpoint.dispatch_ctor(&pwasm_ethereum::input());
}
| 40.012346 | 188 | 0.685282 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.