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
cf2e422102e19550ee40740fce8c1dfc2aad5919
1,095
php
PHP
application/config/app/constants.php
ktsuench/real_update
4bfbdee25442a4c3ba9a46eb478333d9473118f0
[ "MIT" ]
null
null
null
application/config/app/constants.php
ktsuench/real_update
4bfbdee25442a4c3ba9a46eb478333d9473118f0
[ "MIT" ]
null
null
null
application/config/app/constants.php
ktsuench/real_update
4bfbdee25442a4c3ba9a46eb478333d9473118f0
[ "MIT" ]
null
null
null
<?php defined('BASEPATH') OR exit('No direct script access allowed'); defined('ENV_DEVELOPMENT') OR define('ENV_DEVELOPMENT' , 'development'); defined('ENV_TESTING') OR define('ENV_TESTING' , 'testing'); defined('ENV_PRODUCTION') OR define('ENV_PRODUCTION' , 'production'); defined('ENV_LOC_LOCAL') OR define('ENV_LOC_LOCAL' , 'local'); defined('ENV_LOC_REMOTE') OR define('ENV_LOC_REMOTE' , 'remote'); defined('OP_CREATE') OR define('OP_CREATE', 0); defined('OP_UPDATE') OR define('OP_UPDATE', 1); defined('OP_VERIFY') OR define('OP_VERIFY', 2); defined('OP_DELETE') OR define('OP_DELETE', 3); defined('OP_CREATE_BATCH') OR define('OP_CREATE_BATCH', 4); defined('OP_DELETE_ALL') OR define('OP_DELETE_ALL', 5); defined('GUEST') OR define('GUEST', 'guest'); defined('ADMIN') OR define('ADMIN', 'admin'); defined('UPLOAD_TMP') OR define('UPLOAD_TMP', 'uploads/tmp/'); defined('UPLOAD_ANN') OR define('UPLOAD_ANN', 'uploads/ann_content/'); defined('SETTINGS_PATH') OR define('SETTINGS_PATH', 'application/config/app/'); ?>
45.625
79
0.677626
5c73f0a3e4480d5a524bb438df7dda5403ea5f78
819
dart
Dart
lib/src/decorators/box_shape_decorator.dart
fauziridwan1709/ristek_material_component
191a22bbe2116f3f652a0f576061ba7f52313601
[ "MIT" ]
1
2021-11-11T04:21:47.000Z
2021-11-11T04:21:47.000Z
lib/src/decorators/box_shape_decorator.dart
fauziridwan1709/ristek_material_component
191a22bbe2116f3f652a0f576061ba7f52313601
[ "MIT" ]
null
null
null
lib/src/decorators/box_shape_decorator.dart
fauziridwan1709/ristek_material_component
191a22bbe2116f3f652a0f576061ba7f52313601
[ "MIT" ]
null
null
null
// Created by Muhamad Fauzi Ridwan on 07/11/21. part of '_decorators.dart'; class BoxShapeDecorator { BoxShapeDecorator() { _shadowDecorator = BoxShadowDecorator(); _boxDecoration = const BoxDecoration(); } BoxShapeDecorator.withColor(Color color) { _shadowDecorator = BoxShadowDecorator(); _boxDecoration = BoxDecoration(color: color); } BoxShadowDecorator? _shadowDecorator; BoxDecoration? _boxDecoration; BoxDecoration defaultDecoration(BuildContext context) { return _boxDecoration!.copyWith( boxShadow: _shadowDecorator!.defaultShadow(context), borderRadius: BorderRadius.circular(12), ); } BoxDecoration normalDecoration(BuildContext context) { return _boxDecoration!.copyWith( boxShadow: _shadowDecorator!.defaultShadow(context), ); } }
26.419355
58
0.739927
a91019437a40fc34ff5892414e956eca9b6cc7fb
6,754
css
CSS
css/main.css
madhavsankar/madhavsankar.github.io
942ff6c4e7c194f7c280a05515fcbe824a19b951
[ "MIT" ]
4
2015-05-28T17:44:51.000Z
2020-12-01T19:08:35.000Z
css/main.css
madhavsankar/madhavsankar.github.io
942ff6c4e7c194f7c280a05515fcbe824a19b951
[ "MIT" ]
1
2015-01-28T21:36:02.000Z
2015-01-28T21:36:02.000Z
css/main.css
madhavsankar/madhavsankar.github.io
942ff6c4e7c194f7c280a05515fcbe824a19b951
[ "MIT" ]
4
2016-03-16T11:35:36.000Z
2020-09-25T10:01:13.000Z
* { margin: 0; padding: 0; } ::-moz-selection { color: black; background: lightgray; } ::selection { color: black; background: lightgray; } html, body { height: 100%; } body, section, h1, h2, h3, h4 { font-family: Arial, sans-serif; } body, section, h1, h2, h3, h4, h5, h6 { font-family: 'Open Sans', Arial, Helvetica Neue, sans-serif; } a { -webkit-transition: all .3s ease-in-out; transition: all .3s ease-in-out; } a:hover, a:focus { text-decoration: none; } h1, h2, h3, h4, h5, h6 { font-style: normal; text-transform: uppercase; letter-spacing: 3px; font-weight: 300; } code { background: whitesmoke; color: black; text-transform: none; } #footer { padding: 65px 0 150px; background: whitesmoke; border-top: 1px solid lightgray; text-align: center; font-weight: 300; } #footer h3 { margin-bottom: 30px; color: gray; } #footer ul { list-style: none; display: table; margin: 0 auto; } #footer ul li { display: inline-block; min-width: 50px; min-height: 75px; margin: 0 30px; padding: 0 30px; position: relative; } #footer ul li a { color: lightgray; } #footer ul li a i { font-size: 2.6em; } #footer ul li a p { position: absolute; font-weight: 400; letter-spacing: 1px; display: none; left: 0; right: 0; margin: auto; margin-top: 10px; color: inherit; } #footer ul .email:hover a { color: red; } #footer ul .github:hover a { color: #000000; } #footer ul .twitter:hover a { color: #32CCFE; } #footer ul .facebook:hover a { color: #3b5998; } #footer ul .linkedin:hover a { color: #0976b4; } #footer .dash { background-color: #cccccc; } #footer .license { font-family: Georgia, sans-serif; color: lightgray; letter-spacing: 1px; font-size: 13px; margin-top: 15px; } #footer .license a { color: inherit; padding-bottom: 3px; border-bottom: 1px dotted lightgray; } #footer .license a:hover { border-bottom: 1px solid lightgray; } /* Syntax highlighting styles */ /* ----------------------------------------------------------*/ mark { letter-spacing: 1px; padding: 0.5em; } pre { font-size: 18px; padding: 1.5em 1em; border-radius: 0; border: none; border: 1px solid #ccc; border-left: 6px solid #ccc; background: shade(white, 2%); } .highlight { margin-bottom: 30px; position: relative; } .highlight { background-color: #fdf6e3; color: #586e75; } .highlight .lineno { color: #93a1a1; } /* Line Numbers */ .highlight .c { color: #93a1a1; } /* Comment */ .highlight .err { color: #586e75; } /* Error */ .highlight .g { color: #586e75; } /* Generic */ .highlight .k { color: #859900; } /* Keyword */ .highlight .l { color: #586e75; } /* Literal */ .highlight .n { color: #586e75; } /* Name */ .highlight .o { color: #859900; } /* Operator */ .highlight .x { color: #cb4b16; } /* Other */ .highlight .p { color: #586e75; } /* Punctuation */ .highlight .cm { color: #93a1a1; } /* Comment.Multiline */ .highlight .cp { color: #859900; } /* Comment.Preproc */ .highlight .c1 { color: #93a1a1; } /* Comment.Single */ .highlight .cs { color: #859900; } /* Comment.Special */ .highlight .gd { color: #2aa198; } /* Generic.Deleted */ .highlight .ge { color: #586e75; font-style: italic; } /* Generic.Emph */ .highlight .gr { color: #dc322f; } /* Generic.Error */ .highlight .gh { color: #cb4b16; } /* Generic.Heading */ .highlight .gi { color: #859900; } /* Generic.Inserted */ .highlight .go { color: #586e75; } /* Generic.Output */ .highlight .gp { color: #586e75; } /* Generic.Prompt */ .highlight .gs { color: #586e75; font-weight: bold; } /* Generic.Strong */ .highlight .gu { color: #cb4b16; } /* Generic.Subheading */ .highlight .gt { color: #586e75; } /* Generic.Traceback */ .highlight .kc { color: #cb4b16; } /* Keyword.Constant */ .highlight .kd { color: #268bd2; } /* Keyword.Declaration */ .highlight .kn { color: #859900; } /* Keyword.Namespace */ .highlight .kp { color: #859900; } /* Keyword.Pseudo */ .highlight .kr { color: #268bd2; } /* Keyword.Reserved */ .highlight .kt { color: #dc322f; } /* Keyword.Type */ .highlight .ld { color: #586e75; } /* Literal.Date */ .highlight .m { color: #2aa198; } /* Literal.Number */ .highlight .s { color: #2aa198; } /* Literal.String */ .highlight .na { color: #586e75; } /* Name.Attribute */ .highlight .nb { color: #B58900; } /* Name.Builtin */ .highlight .nc { color: #268bd2; } /* Name.Class */ .highlight .no { color: #cb4b16; } /* Name.Constant */ .highlight .nd { color: #268bd2; } /* Name.Decorator */ .highlight .ni { color: #cb4b16; } /* Name.Entity */ .highlight .ne { color: #cb4b16; } /* Name.Exception */ .highlight .nf { color: #268bd2; } /* Name.Function */ .highlight .nl { color: #586e75; } /* Name.Label */ .highlight .nn { color: #586e75; } /* Name.Namespace */ .highlight .nx { color: #586e75; } /* Name.Other */ .highlight .py { color: #586e75; } /* Name.Property */ .highlight .nt { color: #268bd2; } /* Name.Tag */ .highlight .nv { color: #268bd2; } /* Name.Variable */ .highlight .ow { color: #859900; } /* Operator.Word */ .highlight .w { color: #586e75; } /* Text.Whitespace */ .highlight .mf { color: #2aa198; } /* Literal.Number.Float */ .highlight .mh { color: #2aa198; } /* Literal.Number.Hex */ .highlight .mi { color: #2aa198; } /* Literal.Number.Integer */ .highlight .mo { color: #2aa198; } /* Literal.Number.Oct */ .highlight .sb { color: #93a1a1; } /* Literal.String.Backtick */ .highlight .sc { color: #2aa198; } /* Literal.String.Char */ .highlight .sd { color: #586e75; } /* Literal.String.Doc */ .highlight .s2 { color: #2aa198; } /* Literal.String.Double */ .highlight .se { color: #cb4b16; } /* Literal.String.Escape */ .highlight .sh { color: #586e75; } /* Literal.String.Heredoc */ .highlight .si { color: #2aa198; } /* Literal.String.Interpol */ .highlight .sx { color: #2aa198; } /* Literal.String.Other */ .highlight .sr { color: #dc322f; } /* Literal.String.Regex */ .highlight .s1 { color: #2aa198; } /* Literal.String.Single */ .highlight .ss { color: #2aa198; } /* Literal.String.Symbol */ .highlight .bp { color: #268bd2; } /* Name.Builtin.Pseudo */ .highlight .vc { color: #268bd2; } /* Name.Variable.Class */ .highlight .vg { color: #268bd2; } /* Name.Variable.Global */ .highlight .vi { color: #268bd2; } /* Name.Variable.Instance */ .highlight .il { color: #2aa198; } /* Literal.Number.Integer.Long */ .sink { display: inline-block; -webkit-transition-duration: 0.3s; transition-duration: 0.3s; -webkit-transition-property: transform; transition-property: transform; -webkit-transform: translateZ(0); transform: translateZ(0); box-shadow: 0 0 1px transparent; } .sink:hover, .sink:focus, .sink:active { -webkit-transform: translateY(5px); transform: translateY(5px); } .padded { padding-left:15%; padding-right:15%; padding-top:1%;} a { text-decoration-line: none;}
25.877395
259
0.643619
b1952e02093038b8f0cf2e7715525b5d584bb4a5
260
py
Python
python/testData/override/dunderNewPy3k_after.py
jnthn/intellij-community
8fa7c8a3ace62400c838e0d5926a7be106aa8557
[ "Apache-2.0" ]
2
2019-04-28T07:48:50.000Z
2020-12-11T14:18:08.000Z
python/testData/override/dunderNewPy3k_after.py
jnthn/intellij-community
8fa7c8a3ace62400c838e0d5926a7be106aa8557
[ "Apache-2.0" ]
173
2018-07-05T13:59:39.000Z
2018-08-09T01:12:03.000Z
python/testData/override/dunderNewPy3k_after.py
jnthn/intellij-community
8fa7c8a3ace62400c838e0d5926a7be106aa8557
[ "Apache-2.0" ]
2
2020-03-15T08:57:37.000Z
2020-04-07T04:48:14.000Z
class BaseMeta(type): def __new__(cls, name, bases, namespace): return super().__new__(cls, name, bases, namespace) class MyMeta(BaseMeta): def __new__(cls, name, bases, namespace): return super().__new__(cls, name, bases, namespace)
28.888889
59
0.676923
a392f3338ee16f0c71c5cd5e05d6abe86e94dc1c
1,600
java
Java
src/main/java/com/minerarcana/transfiguration/recipe/json/TagJson.java
Mrbysco/Transfiguration
7f3dc354cb0a2c06142cd98c6694786af3840319
[ "MIT" ]
null
null
null
src/main/java/com/minerarcana/transfiguration/recipe/json/TagJson.java
Mrbysco/Transfiguration
7f3dc354cb0a2c06142cd98c6694786af3840319
[ "MIT" ]
null
null
null
src/main/java/com/minerarcana/transfiguration/recipe/json/TagJson.java
Mrbysco/Transfiguration
7f3dc354cb0a2c06142cd98c6694786af3840319
[ "MIT" ]
1
2022-01-26T21:55:12.000Z
2022-01-26T21:55:12.000Z
package com.minerarcana.transfiguration.recipe.json; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import net.minecraft.block.Block; import net.minecraft.entity.EntityType; import net.minecraft.tags.ITag; import net.minecraft.tags.TagCollectionManager; import net.minecraft.util.JSONUtils; import net.minecraft.util.ResourceLocation; public class TagJson { public static ITag<EntityType<?>> getEntityTypeTag(JsonObject jsonObject, String fieldName) { String tagName = JSONUtils.getString(jsonObject, fieldName); ITag<EntityType<?>> entityTypeITag = TagCollectionManager.getManager().getEntityTypeTags().get(new ResourceLocation(tagName)); if (entityTypeITag != null) { return entityTypeITag; } else { throw new JsonParseException("Failed ot find Entity Tag for " + tagName); } } public static ITag<EntityType<?>> getEntityTypeTag(JsonObject jsonObject) { return getEntityTypeTag(jsonObject, "tag"); } public static ITag<Block> getBlockTag(JsonObject jsonObject, String fieldName) { String tagName = JSONUtils.getString(jsonObject, fieldName); ITag<Block> blockITag = TagCollectionManager.getManager().getBlockTags().get(new ResourceLocation(tagName)); if (blockITag != null) { return blockITag; } else { throw new JsonParseException("Failed to find Block Tag for " + tagName); } } public static ITag<Block> getBlockTag(JsonObject jsonObject) { return getBlockTag(jsonObject, "tag"); } }
39.02439
134
0.71
bb7795595bb3e941b206abb9ba94ab5db5d37a06
450
asm
Assembly
oeis/180/A180146.asm
neoneye/loda-programs
84790877f8e6c2e821b183d2e334d612045d29c0
[ "Apache-2.0" ]
11
2021-08-22T19:44:55.000Z
2022-03-20T16:47:57.000Z
oeis/180/A180146.asm
neoneye/loda-programs
84790877f8e6c2e821b183d2e334d612045d29c0
[ "Apache-2.0" ]
9
2021-08-29T13:15:54.000Z
2022-03-09T19:52:31.000Z
oeis/180/A180146.asm
neoneye/loda-programs
84790877f8e6c2e821b183d2e334d612045d29c0
[ "Apache-2.0" ]
3
2021-08-22T20:56:47.000Z
2021-09-29T06:26:12.000Z
; A180146: Eight rooks and one berserker on a 3 X 3 chessboard. G.f.: 1/(1 - 4*x - 3*x^2 + 6*x^3). ; Submitted by Jamie Morken(w4) ; 1,4,19,82,361,1576,6895,30142,131797,576244,2519515,11016010,48165121,210591424,920764999,4025843542,17602120621,76961423116,336496993075,1471259517922,6432760512217,28125838644184,122974079005855 lpb $0 sub $0,1 mul $2,2 mov $3,$2 mul $4,3 add $4,1 mov $2,$4 add $4,$3 lpe mov $0,$4 mul $0,3 add $0,1
26.470588
198
0.7
a3a68029f1eefa6723cd4872fbc28df298d263c9
15,652
ts
TypeScript
src/charting/renderer/YAxisRenderer.ts
rbudnar/ui-chart
11936d63c63ce20d409e62b0c8fd4660f91d14f0
[ "Apache-2.0" ]
null
null
null
src/charting/renderer/YAxisRenderer.ts
rbudnar/ui-chart
11936d63c63ce20d409e62b0c8fd4660f91d14f0
[ "Apache-2.0" ]
null
null
null
src/charting/renderer/YAxisRenderer.ts
rbudnar/ui-chart
11936d63c63ce20d409e62b0c8fd4660f91d14f0
[ "Apache-2.0" ]
null
null
null
import { AxisRenderer, CustomRendererGridLineFunction } from './AxisRenderer'; import { ViewPortHandler } from '../utils/ViewPortHandler'; import { AxisDependency, YAxis, YAxisLabelPosition } from '../components/YAxis'; import { Transformer } from '../utils/Transformer'; import { Align, Canvas, Paint, Path, RectF, Style } from '@nativescript-community/ui-canvas'; import { Utils } from '../utils/Utils'; import { LimitLabelPosition } from '../components/LimitLine'; import { profile } from '@nativescript/core/profiling'; export class YAxisRenderer extends AxisRenderer { protected mYAxis: YAxis; protected mZeroLinePaint: Paint; protected mGridClippingRect: RectF; protected get gridClippingRect() { if (!this.mGridClippingRect) { this.mGridClippingRect = new RectF(0, 0, 0, 0); } return this.mGridClippingRect; } protected mGetTransformedPositionsBuffer; protected mDrawZeroLinePath: Path; protected get drawZeroLinePath() { if (!this.mDrawZeroLinePath) { this.mDrawZeroLinePath = new Path(); } return this.mDrawZeroLinePath; } protected mZeroLineClippingRect: RectF; protected get zeroLineClippingRect() { if (!this.mZeroLineClippingRect) { this.mZeroLineClippingRect = new RectF(0, 0, 0, 0); } return this.mZeroLineClippingRect; } // protected mRenderLimitLinesPath: Path; // protected get renderLimitLinesPath() { // if (!this.mRenderLimitLinesPath) { // this.mRenderLimitLinesPath = new Path(); // } // return this.mRenderLimitLinesPath; // } protected mRenderLimitLinesBuffer; protected get renderLimitLinesBuffer() { if (!this.mRenderLimitLinesBuffer) { this.mRenderLimitLinesBuffer = Utils.createNativeArray(2); } return this.mRenderLimitLinesBuffer; } protected mLimitLineClippingRect: RectF; protected get limitLineClippingRect() { if (!this.mLimitLineClippingRect) { this.mLimitLineClippingRect = new RectF(0, 0, 0, 0); } return this.mLimitLineClippingRect; } constructor(viewPortHandler: ViewPortHandler, yAxis: YAxis, trans: Transformer) { super(viewPortHandler, trans, yAxis); this.mYAxis = yAxis; } get zeroLinePaint() { if (this.mZeroLinePaint) { this.mZeroLinePaint = new Paint(); this.mZeroLinePaint.setAntiAlias(true); this.mZeroLinePaint.setColor('gray'); this.mZeroLinePaint.setStrokeWidth(1); this.mZeroLinePaint.setStyle(Style.STROKE); } return this.mZeroLinePaint; } /** * draws the y-axis labels to the screen */ @profile public renderAxisLabels(c: Canvas) { const axis = this.mYAxis; if (!axis.isEnabled() || !axis.isDrawLabelsEnabled()) return; const positions = this.getTransformedPositions(); const paint = this.axisLabelsPaint; paint.setFont(axis.getFont()); paint.setColor(axis.getTextColor()); const xoffset = axis.getXOffset(); const yoffset = Utils.calcTextHeight(paint, 'A') / 2.5 + axis.getYOffset(); const dependency = axis.getAxisDependency(); const labelPosition = axis.getLabelPosition(); let xPos = 0; let offsetLeft = 0; let rect: RectF; if (this.mAxis.isIgnoringOffsets()) { rect = this.mViewPortHandler.getChartRect(); } else { rect = this.mViewPortHandler.getContentRect(); offsetLeft = this.mViewPortHandler.offsetLeft(); } if (dependency === AxisDependency.LEFT) { if (labelPosition === YAxisLabelPosition.OUTSIDE_CHART) { paint.setTextAlign(Align.RIGHT); xPos = offsetLeft - xoffset; } else { paint.setTextAlign(Align.LEFT); xPos = offsetLeft + xoffset; } } else { if (labelPosition === YAxisLabelPosition.OUTSIDE_CHART) { paint.setTextAlign(Align.LEFT); xPos = rect.right + xoffset; } else { paint.setTextAlign(Align.RIGHT); xPos = rect.right - xoffset; } } this.drawYLabels(c, xPos, positions, yoffset); if (dependency === AxisDependency.LEFT) { this.drawMarkTicket(c, rect.left, positions, -xoffset / 2); } else { this.drawMarkTicket(c, rect.right, positions, +xoffset / 2); } } public renderAxisLine(c: Canvas) { const axis = this.mYAxis; if (!axis.isEnabled() || !axis.isDrawAxisLineEnabled() || axis.getAxisLineWidth() === 0 || axis.mEntryCount === 0) return; const paint = this.axisLinePaint; paint.setColor(axis.getAxisLineColor()); paint.setStrokeWidth(axis.getAxisLineWidth()); const rect = this.mAxis.isIgnoringOffsets() ? this.mViewPortHandler.getChartRect() : this.mViewPortHandler.getContentRect(); if (axis.getAxisDependency() === AxisDependency.LEFT) { c.drawLine(rect.left, rect.top, rect.left, rect.bottom, paint); } else { c.drawLine(rect.right, rect.top, rect.right, rect.bottom, paint); } } /** * draws the y-labels on the specified x-position * * @param fixedPosition * @param positions */ @profile protected drawYLabels(c: Canvas, fixedPosition, positions, offset) { const mYAxis = this.mYAxis; const from = mYAxis.isDrawBottomYLabelEntryEnabled() ? 0 : 1; const to = mYAxis.isDrawTopYLabelEntryEnabled() ? mYAxis.mEntryCount : mYAxis.mEntryCount - 1; // draw const paint = this.axisLabelsPaint; for (let i = from; i < to; i++) { const text = mYAxis.getFormattedLabel(i); c.drawText(text, fixedPosition, positions[i * 2 + 1] + offset, paint); } } /** * Draw mark tickets * @param c * @param fixedPosition * @param positions * @param length */ protected drawMarkTicket(c: Canvas, fixedPosition, positions, ticklength) { const mYAxis = this.mYAxis; if (!mYAxis.isDrawMarkTicksEnabled()) return; const from = mYAxis.isDrawBottomYLabelEntryEnabled() ? 0 : 1; const to = mYAxis.isDrawTopYLabelEntryEnabled() ? mYAxis.mEntryCount : mYAxis.mEntryCount - 1; // draw const paint = this.axisLinePaint; for (let i = from; i < to; i++) { c.drawLine(fixedPosition, positions[i * 2 + 1], fixedPosition + ticklength, positions[i * 2 + 1], paint); } } // protected mRenderGridLinesPath = new Path(); /** * Draws the grid line at the specified position using the provided path. * * @param c * @param rect * @param x * @param y * @param axisValue */ protected drawGridLine(c: Canvas, rect: RectF, x, y, axisValue, paint: Paint, customRendererFunc: CustomRendererGridLineFunction) { if (customRendererFunc) { customRendererFunc(c, this, rect, x, y, axisValue, paint); } else { c.drawLine(rect.left, y, rect.right, y, paint); } } public renderGridLines(c: Canvas) { const axis = this.mYAxis; if (!axis.isEnabled()) return; if (axis.isDrawGridLinesEnabled()) { const clipRestoreCount = c.save(); c.clipRect(this.getGridClippingRect()); const positions = this.getTransformedPositions(); const paint = this.gridPaint; paint.setColor(axis.getGridColor()); paint.setStrokeWidth(axis.getGridLineWidth()); paint.setPathEffect(axis.getGridDashPathEffect()); const rect = this.mAxis.isIgnoringOffsets() ? this.mViewPortHandler.getChartRect() : this.mViewPortHandler.getContentRect(); const customRender = axis.getCustomRenderer(); const customRenderFunction = customRender && customRender.drawGridLine; for (let i = 0; i < positions.length; i += 2) { this.drawGridLine(c, rect, positions[i], positions[i + 1], axis.mEntries[i / 2], paint, customRenderFunction); } c.restoreToCount(clipRestoreCount); } if (axis.isDrawZeroLineEnabled()) { this.drawZeroLine(c); } } public getGridClippingRect() { const rect = this.mAxis.isIgnoringOffsets() ? this.mViewPortHandler.getChartRect() : this.mViewPortHandler.getContentRect(); const gridClippingRect = this.gridClippingRect; gridClippingRect.set(rect); gridClippingRect.inset(0, -this.mAxis.getGridLineWidth()); return gridClippingRect; } /** * Calculates the path for a grid line. * * @param p * @param i * @param positions * @return */ // protected linePath(p: Path, i, positions) { // p.setLines([this.mViewPortHandler.offsetLeft(), positions[i + 1], rect.right, positions[i + 1]]); // // p.moveTo(this.mViewPortHandler.offsetLeft(), positions[i + 1]); // // p.lineTo(rect.right, positions[i + 1]); // return p; // } /** * Transforms the values contained in the axis entries to screen pixels and returns them in form of a let array * of x- and y-coordinates. * * @return */ protected getTransformedPositions() { const axis = this.mYAxis; const length = axis.mEntryCount * 2; if (!this.mGetTransformedPositionsBuffer || this.mGetTransformedPositionsBuffer.length !== length) { this.mGetTransformedPositionsBuffer = Utils.createArrayBuffer(length); } const positions = this.mGetTransformedPositionsBuffer; for (let i = 0; i < length; i += 2) { // only fill y values, x values are not needed for y-labels positions[i] = 0; positions[i + 1] = axis.mEntries[i / 2]; } const result = Utils.pointsFromBuffer(positions); this.mTrans.pointValuesToPixel(result); return Utils.nativeArrayToArray(result); } /** * Draws the zero line. */ protected drawZeroLine(c: Canvas) { const axis = this.mYAxis; const clipRestoreCount = c.save(); const rect = this.mAxis.isIgnoringOffsets() ? this.mViewPortHandler.getChartRect() : this.mViewPortHandler.getContentRect(); const zeroLineClippingRectl = this.zeroLineClippingRect; zeroLineClippingRectl.set(rect); zeroLineClippingRectl.inset(0, -axis.getZeroLineWidth()); c.clipRect(zeroLineClippingRectl); // draw zero line const pos = this.mTrans.getPixelForValues(0, 0); const paint = this.zeroLinePaint; paint.setColor(axis.getZeroLineColor()); paint.setStrokeWidth(axis.getZeroLineWidth()); const zeroLinePath = this.drawZeroLinePath; zeroLinePath.reset(); zeroLinePath.moveTo(rect.left, pos.y); zeroLinePath.lineTo(rect.right, pos.y); // draw a path because lines don't support dashing on lower android versions c.drawPath(zeroLinePath, paint); c.restoreToCount(clipRestoreCount); } /** * Draws the LimitLines associated with this axis to the screen. * * @param c */ public renderLimitLines(c: Canvas) { const axis = this.mYAxis; const limitLines = axis.getLimitLines(); if (limitLines == null || limitLines.length <= 0) return; const pts = this.renderLimitLinesBuffer; pts[0] = 0; pts[1] = 0; let offsetLeft = 0; let rect: RectF; if (axis.isIgnoringOffsets()) { rect = this.mViewPortHandler.getChartRect(); } else { rect = this.mViewPortHandler.getContentRect(); offsetLeft = this.mViewPortHandler.offsetLeft(); } const customRender = axis.getCustomRenderer(); const customRendererFunc = customRender && customRender.drawLimitLine; const clipToContent = axis.clipLimitLinesToContent; for (let i = 0; i < limitLines.length; i++) { const l = limitLines[i]; if (!l.isEnabled()) continue; const lineWidth = l.getLineWidth(); if (clipToContent) { c.save(); const clipRect = this.limitLineClippingRect; clipRect.set(rect); clipRect.inset(0, -lineWidth); c.clipRect(clipRect); } const paint = this.limitLinePaint; paint.setColor(l.getLineColor()); paint.setStrokeWidth(lineWidth); paint.setPathEffect(l.getDashPathEffect()); pts[1] = l.getLimit(); this.mTrans.pointValuesToPixel(pts); if (lineWidth > 0) { if (customRendererFunc) { customRendererFunc(c, this, l, rect, pts[1], paint); } else { c.drawLine(rect.left, pts[1], rect.right, pts[1], paint); } } const label = l.getLabel(); // if drawing the limit-value label is enabled if (label && label !== '') { paint.setStyle(l.getTextStyle()); paint.setPathEffect(null); paint.setColor(l.getTextColor()); paint.setFont(l.getFont()); paint.setStrokeWidth(0.5); const labelLineHeight = Utils.calcTextHeight(paint, label); const xOffset = 4 + l.getXOffset(); const yOffset = l.getLineWidth() + labelLineHeight + l.getYOffset(); const position = l.getLabelPosition(); switch (position) { case LimitLabelPosition.RIGHT_TOP: { paint.setTextAlign(Align.RIGHT); c.drawText(label, rect.right - xOffset, pts[1] - yOffset + labelLineHeight, paint); break; } case LimitLabelPosition.RIGHT_BOTTOM: { paint.setTextAlign(Align.RIGHT); c.drawText(label, rect.right - xOffset, pts[1] + yOffset, paint); break; } case LimitLabelPosition.CENTER_TOP: { paint.setTextAlign(Align.RIGHT); c.drawText(label, rect.right, pts[1] - yOffset + labelLineHeight, paint); break; } case LimitLabelPosition.CENTER_BOTTOM: { paint.setTextAlign(Align.CENTER); c.drawText(label, rect.right, pts[1] + yOffset, paint); break; } case LimitLabelPosition.LEFT_TOP: { paint.setTextAlign(Align.LEFT); c.drawText(label, rect.left + xOffset, pts[1] - yOffset + labelLineHeight, paint); break; } case LimitLabelPosition.LEFT_BOTTOM: { paint.setTextAlign(Align.LEFT); c.drawText(label, offsetLeft + xOffset, pts[1] + yOffset, paint); break; } } } if (clipToContent) { c.restore(); } } } }
37.090047
136
0.581651
5a263c119b42306f9ac12ab3c00ecc2a9e6f9844
437
sql
SQL
src/main/resources/db/migration/V1__Create_Tables.sql
DING-Weibing/crawler
08bae8ec9fbd7e9f0aa85f2ac72689de8416badd
[ "Apache-2.0" ]
null
null
null
src/main/resources/db/migration/V1__Create_Tables.sql
DING-Weibing/crawler
08bae8ec9fbd7e9f0aa85f2ac72689de8416badd
[ "Apache-2.0" ]
2
2021-12-10T01:47:59.000Z
2022-01-21T23:46:35.000Z
src/main/resources/db/migration/V1__Create_Tables.sql
DING-Weibing/crawler
08bae8ec9fbd7e9f0aa85f2ac72689de8416badd
[ "Apache-2.0" ]
null
null
null
create table IF NOT EXISTS LINKS_TO_BE_PROCESSED ( LINK VARCHAR(2000) ); create table IF NOT EXISTS LINKS_ALREADY_PROCESSED ( LINK VARCHAR(2000) ); create table IF NOT EXISTS NEWS ( ID BIGINT auto_increment, TITLE TEXT, CONTENT TEXT, URL VARCHAR(2000), CREATED_AT TIMESTAMP default NOW(), MODIFIED_AT TIMESTAMP default NOW(), constraint NEWS_PK primary key (ID) );
21.85
50
0.659039
0f1d3e4e1e66bf08e614173ccc0975239bd53312
8,296
asm
Assembly
Transynther/x86/_processed/NONE/_xt_sm_/i9-9900K_12_0xca_notsx.log_21829_1379.asm
ljhsiun2/medusa
67d769b8a2fb42c538f10287abaf0e6dbb463f0c
[ "MIT" ]
9
2020-08-13T19:41:58.000Z
2022-03-30T12:22:51.000Z
Transynther/x86/_processed/NONE/_xt_sm_/i9-9900K_12_0xca_notsx.log_21829_1379.asm
ljhsiun2/medusa
67d769b8a2fb42c538f10287abaf0e6dbb463f0c
[ "MIT" ]
1
2021-04-29T06:29:35.000Z
2021-05-13T21:02:30.000Z
Transynther/x86/_processed/NONE/_xt_sm_/i9-9900K_12_0xca_notsx.log_21829_1379.asm
ljhsiun2/medusa
67d769b8a2fb42c538f10287abaf0e6dbb463f0c
[ "MIT" ]
3
2020-07-14T17:07:07.000Z
2022-03-21T01:12:22.000Z
.global s_prepare_buffers s_prepare_buffers: push %r11 push %r12 push %r13 push %r14 push %r8 push %rbx push %rcx push %rdi push %rsi lea addresses_normal_ht+0x16791, %r8 nop sub $59085, %rbx mov (%r8), %r11 nop nop nop and $637, %r12 lea addresses_A_ht+0x358d, %rcx nop nop nop nop nop xor %r14, %r14 mov (%rcx), %rbx sub %rcx, %rcx lea addresses_A_ht+0xbaf5, %r12 nop nop nop nop nop cmp $526, %r13 mov $0x6162636465666768, %r14 movq %r14, (%r12) nop nop nop nop nop cmp %r14, %r14 lea addresses_UC_ht+0x2fc5, %rbx nop nop nop nop and $46428, %r11 mov (%rbx), %cx xor %r8, %r8 lea addresses_UC_ht+0x1b513, %rsi lea addresses_D_ht+0x1a75, %rdi clflush (%rsi) clflush (%rdi) nop nop nop and %r12, %r12 mov $31, %rcx rep movsw nop cmp $29159, %r11 pop %rsi pop %rdi pop %rcx pop %rbx pop %r8 pop %r14 pop %r13 pop %r12 pop %r11 ret .global s_faulty_load s_faulty_load: push %r11 push %r12 push %rax push %rbp push %rcx push %rdi push %rsi // REPMOV lea addresses_WC+0xda75, %rsi lea addresses_UC+0x19f5, %rdi add %r11, %r11 mov $126, %rcx rep movsw add %r11, %r11 // Store lea addresses_A+0x15a91, %rcx nop nop nop nop xor $59967, %r12 movl $0x51525354, (%rcx) nop nop nop add %r11, %r11 // Store lea addresses_WT+0x4875, %r12 nop nop nop nop nop sub $40777, %r11 mov $0x5152535455565758, %rbp movq %rbp, (%r12) and %r11, %r11 // Store lea addresses_WC+0x6275, %rcx nop nop nop nop nop xor $38403, %r11 movw $0x5152, (%rcx) cmp %rcx, %rcx // Store lea addresses_UC+0x1cf35, %rbp nop nop nop nop nop add $50954, %rax mov $0x5152535455565758, %rcx movq %rcx, (%rbp) and %r11, %r11 // Store lea addresses_PSE+0x1d275, %rdi clflush (%rdi) nop nop nop nop add %r12, %r12 movb $0x51, (%rdi) xor $5771, %rax // Store lea addresses_WT+0x1a75, %rcx nop nop and %rdi, %rdi movb $0x51, (%rcx) nop nop nop nop nop add $31978, %rsi // REPMOV lea addresses_normal+0x14275, %rsi lea addresses_WT+0x4d75, %rdi nop nop nop nop nop xor $31052, %rax mov $123, %rcx rep movsb nop nop nop xor %rdi, %rdi // Store lea addresses_PSE+0x4a75, %r12 nop nop nop xor %rbp, %rbp mov $0x5152535455565758, %rsi movq %rsi, %xmm0 vmovups %ymm0, (%r12) nop nop nop nop cmp %rcx, %rcx // Store lea addresses_normal+0x1bc75, %r12 nop nop xor $51098, %rax movb $0x51, (%r12) nop nop nop nop nop xor %rdi, %rdi // Store lea addresses_normal+0x6275, %r11 clflush (%r11) nop nop nop nop nop cmp %rbp, %rbp movb $0x51, (%r11) nop nop nop nop nop cmp %rbp, %rbp // Store lea addresses_RW+0x13275, %rsi clflush (%rsi) inc %rdi movb $0x51, (%rsi) cmp $62625, %rcx // Faulty Load lea addresses_PSE+0x4a75, %rdi nop nop nop nop sub $46842, %rbp movups (%rdi), %xmm7 vpextrq $0, %xmm7, %rsi lea oracles, %r11 and $0xff, %rsi shlq $12, %rsi mov (%r11,%rsi,1), %rsi pop %rsi pop %rdi pop %rcx pop %rbp pop %rax pop %r12 pop %r11 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_PSE', 'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 0}} {'OP': 'REPM', 'src': {'same': False, 'congruent': 10, 'type': 'addresses_WC'}, 'dst': {'same': True, 'congruent': 7, 'type': 'addresses_UC'}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_A', 'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 0}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_WT', 'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 8}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_WC', 'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 9}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_UC', 'NT': True, 'AVXalign': False, 'size': 8, 'congruent': 6}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_PSE', 'NT': False, 'AVXalign': True, 'size': 1, 'congruent': 9}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_WT', 'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 8}} {'OP': 'REPM', 'src': {'same': False, 'congruent': 10, 'type': 'addresses_normal'}, 'dst': {'same': False, 'congruent': 8, 'type': 'addresses_WT'}} {'OP': 'STOR', 'dst': {'same': True, 'type': 'addresses_PSE', 'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 0}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_normal', 'NT': True, 'AVXalign': False, 'size': 1, 'congruent': 9}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_normal', 'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 9}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_RW', 'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 10}} [Faulty Load] {'OP': 'LOAD', 'src': {'same': True, 'type': 'addresses_PSE', 'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 0}} <gen_prepare_buffer> {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_normal_ht', 'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 2}} {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_A_ht', 'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 3}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_A_ht', 'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 7}} {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_UC_ht', 'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 4}} {'OP': 'REPM', 'src': {'same': False, 'congruent': 0, 'type': 'addresses_UC_ht'}, 'dst': {'same': False, 'congruent': 10, 'type': 'addresses_D_ht'}} {'58': 21829} 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 */
29.41844
2,999
0.650193
d6c85baf1c29fff4b06d4c7375c176d565a7533f
7,145
dart
Dart
lib/client/elements/map_geo_location.dart
GeReinhart/dart-gex-common-ui-elements
51331d3a9d33d30401c8db2c73f82558785b5f61
[ "BSD-3-Clause" ]
null
null
null
lib/client/elements/map_geo_location.dart
GeReinhart/dart-gex-common-ui-elements
51331d3a9d33d30401c8db2c73f82558785b5f61
[ "BSD-3-Clause" ]
null
null
null
lib/client/elements/map_geo_location.dart
GeReinhart/dart-gex-common-ui-elements
51331d3a9d33d30401c8db2c73f82558785b5f61
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2015, Gérald Reinhart. All rights reserved. Use of this source code // is governed by a BSD-style license that can be found in the LICENSE file. library gex_webapp_kit_client.map_geo_location; import "dart:html"; import 'package:gex_webapp_kit/webapp_kit_client.dart'; import 'package:gex_webapp_kit/webapp_kit_common.dart'; import 'package:google_maps/google_maps.dart'; /** * Location of a gps point on a map * Requiered : define proper import in the main page: see https://github.com/a14n/dart-google-maps */ class MapGeoLocation extends Object with Showable { final LatLng defaultPosition = new LatLng(45.148609248398735, 5.729827880859428); DivElement map; DivElement mapCanvas; num mapSize; String markerUrl; User _user; num markerSize; num zindex; Geocoder _geocoder; GMap _googleMap; Marker _marker; DivElement mapPosition; DivElement mapAddress; CheckboxInputElement lock; bool _editionMode; MapGeoLocation(this.map, this.mapSize, this.markerUrl, this.markerSize, {bool editionMode}) { this.map.style ..position = "relative" ..visibility = null; this.editionMode = editionMode; init(); } set editionMode(bool value) { if (value == null) { _editionMode = true; } else { _editionMode = value; } if (_googleMap != null) { _googleMap.options = new MapOptions() ..draggable = _editionMode ..disableDoubleClickZoom = !_editionMode ..scrollwheel = _editionMode ..zoomControl = _editionMode ..disableDefaultUI = !_editionMode ..mapTypeControl = _editionMode ..mapTypeId = MapTypeId.ROADMAP ..streetViewControl = false; } } set user(User value) { _user = value; if (_user.hasLocation) { _setMarker(new LatLng(_user.locationLat, _user.locationLng)); mapPosition.innerHtml = "${_googleMap.center.lat}, ${_googleMap.center.lng}"; _codeLatLng(); } } void init() { mapCanvas = new DivElement(); mapCanvas.style ..height = "${mapSize}px" ..width = "${mapSize}px" ..zIndex = "${zindex}"; mapPosition = new DivElement(); mapAddress = new DivElement(); lock = new CheckboxInputElement(); lock.checked = !_editionMode; lock.title = "lock"; map.append(mapAddress); map.append(mapCanvas); map.append(lock); map.append(new SpanElement()..text = "lock"); map.append(mapPosition); final mapOptions = new MapOptions() ..center = defaultPosition ..zoom = 6 ..disableDoubleClickZoom = !_editionMode ..scrollwheel = _editionMode ..draggable = _editionMode ..zoomControl = _editionMode ..disableDefaultUI = !_editionMode ..mapTypeControl = _editionMode ..mapTypeId = MapTypeId.ROADMAP ..streetViewControl = false; _geocoder = new Geocoder(); _googleMap = new GMap(mapCanvas, mapOptions); _googleMap.onCenterChanged.listen((_) { _keepMarkerInCenter(); }); lock.onClick.listen((_) { editionMode = !lock.checked; }); _googleMap.onMouseover.listen((_) { _canKeepMarkerInCenter = true; }); _googleMap.onDrag.listen((_) { _canKeepMarkerInCenter = true; }); } @override bool isShowed() { return map.style.display != "hidden"; } @override void show() { map.style.display = null; event.trigger(_googleMap, 'resize', []); if (_marker != null) { _googleMap.panTo(_marker.position); } } set size( num value){ mapSize = value ; mapCanvas.style ..height = "${mapSize}px" ..width = "${mapSize}px"; event.trigger(_googleMap, 'resize', []); } bool _canKeepMarkerInCenter = false; void _keepMarkerInCenter() { if (_canKeepMarkerInCenter && _editionMode) { if (_marker != null) { _marker.position = _googleMap.center; mapPosition.innerHtml = "${_googleMap.center.lat}, ${_googleMap.center.lng}"; _codeLatLng(); } } } @override void hide() { map.style.display = "hidden"; } void geoLocation() { if (window.navigator.geolocation != null) { window.navigator.geolocation.getCurrentPosition().then((position) { _setMarker(new LatLng(position.coords.latitude, position.coords.longitude)); mapPosition.innerHtml = "${_googleMap.center.lat}, ${_googleMap.center.lng}"; _codeLatLng(); }, onError: (error) { _handleNoGeolocation(); }); } else { // Browser doesn't support Geolocation _handleNoGeolocation(); } } void _handleNoGeolocation() { _googleMap.center = defaultPosition; _setMarker(defaultPosition); mapPosition.innerHtml = "${_googleMap.center.lat}, ${_googleMap.center.lng}"; _codeLatLng(); } LatLng get location => _googleMap.center; String get address => mapAddress.innerHtml; void _codeLatLng() { final request = new GeocoderRequest()..location = location; _geocoder.geocode(request, (List<GeocoderResult> results, GeocoderStatus status) { if (status == GeocoderStatus.OK) { if (results[1] != null) { mapAddress.innerHtml = results[1].formattedAddress; } else { mapAddress.innerHtml = ""; } } }); } void _setMarker(LatLng location) { // Add markers to the map // Marker sizes are expressed as a Size of X,Y // where the origin of the image (0,0) is located // in the top left of the image. // Origins, anchor positions and coordinates of the marker // increase in the X direction to the right and in // the Y direction down. // TODO issue for MarkerImage deprecated final image = new Icon() ..url = _user.avatarUrl // This marker is 20 pixels wide by 32 pixels tall. ..size = new Size(20, 32) // The origin for this image is 0,0. ..origin = new Point(0, 0) // The anchor for this image is the base of the flagpole at 0,32. ..anchor = new Point(0, 32); // TODO issue for MarkerImage deprecated final shadow = new Icon() ..url = this.markerUrl // The shadow image is larger in the horizontal dimension // while the position and offset are the same as for the main image. ..size = new Size(37, 32) ..origin = new Point(0, 0) ..anchor = new Point(0, 32); // Shapes define the clickable region of the icon. // The type defines an HTML &lt;area&gt; element 'poly' which // traces out a polygon as a series of X,Y points. The final // coordinate closes the poly by connecting to the first // coordinate. final shape = new MarkerShape() ..coords = [1, 1, 1, 20, 18, 20, 18, 1] ..type = MarkerShapeType.POLY; var markerOptions = new MarkerOptions() ..position = location ..map = _googleMap // ..shadow = shadow // ..icon = image // ..shape = shape ..title = _user.displayName; if (_marker == null) { _marker = new Marker(markerOptions); } else { _marker.options = markerOptions; } _googleMap.panTo(location); } }
29.282787
98
0.639468
05e42f315833cab5bc5272cbd2173ea8012ff7f5
979
py
Python
python/paddle/v2/fluid/tests/test_maxout_op.py
QingshuChen/Paddle
25a92be3e123ed21fd98c7be6bd7e3a6320756a3
[ "Apache-2.0" ]
null
null
null
python/paddle/v2/fluid/tests/test_maxout_op.py
QingshuChen/Paddle
25a92be3e123ed21fd98c7be6bd7e3a6320756a3
[ "Apache-2.0" ]
9
2017-09-13T07:39:31.000Z
2017-10-18T05:58:23.000Z
python/paddle/v2/fluid/tests/test_maxout_op.py
QingshuChen/Paddle
25a92be3e123ed21fd98c7be6bd7e3a6320756a3
[ "Apache-2.0" ]
null
null
null
import unittest import numpy as np from op_test import OpTest def maxout_forward_naive(input, groups): s0, s1, s2, s3 = input.shape return np.ndarray([s0, s1 / groups, groups, s2, s3], \ buffer = input, dtype=input.dtype).max(axis=(2)) class TestMaxOutOp(OpTest): def setUp(self): self.op_type = "maxout" self.init_test_case() input = np.random.random(self.shape).astype("float32") output = self.MaxOut_forward_naive(input, self.groups).astype("float32") self.inputs = {'X': input} self.attrs = {'groups': self.groups} self.outputs = {'Out': output.astype('float32')} def test_check_output(self): self.check_output() def test_check_grad(self): self.check_grad(['X'], 'Out') def init_test_case(self): self.MaxOut_forward_naive = maxout_forward_naive self.shape = [100, 6, 2, 2] self.groups=2 if __name__ == '__main__': unittest.main()
24.475
80
0.630235
142b07641780dd9f2beff3cb8573129b0f7993a6
505
ts
TypeScript
src/Services/DataService/Reducers/UnloadAllReducer.ts
Rediker-Software/redux-data-service
739bd4b3c88a71baa562f83181c42f5b26ef0929
[ "MIT" ]
9
2018-06-29T17:23:35.000Z
2021-06-03T13:31:48.000Z
src/Services/DataService/Reducers/UnloadAllReducer.ts
Rediker-Software/redux-data-service
739bd4b3c88a71baa562f83181c42f5b26ef0929
[ "MIT" ]
14
2018-08-01T21:39:14.000Z
2019-03-27T13:57:30.000Z
src/Services/DataService/Reducers/UnloadAllReducer.ts
Rediker-Software/redux-data-service
739bd4b3c88a71baa562f83181c42f5b26ef0929
[ "MIT" ]
4
2018-07-31T14:32:11.000Z
2018-12-11T13:58:54.000Z
import { IModelData } from "../../../Model/IModel"; import { IAction } from "../../IService"; import { DataServiceStateRecord, IDataServiceStateRecord } from "../DataServiceStateRecord"; /** Disconnects all IModel instances from the store and returns a new copy of the store */ export function unloadAllReducer<T extends IModelData>(state: IDataServiceStateRecord<T>, action: IAction<null>) { state.items.forEach((model) => { model.markForDestruction(); }); return DataServiceStateRecord(); }
38.846154
114
0.730693
a491d872e0c64c7a4be24c1ee4d344f3cc1922e5
6,312
php
PHP
locales/japan.php
theblueman42/apcal
335c04618e005e9aea07e3eeff5e72e94a1d69c9
[ "OLDAP-2.5", "OLDAP-2.8" ]
null
null
null
locales/japan.php
theblueman42/apcal
335c04618e005e9aea07e3eeff5e72e94a1d69c9
[ "OLDAP-2.5", "OLDAP-2.8" ]
null
null
null
locales/japan.php
theblueman42/apcal
335c04618e005e9aea07e3eeff5e72e94a1d69c9
[ "OLDAP-2.5", "OLDAP-2.8" ]
null
null
null
<?php /* * You may not change or alter any portion of this comment or credits * of supporting developers from this source code or any supporting source code * which is considered copyrighted (c) material of the original comment or credit authors. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. */ /** * @copyright {@link http://xoops.org/ XOOPS Project} * @license {@link http://www.fsf.org/copyleft/gpl.html GNU public license} * @package * @since * @author XOOPS Development Team, * @author GIJ=CHECKMATE (PEAK Corp. http://www.peak.ne.jp/) */ $this->holidays = array( '2001-1-1' => '¸µÃ¶', '2001-1-8' => 'À®¿Í¤ÎÆü', '2001-2-11' => '·ú¹ñµ­Ç°¤ÎÆü', '2001-2-12' => '¿¶ÂØµÙÆü', '2001-3-20' => '½Õʬ¤ÎÆü', '2001-4-29' => '¤ß¤É¤ê¤ÎÆü', '2001-4-30' => '¿¶ÂØµÙÆü', '2001-5-3' => '·ûË¡µ­Ç°Æü', '2001-5-4' => '¹ṉ̃¤ÎµÙÆü', '2001-5-5' => '¤³¤É¤â¤ÎÆü', '2001-7-20' => '³¤¤ÎÆü', '2001-9-15' => '·ÉÏ·¤ÎÆü', '2001-9-23' => '½©Ê¬¤ÎÆü', '2001-9-24' => '¿¶ÂØµÙÆü', '2001-10-8' => 'Âΰé¤ÎÆü', '2001-11-3' => 'ʸ²½¤ÎÆü', '2001-11-23' => '¶ÐÏ«´¶¼Õ¤ÎÆü', '2001-12-23' => 'Å·¹ÄÃÂÀ¸Æü', '2001-12-24' => '¿¶ÂØµÙÆü', '2002-1-1' => '¸µÃ¶', '2002-1-14' => 'À®¿Í¤ÎÆü', '2002-2-11' => '·ú¹ñµ­Ç°¤ÎÆü', '2002-3-21' => '½Õʬ¤ÎÆü', '2002-4-29' => '¤ß¤É¤ê¤ÎÆü', '2002-5-3' => '·ûË¡µ­Ç°Æü', '2002-5-4' => '¹ṉ̃¤ÎµÙÆü', '2002-5-5' => '¤³¤É¤â¤ÎÆü', '2002-5-6' => '¿¶ÂØµÙÆü', '2002-7-20' => '³¤¤ÎÆü', '2002-9-15' => '·ÉÏ·¤ÎÆü', '2002-9-16' => '¿¶ÂØµÙÆü', '2002-9-23' => '½©Ê¬¤ÎÆü', '2002-10-14' => 'Âΰé¤ÎÆü', '2002-11-3' => 'ʸ²½¤ÎÆü', '2002-11-4' => '¿¶ÂØµÙÆü', '2002-11-23' => '¶ÐÏ«´¶¼Õ¤ÎÆü', '2002-12-23' => 'Å·¹ÄÃÂÀ¸Æü', '2003-1-1' => '¸µÃ¶', '2003-1-13' => 'À®¿Í¤ÎÆü', '2003-2-11' => '·ú¹ñµ­Ç°¤ÎÆü', '2003-3-21' => '½Õʬ¤ÎÆü', '2003-4-29' => '¤ß¤É¤ê¤ÎÆü', '2003-5-3' => '·ûË¡µ­Ç°Æü', '2003-5-4' => '¹ṉ̃¤ÎµÙÆü', '2003-5-5' => '¤³¤É¤â¤ÎÆü', '2003-7-20' => '³¤¤ÎÆü', '2003-7-21' => '¿¶ÂØµÙÆü', '2003-9-15' => '·ÉÏ·¤ÎÆü', '2003-9-23' => '½©Ê¬¤ÎÆü', '2003-10-13' => 'Âΰé¤ÎÆü', '2003-11-3' => 'ʸ²½¤ÎÆü', '2003-11-23' => '¶ÐÏ«´¶¼Õ¤ÎÆü', '2003-11-24' => '¿¶ÂØµÙÆü', '2003-12-23' => 'Å·¹ÄÃÂÀ¸Æü', '2004-1-1' => '¸µÃ¶', '2004-1-12' => 'À®¿Í¤ÎÆü', '2004-2-11' => '·ú¹ñµ­Ç°¤ÎÆü', '2004-3-20' => '½Õʬ¤ÎÆü', '2004-4-29' => '¤ß¤É¤ê¤ÎÆü', '2004-5-3' => '·ûË¡µ­Ç°Æü', '2004-5-4' => '¹ṉ̃¤ÎµÙÆü', '2004-5-5' => '¤³¤É¤â¤ÎÆü', '2004-7-19' => '³¤¤ÎÆü', '2004-9-20' => '·ÉÏ·¤ÎÆü', '2004-9-23' => '½©Ê¬¤ÎÆü', '2004-10-11' => 'Âΰé¤ÎÆü', '2004-11-3' => 'ʸ²½¤ÎÆü', '2004-11-23' => '¶ÐÏ«´¶¼Õ¤ÎÆü', '2004-12-23' => 'Å·¹ÄÃÂÀ¸Æü', '2005-1-1' => '¸µÃ¶', '2005-1-10' => 'À®¿Í¤ÎÆü', '2005-2-11' => '·ú¹ñµ­Ç°¤ÎÆü', '2005-3-20' => '½Õʬ¤ÎÆü', '2005-3-21' => '¿¶ÂØµÙÆü', '2005-4-29' => '¤ß¤É¤ê¤ÎÆü', '2005-5-3' => '·ûË¡µ­Ç°Æü', '2005-5-4' => '¹ṉ̃¤ÎµÙÆü', '2005-5-5' => '¤³¤É¤â¤ÎÆü', '2005-7-18' => '³¤¤ÎÆü', '2005-9-19' => '·ÉÏ·¤ÎÆü', '2005-9-23' => '½©Ê¬¤ÎÆü', '2005-10-10' => 'Âΰé¤ÎÆü', '2005-11-3' => 'ʸ²½¤ÎÆü', '2005-11-23' => '¶ÐÏ«´¶¼Õ¤ÎÆü', '2005-12-23' => 'Å·¹ÄÃÂÀ¸Æü', '2006-1-1' => '¸µÃ¶', '2006-1-2' => '¿¶ÂØµÙÆü', '2006-1-9' => 'À®¿Í¤ÎÆü', '2006-2-11' => '·ú¹ñµ­Ç°¤ÎÆü', '2006-3-21' => '½Õʬ¤ÎÆü', '2006-4-29' => '¤ß¤É¤ê¤ÎÆü', '2006-5-3' => '·ûË¡µ­Ç°Æü', '2006-5-4' => '¹ṉ̃¤ÎµÙÆü', '2006-5-5' => '¤³¤É¤â¤ÎÆü', '2006-7-17' => '³¤¤ÎÆü', '2006-9-18' => '·ÉÏ·¤ÎÆü', '2006-9-23' => '½©Ê¬¤ÎÆü', '2006-10-9' => 'Âΰé¤ÎÆü', '2006-11-3' => 'ʸ²½¤ÎÆü', '2006-11-23' => '¶ÐÏ«´¶¼Õ¤ÎÆü', '2006-12-23' => 'Å·¹ÄÃÂÀ¸Æü', '2007-1-1' => '¸µÃ¶', '2007-1-8' => 'À®¿Í¤ÎÆü', '2007-2-11' => '·ú¹ñµ­Ç°¤ÎÆü', '2007-2-12' => '¿¶ÂØµÙÆü', '2007-3-21' => '½Õʬ¤ÎÆü', '2007-4-29' => '¾¼ÏÂ¤ÎÆü', '2007-4-30' => '¿¶ÂØµÙÆü', '2007-5-3' => '·ûË¡µ­Ç°Æü', '2007-5-4' => '¤ß¤É¤ê¤ÎÆü', '2007-5-5' => '¤³¤É¤â¤ÎÆü', '2007-7-16' => '³¤¤ÎÆü', '2007-9-17' => '·ÉÏ·¤ÎÆü', '2007-9-23' => '½©Ê¬¤ÎÆü', '2007-9-24' => '¿¶ÂØµÙÆü', '2007-10-8' => 'Âΰé¤ÎÆü', '2007-11-3' => 'ʸ²½¤ÎÆü', '2007-11-23' => '¶ÐÏ«´¶¼Õ¤ÎÆü', '2007-12-23' => 'Å·¹ÄÃÂÀ¸Æü', '2007-12-24' => '¿¶ÂØµÙÆü', '2008-1-1' => '¸µÃ¶', '2008-1-14' => 'À®¿Í¤ÎÆü', '2008-2-11' => '·ú¹ñµ­Ç°¤ÎÆü', '2008-3-20' => '½Õʬ¤ÎÆü', '2008-4-29' => '¾¼ÏÂ¤ÎÆü', '2008-5-3' => '·ûË¡µ­Ç°Æü', '2008-5-4' => '¤ß¤É¤ê¤ÎÆü', '2008-5-5' => '¤³¤É¤â¤ÎÆü', '2008-5-6' => '¿¶ÂØµÙÆü', '2008-7-21' => '³¤¤ÎÆü', '2008-9-15' => '·ÉÏ·¤ÎÆü', '2008-9-23' => '½©Ê¬¤ÎÆü', '2008-10-13' => 'Âΰé¤ÎÆü', '2008-11-3' => 'ʸ²½¤ÎÆü', '2008-11-23' => '¶ÐÏ«´¶¼Õ¤ÎÆü', '2008-11-24' => '¿¶ÂØµÙÆü', '2008-12-23' => 'Å·¹ÄÃÂÀ¸Æü', '2009-1-1' => '¸µÃ¶', '2009-1-12' => 'À®¿Í¤ÎÆü', '2009-2-11' => '·ú¹ñµ­Ç°¤ÎÆü', '2009-3-20' => '½Õʬ¤ÎÆü', '2009-4-29' => '¾¼ÏÂ¤ÎÆü', '2009-5-3' => '·ûË¡µ­Ç°Æü', '2009-5-4' => '¤ß¤É¤ê¤ÎÆü', '2009-5-5' => '¤³¤É¤â¤ÎÆü', '2009-5-6' => '¿¶ÂØµÙÆü', '2009-7-20' => '³¤¤ÎÆü', '2009-9-21' => '·ÉÏ·¤ÎÆü', '2009-9-22' => '¹ṉ̃¤ÎµÙÆü', '2009-9-23' => '½©Ê¬¤ÎÆü', '2009-10-12' => 'Âΰé¤ÎÆü', '2009-11-3' => 'ʸ²½¤ÎÆü', '2009-11-23' => '¶ÐÏ«´¶¼Õ¤ÎÆü', '2009-12-23' => 'Å·¹ÄÃÂÀ¸Æü', '2010-1-1' => '¸µÃ¶', '2010-1-11' => 'À®¿Í¤ÎÆü', '2010-2-11' => '·ú¹ñµ­Ç°¤ÎÆü', '2010-3-21' => '½Õʬ¤ÎÆü', '2010-3-22' => '¿¶ÂØµÙÆü', '2010-4-29' => '¾¼ÏÂ¤ÎÆü', '2010-5-3' => '·ûË¡µ­Ç°Æü', '2010-5-4' => '¤ß¤É¤ê¤ÎÆü', '2010-5-5' => '¤³¤É¤â¤ÎÆü', '2010-7-19' => '³¤¤ÎÆü', '2010-9-20' => '·ÉÏ·¤ÎÆü', '2010-9-23' => '½©Ê¬¤ÎÆü', '2010-10-11' => 'Âΰé¤ÎÆü', '2010-11-3' => 'ʸ²½¤ÎÆü', '2010-11-23' => '¶ÐÏ«´¶¼Õ¤ÎÆü', '2010-12-23' => 'Å·¹ÄÃÂÀ¸Æü' );
31.247525
90
0.428074
a444f6e30936b7bb754c18e52b2da39944a3af71
1,039
php
PHP
application/Common/Controller/OperatorbaseController.class.php
hafrans/ujn-ujncard-php
139ea1993e7e6ed5fc0f42c587dd4f903bcd7e47
[ "Apache-2.0" ]
null
null
null
application/Common/Controller/OperatorbaseController.class.php
hafrans/ujn-ujncard-php
139ea1993e7e6ed5fc0f42c587dd4f903bcd7e47
[ "Apache-2.0" ]
null
null
null
application/Common/Controller/OperatorbaseController.class.php
hafrans/ujn-ujncard-php
139ea1993e7e6ed5fc0f42c587dd4f903bcd7e47
[ "Apache-2.0" ]
null
null
null
<?php namespace Common\Controller; use Common\Controller\HomebaseController; use Campus\Model\EcardOperatorsModel; class OperatorbaseController extends HomebaseController{ protected $user_model; protected $user; protected $userid; function _initialize() { parent::_initialize(); $this->check_login(); if(OperatorbaseController::is_user_login()){ $this->userid=EcardOperatorsModel::get_current_userid(); $this->users_model=D("Campus/EcardOperators"); $this->user=$this->users_model->where(array("id"=>$this->userid))->find(); } } public function check_login(){ $session_user=session('optr'); if(empty($session_user)){ $this->error('您还没有登录!',leuu('Campus/login/index',array('redirect'=>base64_encode($_SERVER['HTTP_REFERER'])))); } if($session_user['status'] == 0){ $this->error('该用户已被禁用,请联系管理员',leuu('Campus/login/index',array('redirect'=>base64_encode($_SERVER['HTTP_REFERER'])))); } } public static function is_user_login(){ return !empty($_SESSION['optr']); } }
25.975
123
0.700674
0732e39f94a71d3a6f35063dae48445a945df15f
225
css
CSS
src/styles/index.css
Kh-Ol-An/esports
f9e1f9bc611ece56e35c4c1982c74ad828f06ffe
[ "Unlicense" ]
null
null
null
src/styles/index.css
Kh-Ol-An/esports
f9e1f9bc611ece56e35c4c1982c74ad828f06ffe
[ "Unlicense" ]
null
null
null
src/styles/index.css
Kh-Ol-An/esports
f9e1f9bc611ece56e35c4c1982c74ad828f06ffe
[ "Unlicense" ]
null
null
null
html { font-size: 16px; box-sizing: border-box; overflow-x: hidden; } body { background: #141418; } *, *::before, *::after { box-sizing: border-box; } img { display: block; max-width: 100%; height: auto; }
10.227273
25
0.595556
ff3e7479d936c4d7528161ea01f28f7b8c279b1f
3,322
py
Python
test/distributed/fsdp/test_fsdp_param_exec_order_wrap.py
YifanShenSZ/pytorch
b4232f7cbe407909f9d95b91304c73fdc4c66a50
[ "Intel" ]
null
null
null
test/distributed/fsdp/test_fsdp_param_exec_order_wrap.py
YifanShenSZ/pytorch
b4232f7cbe407909f9d95b91304c73fdc4c66a50
[ "Intel" ]
null
null
null
test/distributed/fsdp/test_fsdp_param_exec_order_wrap.py
YifanShenSZ/pytorch
b4232f7cbe407909f9d95b91304c73fdc4c66a50
[ "Intel" ]
null
null
null
# Owner(s): ["oncall: distributed"] import torch from torch.testing._internal.common_fsdp import FSDPTest from torch.testing._internal.common_distributed import skip_if_lt_x_gpu from torch.distributed.fsdp.wrap import ParamExecOrderWrapPolicy, always_wrap_policy from torch.distributed.fsdp.fully_sharded_data_parallel import ShardingStrategy from torch.distributed.fsdp import FullyShardedDataParallel as FSDP from torch.testing._internal.common_utils import ( instantiate_parametrized_tests, parametrize, run_tests, ) class Model(torch.nn.Module): def __init__(self) -> None: super().__init__() self.layer0 = torch.nn.Linear(6, 6) self.layer1 = torch.nn.Linear(6, 6, bias=False) self.layer2 = torch.nn.Sequential( torch.nn.Linear(6, 3, bias=False), torch.nn.ReLU(), torch.nn.Linear(3, 6, bias=False), ) self.relu = torch.nn.ReLU() def forward(self, x): # `layer0` -> `layer2` -> `layer1` # the forward execution order is NOT consistent with the model definition order. z = self.relu(self.layer0(x)) z = self.relu(self.layer2(z)) z = self.relu(self.layer1(z)) return z def get_input(self, device: torch.device): return (torch.randn((8, 6)).to(device), ) def get_loss(self, input, output): return (output - input[0]).sum() @staticmethod def wrap(sharding_strategy: ShardingStrategy, device: torch.device, init_policy=always_wrap_policy): model = Model() wrap_policy = ParamExecOrderWrapPolicy(init_policy=init_policy) fsdp_model = FSDP(model, auto_wrap_policy=wrap_policy, sharding_strategy=sharding_strategy) return fsdp_model.to(device) class TestFSDPExecOrder(FSDPTest): @property def device(self): return torch.device("cuda") @skip_if_lt_x_gpu(2) @parametrize( "sharding_strategy", [ShardingStrategy.FULL_SHARD, ShardingStrategy.SHARD_GRAD_OP], ) @parametrize("iters", [1, 3]) def test_fsdp_flatten_params_exec_order(self, sharding_strategy: ShardingStrategy, iters: int): """Tests the basic APIs of FSDP with ParamExecOrderWrapPolicy""" fsdp_model = Model.wrap(sharding_strategy, self.device) self.assertTrue(fsdp_model._is_param_exec_order_prep_stage()) for _ in range(iters): input = fsdp_model.module.get_input(self.device) output = fsdp_model(*input) loss = fsdp_model.module.get_loss(input, output).to(self.device) loss.backward() params_list = list(fsdp_model.parameters()) # Since the forward execution order is NOT consistent with the model definition order, # the ordering in flatten_named_params_exec_order should be different from named_parameters self.assertEqual( fsdp_model._fsdp_params_exec_order, [ params_list[0], params_list[2], params_list[3], params_list[1] ] ) self.assertTrue(fsdp_model._use_param_exec_order_policy()) self.assertTrue(not fsdp_model._is_param_exec_order_prep_stage()) instantiate_parametrized_tests(TestFSDPExecOrder) if __name__ == "__main__": run_tests()
36.911111
104
0.675196
db6b70fadf3a05b484aa88b4d26176945667f2fe
20,852
php
PHP
moodledata/lang/es_mx/tool_lp.php
Kvosarkoceles/educacionintegral.net
2716019e17ac1b306c5294ea8740b6d1c9c170e1
[ "MIT" ]
1
2020-08-10T18:03:38.000Z
2020-08-10T18:03:38.000Z
moodledata/lang/es_mx/tool_lp.php
Kvosarkoceles/educacionintegral.net
2716019e17ac1b306c5294ea8740b6d1c9c170e1
[ "MIT" ]
null
null
null
moodledata/lang/es_mx/tool_lp.php
Kvosarkoceles/educacionintegral.net
2716019e17ac1b306c5294ea8740b6d1c9c170e1
[ "MIT" ]
1
2020-08-09T20:20:50.000Z
2020-08-09T20:20:50.000Z
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Strings for component 'tool_lp', language 'es_mx', branch 'MOODLE_39_STABLE' * * @package tool_lp * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); $string['actions'] = 'Acciones'; $string['activities'] = 'Actividades'; $string['addcohorts'] = 'Añadir cohortes'; $string['addcohortstosync'] = 'Añadir cohortes a sincronizar'; $string['addcompetency'] = 'Añadir competencia'; $string['addcoursecompetencies'] = 'Añadir competencias al curso'; $string['addcrossreferencedcompetency'] = 'Añadir competencia de referencia-cruzada'; $string['addingcompetencywillresetparentrule'] = 'El añadir una competencia quitará la regla configurada en \'{$a}\'. ¿ Desea Usted continuar?'; $string['addnewcompetency'] = 'Añadir nueva competencia'; $string['addnewcompetencyframework'] = 'Añadir nueva estructura de competencia'; $string['addnewplan'] = 'Añadir nuevo plan de aprendizaje'; $string['addnewtemplate'] = 'Añadir nueva plantilla de plan de aprendizaje'; $string['addnewuserevidence'] = 'Añadir nueva evidencia'; $string['addtemplatecompetencies'] = 'Añadir competencias a plantilla de plan de aprendizaje'; $string['aisrequired'] = '\'{$a}\' es requerida'; $string['aplanswerecreated'] = '{$a} planes de aprendizaje fueron creados.'; $string['aplanswerecreatedmoremayrequiresync'] = '{$a} planes de aprendizaje fueron creados; se crearán más durante la siguiente sincronización.'; $string['assigncohorts'] = 'Asignar cohortes'; $string['averageproficiencyrate'] = 'La tasa de pericia/dominio promedio para planes de aprendizaje completados basada en esta plantilla es {$a} %'; $string['cancelreviewrequest'] = 'Cancelar solicitud de revisión'; $string['cannotaddrules'] = 'Esta competencia no puede ser configurada.'; $string['cannotcreateuserplanswhentemplateduedateispassed'] = 'No se pueden crear nuevos planes de aprendizaje. La fecha de validez de esta plantilla ha expirado o está a punto de expirar.'; $string['cannotcreateuserplanswhentemplatehidden'] = 'No se pueden crear nuevos planes de aprendizaje mientras esta plantilla esté oculta.'; $string['category'] = 'Categoría'; $string['chooserating'] = 'Elija una valoración...'; $string['cohortssyncedtotemplate'] = 'Cohortes sincronizados a esta plantilla de plan de aprendizaje'; $string['competenciesforframework'] = 'Competencias para {$a}'; $string['competenciesmostoftennotproficient'] = 'Las competencias que con más frecuencia no están dominadas en planes de aprendizaje completados.'; $string['competenciesmostoftennotproficientincourse'] = 'Las competencias que con más frecuencia no están dominadas en este curso'; $string['competencycannotbedeleted'] = 'La competencia \'{$a}\' no puede ser eliminada'; $string['competencycreated'] = 'Competencia creada'; $string['competencycrossreferencedcompetencies'] = '{$a}competencias con referencias-cruzadas'; $string['competencyframework'] = 'Estructura de competencia'; $string['competencyframeworkcreated'] = 'Estructura de competencia creada.'; $string['competencyframeworkname'] = 'Nombre'; $string['competencyframeworkroot'] = 'Sin padre (Competencia de nivel superior)'; $string['competencyframeworks'] = 'Estructuras de competencia'; $string['competencyframeworksrepository'] = 'Repositorio de estructuras de competencia'; $string['competencyframeworkupdated'] = 'Estructura de competencia actualizada'; $string['competencyoutcome_complete'] = 'Marcar como completa'; $string['competencyoutcome_evidence'] = 'Anexar una evidencia'; $string['competencyoutcome_none'] = 'Ninguno(a)'; $string['competencyoutcome_recommend'] = 'ecomendar la competencia'; $string['competencypicker'] = 'Selector de competencia'; $string['competencyrule'] = 'Regla de competencia'; $string['competencyupdated'] = 'Competencia actualizada'; $string['completeplan'] = 'Completar este plan de aprendizaje'; $string['completeplanconfirm'] = '¿Configurar el plan de aprendizaje \'{$a}\' a completado? Si así fuera, el estatus actual de todas las competencias de los usuarios será grabado, y el plan se volverá de solo lectura.'; $string['configurecoursecompetencysettings'] = 'Configurar competencias del curso'; $string['configurescale'] = 'Configurar escalas'; $string['coursecompetencies'] = 'Competencias del curso'; $string['coursecompetencyratingsarenotpushedtouserplans'] = 'Las valoraciones de competencia en este curso no afectan a los planes de aprendizaje.'; $string['coursecompetencyratingsarepushedtouserplans'] = 'Las valoraciones de competencia en este curso son actualizadas inmediatamente dentro de planes de aprendizaje.'; $string['coursecompetencyratingsquestion'] = 'Cuando se valúa una competencia de curso, ¿se actualiza la valoración de la competencia en los planes de aprendizaje, o esto solamente es aplicado al curso?'; $string['coursesusingthiscompetency'] = 'Cursos enlazados a esta competencia'; $string['coveragesummary'] = '{$a->competenciescoveredcount} de {$a->competenciescount} competencias están cubiertas ( {$a->coveragepercentage} % )'; $string['createlearningplans'] = 'Crear planes de aprendizaje'; $string['createplans'] = 'Crear planes de aprendizaje'; $string['crossreferencedcompetencies'] = 'Competencias con referencias-cruzadas'; $string['default'] = 'Por defecto'; $string['deletecompetency'] = 'Eliminar competencia \'{$a}\'?'; $string['deletecompetencyframework'] = '¿Eliminar estructura de competencia \'{$a}\'?'; $string['deletecompetencyparenthasrule'] = '¿Eliminar competencia \'{$a}\'? Esto también eliminará la regla configurada para su padre.'; $string['deleteplan'] = '¿Eliminar plan de aprendizaje \'{$a}\'?'; $string['deleteplans'] = 'Eliminar los planes de aprendizaje'; $string['deletetemplate'] = 'Eliminar plantilla de plan de aprenzaje \'{$a}\'?'; $string['deletetemplatewithplans'] = 'Esta plantilla tiene planes de aprendizaje asociados. Usted tiene que indicar como procesar esos planes.'; $string['deletethisplan'] = 'Eliminar este plan de aprendizaje'; $string['deletethisuserevidence'] = 'Eliminar esta competencia'; $string['deleteuserevidence'] = '¿Eliminar la evidencia de aprendizaje previo \'{$a}\'?'; $string['description'] = 'Descripción'; $string['duedate'] = 'Fecha prometida/esperada'; $string['duedate_help'] = 'La fecha en la que un plan de aprendizaje debería de estar completado.'; $string['editcompetency'] = 'Editar competencia'; $string['editcompetencyframework'] = 'Editar estructura de competencia'; $string['editplan'] = 'Editar plan de aprendizaje'; $string['editrating'] = 'Editar valoración'; $string['edittemplate'] = 'Editar plantilla de plan de aprendizaje'; $string['editthisplan'] = 'Editar este plan de aprendizaje'; $string['editthisuserevidence'] = 'Editar esta evidencia'; $string['edituserevidence'] = 'Editar evidencia'; $string['evidence'] = 'Evidencia'; $string['filterbyactivity'] = 'Filtrar competencias por recurso o actividad'; $string['findcourses'] = 'Encontrar cursos'; $string['frameworkcannotbedeleted'] = 'La estructura de competencia \'{$a}\' no puede ser eliminada'; $string['hidden'] = 'Oculto'; $string['hiddenhint'] = '(oculto)'; $string['idnumber'] = 'Número ID'; $string['inheritfromframework'] = 'Heredar de estructura de competencia (por defecto)'; $string['itemstoadd'] = 'Ítems para añadir'; $string['jumptocompetency'] = 'Saltar a competencia'; $string['jumptouser'] = 'Saltar a usuario'; $string['learningplancompetencies'] = 'Competencias del plan de aprendizaje'; $string['learningplans'] = 'Planes de aprendizaje'; $string['levela'] = 'Nivel {$a}'; $string['linkcompetencies'] = 'Enlazar competencias'; $string['linkcompetency'] = 'Enlazar competencia'; $string['linkedcompetencies'] = 'Competencias enlazadas'; $string['linkedcourses'] = 'Cursos enlazados'; $string['linkedcourseslist'] = 'Cursos enlazados:'; $string['listcompetencyframeworkscaption'] = 'Lista de estructuras de competencia'; $string['listofevidence'] = 'Lista de evidencia'; $string['listplanscaption'] = 'Lista de planes de aprendizaje'; $string['listtemplatescaption'] = 'Lista de plantillas de plan de aprendizaje'; $string['loading'] = 'Cargando...'; $string['locatecompetency'] = 'Localizar competencia'; $string['managecompetenciesandframeworks'] = 'Gestionar competencias y estructuras'; $string['modcompetencies'] = 'Competencias del curso'; $string['modcompetencies_help'] = 'Competencias del curso enlazadas a esta actividad.'; $string['move'] = 'Mover'; $string['movecompetency'] = 'Mover competencia'; $string['movecompetencyafter'] = 'Mover competencia después de \'{$a}\''; $string['movecompetencyframework'] = 'Mover estructura de competencia'; $string['movecompetencytochildofselfwillresetrules'] = 'El mover la competencia quitará su propia regla, y las reglas configuradas en sus padres y su destino. ¿Desea continuar?'; $string['movecompetencywillresetrules'] = 'Al mover la competencia se quitarán las reglas configuradas para su padre y en su destino. ¿Desea continuar?'; $string['moveframeworkafter'] = 'Mover estructura de competencia después de \'{$a}\''; $string['movetonewparent'] = 'Reacomodar'; $string['myplans'] = 'Mis planes de aprendizaje'; $string['nfiles'] = '{$a}archivo(s)'; $string['noactivities'] = 'Sin actividades'; $string['nocompetencies'] = 'No se han creado competencias en esta estructura.'; $string['nocompetenciesinactivity'] = 'No se han enlazado competencias a esta actividad o recurso.'; $string['nocompetenciesincourse'] = 'No se han enlazado competencias a este curso.'; $string['nocompetenciesinevidence'] = 'No se han ligado competencias a esta evidencia.'; $string['nocompetenciesinlearningplan'] = 'No se han ligado competencias a este plan de aprendizaje'; $string['nocompetenciesinlist'] = 'No se ha seleccionado ninguna competencia.'; $string['nocompetenciesintemplate'] = 'No se han enlazado competencias a esta plantilla de plan de aprendizaje.'; $string['nocompetencyframeworks'] = 'Todavía no se han creado estructuras de competencias.'; $string['nocompetencyselected'] = 'Sin competencias seleccionadas'; $string['nocrossreferencedcompetencies'] = 'No se han referenciado cruzadamente otras competencias con esta competencia.'; $string['noevidence'] = 'Sin evidencia'; $string['nofiles'] = 'Sin archivos'; $string['nolinkedcourses'] = 'Ningún curso está ligado a esta competencia.'; $string['noparticipants'] = 'No se encontraron participantes.'; $string['noplanswerecreated'] = 'No se crearon planes de aprendizaje.'; $string['notemplates'] = 'Todavía no se han creado plantillas de plan de aprendizaje.'; $string['nourl'] = 'Sin URL'; $string['nouserevidence'] = 'Todavía no se ha añadido evidencia de aprendizaje previo.'; $string['nouserplans'] = 'Todavía no se han creado planes de aprendizaje.'; $string['oneplanwascreated'] = 'Se creó un plan de aprendizaje'; $string['outcome'] = 'Resultado'; $string['parentcompetency'] = 'Padre'; $string['parentcompetency_edit'] = 'Editar padre'; $string['parentcompetency_help'] = 'Definir el padre debajo del cual se añadirá esta competencia. Puede ser, ya sea otra competencia dentro de la misma estructura, o la raíz de la estructura de la competencia para una competencia de nivel superior.'; $string['path'] = 'Ruta:'; $string['planapprove'] = 'Hacer activa'; $string['plancompleted'] = 'Plan de aprendizaje activo'; $string['plancreated'] = 'Plan de aprendizaje creado'; $string['plandescription'] = 'Descripción'; $string['planname'] = 'Nombre'; $string['plantemplate'] = 'Seleccionar plantilla de plan de aprendizaje'; $string['plantemplate_help'] = 'Un plan de aprendizaje creado desde una plantila contendrá una lista de competencias que concuerdan con la plantilla. Las actualizaciones a la plantilla se reflejarán en todos los planes creados desde esa plantilla.'; $string['planunapprove'] = 'Regresar a borrador'; $string['planupdated'] = 'Plan de aprendizaje actualizado'; $string['pluginname'] = 'Planes de aprendizaje'; $string['points'] = 'Puntos'; $string['pointsgivenfor'] = 'Puntos dados para \'{$a}\''; $string['privacy:metadata'] = 'El plugin de Planes de aprendizaje no almacena ningún dato personal.'; $string['proficient'] = 'Dominio/pericia'; $string['progress'] = 'Progreso'; $string['rate'] = 'Valorar'; $string['ratecomment'] = 'Notas de evidencia'; $string['rating'] = 'Valoración'; $string['ratingaffectsonlycourse'] = 'El valuar una competencia solamente actualiza la competencia dentro de este curso.'; $string['ratingaffectsuserplans'] = 'El valuar una competencia también actualiza la competencia en todos los planes de aprendizaje'; $string['reopenplan'] = 'Reabrir este plan de aprendizaje'; $string['reopenplanconfirm'] = '¿Reabrir el plan de aprendizaje \'{$a}\'? Si así fuera, el estatus de las competencias de los usuarios que estaban grabadas al momento de que el plan fuera previamente completado será eliminado, y el plan se volverá activo nuevamente.'; $string['requestreview'] = 'Solicitar revisión'; $string['reviewer'] = 'Revisor'; $string['reviewstatus'] = 'Revisar estatus'; $string['savechanges'] = 'Guardar cambios'; $string['scale'] = 'Escala'; $string['scale_help'] = 'Una escala determina como se mide la capacidad/pericia/expertez/dominio en una competencia. Después de seleccionar una escala, Usted debe de configurarla. * El ítem seleccionado como \'Por defecto\' es la valoración dada cuando se completa automáticamente una competencia. * El ítem (los items) seleccionado(s) como \'Dominio/pericia\' indica(n) cual(es) valor(es) calificarán las competencias como dominada cuando sean valoradas.'; $string['scalevalue'] = 'Valor de escala'; $string['search'] = 'Buscar...'; $string['selectcohortstosync'] = 'Seleccionar cohortes a sincronizar'; $string['selectcompetencymovetarget'] = 'Seleccionar una ubicación hacia donde mover esta competencia:'; $string['selectedcompetency'] = 'Competencia seleccionada'; $string['selectuserstocreateplansfor'] = 'Seleccionar usuarios a partir de los cuales crear plan de aprendizaje'; $string['sendallcompetenciestoreview'] = 'Mandar a todas las competencias en revisión para evidencia de aprendizaje previo \'{$a}\''; $string['sendcompetenciestoreview'] = 'Mandar competencias para revisión'; $string['shortname'] = 'Nombre'; $string['sitedefault'] = '(Valor por defecto del sitio)'; $string['startreview'] = 'Iniciar revisión'; $string['state'] = 'Estado'; $string['status'] = 'Estatus'; $string['stopreview'] = 'Terminar revisión'; $string['stopsyncingcohort'] = 'Detener sincronización de cohorte'; $string['taxonomies'] = 'Taxonomías'; $string['taxonomy_add_behaviour'] = 'Añadir comportamiento'; $string['taxonomy_add_competency'] = 'Añadir competencia'; $string['taxonomy_add_concept'] = 'Añadir concepto'; $string['taxonomy_add_domain'] = 'Añadir dominio'; $string['taxonomy_add_indicator'] = 'Añadir indicador'; $string['taxonomy_add_level'] = 'Añadir nivel'; $string['taxonomy_add_outcome'] = 'Añadir resultado'; $string['taxonomy_add_practice'] = 'Añadir práctica'; $string['taxonomy_add_proficiency'] = 'Añadir pericia/dominio'; $string['taxonomy_add_skill'] = 'Añadir habilidad'; $string['taxonomy_add_value'] = 'Añadir valor'; $string['taxonomy_edit_behaviour'] = 'Editar comportamiento'; $string['taxonomy_edit_competency'] = 'Editar competencia'; $string['taxonomy_edit_concept'] = 'Editar concepto'; $string['taxonomy_edit_domain'] = 'Editar dominio'; $string['taxonomy_edit_indicator'] = 'Editar indicador'; $string['taxonomy_edit_level'] = 'Editar nivel'; $string['taxonomy_edit_outcome'] = 'Editar resultado'; $string['taxonomy_edit_practice'] = 'Editar práctica'; $string['taxonomy_edit_proficiency'] = 'Editar pericia/dominio'; $string['taxonomy_edit_skill'] = 'Editar habilidad'; $string['taxonomy_edit_value'] = 'Editar valor'; $string['taxonomy_parent_behaviour'] = 'Comportamiento paterno'; $string['taxonomy_parent_competency'] = 'Competencia paterna'; $string['taxonomy_parent_concept'] = 'Concepto paterno'; $string['taxonomy_parent_domain'] = 'Dominio paterno'; $string['taxonomy_parent_indicator'] = 'Indicador paterno'; $string['taxonomy_parent_level'] = 'Nivel paterno'; $string['taxonomy_parent_outcome'] = 'Resultado paterno'; $string['taxonomy_parent_practice'] = 'Práctica patrna'; $string['taxonomy_parent_proficiency'] = 'Pericia/dominio paterna'; $string['taxonomy_parent_skill'] = 'Habilidad paterna'; $string['taxonomy_parent_value'] = 'Valor paterno'; $string['taxonomy_selected_behaviour'] = 'Comportamiento seleccionado'; $string['taxonomy_selected_competency'] = 'Competencia seleccionada'; $string['taxonomy_selected_concept'] = 'Concepto seleccionado'; $string['taxonomy_selected_domain'] = 'Dominio seleccionado'; $string['taxonomy_selected_indicator'] = 'Indicador seleccionado'; $string['taxonomy_selected_level'] = 'Nivel seleccionado'; $string['taxonomy_selected_outcome'] = 'Resultado seleccionado'; $string['taxonomy_selected_practice'] = 'Práctica seleccionada'; $string['taxonomy_selected_proficiency'] = 'Pericia/dominio seleccionada'; $string['taxonomy_selected_skill'] = 'Habilidad seleccionada'; $string['taxonomy_selected_value'] = 'Valor seleccionado'; $string['template'] = 'Plantilla de plan de aprendizaje'; $string['templatebased'] = 'Plantilla basada'; $string['templatecohortnotsyncedwhileduedateispassed'] = 'Las cohortes no serán sincronizadas si ya ha pasada la fecha esperada de la plantilla.'; $string['templatecohortnotsyncedwhilehidden'] = 'Las cohortes no serán sincronizadas mientras esta plantilla esté oculta.'; $string['templatecompetencies'] = 'Competencias de plantilla de plan de aprendizaje'; $string['templatecreated'] = 'Plantilla de plan de aprendizaje creada'; $string['templatename'] = 'Nombre'; $string['templates'] = 'Plantillas de plan de aprendizaje'; $string['templateupdated'] = 'Plantilla de plan de aprendizaje actualizada'; $string['totalrequiredtocomplete'] = 'Total necesario para completar'; $string['unlinkcompetencycourse'] = '¿Desligar a la competencia \'{$a}\' del curso?'; $string['unlinkcompetencyplan'] = '¿Desligar a la competencia \'{$a}\' del plan de aprendizaje?'; $string['unlinkcompetencytemplate'] = '¿Desligar a la competencia \'{$a}\' de la plantilla del plan de aprendizaje?'; $string['unlinkplanstemplate'] = 'Desligar los planes de aprendizaje de sus plantillas'; $string['unlinkplantemplate'] = 'Desligar de la plantilla del plan de aprendizaje'; $string['unlinkplantemplateconfirm'] = '¿Des-enlazar el plan de aprendizaje \'{$a}\' de su plantilla? Cualquier cambio realizado a la plantilla ya no se aplicará al plan. Esta acción no puede deshacerse.'; $string['uponcoursecompletion'] = 'Al completarse el curso:'; $string['uponcoursemodulecompletion'] = 'Al completarse la actividad:'; $string['usercompetencyfrozen'] = 'Este registro ahora está congelado. Refleja el estado de la competencia del usuario cuando su plan de aprendizaje fue marcado como completado.'; $string['userevidence'] = 'Evidencia de aprendizaje previo'; $string['userevidencecreated'] = 'Evidencia de aprendizaje previo creada'; $string['userevidencedescription'] = 'Descripción'; $string['userevidencefiles'] = 'Archivos'; $string['userevidencename'] = 'Nombre'; $string['userevidencesummary'] = 'Resumen'; $string['userevidenceupdated'] = 'Evidencia de aprendizaje previo actualizada'; $string['userevidenceurl'] = 'URL'; $string['userevidenceurl_help'] = 'La URL debe comenzar con \'http://\' o \'https://\'.'; $string['viewdetails'] = 'Ver detalles'; $string['visible'] = 'VIsible'; $string['visible_help'] = 'Una estructura de competencia puede ocultarse mientras esté siendo configurada o actualizada a una nueva versión.'; $string['when'] = 'Cuando'; $string['xcompetencieslinkedoutofy'] = '{$a->x} de {$a->y} competencias enlazadas a cursos'; $string['xcompetenciesproficientoutofy'] = '{$a->x} de un total de {$a->y} competencias se tienen dominadas'; $string['xcompetenciesproficientoutofyincourse'] = 'Usted es capaz/perito/experto en {$a->x} de un total de {$a->y} competencias en este curso.'; $string['xplanscompletedoutofy'] = '{$a->x} de {$a->y} planes de aprendizaje completados para esta planrtilla';
69.506667
268
0.75681
2c906b8675acf3ad18b366d41cc93f6c756f3ca3
2,235
py
Python
ListaExercicios3/ex1.py
GabrielSouzaGit/PythonStudies
49ec26d4ae45999695ab32f8e1f27587adb5ca4b
[ "MIT" ]
null
null
null
ListaExercicios3/ex1.py
GabrielSouzaGit/PythonStudies
49ec26d4ae45999695ab32f8e1f27587adb5ca4b
[ "MIT" ]
null
null
null
ListaExercicios3/ex1.py
GabrielSouzaGit/PythonStudies
49ec26d4ae45999695ab32f8e1f27587adb5ca4b
[ "MIT" ]
null
null
null
'''Uma empresa decidiu fazer um levantamento em relação aos candidatos que se apresentarem para preenchi- mento de vagas em seu quadro de funcionários. Supondo que você seja o programador dessa empresa, faça um programa que leia, para cada candidato, a idade, o sexo (M ou F), e a experiência no serviço (S ou N). Para encerrar a entrada de dados, digite a idade igual a zero. O programa também deve calcular e mostrar:¶ O número de candidatos do sexo feminino. O número de candidatos do sexo masculino. A idade média dos homens que já tem experiência no serviço. A porcentagem dos homens com mais de 45 anos entre o total dos homens. O número de mulheres com idade inferior a 21 anos e com experiência no serviço. A menor idade entre as mulheres que já tem experiência no serviço.''' menor_idade_fem = 150 quant_fem = 0 quant_exp_fem = 0 quant_masc = 0 quant_exp_masc = 0 quant_idade_masc = 0 soma_idade_masc = 0 while True: idade = int(input('Digite a sua idade: ')) if idade == 0: break sexo = input("Digite o seu sexo (M ou F)\n") experiencia = input("Têm experiência no serviço (S ou N)\n") if sexo == "F": quant_fem = quant_fem + 1 if experiencia == "S": if menor_idade_fem > idade: menor_idade_fem = idade if idade <= 21: quant_exp_fem = quant_exp_fem + 1 if sexo == "M": quant_masc = quant_masc + 1 if experiencia == "S": soma_idade_masc = soma_idade_masc + idade quant_exp_masc = quant_exp_masc + 1 if (idade >= 45): quant_idade_masc = quant_idade_masc + 1 if quant_fem == 0: menor_idade_fem = 0 print(f'O número de candidatos do sexo feminino: {quant_fem}') print(f'O número de candidatos do sexo masculino: {quant_masc}') print( f'A idade média dos homens que já tem experiência no serviço: {soma_idade_masc / quant_exp_masc}') print( f'A porcentagem dos homens com mais de 45 anos entre o total dos homens: {quant_idade_masc}') print( f'O número de mulheres com idade inferior a 21 anos e com experiência no serviço: {quant_exp_fem}') print( f'A menor idade entre as mulheres que já tem experiência no serviço: {menor_idade_fem}')
47.553191
420
0.694407
0abc40ef9a088968291395f8bd2e884bd2c9779f
10,280
cs
C#
MessageRouter/MessageRouter.Tests/BusinessLogic/DataContractManagerTests.cs
MarcinZiabek/netmq-router
8ae33c6aee7909231d66d4832f5ce145838b9ead
[ "MIT" ]
11
2019-02-16T18:59:35.000Z
2021-11-07T20:19:01.000Z
MessageRouter/MessageRouter.Tests/BusinessLogic/DataContractManagerTests.cs
MarcinZiabek/netmq-router
8ae33c6aee7909231d66d4832f5ce145838b9ead
[ "MIT" ]
2
2018-03-23T20:08:11.000Z
2018-04-22T19:26:40.000Z
MessageRouter/MessageRouter.Tests/BusinessLogic/DataContractManagerTests.cs
MarcinZiabek/netmq-router
8ae33c6aee7909231d66d4832f5ce145838b9ead
[ "MIT" ]
4
2018-08-05T11:37:41.000Z
2021-10-05T15:14:07.000Z
using System.Collections.Generic; using System.Linq; using MessageRouter.BusinessLogic; using MessageRouter.Infrastructure; using MessageRouter.Models; using Moq; using NUnit.Framework; namespace NetmqRouter.Tests.BusinessLogic { [TestFixture] public class DataContractManagerTests { #region Test Classes internal class ClassA { } internal class ClassB : ClassA { } internal class ClassC : ClassB { } #endregion #region Indexing [Test] public void IndexRoutes() { // arrange var routeA = new Route("RouteA", typeof(string)); var routeB = new Route("RouteB", typeof(int)); var routeC = new Route("RouteC", typeof(void)); var routes = new List<Route>() { routeA, routeB, routeC }; var contract = new Mock<IDataContractAccess>(); contract.Setup(x => x.Routes).Returns(routes); // act var routesDictionary = DataContractManager.IndexRoutes(contract.Object); // assert Assert.AreEqual(new[] { routeA.Name, routeB.Name, routeC.Name }, routesDictionary.Keys); Assert.AreEqual(routeA, routesDictionary[routeA.Name]); Assert.AreEqual(routeB, routesDictionary[routeB.Name]); Assert.AreEqual(routeC, routesDictionary[routeC.Name]); } [Test] public void IndexSubscribers() { // arrange var routeA = new Route("RouteA", typeof(string)); var routeB = new Route("RouteB", typeof(int)); var routeC = new Route("RouteC", typeof(void)); var subscriber1 = new Subscriber(routeA, null, _ => null); var subscriber2 = new Subscriber(routeA, routeB, _ => null); var subscriber3 = new Subscriber(routeC, null, _ => null); var subscriber4 = new Subscriber(routeC, routeB, _ => null); var subscribers = new List<Subscriber>() { subscriber1, subscriber2, subscriber3, subscriber4 }; var contract = new Mock<IDataContractAccess>(); contract.Setup(x => x.Subscribers).Returns(subscribers); // act var subscribersDictionary = DataContractManager.IndexSubscribers(contract.Object); // assert Assert.AreEqual(new[] { routeA.Name, routeC.Name }, subscribersDictionary.Keys); Assert.AreEqual(new[] { subscriber1, subscriber2 }, subscribersDictionary[routeA.Name]); Assert.AreEqual(new[] { subscriber3, subscriber4 }, subscribersDictionary[routeC.Name]); } [Test] public void IndexSerializers() { // arrange var routeA = new Route("RouteA", typeof(ClassA)); var routeB = new Route("RouteB", typeof(ClassB)); var routeC = new Route("RouteC", typeof(ClassC)); var routeG = new Route("RouteG", typeof(object)); var serializerMockA = new Mock<IGeneralSerializer<ClassA>>(); serializerMockA.Setup(x => x.Serialize(It.IsAny<ClassA>())).Returns(new[] {(byte) 'A'}); var serializerMockB = new Mock<ITypeSerializer<ClassB>>(); serializerMockB.Setup(x => x.Serialize(It.IsAny<ClassB>())).Returns(new[] {(byte) 'B'}); var serializerMockG = new Mock<IGeneralSerializer<object>>(); serializerMockG.Setup(x => x.Serialize(It.IsAny<object>())).Returns(new[] {(byte) 'G'}); var serializerA = Serializer.FromGeneralSerializer(serializerMockA.Object); var serializerB = Serializer.FromTypeSerializer(serializerMockB.Object); var serializerG = Serializer.FromGeneralSerializer(serializerMockG.Object); var routes = new List<Route>() { routeA, routeB, routeC, routeG }; var serializers = new List<Serializer>() { serializerA, serializerB, serializerG }; var contract = new Mock<IDataContractAccess>(); contract.Setup(x => x.Routes).Returns(routes); contract.Setup(x => x.Serializers).Returns(serializers); // act var mapping = DataContractManager.IndexSerializers(contract.Object); // assert Assert.AreEqual((byte)'A', mapping[routeA.DataType].Serialize(null)[0]); Assert.AreEqual((byte)'B', mapping[routeB.DataType].Serialize(null)[0]); Assert.AreEqual((byte)'A', mapping[routeC.DataType].Serialize(null)[0]); Assert.AreEqual((byte)'G', mapping[routeG.DataType].Serialize(null)[0]); } #endregion #region GetIncomingRouteNames [Test] public void GetIncomingRouteNamesFromSubscribers() { // arrange var builder = new DataContractBuilder(); var serializer = new Mock<ITypeSerializer<string>>(); builder.RegisterSerializer(serializer.Object); var routeA = new Route("RouteA", typeof(string)); var routeB = new Route("RouteB", typeof(string)); var routeC = new Route("RouteC", typeof(string)); var routeD = new Route("RouteD", typeof(string)); builder.RegisterRoute(routeA); builder.RegisterRoute(routeB); builder.RegisterRoute(routeC); builder.RegisterRoute(routeD); // act builder.RegisterSubscriber(new Subscriber(routeA, routeB, _ => null)); builder.RegisterSubscriber(new Subscriber(routeC, routeD, _ => null)); var dataContract = new DataContractManager(builder); // assert var routeNames = dataContract .GetIncomingRouteNames() .ToArray(); var exptectedRouteNames = new[] { routeA.Name, routeC.Name }; Assert.AreEqual(exptectedRouteNames, routeNames); } #endregion #region SubscriberCalling [Test] public void CallRoute() { // arrange var routeI = new Route("RouteI", typeof(ClassA)); var routeV = new Route("RouteV", typeof(void)); var routeR1 = new Route("routeR1", typeof(ClassB)); var routeR2 = new Route("routeR2", typeof(ClassB)); var serializerMockA = new Mock<ITypeSerializer<ClassA>>(); serializerMockA.Setup(x => x.Serialize(It.IsAny<ClassA>())).Returns(new[] {(byte) 'A'}); var serializerMockB = new Mock<ITypeSerializer<ClassB>>(); serializerMockB.Setup(x => x.Serialize(It.IsAny<ClassB>())).Returns(new[] {(byte) 'B'}); var responseClass1 = new ClassB(); var responseClass2 = new ClassB(); var subscriberA = new Subscriber(routeI, routeR1, _ => responseClass1); var subscriberB = new Subscriber(routeI, null, _ => null); var subscriberC = new Subscriber(routeI, routeR2, _ => responseClass2); var routes = new List<Route> { routeI, routeV, routeR1, routeR2 }; var serializers = new List<Serializer> { Serializer.FromTypeSerializer(serializerMockA.Object), Serializer.FromTypeSerializer(serializerMockB.Object) }; var subscribers = new List<Subscriber> { subscriberA, subscriberB, subscriberC }; var configuration = new Mock<IDataContractAccess>(); configuration.Setup(x => x.Routes).Returns(routes); configuration.Setup(x => x.Serializers).Returns(serializers); configuration.Setup(x => x.Subscribers).Returns(subscribers); var contract = new DataContractManager(configuration.Object); // act var response = contract .CallRoute(new Message(routeI.Name, new ClassA())) .ToList(); // assert Assert.AreEqual(2, response.Count); Assert.AreEqual(new Message(routeR1.Name, responseClass1), response[0]); Assert.AreEqual(new Message(routeR2.Name, responseClass2), response[1]); } #endregion #region Serialization [Test] public void EventSerialization() { // arrange var eventRoute = new Route("EventRoute", typeof(void)); var configuration = new Mock<IDataContractAccess>(); configuration.Setup(x => x.Routes).Returns(new List<Route> {eventRoute}); configuration.Setup(x => x.Serializers).Returns(new List<Serializer>()); configuration.Setup(x => x.Subscribers).Returns(new List<Subscriber>()); var contract = new DataContractManager(configuration.Object); var message = new Message("EventRoute", null); // act var serializedMessage = contract.Serialize(message); // assert var expectedMessage = new SerializedMessage("EventRoute", null); Assert.AreEqual(expectedMessage, serializedMessage); } [Test] public void EventDeserialization() { // arrange var eventRoute = new Route("EventRoute", typeof(void)); var configuration = new Mock<IDataContractAccess>(); configuration.Setup(x => x.Routes).Returns(new List<Route> {eventRoute}); configuration.Setup(x => x.Serializers).Returns(new List<Serializer>()); configuration.Setup(x => x.Subscribers).Returns(new List<Subscriber>()); var contract = new DataContractManager(configuration.Object); var serializedMessage = new SerializedMessage("EventRoute", new byte[0]); // act var message = contract.Deserialize(serializedMessage); // assert var expectedMessage = new Message("EventRoute", null); Assert.AreEqual(expectedMessage, message); } #endregion } }
35.818815
100
0.581031
891c9fa24766eb1281981e8cb100bbbf29f92dbc
394
rs
Rust
src/spinner.rs
uasi/gha-release-experiments
9498fa1935e6eaea4af4280abc8209b1052bab10
[ "Apache-2.0" ]
null
null
null
src/spinner.rs
uasi/gha-release-experiments
9498fa1935e6eaea4af4280abc8209b1052bab10
[ "Apache-2.0" ]
null
null
null
src/spinner.rs
uasi/gha-release-experiments
9498fa1935e6eaea4af4280abc8209b1052bab10
[ "Apache-2.0" ]
null
null
null
use indicatif::{ProgressBar, ProgressStyle}; pub fn new_spinner(msg: &str) -> ProgressBar { let style = ProgressStyle::default_spinner() .tick_strings(&["", ".", "..", "...", "....", ".....", "... Done."]) .template("{msg}{spinner}"); let spinner = ProgressBar::new(1).with_style(style); spinner.set_message(msg); spinner.enable_steady_tick(160); spinner }
32.833333
76
0.596447
6df19a715028d2447a111bd7965efb5146e32743
9,828
c
C
cyclone_crypto/sha512.c
Velleman/VM204-Firmware
f6836dff40ec70fc2de66a3b2c6f03fa4c36c223
[ "MIT" ]
4
2016-04-17T00:48:37.000Z
2020-03-17T01:42:20.000Z
cyclone_crypto/sha512.c
Velleman/VM204-Firmware
f6836dff40ec70fc2de66a3b2c6f03fa4c36c223
[ "MIT" ]
null
null
null
cyclone_crypto/sha512.c
Velleman/VM204-Firmware
f6836dff40ec70fc2de66a3b2c6f03fa4c36c223
[ "MIT" ]
6
2016-04-17T00:48:41.000Z
2022-01-28T13:50:45.000Z
/** * @file sha512.c * @brief SHA-512 (Secure Hash Algorithm 512) * * @section License * * Copyright (C) 2010-2015 Oryx Embedded SARL. All rights reserved. * * This file is part of CycloneCrypto Open. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * @section Description * * SHA-512 is a secure hash algorithm for computing a condensed representation * of an electronic message. Refer to FIPS 180-4 for more details * * @author Oryx Embedded SARL (www.oryx-embedded.com) * @version 1.6.0 **/ //Switch to the appropriate trace level #define TRACE_LEVEL CRYPTO_TRACE_LEVEL //Dependencies #include <string.h> #include "crypto.h" #include "sha512.h" //Check crypto library configuration #if (SHA384_SUPPORT == ENABLED || SHA512_SUPPORT == ENABLED || SHA512_224_SUPPORT == ENABLED || SHA512_256_SUPPORT == ENABLED) //SHA-512 auxiliary functions #define CH(x, y, z) (((x) & (y)) | (~(x) & (z))) #define MAJ(x, y, z) (((x) & (y)) | ((x) & (z)) | ((y) & (z))) #define SIGMA1(x) (ROR64(x, 28) ^ ROR64(x, 34) ^ ROR64(x, 39)) #define SIGMA2(x) (ROR64(x, 14) ^ ROR64(x, 18) ^ ROR64(x, 41)) #define SIGMA3(x) (ROR64(x, 1) ^ ROR64(x, 8) ^ SHR64(x, 7)) #define SIGMA4(x) (ROR64(x, 19) ^ ROR64(x, 61) ^ SHR64(x, 6)) //SHA-512 padding static const uint8_t padding[128] = { 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; //SHA-512 constants static const uint64_t k[80] = { 0x428A2F98D728AE22, 0x7137449123EF65CD, 0xB5C0FBCFEC4D3B2F, 0xE9B5DBA58189DBBC, 0x3956C25BF348B538, 0x59F111F1B605D019, 0x923F82A4AF194F9B, 0xAB1C5ED5DA6D8118, 0xD807AA98A3030242, 0x12835B0145706FBE, 0x243185BE4EE4B28C, 0x550C7DC3D5FFB4E2, 0x72BE5D74F27B896F, 0x80DEB1FE3B1696B1, 0x9BDC06A725C71235, 0xC19BF174CF692694, 0xE49B69C19EF14AD2, 0xEFBE4786384F25E3, 0x0FC19DC68B8CD5B5, 0x240CA1CC77AC9C65, 0x2DE92C6F592B0275, 0x4A7484AA6EA6E483, 0x5CB0A9DCBD41FBD4, 0x76F988DA831153B5, 0x983E5152EE66DFAB, 0xA831C66D2DB43210, 0xB00327C898FB213F, 0xBF597FC7BEEF0EE4, 0xC6E00BF33DA88FC2, 0xD5A79147930AA725, 0x06CA6351E003826F, 0x142929670A0E6E70, 0x27B70A8546D22FFC, 0x2E1B21385C26C926, 0x4D2C6DFC5AC42AED, 0x53380D139D95B3DF, 0x650A73548BAF63DE, 0x766A0ABB3C77B2A8, 0x81C2C92E47EDAEE6, 0x92722C851482353B, 0xA2BFE8A14CF10364, 0xA81A664BBC423001, 0xC24B8B70D0F89791, 0xC76C51A30654BE30, 0xD192E819D6EF5218, 0xD69906245565A910, 0xF40E35855771202A, 0x106AA07032BBD1B8, 0x19A4C116B8D2D0C8, 0x1E376C085141AB53, 0x2748774CDF8EEB99, 0x34B0BCB5E19B48A8, 0x391C0CB3C5C95A63, 0x4ED8AA4AE3418ACB, 0x5B9CCA4F7763E373, 0x682E6FF3D6B2B8A3, 0x748F82EE5DEFB2FC, 0x78A5636F43172F60, 0x84C87814A1F0AB72, 0x8CC702081A6439EC, 0x90BEFFFA23631E28, 0xA4506CEBDE82BDE9, 0xBEF9A3F7B2C67915, 0xC67178F2E372532B, 0xCA273ECEEA26619C, 0xD186B8C721C0C207, 0xEADA7DD6CDE0EB1E, 0xF57D4F7FEE6ED178, 0x06F067AA72176FBA, 0x0A637DC5A2C898A6, 0x113F9804BEF90DAE, 0x1B710B35131C471B, 0x28DB77F523047D84, 0x32CAAB7B40C72493, 0x3C9EBE0A15C9BEBC, 0x431D67C49C100D4C, 0x4CC5D4BECB3E42B6, 0x597F299CFC657E2A, 0x5FCB6FAB3AD6FAEC, 0x6C44198C4A475817 }; //SHA-512 object identifier (2.16.840.1.101.3.4.2.3) static const uint8_t sha512Oid[] = {0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03}; //Common interface for hash algorithms const HashAlgo sha512HashAlgo = { "SHA-512", sha512Oid, sizeof(sha512Oid), sizeof(Sha512Context), SHA512_BLOCK_SIZE, SHA512_DIGEST_SIZE, (HashAlgoCompute) sha512Compute, (HashAlgoInit) sha512Init, (HashAlgoUpdate) sha512Update, (HashAlgoFinal) sha512Final }; /** * @brief Digest a message using SHA-512 * @param[in] data Pointer to the message being hashed * @param[in] length Length of the message * @param[out] digest Pointer to the calculated digest * @return Error code **/ error_t sha512Compute(const void *data, size_t length, uint8_t *digest) { //Allocate a memory buffer to hold the SHA-512 context Sha512Context *context = osAllocMem(sizeof(Sha512Context)); //Failed to allocate memory? if(!context) return ERROR_OUT_OF_MEMORY; //Initialize the SHA-512 context sha512Init(context); //Digest the message sha512Update(context, data, length); //Finalize the SHA-512 message digest sha512Final(context, digest); //Free previously allocated memory osFreeMem(context); //Successful processing return NO_ERROR; } /** * @brief Initialize SHA-512 message digest context * @param[in] context Pointer to the SHA-512 context to initialize **/ void sha512Init(Sha512Context *context) { //Set initial hash value context->h[0] = 0x6A09E667F3BCC908; context->h[1] = 0xBB67AE8584CAA73B; context->h[2] = 0x3C6EF372FE94F82B; context->h[3] = 0xA54FF53A5F1D36F1; context->h[4] = 0x510E527FADE682D1; context->h[5] = 0x9B05688C2B3E6C1F; context->h[6] = 0x1F83D9ABFB41BD6B; context->h[7] = 0x5BE0CD19137E2179; //Number of bytes in the buffer context->size = 0; //Total length of the message context->totalSize = 0; } /** * @brief Update the SHA-512 context with a portion of the message being hashed * @param[in] context Pointer to the SHA-512 context * @param[in] data Pointer to the buffer being hashed * @param[in] length Length of the buffer **/ void sha512Update(Sha512Context *context, const void *data, size_t length) { //Process the incoming data while(length > 0) { //The buffer can hold at most 128 bytes size_t n = MIN(length, 128 - context->size); //Copy the data to the buffer memcpy(context->buffer + context->size, data, n); //Update the SHA-512 context context->size += n; context->totalSize += n; //Advance the data pointer data = (uint8_t *) data + n; //Remaining bytes to process length -= n; //Process message in 16-word blocks if(context->size == 128) { //Transform the 16-word block sha512ProcessBlock(context); //Empty the buffer context->size = 0; } } } /** * @brief Finish the SHA-512 message digest * @param[in] context Pointer to the SHA-512 context * @param[out] digest Calculated digest (optional parameter) **/ void sha512Final(Sha512Context *context, uint8_t *digest) { uint_t i; size_t paddingSize; uint64_t totalSize; //Length of the original message (before padding) totalSize = context->totalSize * 8; //Pad the message so that its length is congruent to 112 modulo 128 paddingSize = (context->size < 112) ? (112 - context->size) : (128 + 112 - context->size); //Append padding sha512Update(context, padding, paddingSize); //Append the length of the original message context->w[14] = 0; context->w[15] = htobe64(totalSize); //Calculate the message digest sha512ProcessBlock(context); //Convert from host byte order to big-endian byte order for(i = 0; i < 8; i++) context->h[i] = htobe64(context->h[i]); //Copy the resulting digest if(digest != NULL) memcpy(digest, context->digest, SHA512_DIGEST_SIZE); } /** * @brief Process message in 16-word blocks * @param[in] context Pointer to the SHA-512 context **/ void sha512ProcessBlock(Sha512Context *context) { uint_t t; uint64_t temp1; uint64_t temp2; //Initialize the 8 working registers uint64_t a = context->h[0]; uint64_t b = context->h[1]; uint64_t c = context->h[2]; uint64_t d = context->h[3]; uint64_t e = context->h[4]; uint64_t f = context->h[5]; uint64_t g = context->h[6]; uint64_t h = context->h[7]; //Process message in 16-word blocks uint64_t *w = context->w; //Convert from big-endian byte order to host byte order for(t = 0; t < 16; t++) w[t] = betoh64(w[t]); //Prepare the message schedule for(t = 16; t < 80; t++) w[t] = SIGMA4(w[t - 2]) + w[t - 7] + SIGMA3(w[t - 15]) + w[t - 16]; //SHA-512 hash computation for(t = 0; t < 80; t++) { //Calculate T1 and T2 temp1 = h + SIGMA2(e) + CH(e, f, g) + k[t] + w[t]; temp2 = SIGMA1(a) + MAJ(a, b, c); //Update the working registers h = g; g = f; f = e; e = d + temp1; d = c; c = b; b = a; a = temp1 + temp2; } //Update the hash value context->h[0] += a; context->h[1] += b; context->h[2] += c; context->h[3] += d; context->h[4] += e; context->h[5] += f; context->h[6] += g; context->h[7] += h; } #endif
32.76
126
0.689153
437b477f46b42899b53df28c5a2374d8c64e2ebe
789
tsx
TypeScript
src/components/svg/MonoIcon/Edit/index.tsx
adam-sv/arc
5e37bdbfd907f68a90275eba16ad340409e0a17a
[ "MIT" ]
2
2021-04-03T16:30:46.000Z
2021-08-08T21:13:18.000Z
src/components/svg/MonoIcon/Edit/index.tsx
adam-sv/arc
5e37bdbfd907f68a90275eba16ad340409e0a17a
[ "MIT" ]
null
null
null
src/components/svg/MonoIcon/Edit/index.tsx
adam-sv/arc
5e37bdbfd907f68a90275eba16ad340409e0a17a
[ "MIT" ]
1
2022-01-31T03:00:23.000Z
2022-01-31T03:00:23.000Z
import React from 'react'; import { cn } from '@adam-sv/arc'; import './style.css'; interface IProps { className?: string; } export default ({ className }: IProps) => ( <svg className={cn('MonoIcon-Edit', className)} width="24" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" > <path fillRule="evenodd" clipRule="evenodd" d="M16.2929 2.29289C16.6834 1.90237 17.3166 1.90237 17.7071 2.29289L21.7071 6.29289C22.0976 6.68342 22.0976 7.31658 21.7071 7.70711L8.70711 20.7071C8.51957 20.8946 8.26522 21 8 21H4C3.44772 21 3 20.5523 3 20V16C3 15.7348 3.10536 15.4804 3.29289 15.2929L13.2927 5.2931L16.2929 2.29289ZM14 7.41421L5 16.4142V19H7.58579L16.5858 10L14 7.41421ZM18 8.58579L15.4142 6L17 4.41421L19.5858 7L18 8.58579Z" /> </svg> );
34.304348
400
0.683143
ef78082041a53e2319ffcf9636c78dd430010b06
785
c
C
time/strtime.c
kingJHome/linuxSysCode
dfcecc5a08e957c1e8e2517bea466d08e7bdced0
[ "MIT" ]
null
null
null
time/strtime.c
kingJHome/linuxSysCode
dfcecc5a08e957c1e8e2517bea466d08e7bdced0
[ "MIT" ]
null
null
null
time/strtime.c
kingJHome/linuxSysCode
dfcecc5a08e957c1e8e2517bea466d08e7bdced0
[ "MIT" ]
null
null
null
#define _XOPEN_SOURCE #include <time.h> #include <locale.h> #include "tlpi_hdr.h" #define SBUF_SIZE 1000 int main(int argc,char *argv[]){ struct tm tm; char sbuf[SBUF_SIZE]; char *ofmt; if(argc < 3 || strcmp(argv[1],"--help") == 0){ usageError("%s input-date-time in-format [out-format]\n", argv[0]); } if(setlocale(LC_ALL,"") == NULL){ errExit("setlocale"); } memset(&tm, 0, sizeof(struct tm)); if(strptime(argv[1], argv[2], &tm) == NULL){ fatal("strptime"); } tm.tm_isdst = -1; printf("calendar time (seconds since Epoch): %ld\n", (long)mktime(&tm)); ofmt = (argc > 3) ? argv[3] : "%H:%M:%S %A,%d %B %Y %Z"; if(strftime(sbuf, SBUF_SIZE, ofmt, &tm) == 0){ fatal("strftime returned 0"); } printf("strftime() yields: %s\n", sbuf); exit(EXIT_SUCCESS); }
21.216216
73
0.615287
2d6ff3bf635a35b3bea1749f92c438fe74b4aedf
5,130
css
CSS
public/stylesheets/style.css
EvgenSalyakin/UranTest
ca182b0d27e5184b949a33ea334674757ec324ed
[ "MIT" ]
null
null
null
public/stylesheets/style.css
EvgenSalyakin/UranTest
ca182b0d27e5184b949a33ea334674757ec324ed
[ "MIT" ]
null
null
null
public/stylesheets/style.css
EvgenSalyakin/UranTest
ca182b0d27e5184b949a33ea334674757ec324ed
[ "MIT" ]
null
null
null
/* Base style ========================================================================== */ html { height: 100%; box-sizing: border-box; background: linear-gradient(253deg, #0cc898, #1797d2, #864fe1); background-size: 1000% 10000%; -webkit-animation: Background 25s ease infinite; -moz-animation: Background 25s ease infinite; animation: Background 25s ease infinite; } body { font: 14px "Lucida Grande", Helvetica, Arial, sans-serif; background: url(https://i.imgur.com/wCG2csZ.png); background-size: contain; width: 100%; height: auto; box-sizing: border-box; } @-webkit-keyframes Background { 0% { background-position: 0% 50% } 50% { background-position: 100% 50% } 100% { background-position: 0% 50% } } @-moz-keyframes Background { 0% { background-position: 0% 50% } 50% { background-position: 100% 50% } 100% { background-position: 0% 50% } } @keyframes Background { 0% { background-position: 0% 50% } 50% { background-position: 100% 50% } 100% { background-position: 0% 50% } } .wrap { padding: 25px; max-width: 1200px; margin: 0 auto; } header, footer, main { flex: 1 1 100%; } /* Header block style ========================================================================== */ header { position: relative; } .full-screen { background-size: cover; background-position: center; width: 100%; display: -webkit-flex; display: flex; -webkit-flex-direction: column; /* works with row or column */ flex-direction: column; -webkit-align-items: center; align-items: center; -webkit-justify-content: center; justify-content: center; text-align: center; } h1 { color: #fff; font-family: 'Open Sans', sans-serif; font-weight: 800; font-size: 45px; margin: 15px 0 25px; letter-spacing: -2px; text-align: center; text-shadow: 1px 2px 1px rgba(0, 0, 0, .6); } h1:after { display: block; color: #fff; letter-spacing: 1px; font-family: 'Poiret One', sans-serif; content: 'by Evgen S.'; font-size: 0.5em; text-align: center; } .button-line { position: absolute; top: 10px; right: 10px; font-family: 'Open Sans', sans-serif; text-transform: uppercase; letter-spacing: 2px; background: transparent; border: 1px solid #fff; color: #fff; text-align: center; font-size: 13px; font-weight: bold; opacity: .8; padding: 5px 5px; text-decoration: none; transition: all .5s ease; margin: 0 auto; display: block; width: 100px; } .button-line:hover { opacity: 1; } header ul { border: 1px solid rgba(255, 255, 255, 0.75); background-color: rgba(255, 255, 255, 0.2); color: rgb(10, 58, 97); list-style: none; padding: 5px; margin: 0; position: absolute; top: 49px; right: 10px; } header ul li { border-bottom: 1px solid rgba(255, 255, 255, 0.75); } header ul li:last-child { border-bottom: none; } header ul a { color: rgb(10, 58, 97); text-decoration: none; display: block; padding: 5px 10px; } header ul a:hover, header ul a:focus { color: rgb(255, 255, 255); } .hide { display: none; } @media screen and (max-width: 600px){ h1 { font-size: 30px; margin: 15px 0 25px; letter-spacing: 1px; padding-right: 100px; } } /* Main block style ========================================================================== */ main { margin: 20px 0; display: flex; flex-flow: row wrap; height: auto; } .article { padding: 10px; text-align: center; border: 1px solid rgba(255, 255, 255, 0.75); background-color: rgba(255, 255, 255, 0.2); color: rgb(10, 58, 97); margin: 10px; flex-grow: 1; flex-shrink: 1; flex-basis: 0; min-width: 170px; } .article h2 { color: #ffffff; text-shadow: 2px 2px 1px rgba(0, 0, 0, 0.5); } .article h5 { padding-left: 55px; font-style: italic; color: #575757; text-align: justify; } .article h6 { padding: 0; margin: 0; text-align: right; } .article p { text-align: justify; } main:nth-of-type(4) .column:first-of-type { flex-grow: 2; flex-shrink: 2; flex-basis: 60px; } /* Footer block style ========================================================================== */ footer { color: #ffffff; text-shadow: 2px 2px 1px rgba(0, 0, 0, 0.5); position: fixed; bottom: 0; right: 0; left: 0; padding: 0 25px; background: rgba(33, 150, 243, 1); box-shadow: 0px -6px 28px rgba(0, 0, 0, 0.25), 1px -2px 10px rgba(0, 0, 0, 0.22); text-align: center; } footer a { color: #9cecff; text-shadow: 2px 2px 1px rgba(0, 0, 0, 0.5); text-decoration: none; padding: 0 10px; } footer a:hover, footer a:focus { color: #ffffff; text-shadow: 2px 2px 1px rgba(4, 16, 36, 0.5); text-decoration: none; padding: 0 10px; }
19.285714
85
0.549903
10b9404634ee8f17064decc71ca4da5e95e3239a
544
sql
SQL
Cap13/02-WebApp/sql/sp_createUser.sql
CezarPoeta/Python-Fundamentos
53972d21bea86fdba90a3fafa487be6959ccebb8
[ "MIT" ]
1
2020-07-31T20:31:19.000Z
2020-07-31T20:31:19.000Z
Cap13/02-WebApp/sql/sp_createUser.sql
CezarPoeta/Python-Fundamentos
53972d21bea86fdba90a3fafa487be6959ccebb8
[ "MIT" ]
null
null
null
Cap13/02-WebApp/sql/sp_createUser.sql
CezarPoeta/Python-Fundamentos
53972d21bea86fdba90a3fafa487be6959ccebb8
[ "MIT" ]
null
null
null
CREATE DEFINER=`appuser`@`localhost` PROCEDURE `sp_createUser`( IN p_name VARCHAR(45), IN p_email VARCHAR(45), IN p_password VARCHAR(45) ) BEGIN if ( select exists (select 1 from tbl_user where user_email = p_email) ) THEN select 'User Existe !!'; ELSE insert into tbl_user ( user_name, user_email, user_password ) values ( p_name, p_email, p_password ); END IF; END$$
20.148148
81
0.511029
9218092aad5037ed6fd07e0ed2677030ad508cb4
1,794
kt
Kotlin
app/src/main/java/com/example/lucknowcityguide/PlaceHolderFragment.kt
shashankmunda/City-Tour-Guide
40e9132d32e5a76afb2e0e5445b748f07b7c9305
[ "CC0-1.0" ]
null
null
null
app/src/main/java/com/example/lucknowcityguide/PlaceHolderFragment.kt
shashankmunda/City-Tour-Guide
40e9132d32e5a76afb2e0e5445b748f07b7c9305
[ "CC0-1.0" ]
null
null
null
app/src/main/java/com/example/lucknowcityguide/PlaceHolderFragment.kt
shashankmunda/City-Tour-Guide
40e9132d32e5a76afb2e0e5445b748f07b7c9305
[ "CC0-1.0" ]
null
null
null
package com.example.lucknowcityguide import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.fragment.app.Fragment class PlaceHolderFragment : Fragment() { private var imgView: ImageView? = null private var bgs = intArrayOf(R.drawable.welcome_page, R.drawable.girltourist, R.drawable.bookmark) override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val rootView = inflater.inflate(R.layout.fragment_pager, container, false) val titles = resources.getStringArray(R.array.section_format) val desc = resources.getStringArray(R.array.section_desc) val titleView = rootView.findViewById<TextView>(R.id.section_label) titleView.text = titles[requireArguments().getInt(ARG_SECTION_NUMBER) - 1] val descView = rootView.findViewById<TextView>(R.id.desc_text) descView.text = desc[requireArguments().getInt(ARG_SECTION_NUMBER) - 1] imgView = rootView.findViewById(R.id.section_img) imgView!!.setBackgroundResource(bgs[requireArguments().getInt(ARG_SECTION_NUMBER) - 1]) return rootView } companion object { private const val ARG_SECTION_NUMBER = "section_number" /* To return a new instance of the fragment for a given section number*/ @JvmStatic fun newInstance(sectionNumber: Int): PlaceHolderFragment { val fragment = PlaceHolderFragment() val args = Bundle() args.putInt(ARG_SECTION_NUMBER, sectionNumber) fragment.arguments = args return fragment } } }
39
102
0.702341
c9a454f53a892538c50bf713a7dd698d086eab90
1,482
ts
TypeScript
packages/object/src/set-props.test.ts
devdigital/utilz
6936f55a4d3869184e84e62c9a746f39cbcea172
[ "MIT" ]
null
null
null
packages/object/src/set-props.test.ts
devdigital/utilz
6936f55a4d3869184e84e62c9a746f39cbcea172
[ "MIT" ]
10
2020-09-14T14:45:19.000Z
2021-08-04T07:21:23.000Z
packages/object/src/set-props.test.ts
devdigital/utilz
6936f55a4d3869184e84e62c9a746f39cbcea172
[ "MIT" ]
null
null
null
import { setProps } from './set-props' describe('setProps', () => { it('throws exception given undefined object', () => { expect(setProps()).toThrow('No object specified.') }) it('returns empty object given empty object', () => { expect(setProps()({})).toEqual({}) }) it('returns props set to undefined when value is undefined', () => { expect(setProps()({ foo: 'bar' })).toEqual({ foo: undefined }) }) it('returns props set to null when value is null', () => { expect(setProps(null)({ foo: 'bar' })).toEqual({ foo: null }) }) it('returns props set to value', () => { expect(setProps(0)({ foo: 'bar', baz: 'foo' })).toEqual({ foo: 0, baz: 0 }) }) it('returns nested props set to value', () => { expect(setProps(0)({ foo: 'bar', baz: { foo: { bar: 'foo' } } })).toEqual({ foo: 0, baz: { foo: { bar: 0 } }, }) }) it('does not modify the object', () => { const value = { foo: 'bar', } setProps(0)(value) expect(value).toEqual({ foo: 'bar' }) }) it('should pass key to provided function', () => { const value = { foo: 'bar', } expect(setProps(({ key }: { key: any }) => key)(value)).toEqual({ foo: 'foo', }) }) it('should pass value to provided function', () => { const value = { foo: 'bar', } expect( setProps(({ value }: { value: any }) => `updated-${value}`)(value) ).toEqual({ foo: 'updated-bar', }) }) })
23.903226
79
0.521592
da77c59b6bac0c56a1b4d33d3847e74588434984
343
php
PHP
app/Http/Controllers/Admin/PanelController.php
amirmsj1374/amarket
294b3124c2ebe950355d8a9cbc0cb63dddd1b751
[ "MIT" ]
null
null
null
app/Http/Controllers/Admin/PanelController.php
amirmsj1374/amarket
294b3124c2ebe950355d8a9cbc0cb63dddd1b751
[ "MIT" ]
4
2021-02-02T19:04:06.000Z
2022-02-27T05:40:33.000Z
app/Http/Controllers/Admin/PanelController.php
amirmsj1374/amarket
294b3124c2ebe950355d8a9cbc0cb63dddd1b751
[ "MIT" ]
null
null
null
<?php namespace App\Http\Controllers\Admin; use App\Http\Controllers\Controller; use Carbon\Carbon; use Illuminate\Http\Request; class PanelController extends Controller { public function index() { return view('admin.index'); } public function UploadImageSubject() { $year = Carbon::now()->year; } }
15.590909
42
0.670554
7d9d65eb17e97e5579a1e9e8b1c7479cd04506f4
250
swift
Swift
EditListSample/EditListSampleApp.swift
usk-sample/EditListSample
26e698b113bfe1a7c6f5f6671f86f33ad108de73
[ "MIT" ]
null
null
null
EditListSample/EditListSampleApp.swift
usk-sample/EditListSample
26e698b113bfe1a7c6f5f6671f86f33ad108de73
[ "MIT" ]
null
null
null
EditListSample/EditListSampleApp.swift
usk-sample/EditListSample
26e698b113bfe1a7c6f5f6671f86f33ad108de73
[ "MIT" ]
null
null
null
// // EditListSampleApp.swift // EditListSample // // Created by Yusuke Hasegawa on 2021/06/10. // import SwiftUI @main struct EditListSampleApp: App { var body: some Scene { WindowGroup { ContentView() } } }
13.888889
45
0.6
43aa6ad66ac9a1c19676c72a29d9838781420356
4,516
ts
TypeScript
src/engine/dataset_fakes_test.ts
rouismia/tfjs-layers
c8f12d3ae460685a66b9a7df960194a0bd77bf3b
[ "Apache-2.0" ]
null
null
null
src/engine/dataset_fakes_test.ts
rouismia/tfjs-layers
c8f12d3ae460685a66b9a7df960194a0bd77bf3b
[ "Apache-2.0" ]
null
null
null
src/engine/dataset_fakes_test.ts
rouismia/tfjs-layers
c8f12d3ae460685a66b9a7df960194a0bd77bf3b
[ "Apache-2.0" ]
null
null
null
/** * @license * Copyright 2018 Google LLC * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. * ============================================================================= */ import {Tensor} from '@tensorflow/tfjs-core'; import {describeMathCPUAndGPU} from '../utils/test_utils'; import {FakeNumericDataset} from './dataset_fakes'; import {TensorMap} from './dataset_stub'; describeMathCPUAndGPU('FakeNumericDataset', () => { it('1D features, 1D targets', async () => { const dataset = new FakeNumericDataset( {xShape: [3], yShape: [1], batchSize: 8, numBatches: 5}); for (let k = 0; k < 2; ++k) { // Run twice to make sure that calling iteartor() multiple times works. const iterator = await dataset.iterator(); for (let i = 0; i < 5; ++i) { const result = await iterator.next(); expect(result.value.length).toEqual(2); expect((result.value[0] as Tensor).shape).toEqual([8, 3]); expect((result.value[1] as Tensor).shape).toEqual([8, 1]); expect(result.done).toEqual(false); } for (let i = 0; i < 3; ++i) { const result = await iterator.next(); expect(result.value).toBeNull(); expect(result.done).toEqual(true); } } }); it('2D features, 1D targets', async () => { const dataset = new FakeNumericDataset( {xShape: [3, 4], yShape: [2], batchSize: 8, numBatches: 5}); for (let k = 0; k < 2; ++k) { // Run twice to make sure that calling iteartor() multiple times works. const iterator = await dataset.iterator(); for (let i = 0; i < 5; ++i) { const result = await iterator.next(); expect(result.value.length).toEqual(2); expect((result.value[0] as Tensor).shape).toEqual([8, 3, 4]); expect((result.value[1] as Tensor).shape).toEqual([8, 2]); expect(result.done).toEqual(false); } for (let i = 0; i < 3; ++i) { const result = await iterator.next(); expect(result.value).toBeNull(); expect(result.done).toEqual(true); } } }); it('Multiple 2D features, 1D targets', async () => { const dataset = new FakeNumericDataset({ xShape: {'input1': [3, 4], 'input2': [2, 3]}, yShape: [2], batchSize: 8, numBatches: 5 }); for (let k = 0; k < 2; ++k) { // Run twice to make sure that calling iteartor() multiple times works. const iterator = await dataset.iterator(); for (let i = 0; i < 5; ++i) { const result = await iterator.next(); expect(result.value.length).toEqual(2); const xs = result.value[0] as TensorMap; expect(xs['input1'].shape).toEqual([8, 3, 4]); expect(xs['input2'].shape).toEqual([8, 2, 3]); expect((result.value[1] as Tensor).shape).toEqual([8, 2]); expect(result.done).toEqual(false); } for (let i = 0; i < 3; ++i) { const result = await iterator.next(); expect(result.value).toBeNull(); expect(result.done).toEqual(true); } } }); it('Invalid batchSize leads to Error', () => { expect( () => new FakeNumericDataset( {xShape: [3], yShape: [1], batchSize: -8, numBatches: 5})) .toThrow(); expect( () => new FakeNumericDataset( {xShape: [3], yShape: [1], batchSize: 8.5, numBatches: 5})) .toThrow(); expect( () => new FakeNumericDataset( {xShape: [3], yShape: [1], batchSize: 0, numBatches: 5})) .toThrow(); expect( () => new FakeNumericDataset( // tslint:disable-next-line:no-any {xShape: [3], yShape: [1], batchSize: 'foo' as any, numBatches: 5})) .toThrow(); }); it('Invalid numBatches leads to Error', () => { expect( () => new FakeNumericDataset( {xShape: [3], yShape: [1], batchSize: 8, numBatches: -5})) .toThrow(); expect( () => new FakeNumericDataset( {xShape: [3], yShape: [1], batchSize: 8, numBatches: 5.5})) .toThrow(); expect( () => new FakeNumericDataset( {xShape: [3], yShape: [1], batchSize: 8, numBatches: 0})) .toThrow(); expect( () => new FakeNumericDataset( // tslint:disable-next-line:no-any {xShape: [3], yShape: [1], batchSize: 8, numBatches: 'foo' as any})) .toThrow(); }); });
35.559055
80
0.547166
d67baa0325bb20fe3127fe952bd69d28a8dcd3e5
1,485
cs
C#
test/CollectionJson.Client.Tests/CollectionJsonContentTest.cs
WebApiContrib/CollectionJson.Net
03321523e92dce0929902e4ba5ca241946a40afa
[ "Apache-2.0" ]
36
2015-01-13T18:51:12.000Z
2021-09-08T10:13:26.000Z
test/CollectionJson.Client.Tests/CollectionJsonContentTest.cs
WebApiContrib/CollectionJson.Net
03321523e92dce0929902e4ba5ca241946a40afa
[ "Apache-2.0" ]
9
2015-01-22T15:29:44.000Z
2017-04-04T16:36:00.000Z
test/CollectionJson.Client.Tests/CollectionJsonContentTest.cs
WebApiContrib/CollectionJson.Net
03321523e92dce0929902e4ba5ca241946a40afa
[ "Apache-2.0" ]
10
2015-02-24T23:41:27.000Z
2017-07-05T20:23:36.000Z
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Should; using Xunit; namespace CollectionJson.Client.Tests { public class CollectionJsonContentTest { [Fact] public async void WhenCreatingCollectionJsonContentObjectIsSerializedToCollectionJson() { var coll = new Collection(); var content = new CollectionJsonContent(coll); var stream = new MemoryStream(); await content.CopyToAsync(stream); var reader = new StreamReader(stream); stream.Position = 0; var json = reader.ReadToEnd(); json.ShouldContain("\"collection\""); } [Fact] public async void WhenCreatingCollectionJsonContentWithErrorObjectIsSerializedWithError() { var coll = new Collection() { Error = new Error() { Code = "1234", Message = "Hello world", Title = "An error occurred" } }; var content = new CollectionJsonContent(coll); var stream = new MemoryStream(); await content.CopyToAsync(stream); var reader = new StreamReader(stream); stream.Position = 0; var json = reader.ReadToEnd(); json.ShouldContain("\"error\""); } } }
30.306122
97
0.562963
527790b61eb9b7c2b44e2567eadbdf071997073f
278
rb
Ruby
db/migrate/20200515182402_create_gigs.rb
mohsinmalik568/Needpedia
6ccd3e4c391a0545dd56352dd721b4fe0d7542ca
[ "MIT" ]
1
2019-10-25T19:43:58.000Z
2019-10-25T19:43:58.000Z
db/migrate/20200515182402_create_gigs.rb
mohsinmalik568/Needpedia
6ccd3e4c391a0545dd56352dd721b4fe0d7542ca
[ "MIT" ]
19
2019-12-31T19:11:09.000Z
2022-03-31T01:09:58.000Z
db/migrate/20200515182402_create_gigs.rb
mohsinmalik568/Needpedia
6ccd3e4c391a0545dd56352dd721b4fe0d7542ca
[ "MIT" ]
5
2020-03-04T18:00:31.000Z
2021-11-22T02:52:48.000Z
class CreateGigs < ActiveRecord::Migration[6.0] def change create_table :gigs do |t| t.references :user, null: false, foreign_key: true t.string :title t.string :area_tag t.string :body t.integer :amount t.timestamps end end end
19.857143
56
0.636691
e27454bae79faea38e22499b03cecff830227070
1,017
py
Python
taxonomy-to-dot.py
jmccrae/saffron
bcf009f176713ced1d707324043124670827125b
[ "Apache-2.0" ]
17
2019-09-11T10:20:14.000Z
2022-03-24T16:48:00.000Z
taxonomy-to-dot.py
jmccrae/saffron
bcf009f176713ced1d707324043124670827125b
[ "Apache-2.0" ]
10
2020-09-02T16:20:10.000Z
2022-03-10T10:50:44.000Z
taxonomy-to-dot.py
jmccrae/saffron
bcf009f176713ced1d707324043124670827125b
[ "Apache-2.0" ]
3
2020-09-18T06:57:18.000Z
2021-06-14T17:02:58.000Z
import sys import json def gen_label(taxo, topic_wts): if "root" in taxo: if taxo["root"] in topic_wts: print(" \"%s\" [ weight=%.4f ];" % (taxo["root"], topic_wts[taxo["root"]])) else: print(" \"%s\";" % (taxo["root"])) if "children" in taxo: for child in taxo["children"]: gen_label(child, topic_wts) def gen_link(taxo): if "root" in taxo and "children" in taxo: src = taxo["root"] for child in taxo["children"]: trg = child["root"] print(" \"" + src + "\" -> \"" + trg + "\";") gen_link(child) def main(args): taxonomy = json.load(open(args[0])) if len(args) >= 2: topics = json.load(open(args[1])) topic_wts = { x["topic_string"]: x["score"] for x in topics } else: topic_wts = {} print("digraph G {") gen_label(taxonomy, topic_wts) gen_link(taxonomy) print("}") if __name__ == "__main__": main(sys.argv[1:])
24.214286
88
0.511308
25a9778d8dbe9f498312b8705d65c505dd81f7ee
2,031
js
JavaScript
services/tarearoute.js
Amatea/APIDendros
be39349ac0b2dc75a5fb7edcd45d64367c258b84
[ "MIT" ]
null
null
null
services/tarearoute.js
Amatea/APIDendros
be39349ac0b2dc75a5fb7edcd45d64367c258b84
[ "MIT" ]
null
null
null
services/tarearoute.js
Amatea/APIDendros
be39349ac0b2dc75a5fb7edcd45d64367c258b84
[ "MIT" ]
null
null
null
var express = require('express'); var Tarea = require('../dbconnection/tareaconection.js'); var tarearouter = express.Router(); tarearouter.use(function(req,res,next){ console.log('something is happening'); next(); }); tarearouter.route('/tareas') .get(function(req, res) { Tarea.find(function(err, tarea) { if (err) { return res.send(err); } res.json(tarea); }); }); tarearouter.route('/tareas') .post(function(req, res) { var tarea = new Tarea(req.body); tarea.save(function(err) { if (err) { return res.send(err); } res.send({ message: 'Tarea Added' }); }); }); tarearouter.route('/tareas') .get(function(req, res) { Tarea.find(function(err, tarea) { if (err) { return res.send(err); } res.json(tarea); }); }) .post(function(req, res) { var tarea = new Tarea(req.body); tarea.save(function(err) { if (err) { return res.send(err); } res.send({ message: 'Tarea Added' }); }); }); tarearouter.route('/tareas/:id') .put(function(req,res){ Tarea.findOne({ _id: req.params.id }, function(err, tarea) { if (err) { return res.send(err); } for (prop in req.body) { tarea[prop] = req.body[prop]; } // save the movie tarea.save(function(err) { if (err) { return res.send(err); } res.json({ message: 'Tarea updated!' }); }); }); }); tarearouter.route('/tareas/:id') .get(function(req, res) { Tarea.findOne({ _id: req.params.id}, function(err, tarea) { if (err) { return res.send(err); } res.json(tarea); }); }); tarearouter.route('/tareas/:id') .delete(function(req, res) { Tarea.remove({ _id: req.params.id }, function(err, tarea) { if (err) { return res.send(err); } res.json({ message: 'Satisfactoriamente deleted' }); }); }); module.exports = tarearouter;
20.938144
65
0.537666
daea0a2da08dea345382a6a4577d6c7ca409c105
1,328
tsx
TypeScript
packages/preview/src/components/pages/search/search-iconset.tsx
coreyward/meronex-icons
8412306ee3ef85ad8da3a0fe55181b3a2b7b307b
[ "MIT" ]
41
2020-08-05T22:26:10.000Z
2022-03-03T04:11:02.000Z
packages/preview/src/components/pages/search/search-iconset.tsx
coreyward/meronex-icons
8412306ee3ef85ad8da3a0fe55181b3a2b7b307b
[ "MIT" ]
6
2020-07-31T17:23:42.000Z
2021-11-25T12:19:39.000Z
packages/preview/src/components/pages/search/search-iconset.tsx
coreyward/meronex-icons
8412306ee3ef85ad8da3a0fe55181b3a2b7b307b
[ "MIT" ]
4
2020-07-31T07:37:59.000Z
2021-01-21T22:00:11.000Z
import Icon from "@components/@core/icon"; import loadable from "@loadable/component"; import React from "react"; import { getIcons } from "@utils/getIcons"; import SearchPageIconLoading from "./loading"; declare global { interface Window { iconSetCache: any; } } export default function SearchIconSet({ icon, query, setResults }) { let iconSetCache = window.iconSetCache; if (!iconSetCache) { window.iconSetCache = new Map(); iconSetCache = window.iconSetCache; } let IconSet = iconSetCache.get(icon.id); if (!IconSet) { IconSet = loadable.lib(() => getIcons(icon.id)); iconSetCache.set(icon.id, IconSet); } return ( <IconSet fallback={<SearchPageIconLoading />}> {({ default: icons }) => { const found = Object.keys(icons).filter((name) => name.toLowerCase().includes(query) ); return ( <> {found.map((name) => ( <Icon key={name} icon={icons[name]} name={name} /> ))} {setResults((prevResults) => { return prevResults.hasOwnProperty(icon.id) ? prevResults : { ...prevResults, [icon.id]: found.length, }; })} </> ); }} </IconSet> ); }
26.039216
68
0.545181
02954ff26fce66fce1def1ce92dfbf15a53f08d5
135
sh
Shell
install.sh
lbdm44/.dotfiles
57bc1b8d388dba461855ddd1fd4457ab0929098f
[ "MIT" ]
null
null
null
install.sh
lbdm44/.dotfiles
57bc1b8d388dba461855ddd1fd4457ab0929098f
[ "MIT" ]
null
null
null
install.sh
lbdm44/.dotfiles
57bc1b8d388dba461855ddd1fd4457ab0929098f
[ "MIT" ]
null
null
null
#!/usr/bin/env zsh pushd $DOTFILES for folder in $(echo $STOW_FOLDERS | sed "s/,/ /g") do stow -t ~ --restow $folder done popd
12.272727
51
0.622222
e030af503a6d95d1cb474d774ea843b7fcf4ea02
570
h
C
Advanced_Programming/Exercise_Sheet_03/temperatureRegulator.h
BrandnerKasper/AdvancedProgramming
e16d843ba98b1736bc8ed4d72d243d81570bea19
[ "MIT" ]
null
null
null
Advanced_Programming/Exercise_Sheet_03/temperatureRegulator.h
BrandnerKasper/AdvancedProgramming
e16d843ba98b1736bc8ed4d72d243d81570bea19
[ "MIT" ]
null
null
null
Advanced_Programming/Exercise_Sheet_03/temperatureRegulator.h
BrandnerKasper/AdvancedProgramming
e16d843ba98b1736bc8ed4d72d243d81570bea19
[ "MIT" ]
null
null
null
#ifndef A_P_EX_03_TEMPERATUREREGULATOR_H #define A_P_EX_03_TEMPERATUREREGULATOR_H #include <iostream> #include <string> class TemperatureRegulator { public: static TemperatureRegulator& instance(); void setTemperature(int temp) {temperature = temp;} int getTemperature() {return temperature;} void print() {std::cout << "The temperature is " + std::to_string(temperature) + " Celsius." << std::endl;} private: TemperatureRegulator(); ~TemperatureRegulator(); private: int temperature = 0; }; #endif //A_P_EX_03_TEMPERATUREREGULATOR_H
21.923077
111
0.733333
b3ca764e311bc07612334fcb33bb4344cd61f8ba
862
kt
Kotlin
src/main/kotlin/com/eton/ui/feature/notes/util/NoteOrder.kt
V9vek/Eton-Desktop
8035ec81d9b2f840f8d8e152b1d314c93411db24
[ "Apache-2.0" ]
3
2022-01-20T13:58:39.000Z
2022-01-21T04:54:59.000Z
src/main/kotlin/com/eton/ui/feature/notes/util/NoteOrder.kt
V9vek/Eton-Desktop
8035ec81d9b2f840f8d8e152b1d314c93411db24
[ "Apache-2.0" ]
null
null
null
src/main/kotlin/com/eton/ui/feature/notes/util/NoteOrder.kt
V9vek/Eton-Desktop
8035ec81d9b2f840f8d8e152b1d314c93411db24
[ "Apache-2.0" ]
1
2022-03-02T20:19:37.000Z
2022-03-02T20:19:37.000Z
package com.eton.util /** * Within Title, Date, Color: ASCENDING or DESCENDING type */ sealed class OrderType { object Ascending : OrderType() object Descending : OrderType() } /** * Sort notes based on TITLE, DATE, COLOR */ sealed class NoteOrder(val orderType: OrderType) { class Title(orderType: OrderType) : NoteOrder(orderType) class Date(orderType: OrderType) : NoteOrder(orderType) class Color(orderType: OrderType) : NoteOrder(orderType) /** * returns the copy of NoteOrder BUT with passed OrderType */ fun copy(orderType: OrderType): NoteOrder { return when (this) { is Title -> Title(orderType = orderType) is Date -> Date(orderType = orderType) is Color -> Color(orderType = orderType) else -> Date(orderType = orderType) } } }
21.02439
62
0.636891
4fa957f635ab169788e53dfff1024e1f7a785c3c
1,649
rb
Ruby
simple_es.rb
zephraph/peer-learning-event-sourcing
6f40fc384b627b66903fc0a18c41ff3e323b01a2
[ "MIT" ]
1
2021-04-07T15:22:01.000Z
2021-04-07T15:22:01.000Z
simple_es.rb
zephraph/peer-learning-event-sourcing
6f40fc384b627b66903fc0a18c41ff3e323b01a2
[ "MIT" ]
5
2021-04-16T13:43:26.000Z
2021-04-16T16:01:09.000Z
simple_es.rb
zephraph/peer-learning-event-sourcing
6f40fc384b627b66903fc0a18c41ff3e323b01a2
[ "MIT" ]
5
2021-04-06T17:24:35.000Z
2021-04-16T17:03:13.000Z
# rubocop:disable class AccountAggregate attr_reader :user, :amount def initialize(user:, amount:) raise ArgumentError, 'user must be a string' unless user.instance_of?(String) raise ArgumentError, 'amount must be a number' unless amount.to_f.instance_of?(Float) @user = user @amount = amount.to_f end def to_s "Account: `#{user}` | Balance: #{amount}" end def copy(**args) new_args = { user: user, amount: amount }.merge(args) self.class.new(new_args) end end class BaseEvent def apply raise 'not implemented' end end class CreateAccount < BaseEvent attr_reader :user STARTING_AMOUNT = 0 def initialize(user) @user = user end def apply(_aggregate = nil) puts "opening a new account for #{user}" AccountAggregate.new(user: user, amount: STARTING_AMOUNT) end end class AddToAccount < BaseEvent attr_reader :amount def initialize(amount) @amount = amount end def apply(aggregate) puts "adding #{amount} to #{aggregate.user}'s account" aggregate.copy(amount: aggregate.amount + amount) end end class SubtractFromAccount < BaseEvent attr_reader :amount def initialize(amount) @amount = amount end def apply(aggregate) puts "subtracting #{amount} from #{aggregate.user}'s account" aggregate.copy(amount: aggregate.amount - amount) end end # require('./simple_es.rb') # => true # => #<CreateAccount:0x00007f8bb11675d0 @user="erik"> e1 = CreateAccount.new('erik') e2 = AddToAccount.new(50) e3 = SubtractFromAccount.new(42) account = [e1, e2, e3].inject(nil) do |aggregate, event| event.apply(aggregate) end puts account
20.6125
89
0.699212
143c9a5d2a14ba26100ab368e13a454a673a0b74
553
tsx
TypeScript
src/components/JumpDialog.tsx
AhmedSayed77/bewitched
917d3b2e76346493c23e4e7ccebab9c96d3e1560
[ "MIT" ]
null
null
null
src/components/JumpDialog.tsx
AhmedSayed77/bewitched
917d3b2e76346493c23e4e7ccebab9c96d3e1560
[ "MIT" ]
null
null
null
src/components/JumpDialog.tsx
AhmedSayed77/bewitched
917d3b2e76346493c23e4e7ccebab9c96d3e1560
[ "MIT" ]
null
null
null
import React from "react"; import { AppState, SetStateFn } from "../utils"; import { InputField } from "./InputField"; type JumpDialogProps = { setAppState: SetStateFn<AppState>; jumpToOffsset: (jumpOffset: number) => void; } export const JumpDialog = ({ setAppState, jumpToOffsset }: JumpDialogProps) => { return <InputField label='Jump to (hex): ' mask={/^[0-9a-f]*$/} onEnter={address => { jumpToOffsset(parseInt(address, 16)); setAppState(AppState.Edit); }} onEscape={() => setAppState(AppState.Edit)} />; }
27.65
80
0.650995
dd9fd7cea6be6d5519698b1e935a6aaf4783cca8
13,325
java
Java
java/java-impl/src/com/intellij/javadoc/JavadocGeneratorRunProfile.java
Sajaki/intellij-community
6748af2c40567839d11fd652ec77ba263c074aad
[ "Apache-2.0" ]
1
2020-05-30T04:49:44.000Z
2020-05-30T04:49:44.000Z
java/java-impl/src/com/intellij/javadoc/JavadocGeneratorRunProfile.java
Cyril-lamirand/intellij-community
60ab6c61b82fc761dd68363eca7d9d69663cfa39
[ "Apache-2.0" ]
2
2022-02-19T09:45:05.000Z
2022-02-27T20:32:55.000Z
java/java-impl/src/com/intellij/javadoc/JavadocGeneratorRunProfile.java
Cyril-lamirand/intellij-community
60ab6c61b82fc761dd68363eca7d9d69663cfa39
[ "Apache-2.0" ]
2
2020-03-15T08:57:37.000Z
2020-04-07T04:48:14.000Z
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.javadoc; import com.intellij.analysis.AnalysisScope; import com.intellij.execution.CantRunException; import com.intellij.execution.ExecutionException; import com.intellij.execution.Executor; import com.intellij.execution.configurations.*; import com.intellij.execution.filters.ArgumentFileFilter; import com.intellij.execution.filters.RegexpFilter; import com.intellij.execution.process.OSProcessHandler; import com.intellij.execution.process.ProcessAdapter; import com.intellij.execution.process.ProcessEvent; import com.intellij.execution.process.ProcessTerminatedListener; import com.intellij.execution.runners.ExecutionEnvironment; import com.intellij.ide.BrowserUtil; import com.intellij.java.JavaBundle; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleUtilCore; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.projectRoots.JavaSdk; import com.intellij.openapi.projectRoots.JavaSdkType; import com.intellij.openapi.projectRoots.JavaSdkVersion; import com.intellij.openapi.projectRoots.Sdk; import com.intellij.openapi.projectRoots.ex.JavaSdkUtil; import com.intellij.openapi.projectRoots.ex.PathUtilEx; import com.intellij.openapi.roots.JavadocOrderRootType; import com.intellij.openapi.roots.OrderEnumerator; import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.CharsetToolkit; import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.*; import org.jetbrains.annotations.NotNull; import javax.swing.*; import java.io.*; import java.nio.charset.Charset; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; public class JavadocGeneratorRunProfile implements ModuleRunProfile { private final Project myProject; private final AnalysisScope myGenerationScope; private final JavadocConfiguration myConfiguration; public JavadocGeneratorRunProfile(Project project, AnalysisScope generationScope, JavadocConfiguration configuration) { myProject = project; myGenerationScope = generationScope; myConfiguration = configuration; } public static Sdk getSdk(@NotNull Project project) { return PathUtilEx.getAnyJdk(project); } @Override public RunProfileState getState(@NotNull Executor executor, @NotNull ExecutionEnvironment env) { return new MyJavaCommandLineState(myConfiguration, myProject, myGenerationScope, env); } @NotNull @Override public String getName() { return JavaBundle.message("javadoc.settings.title"); } @Override public Icon getIcon() { return null; } private static class MyJavaCommandLineState extends CommandLineState { private static final String INDEX_HTML = "index.html"; private final AnalysisScope myGenerationOptions; private final Project myProject; private final JavadocConfiguration myConfiguration; private final ArgumentFileFilter myArgFileFilter = new ArgumentFileFilter(); MyJavaCommandLineState(JavadocConfiguration configuration, Project project, AnalysisScope generationOptions, ExecutionEnvironment env) { super(env); myGenerationOptions = generationOptions; myProject = project; myConfiguration = configuration; addConsoleFilters( new RegexpFilter(project, "$FILE_PATH$:$LINE$:"), myArgFileFilter); } @Override @NotNull protected OSProcessHandler startProcess() throws ExecutionException { OSProcessHandler handler = JavaCommandLineStateUtil.startProcess(createCommandLine()); ProcessTerminatedListener.attach(handler, myProject, JavaBundle.message("javadoc.generate.exited")); handler.addProcessListener(new ProcessAdapter() { @Override public void processTerminated(@NotNull ProcessEvent event) { if (myConfiguration.OPEN_IN_BROWSER && event.getExitCode() == 0) { File index = new File(myConfiguration.OUTPUT_DIRECTORY, INDEX_HTML); if (index.exists()) { BrowserUtil.browse(index); } } } }); return handler; } private GeneralCommandLine createCommandLine() throws ExecutionException { GeneralCommandLine cmdLine = new GeneralCommandLine(); Sdk jdk = getSdk(myProject); setExecutable(jdk, cmdLine); setParameters(jdk, cmdLine); return cmdLine; } private void setExecutable(Sdk jdk, GeneralCommandLine cmdLine) throws ExecutionException { String binPath = jdk != null && jdk.getSdkType() instanceof JavaSdkType ? ((JavaSdkType)jdk.getSdkType()).getBinPath(jdk) : null; if (binPath == null) { throw new CantRunException(JavaBundle.message("javadoc.generate.no.jdk.path")); } cmdLine.setWorkDirectory((File)null); String toolName = SystemInfo.isWindows ? "javadoc.exe" : "javadoc"; File tool = new File(binPath, toolName); if (!tool.exists()) { tool = new File(new File(binPath).getParent(), toolName); if (!tool.exists()) { tool = new File(new File(System.getProperty("java.home")).getParent(), "bin/" + toolName); if (!tool.exists()) { throw new CantRunException(JavaBundle.message("javadoc.generate.no.jdk.path")); } } } cmdLine.setExePath(tool.getPath()); if (myConfiguration.HEAP_SIZE != null && myConfiguration.HEAP_SIZE.trim().length() != 0) { String param = JavaSdkUtil.isJdkAtLeast(jdk, JavaSdkVersion.JDK_1_2) ? "-J-Xmx" : "-J-mx"; cmdLine.getParametersList().prepend(param + myConfiguration.HEAP_SIZE + "m"); } } /* http://docs.oracle.com/javase/7/docs/technotes/tools/windows/javadoc.html#runningjavadoc */ private void setParameters(Sdk jdk, GeneralCommandLine cmdLine) throws CantRunException { ParametersList parameters = cmdLine.getParametersList(); if (myConfiguration.LOCALE != null && myConfiguration.LOCALE.length() > 0) { parameters.add("-locale"); parameters.add(myConfiguration.LOCALE); } if (myConfiguration.OPTION_SCOPE != null) { parameters.add("-" + myConfiguration.OPTION_SCOPE); } if (!myConfiguration.OPTION_HIERARCHY) { parameters.add("-notree"); } if (!myConfiguration.OPTION_NAVIGATOR) { parameters.add("-nonavbar"); } if (!myConfiguration.OPTION_INDEX) { parameters.add("-noindex"); } else if (myConfiguration.OPTION_SEPARATE_INDEX) { parameters.add("-splitindex"); } if (myConfiguration.OPTION_DOCUMENT_TAG_USE) { parameters.add("-use"); } if (myConfiguration.OPTION_DOCUMENT_TAG_AUTHOR) { parameters.add("-author"); } if (myConfiguration.OPTION_DOCUMENT_TAG_VERSION) { parameters.add("-version"); } if (!myConfiguration.OPTION_DOCUMENT_TAG_DEPRECATED) { parameters.add("-nodeprecated"); } else if (!myConfiguration.OPTION_DEPRECATED_LIST) { parameters.add("-nodeprecatedlist"); } parameters.addParametersString(myConfiguration.OTHER_OPTIONS); if (myConfiguration.OPTION_LINK_TO_JDK_DOCS) { for (String url : jdk.getRootProvider().getUrls(JavadocOrderRootType.getInstance())) { parameters.add("-link"); parameters.add(url); } } if (myConfiguration.OUTPUT_DIRECTORY != null) { parameters.add("-d"); parameters.add(myConfiguration.OUTPUT_DIRECTORY.replace('/', File.separatorChar)); } try { File argsFile = FileUtil.createTempFile("javadoc_args", null); Charset cs = CharsetToolkit.getPlatformCharset(); try (PrintWriter writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(argsFile), cs))) { Set<Module> modules = new LinkedHashSet<>(); Set<VirtualFile> sources = new HashSet<>(); Runnable r = () -> myGenerationOptions.accept(new MyContentIterator(myProject, modules, sources)); String title = JavaBundle.message("javadoc.generate.sources.progress"); if (!ProgressManager.getInstance().runProcessWithProgressSynchronously(r, title, true, myProject)) { return; } if (sources.isEmpty()) { throw new CantRunException(JavaBundle.message("javadoc.generate.no.classes.in.selected.packages.error")); } boolean hasJavaModules = sources.stream().anyMatch(f -> PsiJavaModule.MODULE_INFO_FILE.equals(f.getName())); if (hasJavaModules && modules.size() > 1) { throw new CantRunException("At the moment, IDEA cannot generate Javadoc for multiple modules" + " with module-info.java files in them. Sorry. We're working on this."); } OrderEnumerator sourcePathEnumerator = ProjectRootManager.getInstance(myProject).orderEntries(modules); if (!myConfiguration.OPTION_INCLUDE_LIBS) { sourcePathEnumerator = sourcePathEnumerator.withoutSdk().withoutLibraries(); } if (!myGenerationOptions.isIncludeTestSource()) { sourcePathEnumerator = sourcePathEnumerator.productionOnly(); } List<VirtualFile> sourceRoots = sourcePathEnumerator.getSourcePathsList().getRootDirs(); OrderEnumerator classPathEnumerator = ProjectRootManager.getInstance(myProject).orderEntries(modules).withoutModuleSourceEntries(); if (jdk.getSdkType() instanceof JavaSdk) { classPathEnumerator = classPathEnumerator.withoutSdk(); } if (!myGenerationOptions.isIncludeTestSource()) { classPathEnumerator = classPathEnumerator.productionOnly(); } List<VirtualFile> classRoots = classPathEnumerator.getPathsList().getRootDirs(); if (sourceRoots.size() + classRoots.size() > 0) { if (hasJavaModules && JavaSdkUtil.isJdkAtLeast(jdk, JavaSdkVersion.JDK_1_9)) { if (!sourceRoots.isEmpty()) { String path = sourceRoots.stream().map(MyJavaCommandLineState::localPath).collect(Collectors.joining(File.pathSeparator)); writer.println("--source-path"); writer.println(StringUtil.wrapWithDoubleQuote(path)); } if (!classRoots.isEmpty()) { String path = classRoots.stream().map(MyJavaCommandLineState::localPath).collect(Collectors.joining(File.pathSeparator)); writer.println("--module-path"); writer.println(StringUtil.wrapWithDoubleQuote(path)); } } else { // placing source roots on a classpath is perfectly legal and allows generating correct Javadoc // when a module without a module-info.java file depends on another module that has one Stream<VirtualFile> roots = Stream.concat(sourceRoots.stream(), classRoots.stream()); String path = roots.map(MyJavaCommandLineState::localPath).collect(Collectors.joining(File.pathSeparator)); writer.println("-classpath"); writer.println(StringUtil.wrapWithDoubleQuote(path)); } } for (VirtualFile source : sources) { writer.println(StringUtil.wrapWithDoubleQuote(source.getPath())); } } myArgFileFilter.setPath(argsFile.getPath(), cs); parameters.add("@" + argsFile.getPath()); OSProcessHandler.deleteFileOnTermination(cmdLine, argsFile); cmdLine.setCharset(cs); } catch (IOException e) { throw new CantRunException(JavaBundle.message("javadoc.generate.temp.file.error"), e); } } private static String localPath(VirtualFile root) { // @argfile require forward slashes in quoted paths return VfsUtil.getLocalFile(root).getPath(); } } private static class MyContentIterator extends PsiRecursiveElementWalkingVisitor { private final PsiManager myPsiManager; private final Set<? super Module> myModules; private final Set<? super VirtualFile> mySourceFiles; MyContentIterator(Project project, Set<? super Module> modules, Set<? super VirtualFile> sources) { myPsiManager = PsiManager.getInstance(project); myModules = modules; mySourceFiles = sources; } @Override public void visitFile(@NotNull PsiFile file) { if (file instanceof PsiJavaFile && !(file instanceof ServerPageFile)) { VirtualFile vFile = file.getVirtualFile(); if (vFile != null && vFile.isInLocalFileSystem()) { mySourceFiles.add(vFile); Module module = ModuleUtilCore.findModuleForFile(vFile, myPsiManager.getProject()); if (module != null) { myModules.add(module); } } } } } }
41.126543
141
0.693659
b8f16da7d6ed337d9149f4dbc8e8ff9181270c74
11,989
h
C
engine/src/base/log/logger.h
Oghma/speect
f618e8d651cb9ec4c90cc244af3e7aa993599f6d
[ "BSD-2-Clause", "BSD-3-Clause" ]
5
2016-01-29T14:39:46.000Z
2019-04-24T14:45:55.000Z
engine/src/base/log/logger.h
Oghma/speect
f618e8d651cb9ec4c90cc244af3e7aa993599f6d
[ "BSD-2-Clause", "BSD-3-Clause" ]
null
null
null
engine/src/base/log/logger.h
Oghma/speect
f618e8d651cb9ec4c90cc244af3e7aa993599f6d
[ "BSD-2-Clause", "BSD-3-Clause" ]
7
2015-09-17T14:45:05.000Z
2020-03-30T13:19:29.000Z
/************************************************************************************/ /* Copyright (c) 2008-2011 The Department of Arts and Culture, */ /* The Government of the Republic of South Africa. */ /* */ /* Contributors: Meraka Institute, CSIR, South Africa. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining a copy */ /* of this software and associated documentation files (the "Software"), to deal */ /* in the Software without restriction, including without limitation the rights */ /* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell */ /* copies of the Software, and to permit persons to whom the Software is */ /* furnished to do so, subject to the following conditions: */ /* The above copyright notice and this permission notice shall be included in */ /* all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR */ /* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, */ /* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE */ /* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER */ /* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, */ /* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN */ /* THE SOFTWARE. */ /* */ /************************************************************************************/ /* */ /* AUTHOR : Aby Louw */ /* DATE : 29 September 2009 */ /* */ /************************************************************************************/ /* */ /* Basic logging facilities. */ /* */ /* */ /************************************************************************************/ #ifndef _SPCT_LOGGER_H__ #define _SPCT_LOGGER_H__ /** * @file logger.h * Basic logging facilities. */ /** * @ingroup SLogging * @defgroup SLogger Loggers * Basic logging facilities. * The logging system provides a very basic mechanism to write * messages to different types of streams. It is used by all the error * and debug reporting facilities in @ref SErrDbg, and therefore aims * to be as robust as possible. If any error occurs during one of the * logger functions, an error will be printed to @c stderr. If a * logger is unsuccessful at writing the log message to the log stream * then it will log the message to @c stdout. * * @{ */ /************************************************************************************/ /* */ /* Modules used */ /* */ /************************************************************************************/ #include <stdarg.h> #include "include/common.h" #include "base/errdbg/errdbg_defs.h" /************************************************************************************/ /* */ /* Begin external c declaration */ /* */ /************************************************************************************/ S_BEGIN_C_DECLS /************************************************************************************/ /* */ /* Logger object */ /* */ /************************************************************************************/ /** * Opaque data type for logger private info. Defined by each logger as * required. */ typedef struct s_logger_private_info s_logger_private_info; /* forward declaration */ typedef struct s_logger s_logger; /** * The s_logger structure definition. The logger consists of private * data which can be anything required by the specific implementation, * as it is only defined as an opaque type. The different logger * implementations must implement the function pointers as described. * If any error occurs during one of the logger functions, the logger * must try and continue and print the error to @c stderr. */ struct s_logger { /** * Logger private data. Defined by each logger as * required (opaque type). */ s_logger_private_info *data; /** * Format and write the given logging event information to the * logger. Must be implemented by each logger as it is called by * #s_logger_vwrite and #s_logger_write. If the message cannot be * formatted or written successfully then the calling function * (#s_logger_vwrite or #s_logger_write) will attemp to write the * message to @c stdout. * * @param self This logger object. * @param level The event level. * @param error_msg As defined by #s_erc. * @param func_name Calling function name. * @param file_name Calling function file name. * @param line_num Calling line number in function. * @param user_msg A format string specifying the string to write * and the format of the arguments in the va_list. * @param argp The va_list, see the standard function @c * vprintf(). The value of argp is undefined after the call to * this function. * * @return Error code. */ s_erc (*v_write)(const s_logger *self, s_log_event level, const char *error_msg, const char *func_name, const char *file_name, int line_num, const char *user_msg, va_list argp); /** * Destroy the logger object's associated resources. The logger's * memory itself must @b not be freed. Must be implemented by * each logger as it is called by #s_logger_destroy. * * @param logger This logger object. * * @return Error code. */ s_erc (*destroy)(s_logger *self); }; /************************************************************************************/ /* */ /* Function prototypes */ /* */ /************************************************************************************/ /** * @name Logger Creators * @{ */ /** * Create a new file stream logger. The logging * message will be in the standard layout format. * * @param path The full path and file name of the file which to * log to. If the file already exists, then it will be overwritten. * * @return Pointer to newly created file stream logger, or #NULL on error. * * @note Only thread safe if compiled with threading library, and * whether the standard ISO C vfprintf() function is thread-safe, * see @ref SThreads. * * @sa @ref SFileStream, @ref SLayoutStd * * @todo check MT safety */ S_API s_logger *s_logger_file_new(const char *path); /** * Create a new console stream logger. The logging message will be in * the standard layout format. * * @param log_to_stdout If #TRUE then logging will be to @c stdout, * otherwise streaming will be to @c stderr. * * @return Pointer to newly created console stream logger, or #NULL * on error. * * @note Only thread safe if compiled with threading library, and * whether the standard ISO C vfprintf() function is thread-safe, * see @ref SThreads. * * @sa @ref SConsoleStream, @ref SLayoutStd * * @todo check MT safety */ S_API s_logger *s_logger_console_new(s_bool log_to_stdout); /** * Create a new null logger. A null logger does not log any messages. * * @return Pointer to newly created null logger, or #NULL on error. * * @note The null logger must be destroyed (#s_logger_destroy) and * freed in the same manner as the other loggers. */ S_API s_logger *s_logger_null_new(void); /** * @} */ /** * @name Logging Functions * @{ */ /** * Format and write the given logging event information to the * logger. * * @param logger The logger to write to. * @param level The event level. * @param error_msg As defined by #s_erc. * @param func_name Calling function name. * @param file_name Calling function file name. * @param line_num Calling line number in function. * @param user_msg A format string specifying the string to write and * the format of the variable length argument list. Same as the the * standard @c printf() function. * * @return Error code. */ S_API s_erc s_logger_write(const s_logger *logger, s_log_event level, const char *error_msg, const char *func_name, const char *file_name, int line_num, const char *user_msg, ...); /** * Format and write the given logging event information to the * logger (called with @a va_list). Equivalent to the #s_logger_write * except that it is called with a va_list instead of a variable * number of arguments, same as the standard function @c vprintf(). * * @param logger The logger to write to. * @param level The event level. * @param error_msg As defined by #s_erc. * @param func_name Calling function name. * @param file_name Calling function file name. * @param line_num Calling line number in function. * @param user_msg A format string specifying the string to write * and the format of the arguments in the va_list. * @param argp The va_list, see the standard function * ISO C @c vprintf(). The value of @c argp is undefined after the call * to this function. * * @return Error code. */ S_API s_erc s_logger_vwrite(const s_logger *logger, s_log_event level, const char *error_msg, const char *func_name, const char *file_name, int line_num, const char *user_msg, va_list argp); /** * @} */ /** * @name Logger Destroyer * @{ */ /** * Destroy the given logger's associated resources. The logger @b must * still be free'd with #S_FREE after this call. * * @param logger The logger object's resources to destroy. * * @return error Error code. * * @note Thread-safety is dependent on the underlying implementation. */ S_API s_erc s_logger_destroy(s_logger *logger); /** * @} */ /************************************************************************************/ /* */ /* End external c declaration */ /* */ /************************************************************************************/ S_END_C_DECLS /** * @} * end documentation */ #endif /* _SPCT_LOGGER_H__ */
37.003086
93
0.498791
2b7b040e676fd2af611cec607fd19e754f1f48d4
2,014
cs
C#
AegisBot/Implementations/ServiceFactory.cs
thomasonb/AegisBot
26f46484149e80cb0cab939a86f08ae2120461d9
[ "MIT" ]
null
null
null
AegisBot/Implementations/ServiceFactory.cs
thomasonb/AegisBot
26f46484149e80cb0cab939a86f08ae2120461d9
[ "MIT" ]
3
2017-03-03T21:10:51.000Z
2017-04-12T17:36:53.000Z
AegisBot/Implementations/ServiceFactory.cs
thomasonb/AegisBot
26f46484149e80cb0cab939a86f08ae2120461d9
[ "MIT" ]
null
null
null
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using AegisBot.Interfaces; using Discord; using System.IO; using Newtonsoft.Json; using System.Reflection; namespace AegisBot.Implementations { public class ServiceFactory { private static string saveDir = new DirectoryInfo(Assembly.GetExecutingAssembly().Location).Parent?.Parent?.Parent?.FullName + "\\Services"; public static List<IAegisService> Services = new List<IAegisService>(); public static List<IAegisService> GetServicesForCommand(string command) { return Services.Where(x => x.ContainsCommand(command)).ToList(); } public static IAegisService GetService<T>() where T : IAegisService { return Services.FirstOrDefault(x => x.GetType() == typeof(T)); } public static IAegisService GetService(string ServiceName) { return Services.FirstOrDefault(x => x.GetType().Name.ToLower() == ServiceName.ToLower()); } public static void LoadService<T>(DiscordClient client) where T : IAegisService { string ServiceFile = Directory.GetFiles(saveDir).FirstOrDefault(x => x.Substring(0, x.IndexOf(".")).Contains(typeof(T).Name)); IAegisService service; if (ServiceFile != null) { using (StreamReader sr = new StreamReader(ServiceFile)) { service = JsonConvert.DeserializeObject<T>(sr.ReadToEnd()); } } else { service = Activator.CreateInstance<T>(); } if (!Services.Any(x => x.GetType() == typeof(T))) { Services.Add(service); service.SaveService(); } service.LoadCommands(); (Services.First(x => x.GetType() == typeof(T)) as AegisService).Client = client; } } }
32.483871
148
0.596326
6dab9326812d9bdad372f2f07f2c38bf5b88db76
4,041
ts
TypeScript
client/app/signup/signup.component.ts
pontsoleil/wuwei
54c4997a95fbd3ae8e97a6a73534288c65b34611
[ "MIT" ]
null
null
null
client/app/signup/signup.component.ts
pontsoleil/wuwei
54c4997a95fbd3ae8e97a6a73534288c65b34611
[ "MIT" ]
4
2015-03-12T23:48:09.000Z
2020-09-01T22:23:27.000Z
client/app/signup/signup.component.ts
pontsoleil/WuWei
54c4997a95fbd3ae8e97a6a73534288c65b34611
[ "MIT" ]
null
null
null
import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms'; import { Router } from '@angular/router'; import { CognitoUserService } from '../services'; import { ToastService } from '../mdb-type/pro/alerts'; @Component({ selector: 'app-signup', templateUrl: './signup.component.html', styleUrls: ['./signup.component.scss'] }) export class SignupComponent implements OnInit { public signupForm: FormGroup; public successfullySignup: boolean; public name = new FormControl('', [ Validators.required, ]); public nickname = new FormControl('', [ Validators.required, ]); public email = new FormControl('', [ Validators.required, Validators.pattern('^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$') ]); public password = new FormControl('', [ Validators.required, // Validators.minLength(8), // minLength doesn't work Validators.pattern('^(?=.*[a-z])(?=.*[A-Z])(?!.*\s).{8,}$') // MUST contain both upper and lower case letter ]); // see https://www.concretepage.com/angular-2/angular-2-4-pattern-validation-example#formControl // and https://regex101.com/r/uE5lT4/4 for testing get name_() { return this.signupForm.get('name'); } get nickname_() { return this.signupForm.get('nickname'); } get email_() { return this.signupForm.get('email'); } get password_() { return this.signupForm.get('password'); } public confirmationForm: FormGroup; public name2 = new FormControl('', [ Validators.required, ]); public confirmationCode = new FormControl('', [ Validators.required, ]); get name2_() { return this.signupForm.get('name2'); } get confirmationCode_() { return this.signupForm.get('confirmationCode'); } constructor( private fb: FormBuilder, private router: Router, private toast: ToastService, private auth: CognitoUserService ) { } ngOnInit() { this.initForm(); const tab1 = document.querySelector('.nav-item a[href="#panel1"]'); const tab2 = document.querySelector('.nav-item a[href="#panel2"]'); const panel1 = document.getElementById('panel1'); const panel2 = document.getElementById('panel2'); tab1.addEventListener('click', (evt) => { evt.preventDefault(); panel1.classList.add('active'); panel2.classList.remove('active'); }, false); tab2.addEventListener('click', (evt) => { evt.preventDefault(); panel1.classList.remove('active'); panel2.classList.add('active'); }, false); } initForm() { this.signupForm = this.fb.group({ 'name': this.name, 'nickname': this.nickname, 'email': this.email, 'password': this.password }); this.confirmationForm = this.fb.group({ 'name2': this.name2, 'confirmationCode': this.confirmationCode }); } onSubmitSignup(value: any) { const name = value.name, nickname = value.nickname, email = value.email, password = value.password; this.auth .signUp(name, nickname, email, password) .then((result) => { console.log(result); this.toastMessage('Register finished.', 'success'); this.successfullySignup = true; }) .catch((err) => { this.toastMessage(err.message, 'error'); console.log(err); }); } onSubmitConfirmation(value: any) { const name2 = value.name2, confirmationCode = value.confirmationCode; console.log(name2); this.auth .confirmation(name2, confirmationCode) .then((result) => { return console.log(result) || this.router.navigate(['/signin']); }) .catch((err) => { console.log(err); }); } close() { return this.router.navigate(['/']); } toastMessage(message: string, action: string) { const options = { closeButton: true, positionClass: 'toast-bottom-center' }; this.toast[action](message, action.toUpperCase(), options); } }
30.383459
112
0.62831
0720b50d4639bd9e83ea7973b875bc91dc954636
1,094
lua
Lua
premake5.lua
AlexSierraTI/freetype-gl
0b48c369f10f73104740bd0f1380aecf1413af9e
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
premake5.lua
AlexSierraTI/freetype-gl
0b48c369f10f73104740bd0f1380aecf1413af9e
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
premake5.lua
AlexSierraTI/freetype-gl
0b48c369f10f73104740bd0f1380aecf1413af9e
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
project "freetype-gl" kind "StaticLib" language "C" staticruntime "on" targetdir ("bin/" .. outputdir .. "/%{prj.name}") objdir ("bin-int/" .. outputdir .. "/%{prj.name}") files { "distance-field.h", "edtaa3func.h", "font-manager.h", "freetype-gl.h", "markup.h", "opengl.h", "platform.h", "text-buffer.h", "texture-atlas.h", "texture-font.h", "utf8-utils.h", "vec234.h", "vector.h", "vertex-attribute.h", "vertex-buffer.h", "distance-field.c", "edtaa3func.c", "font-manager.c", "platform.c", "text-buffer.c", "texture-atlas.c", "texture-font.c", "utf8-utils.c", "vector.c", "vertex-attribute.c", "vertex-buffer.c" } defines { "_CRT_SECURE_NO_WARNINGS", "_CRT_NONSTDC_NO_DEPRECATE", "FREETYPE_GL_USE_VAO", "GL_WITH_GLAD" } includedirs { "windows/glew", "windows/glew/include", "windows/freetype", "../glad/include" } filter "system:windows" systemversion "latest" filter "configurations:Debug" runtime "Debug" symbols "on" filter "configurations:Release" runtime "Release" optimize "on"
16.575758
51
0.630713
427e84dda2b18d5c8ad6deae82be9192957ea208
91
sql
SQL
packages/notifications/sql/postgresql/upgrade/upgrade-5.8.1d3-5.8.1d4.sql
iuri/tutortronics
463ea1535773d06ce34d269136eab3ecaffcb1cf
[ "Info-ZIP", "ImageMagick" ]
null
null
null
packages/notifications/sql/postgresql/upgrade/upgrade-5.8.1d3-5.8.1d4.sql
iuri/tutortronics
463ea1535773d06ce34d269136eab3ecaffcb1cf
[ "Info-ZIP", "ImageMagick" ]
null
null
null
packages/notifications/sql/postgresql/upgrade/upgrade-5.8.1d3-5.8.1d4.sql
iuri/tutortronics
463ea1535773d06ce34d269136eab3ecaffcb1cf
[ "Info-ZIP", "ImageMagick" ]
null
null
null
select define_function_args ('notification_delivery_method__delete','delivery_method_id');
45.5
90
0.879121
39b054c57e5e13c4f2a2570f32079c3f9d312e67
739
ps1
PowerShell
data/test/powershell/39b054c57e5e13c4f2a2570f32079c3f9d312e67Invoke-ZapApiRequest.ps1
aliostad/deep-learning-lang-detection
d6b031f3ebc690cf2ffd0ae1b08ffa8fb3b38a62
[ "MIT" ]
84
2017-10-25T15:49:21.000Z
2021-11-28T21:25:54.000Z
data/test/powershell/39b054c57e5e13c4f2a2570f32079c3f9d312e67Invoke-ZapApiRequest.ps1
vassalos/deep-learning-lang-detection
cbb00b3e81bed3a64553f9c6aa6138b2511e544e
[ "MIT" ]
5
2018-03-29T11:50:46.000Z
2021-04-26T13:33:18.000Z
data/test/powershell/39b054c57e5e13c4f2a2570f32079c3f9d312e67Invoke-ZapApiRequest.ps1
vassalos/deep-learning-lang-detection
cbb00b3e81bed3a64553f9c6aa6138b2511e544e
[ "MIT" ]
24
2017-11-22T08:31:00.000Z
2022-03-27T01:22:31.000Z
<# .Synopsis This Script will Invoke ZAP API And will be call by various other scripts which needs to access ZAP API .Example .\Invoke-ZapApiRequest [URL to attack] [Proxy from ZAP] .Notes Author: Mrityunjaya Pathak Date : March 2015 #> param( #Url on which ZAP operation will be performed(only http url) $URL =$(throw "Missing URL value"), #ZAP Proxy URI $proxy="http://localhost:8080", #stop ZAP if any error occurs [switch]$KillZapOnError ) try{ Invoke-WebRequest -uri $url -Proxy $proxy # write-host $s } catch{ Write-Warning "$(get-date) $PSCommandPath : Invoke-Webrequest failed. $_" if($KillZapOnError.IsPresent){ Stop-Zap -killonly } }
26.392857
111
0.648173
e75283b5518769744a5f20aac9630bbb0da6291f
1,648
php
PHP
src/FondOfSpryker/Yves/Contentful/Router/ResourceCreator/BlogTagResourceCreator.php
fond-of/spryker-contentful
e293fb40814805433972dfe2b3a652ba6e07f9c6
[ "MIT" ]
4
2018-03-06T09:51:23.000Z
2019-12-17T11:16:39.000Z
src/FondOfSpryker/Yves/Contentful/Router/ResourceCreator/BlogTagResourceCreator.php
fond-of/spryker-contentful
e293fb40814805433972dfe2b3a652ba6e07f9c6
[ "MIT" ]
null
null
null
src/FondOfSpryker/Yves/Contentful/Router/ResourceCreator/BlogTagResourceCreator.php
fond-of/spryker-contentful
e293fb40814805433972dfe2b3a652ba6e07f9c6
[ "MIT" ]
null
null
null
<?php namespace FondOfSpryker\Yves\Contentful\Router\ResourceCreator; use Silex\Application; use Spryker\Shared\Application\Communication\ControllerServiceBuilder; use Spryker\Yves\Kernel\BundleControllerAction; use Spryker\Yves\Kernel\ClassResolver\Controller\ControllerResolver; use Spryker\Yves\Kernel\Controller\BundleControllerActionRouteNameResolver; class BlogTagResourceCreator implements ResourceCreatorInterface { private const RESOURCE_TYPE = 'blog'; private const CONTROLLER_METHOD = 'tag'; /** * @return string */ public function getType(): string { return static::RESOURCE_TYPE . ucfirst(static::CONTROLLER_METHOD); } /** * @param \Silex\Application $application * @param string[] $data * * @return string[] */ public function createResource(Application $application, array $data): array { if ($data['type'] !== $this->getType()) { return []; } $bundleControllerAction = new BundleControllerAction('Contentful', static::RESOURCE_TYPE, static::CONTROLLER_METHOD); $routeNameResolver = new BundleControllerActionRouteNameResolver($bundleControllerAction); $controllerResolver = new ControllerResolver(); $controllerServiceBuilder = new ControllerServiceBuilder(); $service = $controllerServiceBuilder->createServiceForController($application, $bundleControllerAction, $controllerResolver, $routeNameResolver); return [ '_controller' => $service, '_route' => $routeNameResolver->resolve(), 'entryId' => $data['value'], ]; } }
32.96
153
0.695388
f42a8b5dcd1138bcf55c131a9d2f0c307ce26e3d
2,836
cs
C#
LoggerVM.cs
DannyD98/PS-C-WPF-Logger-app
b12956439c80a0062a9d7a3047a5bcc460dabbb8
[ "MIT" ]
null
null
null
LoggerVM.cs
DannyD98/PS-C-WPF-Logger-app
b12956439c80a0062a9d7a3047a5bcc460dabbb8
[ "MIT" ]
null
null
null
LoggerVM.cs
DannyD98/PS-C-WPF-Logger-app
b12956439c80a0062a9d7a3047a5bcc460dabbb8
[ "MIT" ]
null
null
null
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.IO; using System.Runtime.CompilerServices; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Input; namespace WpfLogger { public class LoggerVM : INotifyPropertyChanged { private LoggerModel _model = new LoggerModel(String.Empty, DateTime.Now); public LoggerModel model { get { return _model; } set { OnPropertyChanged("model"); } } public string logInput { get { return model.Message; } set { model.Message = value; OnPropertyChanged("logInput"); } } private ObservableCollection<string> _LoggedData = new ObservableCollection<string>(); public ObservableCollection<string> LoggedData { get { return _LoggedData; } } public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged([CallerMemberName]string propertyName = null) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName)); } public ICommand LogText { get { return new DelegateCommand(LogActivity); } } public ICommand getLog { get { return new DelegateCommand(readLog); } } public ICommand clearLog { get { return new DelegateCommand(clearLogFile); } } public void LogActivity() { model.Date = DateTime.Now; string LogMessage = model.Date.ToShortTimeString() + ", " + model.Date.ToShortDateString() + " " + logInput + "\n"; if (File.Exists("LogFile.txt")) { File.AppendAllText("LogFile.txt", LogMessage); } logInput = String.Empty; } public void readLog() { StreamReader sr = new StreamReader("LogFile.txt"); string readData = String.Empty; LoggedData.Clear(); while (sr.EndOfStream != true) { readData = sr.ReadLine(); if (readData != null) { LoggedData.Add(readData); } } sr.Close(); } public void clearLogFile() { LoggedData.Clear(); File.WriteAllText("LogFile.txt", String.Empty); } } }
28.36
128
0.528209
7cd24044fb4b6191c30724087c87ddb621625914
13,007
ps1
PowerShell
function_Get-VtGroup.ps1
kmsigma/vtPowerShell
b5329057ecb1b8654925a824beecbd2bc3e5fec5
[ "MIT" ]
1
2021-11-12T14:51:00.000Z
2021-11-12T14:51:00.000Z
function_Get-VtGroup.ps1
kmsigma/vtPowerShell
b5329057ecb1b8654925a824beecbd2bc3e5fec5
[ "MIT" ]
null
null
null
function_Get-VtGroup.ps1
kmsigma/vtPowerShell
b5329057ecb1b8654925a824beecbd2bc3e5fec5
[ "MIT" ]
null
null
null
function Get-VtGroup { <# .Synopsis Get groups from Verint / Telligent communities .DESCRIPTION Long description .EXAMPLE Example of how to use this cmdlet .EXAMPLE Another example of how to use this cmdlet .INPUTS Inputs to this cmdlet (if any) .OUTPUTS Output from this cmdlet (if any) .NOTES https://community.telligent.com/community/11/w/api-documentation/64702/list-group-rest-endpoint .COMPONENT The component this cmdlet belongs to .ROLE The role this cmdlet belongs to .FUNCTIONALITY The functionality that best describes this cmdlet #> [CmdletBinding(DefaultParameterSetName = 'Group by Name with Connection File', SupportsShouldProcess = $true, PositionalBinding = $false, HelpUri = 'https://community.telligent.com/community/11/w/api-documentation/64699/group-rest-endpoints', ConfirmImpact = 'Medium')] [Alias()] [OutputType()] Param ( # Get group by name [Parameter(Mandatory = $true, ParameterSetName = 'Group by Name with Authentication Header')] [Parameter(Mandatory = $true, ParameterSetName = 'Group by Name with Connection Profile')] [Parameter(Mandatory = $true, ParameterSetName = 'Group by Name with Connection File')] [Alias("Name")] [string[]]$GroupName, # Group name exact match [Parameter(Mandatory = $false, ParameterSetName = 'Group by Name with Authentication Header')] [Parameter(Mandatory = $false, ParameterSetName = 'Group by Name with Connection Profile')] [Parameter(Mandatory = $false, ParameterSetName = 'Group by Name with Connection File')] [switch]$ExactMatch, # Get group by id number [Parameter(Mandatory = $true, ParameterSetName = 'Group by Id with Authentication Header')] [Parameter(Mandatory = $true, ParameterSetName = 'Group by Id with Connection Profile')] [Parameter(Mandatory = $true, ParameterSetName = 'Group by Id with Connection File')] [Alias("Id")] [int[]]$GroupId, # Community Domain to use (include trailing slash) Example: [https://yourdomain.telligenthosted.net/] [Parameter(Mandatory = $true, ParameterSetName = 'Group by Name with Authentication Header')] [Parameter(Mandatory = $true, ParameterSetName = 'Group by Id with Authentication Header')] [ValidateNotNull()] [ValidateNotNullOrEmpty()] [ValidatePattern('^(http:\/\/|https:\/\/)(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])\/$')] [Alias("Community")] [string]$VtCommunity, # Authentication Header for the community [Parameter(Mandatory = $true, ParameterSetName = 'Group by Name with Authentication Header')] [Parameter(Mandatory = $true, ParameterSetName = 'Group by Id with Authentication Header')] [ValidateNotNull()] [ValidateNotNullOrEmpty()] [System.Collections.Hashtable]$VtAuthHeader, [Parameter(Mandatory = $true, ParameterSetName = 'Group by Name with Connection Profile')] [Parameter(Mandatory = $true, ParameterSetName = 'Group by Id with Connection Profile')] [ValidateNotNull()] [ValidateNotNullOrEmpty()] [System.Management.Automation.PSObject]$Connection, # File holding credentials. By default is stores in your user profile \.vtPowerShell\DefaultCommunity.json [Parameter(ParameterSetName = 'Group by Name Connection File')] [Parameter(ParameterSetName = 'Group by Id with Connection File')] [string]$ProfilePath = ( $env:USERPROFILE ? ( Join-Path -Path $env:USERPROFILE -ChildPath ".vtPowerShell\DefaultCommunity.json" ) : ( Join-Path -Path $env:HOME -ChildPath ".vtPowerShell/DefaultCommunity.json" ) ), # Should we return all details? [Parameter()] [switch]$ReturnDetails, # Number of entries to get per batch (default of 20) [Parameter()] [ValidateRange(1, 100)] [int]$BatchSize = 20, # Get all groups [Parameter()] [ValidateSet("Joinless", "PublicOpen", "PublicClosed", "PrivateUnlisted", "PrivateListed", "All")] [Alias("Type")] [string]$GroupType = "All", # Should I recurse into child groups? Default is false [Parameter(ParameterSetName = 'Group by Id with Authentication Header')] [Parameter(ParameterSetName = 'Group by Id with Connection Profile')] [Parameter(ParameterSetName = 'Group by Id with Connection File')] [switch]$Recurse, # Sort By [Parameter( Mandatory = $false, ValueFromPipeline = $false, ValueFromPipelineByPropertyName = $false, ValueFromRemainingArguments = $false )] [ValidateSet('Name', 'SortOrder', 'LastUpdate', 'ContentIdsOrder')] [string]$SortBy = 'Name', # Sort Order [Parameter( Mandatory = $false, ValueFromPipeline = $false, ValueFromPipelineByPropertyName = $false, ValueFromRemainingArguments = $false )] [ValidateSet('Ascending', 'Descending')] [string]$SortOrder = 'Ascending' ) BEGIN { switch -wildcard ( $PSCmdlet.ParameterSetName ) { '* Connection File' { Write-Verbose -Message "Getting connection information from Connection File ($ProfilePath)" $VtConnection = Get-Content -Path $ProfilePath | ConvertFrom-Json $Community = $VtConnection.Community # Check to see if the VtAuthHeader is empty $AuthHeaders = @{ } $VtConnection.Authentication.PSObject.Properties | ForEach-Object { $AuthHeaders[$_.Name] = $_.Value } } '* Connection Profile' { Write-Verbose -Message "Getting connection information from Connection Profile" $Community = $Connection.Community $AuthHeaders = $Connection.Authentication } '* Authentication Header' { Write-Verbose -Message "Getting connection information from Parameters" $Community = $VtCommunity $AuthHeaders = $VtAuthHeader } } # Check the authentication header for any 'Rest-Method' and revert to a traditional "get" $VtAuthHeader = $AuthHeaders | Update-VtAuthHeader -RestMethod Get -Verbose:$false -WhatIf:$false $UriParameters = @{} $UriParameters['PageSize'] = $BatchSize $UriParameters['PageIndex'] = 0 $UriParameters['GroupTypes'] = $GroupType if ( $ParentGroupId ) { $UriParameters['ParentGroupId'] = $ParentGroupId } if ( $Recurse ) { $UriParameters['IncludeAllSubGroups'] = 'true' } if ( $SortOrder ) { $UriParameters['SortOrder'] = $SortOrder } if ( $SortBy ) { $UriParameters['SortBy'] = $SortBy } $PropertiesToReturn = @( @{ Name = "GroupId"; Expression = { $_.Id } }, @{ Name = "Name"; Expression = { [System.Web.HttpUtility]::HtmlDecode( $_.Name ) } }, "Key", @{ Name = "Description"; Expression = { [System.Web.HttpUtility]::HtmlDecode( $_.Description ) } }, "DateCreated", "Url", "GroupType", "ParentGroupId" ) } PROCESS { switch -Wildcard ( $PSCmdlet.ParameterSetName ) { 'Group by Name *' { ForEach ( $Name in $GroupName ) { $Uri = 'api.ashx/v2/groups.json' $UriParameters['GroupNameFilter'] = $Name $GroupCount = 0 do { Write-Verbose -Message "Making call with '$Uri'" # Get the list of groups with matching name from the call $GroupsResponse = Invoke-RestMethod -Uri ( $Community + $Uri + '?' + ( $UriParameters | ConvertTo-QueryString ) ) -Headers $AuthHeaders if ( $GroupsResponse ) { $GroupCount += $GroupsResponse.Groups.Count # If we need an exact response on the name, then filter for only that exact group if ( $ExactMatch ) { $GroupsResponse.Groups = $GroupsResponse.Groups | Where-Object { [System.Web.HttpUtility]::HtmlDecode( $_.Name ) -eq $Name } } # Should we return everything? if ( $ReturnDetails ) { $GroupsResponse.Groups } else { $GroupsResponse.Groups | Select-Object -Property $PropertiesToReturn } } $UriParameters['PageIndex']++ Write-Verbose -Message "Incrementing Page Index :: $( $UriParameters['PageIndex'] )" } while ( $GroupCount -lt $GroupsResponse.TotalCount ) } } 'Group by Id *' { ForEach ( $Id in $GroupId ) { # Setup the URI - depends on if we are using a parent ID or not if ( $ParentGroupId ) { $Uri = "api.ashx/v2/groups/$ParentGroupId/groups/$Id.json" } else { $Uri = "api.ashx/v2/groups/$Id.json" } # Because everything is encoded in the URI, we don't need to send any $UriParameters Write-Verbose -Message "Making call with '$Uri'" $GroupsResponse = Invoke-RestMethod -Uri ( $Community + $Uri ) -Headers $AuthHeaders -Verbose:$false # Filter if we are using the parent group id if ( $ParentGroupId ) { $GroupsResponse.Group = $GroupsResponse.Group | Where-Object { $_.ParentGroupId -eq $ParentGroupId } } if ( $GroupsResponse.Group ) { if ( $ReturnDetails ) { $GroupsResponse.Group } else { $GroupsResponse.Group | Select-Object -Property $PropertiesToReturn } } else { Write-Warning -Message "No matching groups found for ID: $Id" } } } 'Default' { # No ForEach loop needed here because we are pulling all groups $Uri = 'api.ashx/v2/groups.json' $GroupCount = 0 do { $GroupsResponse = Invoke-RestMethod -Uri ( $Community + $Uri + '?' + ( $UriParameters | ConvertTo-QueryString ) ) -Headers $AuthHeaders -Verbose:$false if ( $ResolveParentName ) { # This calls itself to get the parent group name $GroupsResponse.Groups | Add-Member -MemberType ScriptProperty -Name "ParentGroupName" -Value { Get-VtGroup -GroupId $this.ParentGroupId | Select-Object -Property @{ Name = "Name"; Expression = { [System.Web.HttpUtility]::HtmlDecode( $_.Name ) } } | Select-Object -ExpandProperty Name } -Force } if ( $GroupsResponse ) { $GroupCount += $GroupsResponse.Groups.Count if ( $ParentGroupId ) { $GroupsResponse.Groups = $GroupsResponse.Groups | Where-Object { $_.ParentGroupId -eq $ParentGroupId } } if ( $ReturnDetails ) { $GroupsResponse.Groups } else { $GroupsResponse.Groups | Select-Object -Property $PropertiesToReturn } } $UriParameters['PageIndex']++ Write-Verbose -Message "Incrementing Page Index :: $( $UriParameters['PageIndex'] )" } while ( $GroupCount -lt $GroupsResponse.TotalCount ) } } if ( $PSCmdlet.ShouldProcess( "On this target --> Target", "Did this thing --> Operation" ) ) { } } END { # Nothing to see here } }
45.320557
317
0.538018
de2fe60a06d9d56a145069feaf0f9706adea71ba
408
ps1
PowerShell
Powershell-skriptit/create_admin_groups.ps1
Sitra-Isaacus/Tilastokeskus-Etakayttojarjestelma
791f8e5f47503014f559baa360ff5218e4130e2a
[ "MIT" ]
1
2018-08-27T10:12:57.000Z
2018-08-27T10:12:57.000Z
Powershell-skriptit/create_admin_groups.ps1
Sitra-Isaacus/Tilastokeskus-Etakayttojarjestelma
791f8e5f47503014f559baa360ff5218e4130e2a
[ "MIT" ]
null
null
null
Powershell-skriptit/create_admin_groups.ps1
Sitra-Isaacus/Tilastokeskus-Etakayttojarjestelma
791f8e5f47503014f559baa360ff5218e4130e2a
[ "MIT" ]
null
null
null
#CREATE ADMIN GROUPS #Create da-admins group NEW-ADGroup –name da-admins –groupscope Global –path "OU=da-admins,OU=MgmtUsers,DC=ISAACUS,DC=local” #Create sa-admins group NEW-ADGroup –name sa-admins –groupscope Global –path "OU=sa-admins,OU=MgmtUsers,DC=ISAACUS,DC=local” #Create wa-admins group NEW-ADGroup –name wa-admins –groupscope Global –path "OU=wa-admins,OU=MgmtUsers,DC=ISAACUS,DC=local”
40.8
101
0.762255
4d533e293e73be7b443d113956a9908d05ddfecd
5,072
cs
C#
src/ReverseProxy/Abstractions/RouteDiscovery/Contract/ProxyRoute.cs
wenfeifei/reverse-proxy
1798d3ac3cb409366043945c2fc2104dc13f99cf
[ "MIT" ]
null
null
null
src/ReverseProxy/Abstractions/RouteDiscovery/Contract/ProxyRoute.cs
wenfeifei/reverse-proxy
1798d3ac3cb409366043945c2fc2104dc13f99cf
[ "MIT" ]
null
null
null
src/ReverseProxy/Abstractions/RouteDiscovery/Contract/ProxyRoute.cs
wenfeifei/reverse-proxy
1798d3ac3cb409366043945c2fc2104dc13f99cf
[ "MIT" ]
null
null
null
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Linq; namespace Microsoft.ReverseProxy.Abstractions { /// <summary> /// Describes a route that matches incoming requests based on a the <see cref="Match"/> criteria /// and proxies matching requests to the cluster identified by its <see cref="ClusterId"/>. /// </summary> public sealed class ProxyRoute : IDeepCloneable<ProxyRoute> { /// <summary> /// Globally unique identifier of the route. /// </summary> public string RouteId { get; set; } public ProxyMatch Match { get; private set; } = new ProxyMatch(); /// <summary> /// Optionally, an order value for this route. Routes with lower numbers take precedence over higher numbers. /// </summary> public int? Order { get; set; } /// <summary> /// Gets or sets the cluster that requests matching this route /// should be proxied to. /// </summary> public string ClusterId { get; set; } /// <summary> /// The name of the AuthorizationPolicy to apply to this route. /// If not set then only the FallbackPolicy will apply. /// Set to "Default" to enable authorization with the applications default policy. /// </summary> public string AuthorizationPolicy { get; set; } /// <summary> /// The name of the CorsPolicy to apply to this route. /// If not set then the route won't be automatically matched for cors preflight requests. /// Set to "Default" to enable cors with the default policy. /// Set to "Disable" to refuses cors requests for this route. /// </summary> public string CorsPolicy { get; set; } /// <summary> /// Arbitrary key-value pairs that further describe this route. /// </summary> public IDictionary<string, string> Metadata { get; set; } /// <summary> /// Parameters used to transform the request and response. See <see cref="Service.ITransformBuilder"/>. /// </summary> public IList<IDictionary<string, string>> Transforms { get; set; } /// <inheritdoc/> ProxyRoute IDeepCloneable<ProxyRoute>.DeepClone() { return new ProxyRoute { RouteId = RouteId, Match = Match.DeepClone(), Order = Order, ClusterId = ClusterId, AuthorizationPolicy = AuthorizationPolicy, CorsPolicy = CorsPolicy, Metadata = Metadata?.DeepClone(StringComparer.OrdinalIgnoreCase), Transforms = Transforms?.Select(d => new Dictionary<string, string>(d, StringComparer.OrdinalIgnoreCase)).ToList<IDictionary<string, string>>(), }; } // Used to diff for config changes internal int GetConfigHash() { var hash = 0; if (!string.IsNullOrEmpty(RouteId)) { hash ^= RouteId.GetHashCode(); } if (Match.Methods != null && Match.Methods.Count > 0) { // Assumes un-ordered hash ^= Match.Methods.Select(item => item.GetHashCode()) .Aggregate((total, nextCode) => total ^ nextCode); } if (Match.Hosts != null && Match.Hosts.Count > 0) { // Assumes un-ordered hash ^= Match.Hosts.Select(item => item.GetHashCode()) .Aggregate((total, nextCode) => total ^ nextCode); } if (!string.IsNullOrEmpty(Match.Path)) { hash ^= Match.Path.GetHashCode(); } if (Order.HasValue) { hash ^= Order.GetHashCode(); } if (!string.IsNullOrEmpty(ClusterId)) { hash ^= ClusterId.GetHashCode(); } if (!string.IsNullOrEmpty(AuthorizationPolicy)) { hash ^= AuthorizationPolicy.GetHashCode(); } if (!string.IsNullOrEmpty(CorsPolicy)) { hash ^= CorsPolicy.GetHashCode(); } if (Metadata != null) { hash ^= Metadata.Select(item => HashCode.Combine(item.Key.GetHashCode(), item.Value.GetHashCode())) .Aggregate((total, nextCode) => total ^ nextCode); } if (Transforms != null) { hash ^= Transforms.Select(transform => transform.Select(item => HashCode.Combine(item.Key.GetHashCode(), item.Value.GetHashCode())) .Aggregate((total, nextCode) => total ^ nextCode)) // Unordered Dictionary .Aggregate(seed: 397, (total, nextCode) => total * 31 ^ nextCode); // Ordered List } return hash; } } }
35.71831
160
0.54377
b136c529d4cbf69c79048c639f45c00de790edaa
952
sql
SQL
EMS_DB.sql
davidsaulrodriguez/Employee-Management-System
74934a9f5a3f57bf26c8d7e178e8f7f20c60f6e6
[ "BSD-2-Clause" ]
null
null
null
EMS_DB.sql
davidsaulrodriguez/Employee-Management-System
74934a9f5a3f57bf26c8d7e178e8f7f20c60f6e6
[ "BSD-2-Clause" ]
10
2021-01-25T04:28:21.000Z
2021-02-02T04:59:48.000Z
EMS_DB.sql
davidsaulrodriguez/employee-management-system
74934a9f5a3f57bf26c8d7e178e8f7f20c60f6e6
[ "BSD-2-Clause" ]
null
null
null
-- Drop the ems_db database if it already exists -- DROP DATABASE IF EXISTS ems_db; -- Create the ems_db database -- CREATE DATABASE IF NOT EXISTS ems_db; -- Select and use the ems_db to run the CREATE TABLE commands in -- USE ems_db; -- Create the Department table -- CREATE TABLE department ( id INT AUTO_INCREMENT NOT NULL, name VARCHAR(30) NOT NULL, PRIMARY KEY (id) ); -- Create the employee Role table -- CREATE TABLE role ( id INT AUTO_INCREMENT NOT NULL, title VARCHAR(30) NOT NULL, salary DECIMAL NOT NULL, department_id INT, PRIMARY KEY (id), FOREIGN KEY (department_id) REFERENCES department(id) ); -- Create the Employee table -- CREATE TABLE employee ( id INT AUTO_INCREMENT NOT NULL, first_name VARCHAR(30) NOT NULL, last_name VARCHAR(30) NOT NULL, manager_id INT, role_id INT NOT NULL, PRIMARY KEY (id), FOREIGN KEY (role_id) REFERENCES role(id), FOREIGN KEY (manager_id) REFERENCES employee(id) );
25.72973
67
0.728992
d044b564532abc14e8ba78ac38bd0ef989c457c2
2,084
dart
Dart
lib/src/model/serializers.g.dart
Andersmholmgren/vcore_ecore
1c32dcaf7cc7c2740988a7601a9e8a6069bc77c2
[ "BSD-3-Clause" ]
null
null
null
lib/src/model/serializers.g.dart
Andersmholmgren/vcore_ecore
1c32dcaf7cc7c2740988a7601a9e8a6069bc77c2
[ "BSD-3-Clause" ]
null
null
null
lib/src/model/serializers.g.dart
Andersmholmgren/vcore_ecore
1c32dcaf7cc7c2740988a7601a9e8a6069bc77c2
[ "BSD-3-Clause" ]
null
null
null
// GENERATED CODE - DO NOT MODIFY BY HAND // 2016-04-30T07:40:15.897835Z part of serializers; // ************************************************************************** // Generator: BuiltJsonGenerator // Target: library serializers // ************************************************************************** Serializers _$serializers = (new Serializers().toBuilder() ..add(EAttribute.serializer) ..add(EAnnotation.serializer) ..add(EClass.serializer) ..add(EDataType.serializer) ..add(EEnum.serializer) ..add(EEnumLiteral.serializer) ..add(EFactory.serializer) ..add(EObject.serializer) ..add(EOperation.serializer) ..add(EPackage.serializer) ..add(EParameter.serializer) ..add(EReference.serializer) ..add(EBigDecimal.serializer) ..add(EBigInteger.serializer) ..add(EBoolean.serializer) ..add(EBooleanObject.serializer) ..add(EByte.serializer) ..add(EByteArray.serializer) ..add(EByteObject.serializer) ..add(EChar.serializer) ..add(ECharacterObject.serializer) ..add(EDate.serializer) ..add(EDiagnosticChain.serializer) ..add(EDouble.serializer) ..add(EDoubleObject.serializer) ..add(EEList.serializer) ..add(EEnumerator.serializer) ..add(EFeatureMap.serializer) ..add(EFeatureMapEntry.serializer) ..add(EFloat.serializer) ..add(EFloatObject.serializer) ..add(EInt.serializer) ..add(EIntegerObject.serializer) ..add(EJavaClass.serializer) ..add(EJavaObject.serializer) ..add(ELong.serializer) ..add(ELongObject.serializer) ..add(EMap.serializer) ..add(EResource.serializer) ..add(EResourceSet.serializer) ..add(EShort.serializer) ..add(EShortObject.serializer) ..add(EString.serializer) ..add(EStringToStringMapEntry.serializer) ..add(ETreeIterator.serializer) ..add(EGenericType.serializer) ..add(ETypeParameter.serializer) ..add(EInvocationTargetException.serializer)) .build();
34.163934
77
0.618042
af8fa17184c5e9719b35ae8c9d312b950f95572e
484
py
Python
Code/pixels_count.py
AviTewari/Hydrology-Project
09a721911a119939cd41158be822ed09feb5cdfa
[ "Apache-2.0" ]
1
2021-12-27T10:02:53.000Z
2021-12-27T10:02:53.000Z
Code/pixels_count.py
AviTewari/Hydrology-Project
09a721911a119939cd41158be822ed09feb5cdfa
[ "Apache-2.0" ]
null
null
null
Code/pixels_count.py
AviTewari/Hydrology-Project
09a721911a119939cd41158be822ed09feb5cdfa
[ "Apache-2.0" ]
1
2021-11-17T10:54:52.000Z
2021-11-17T10:54:52.000Z
from modules import * from masks import * from mask_mapping import * def bincount_2d(arr, max_int): counts_full = [0 for n in range(max_int)] for row in arr: counts = np.bincount(row).tolist()#get the counts for the row pad = [0 for n in range(max_int-len(counts))] counts = counts + pad #add extra zeroes to account for colors above the max in the row counts_full = [counts_full[n] + counts[n] for n in range(max_int)] return(counts_full)
40.333333
94
0.67562
183ef3a84b931b250f523433c6a4b2b968409ded
104
ts
TypeScript
packages/effects/src/index.ts
kevinoneill/wee-events
27e0e2507afa5cae310ab9c06e0cc7f01a9f1eeb
[ "MIT" ]
1
2018-09-27T16:59:20.000Z
2018-09-27T16:59:20.000Z
packages/effects/src/index.ts
kevinoneill/wee-events
27e0e2507afa5cae310ab9c06e0cc7f01a9f1eeb
[ "MIT" ]
1
2017-11-29T03:44:32.000Z
2017-11-29T03:44:32.000Z
packages/effects/src/index.ts
kevinoneill/wee-events
27e0e2507afa5cae310ab9c06e0cc7f01a9f1eeb
[ "MIT" ]
null
null
null
export * as aws from "./aws"; export * as env from "./environment"; export * as lambda from "./lambda";
26
37
0.653846
07fe40344d5f5f50fd76669fec4fd5214d29bf44
893
sql
SQL
tests/cross_agent/fixtures/sql_obfuscation/escape_string_constants.postgres.sql
newrelic/newrelic-python-agen
4f292ec1219c0daffc5721a7b3a245b97d0f83ba
[ "Apache-2.0" ]
92
2020-06-12T17:53:23.000Z
2022-03-01T11:13:21.000Z
tests/cross_agent/fixtures/sql_obfuscation/escape_string_constants.postgres.sql
newrelic/newrelic-python-agen
4f292ec1219c0daffc5721a7b3a245b97d0f83ba
[ "Apache-2.0" ]
347
2020-07-10T00:10:19.000Z
2022-03-31T17:58:56.000Z
tests/cross_agent/fixtures/sql_obfuscation/escape_string_constants.postgres.sql
newrelic/newrelic-python-agen
4f292ec1219c0daffc5721a7b3a245b97d0f83ba
[ "Apache-2.0" ]
58
2020-06-17T13:51:57.000Z
2022-03-06T14:26:53.000Z
-- Copyright 2010 New Relic, Inc. -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. # PostgreSQL supports an alternate string quoting mode where backslash escape # sequences are interpreted. # See: http://www.postgresql.org/docs/9.3/static/sql-syntax-lexical.html#SQL-SYNTAX-STRINGS-ESCAPE SELECT "col1", "col2" from "table" WHERE "col3"=E'foo\'bar\\baz' AND country=e'foo\'bar\\baz'
49.611111
98
0.74804
c239c1d6c797284f1bac9060a4f73a04f053c552
8,102
h
C
libs/NDI/include/Processing.NDI.Send.h
nama-gatsuo/ofxNDI
7ad704b5520540aca7340411d30dfc99d6329c0b
[ "MIT" ]
40
2022-01-06T22:42:25.000Z
2022-03-11T23:42:18.000Z
libs/NDI/include/Processing.NDI.Send.h
nama-gatsuo/ofxNDI
7ad704b5520540aca7340411d30dfc99d6329c0b
[ "MIT" ]
15
2021-03-28T05:37:34.000Z
2022-02-13T13:04:57.000Z
libs/NDI/include/Processing.NDI.Send.h
nama-gatsuo/ofxNDI
7ad704b5520540aca7340411d30dfc99d6329c0b
[ "MIT" ]
4
2022-01-07T20:26:15.000Z
2022-02-10T00:42:43.000Z
#pragma once // NOTE : The following MIT license applies to this file ONLY and not to the SDK as a whole. Please review // the SDK documentation for the description of the full license terms, which are also provided in the file // "NDI License Agreement.pdf" within the SDK or online at http://new.tk/ndisdk_license/. Your use of any // part of this SDK is acknowledgment that you agree to the SDK license terms. The full NDI SDK may be // downloaded at http://ndi.tv/ // //*********************************************************************************************************** // // Copyright (C)2014-2021, NewTek, inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and // associated documentation files(the "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and / or sell // copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the // following conditions : // // The above copyright notice and this permission notice shall be included in all copies or substantial // portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT // LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO // EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR // THE USE OR OTHER DEALINGS IN THE SOFTWARE. // //*********************************************************************************************************** // Structures and type definitions required by NDI sending // The reference to an instance of the sender typedef void* NDIlib_send_instance_t; // The creation structure that is used when you are creating a sender typedef struct NDIlib_send_create_t { // The name of the NDI source to create. This is a NULL terminated UTF8 string. const char* p_ndi_name; // What groups should this source be part of. NULL means default. const char* p_groups; // Do you want audio and video to "clock" themselves. When they are clocked then by adding video frames, // they will be rate limited to match the current frame-rate that you are submitting at. The same is true // for audio. In general if you are submitting video and audio off a single thread then you should only // clock one of them (video is probably the better of the two to clock off). If you are submitting audio // and video of separate threads then having both clocked can be useful. bool clock_video, clock_audio; #if NDILIB_CPP_DEFAULT_CONSTRUCTORS NDIlib_send_create_t(const char* p_ndi_name_ = NULL, const char* p_groups_ = NULL, bool clock_video_ = true, bool clock_audio_ = true); #endif // NDILIB_CPP_DEFAULT_CONSTRUCTORS } NDIlib_send_create_t; // Create a new sender instance. This will return NULL if it fails. If you specify leave p_create_settings // null then the sender will be created with default settings. PROCESSINGNDILIB_API NDIlib_send_instance_t NDIlib_send_create(const NDIlib_send_create_t* p_create_settings NDILIB_CPP_DEFAULT_VALUE(NULL)); // This will destroy an existing finder instance. PROCESSINGNDILIB_API void NDIlib_send_destroy(NDIlib_send_instance_t p_instance); // This will add a video frame PROCESSINGNDILIB_API void NDIlib_send_send_video_v2(NDIlib_send_instance_t p_instance, const NDIlib_video_frame_v2_t* p_video_data); // This will add a video frame and will return immediately, having scheduled the frame to be displayed. All // processing and sending of the video will occur asynchronously. The memory accessed by NDIlib_video_frame_t // cannot be freed or re-used by the caller until a synchronizing event has occurred. In general the API is // better able to take advantage of asynchronous processing than you might be able to by simple having a // separate thread to submit frames. // // This call is particularly beneficial when processing BGRA video since it allows any color conversion, // compression and network sending to all be done on separate threads from your main rendering thread. // // Synchronizing events are : // - a call to NDIlib_send_send_video // - a call to NDIlib_send_send_video_async with another frame to be sent // - a call to NDIlib_send_send_video with p_video_data=NULL // - a call to NDIlib_send_destroy PROCESSINGNDILIB_API void NDIlib_send_send_video_async_v2(NDIlib_send_instance_t p_instance, const NDIlib_video_frame_v2_t* p_video_data); // This will add an audio frame PROCESSINGNDILIB_API void NDIlib_send_send_audio_v2(NDIlib_send_instance_t p_instance, const NDIlib_audio_frame_v2_t* p_audio_data); // This will add an audio frame PROCESSINGNDILIB_API void NDIlib_send_send_audio_v3(NDIlib_send_instance_t p_instance, const NDIlib_audio_frame_v3_t* p_audio_data); // This will add a metadata frame PROCESSINGNDILIB_API void NDIlib_send_send_metadata(NDIlib_send_instance_t p_instance, const NDIlib_metadata_frame_t* p_metadata); // This allows you to receive metadata from the other end of the connection PROCESSINGNDILIB_API NDIlib_frame_type_e NDIlib_send_capture( NDIlib_send_instance_t p_instance, // The instance data NDIlib_metadata_frame_t* p_metadata, // The metadata received (can be NULL) uint32_t timeout_in_ms); // The amount of time in milliseconds to wait for data. // Free the buffers returned by capture for metadata PROCESSINGNDILIB_API void NDIlib_send_free_metadata(NDIlib_send_instance_t p_instance, const NDIlib_metadata_frame_t* p_metadata); // Determine the current tally sate. If you specify a timeout then it will wait until it has changed, // otherwise it will simply poll it and return the current tally immediately. The return value is whether // anything has actually change (true) or whether it timed out (false) PROCESSINGNDILIB_API bool NDIlib_send_get_tally(NDIlib_send_instance_t p_instance, NDIlib_tally_t* p_tally, uint32_t timeout_in_ms); // Get the current number of receivers connected to this source. This can be used to avoid even rendering // when nothing is connected to the video source. which can significantly improve the efficiency if you want // to make a lot of sources available on the network. If you specify a timeout that is not 0 then it will // wait until there are connections for this amount of time. PROCESSINGNDILIB_API int NDIlib_send_get_no_connections(NDIlib_send_instance_t p_instance, uint32_t timeout_in_ms); // Connection based metadata is data that is sent automatically each time a new connection is received. You // queue all of these up and they are sent on each connection. To reset them you need to clear them all and // set them up again. PROCESSINGNDILIB_API void NDIlib_send_clear_connection_metadata(NDIlib_send_instance_t p_instance); // Add a connection metadata string to the list of what is sent on each new connection. If someone is already // connected then this string will be sent to them immediately. PROCESSINGNDILIB_API void NDIlib_send_add_connection_metadata(NDIlib_send_instance_t p_instance, const NDIlib_metadata_frame_t* p_metadata); // This will assign a new fail-over source for this video source. What this means is that if this video // source was to fail any receivers would automatically switch over to use this source, unless this source // then came back online. You can specify NULL to clear the source. PROCESSINGNDILIB_API void NDIlib_send_set_failover(NDIlib_send_instance_t p_instance, const NDIlib_source_t* p_failover_source); // Retrieve the source information for the given sender instance. This pointer is valid until NDIlib_send_destroy is called. PROCESSINGNDILIB_API const NDIlib_source_t* NDIlib_send_get_source_name(NDIlib_send_instance_t p_instance);
57.460993
137
0.76944
cdcfc89318cb70e5a2325c9ee89d6c92c01c09c9
164
cs
C#
Hiper.Application.Data.SqlServer.Migrations/Program.cs
ferhen/Hiper.Products
04559adfdaf8dabb7adea9c5f74433cbdd4d5d41
[ "MIT" ]
1
2020-10-26T08:26:04.000Z
2020-10-26T08:26:04.000Z
Hiper.Application.Data.SqlServer.Migrations/Program.cs
ferhen/Hiper.Products
04559adfdaf8dabb7adea9c5f74433cbdd4d5d41
[ "MIT" ]
null
null
null
Hiper.Application.Data.SqlServer.Migrations/Program.cs
ferhen/Hiper.Products
04559adfdaf8dabb7adea9c5f74433cbdd4d5d41
[ "MIT" ]
null
null
null
using System; namespace Hiper.Application.Data.SqlServer.Migrations { class Program { static void Main(string[] args) { } } }
13.666667
53
0.579268
38db6ce18481f9deb4f621076f195d67f5a11093
4,052
php
PHP
app/Http/Controllers/ProductController.php
khairsaeed/record
ba57c3e6f45374213757906f345853ff935664a1
[ "MIT" ]
null
null
null
app/Http/Controllers/ProductController.php
khairsaeed/record
ba57c3e6f45374213757906f345853ff935664a1
[ "MIT" ]
null
null
null
app/Http/Controllers/ProductController.php
khairsaeed/record
ba57c3e6f45374213757906f345853ff935664a1
[ "MIT" ]
null
null
null
<?php namespace App\Http\Controllers; use App\Models\Product; use Illuminate\Http\Request; class ProductController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ function __construct() { $this->middleware('permission:product-list|product-create|product-edit|product-delete', ['only' => ['index','show']]); $this->middleware('permission:product-create', ['only' => ['create','store']]); $this->middleware('permission:product-edit', ['only' => ['edit','update']]); $this->middleware('permission:product-delete', ['only' => ['destroy']]); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $products = Product::latest()->paginate(5); return view('products.index',compact('products')) ->with('i', (request()->input('page', 1) - 1) * 5); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { $product =new Product(); return view('layouts.product.inputProduct',compact('product')); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $data=request()->validate( [ 'hs_name'=>'', 'describe'=>'', 'code'=>'', 'public_name'=>'', // 'trading_flag'=>'', 'ammount'=>'', 'unit'=>'', 'note'=>'', ] ); $data['industry_activity_id']=request()->session()->get('industry_activity')['id']; // dd($data); $product= Product::create($data); //return $this->show($emp); return redirect()->route('material.show', $data['industry_activity_id'])->with('mesCreate',' تم اضافة منتج بنجاح '); } /** * Display the specified resource. * * @param \App\Product $product * @return \Illuminate\Http\Response */ public function show(Product $product) { $primeryMaterials=$product->primeryMaterial()->get(); return view('layouts.product.showProducts',compact('product','primeryMaterials')); } /** * Show the form for editing the specified resource. * * @param \App\Product $product * @return \Illuminate\Http\Response */ public function edit(Product $product) { return view('layouts.product.editProduct',compact('product')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param \App\Product $product * @return \Illuminate\Http\Response */ public function update(Request $request, Product $product) { $data= request()->validate([ 'hs_name'=>'', 'describe'=>'', 'code'=>'', 'public_name'=>'', // 'trading_flag'=>'', 'ammount'=>'', 'unit'=>'', 'note'=>'', ]); $product->update($data); return redirect()->route('material.show', $request->session()->get('industry_activity')->id)->with('mesCreate',' تم تعديل منتج بنجاح '); } /** * Remove the specified resource from storage. * * @param \App\Product $product * @return \Illuminate\Http\Response */ public function destroy( request $request ,Product $product) { $product->delete(); return redirect()->route('material.show', $request->session()->get('industry_activity')->id)->with('mesCreate',' تم تعديل منتج بنجاح '); } }
28.138889
146
0.523445
8e7ec0cebfeef99f457b6dacc81c2b71fcdf38c2
594
js
JavaScript
node.js article notes/Section8to10/startup/logging.js
bala-codes/A-Primer-on-Node.js
a70ef215b75faa6bd714cab25709763b12eefba4
[ "MIT" ]
3
2021-06-13T20:50:22.000Z
2021-06-30T09:04:23.000Z
node.js article notes/Section8to10/startup/logging.js
bala-codes/A-Primer-on-Node.js
a70ef215b75faa6bd714cab25709763b12eefba4
[ "MIT" ]
3
2021-08-13T04:35:34.000Z
2022-02-27T18:29:41.000Z
node.js article notes/Section8to10/startup/logging.js
bala-codes/A-Primer-on-Node.js
a70ef215b75faa6bd714cab25709763b12eefba4
[ "MIT" ]
1
2021-06-13T20:50:25.000Z
2021-06-13T20:50:25.000Z
const winston = require('winston'); require('winston-mongodb'); require('express-async-errors'); module.exports = function() { winston.handleExceptions( new winston.transports.Console({colorize:true, prettyPrint:true}), new winston.transports.File({filename: 'uncaughtExceptions.log'})) process.on('unhandledRejection', (ex) => { throw ex; }) winston.add(new winston.transports.File({ filename: 'combined.log' })) winston.add(new winston.transports.MongoDB({ db: 'mongodb://localhost/movies', level: 'error' })) }
31.263158
74
0.644781
8b933139eb5661560da760b281ab99ed92c70970
517
rb
Ruby
operatehappy/homebrew-hashicorp
df24fe084ec38f08937adcf117540160f6593fbb
[ "Apache-2.0" ]
4
2020-03-13T09:31:29.000Z
2020-03-24T14:06:57.000Z
operatehappy/homebrew-hashicorp
df24fe084ec38f08937adcf117540160f6593fbb
[ "Apache-2.0" ]
6
2020-03-13T19:58:14.000Z
2020-10-06T00:07:06.000Z
operatehappy/homebrew-hashicorp
df24fe084ec38f08937adcf117540160f6593fbb
[ "Apache-2.0" ]
null
null
null
cask '[email protected]' do version '0.8.0' sha256 '075d132842817e22f7306cbb46e90607c40fe5bea28d05e7eab9ee3a2fe02b76' # releases.hashicorp.com was verified as official when first introduced to the cask url 'https://releases.hashicorp.com/envconsul/0.8.0/envconsul_0.8.0_darwin_amd64.zip' appcast 'https://github.com/hashicorp/envconsul/releases.atom' name 'envconsul' homepage 'https://github.com/hashicorp/envconsul' auto_updates false conflicts_with formula: 'envconsul' binary 'envconsul' end
32.3125
87
0.783366
43cbd51198c037a42f8bf3ec916a37de2f85bdfc
470
ts
TypeScript
src/cli/manifest.ts
kosmita427/potential-robot
b8fc98a4237783a9c97d4162ebdf27e5db260b2a
[ "MIT" ]
8
2020-11-22T02:00:49.000Z
2022-03-09T05:48:32.000Z
src/cli/manifest.ts
kosmita427/potential-robot
b8fc98a4237783a9c97d4162ebdf27e5db260b2a
[ "MIT" ]
null
null
null
src/cli/manifest.ts
kosmita427/potential-robot
b8fc98a4237783a9c97d4162ebdf27e5db260b2a
[ "MIT" ]
2
2021-07-17T11:46:42.000Z
2021-11-16T18:22:33.000Z
// NOTE: We can't `import` the package.json file because it's outside of the "src" directory. // eslint-disable-next-line @typescript-eslint/no-var-requires, @typescript-eslint/no-require-imports export const manifest = require("../../package.json") as Manifest; /** * The npm package manifest (package.json) */ export interface Manifest { name: string; version: string; description: string; bin: { [bin: string]: string; }; [key: string]: unknown; }
27.647059
101
0.693617
4bdf0df9c2acee3a1641d050328a95411b0d5dac
166
h
C
2015/day11/test.h
alexandru-andronache/adventofcode
ee41d82bae8b705818fda5bd43e9962bb0686fec
[ "Apache-2.0" ]
3
2021-07-01T14:31:06.000Z
2022-03-29T20:41:21.000Z
2015/day11/test.h
alexandru-andronache/adventofcode
ee41d82bae8b705818fda5bd43e9962bb0686fec
[ "Apache-2.0" ]
null
null
null
2015/day11/test.h
alexandru-andronache/adventofcode
ee41d82bae8b705818fda5bd43e9962bb0686fec
[ "Apache-2.0" ]
null
null
null
#pragma once #include <string> namespace aoc2015_day11 { std::string part_1(const std::string& password); std::string part_2(const std::string& password); }
20.75
52
0.716867
c1e2223c329a726c9f34e2d60d1323e1cfc2249a
7,501
sql
SQL
src/main/tools/ibeaconl.sql
kedaduck/SSM_server_model
5dc2d28fdf8d961675794dd8f5197fc481c02371
[ "Apache-2.0" ]
null
null
null
src/main/tools/ibeaconl.sql
kedaduck/SSM_server_model
5dc2d28fdf8d961675794dd8f5197fc481c02371
[ "Apache-2.0" ]
null
null
null
src/main/tools/ibeaconl.sql
kedaduck/SSM_server_model
5dc2d28fdf8d961675794dd8f5197fc481c02371
[ "Apache-2.0" ]
null
null
null
/* SQLyog Ultimate v12.08 (64 bit) MySQL - 5.6.40-log : Database - ibeacon ********************************************************************* */ /*!40101 SET NAMES utf8 */; /*!40101 SET SQL_MODE=''*/; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; CREATE DATABASE /*!32312 IF NOT EXISTS*/`ibeacon` /*!40100 DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_bin */; USE `ibeacon`; /*Table structure for table `attraction` */ DROP TABLE IF EXISTS `attraction`; CREATE TABLE `attraction` ( `attractioname` varchar(255) COLLATE utf8mb4_bin NOT NULL, `text` varchar(255) COLLATE utf8mb4_bin NOT NULL, `picture` varchar(255) COLLATE utf8mb4_bin DEFAULT NULL, `id` int(11) NOT NULL AUTO_INCREMENT, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=238 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin; /*Data for the table `attraction` */ insert into `attraction`(`attractioname`,`text`,`picture`,`id`) values ('晋祠','晋祠,原为晋王祠(唐叔虞祠),为纪念晋(汾)王及母后邑姜而兴建。位于山西太原市西南悬瓮山麓的晋水之滨。','15c02a774fce8575db464cf09dc1b4e3.jpg',223),('山西博物院','山西博物院位于太原市汾河西畔滨河西路北段13号,前身为1919年创建的山西教育图书博物馆,此后屡次更名。1953年起称山西省博物馆。新馆于2001年8月10日奠基开工,2004年竣工,定名为山西博物院,为国家“九五”重点建设工程,也是山西省建国以来投资规模最大的文化基础设施,是现代化综合性博物馆。','390405f0b8d4a3359e8f60339aab05e3.jpg',224),('太原动物园','太原动物园是城市绿地系统中以履行对野生动物实施野外救护、异地综合保护,野生动物疫情预防控制,疾病预防治疗,科学研究,对社会和公众进行野生动物科普宣传教育,动物饲养管理,繁殖展览,旅游景区公用设施,绿化养护,园容环境卫生、安全消防综合管理,服务接待职能的专类公园和生物多样性保护的示范基地,是社会公益事业的重要组成部分,也是绿化太原、美化太原、打造华夏文明看山西的一流旅游景区和建设一流省会城市的重要载体。','c02d1f0f634f3f2c8eef6b67f82360c3.jpg',225),('二龙山','二龙山景区位于山西省太原市西北角被誉为“人民兵工第一校”的中北大学校园内,是少有的和校园相依托的风景区。山势不太高,但是景色秀丽,山上鲜花遍布,景点众多,二龙山旅游风景区是太原为数不多的避暑胜地。','e1cb4826b422a458f42f6f541c6ef7b4.jpg',226),('崛围山','崛围山位于山西省太原市西北24公里尖草坪区柴村镇呼延村西,南北走向,海拔1400米左右。南有青峰,北有飞云峰。二峰高峻挺拔,夹一东西走向的深沟,隔沟对峙,势如入山门户。从山顶向下俯视,四周群山如涛似浪,宛转盘旋,形成一个巨大的旋涡,像倒立的喇叭,又如硕大的圆盘,“崛围山”之名由此而来。','50f8d220ca226d7554c8c9490d42b588.jpg',227),('但不奋斗吧','的个人呗','5ddde504-a471-4bf3-b501-e64bb3a62ef0.jpg',228),('2rfefre','gregreg','863404d7-e170-4630-a8eb-5c879e2b4e56.',229),('绵山','山西省介休市','4bd56693-dcb3-4f49-aef0-8aa1275b7005.jpg',237); /*Table structure for table `find_people` */ DROP TABLE IF EXISTS `find_people`; CREATE TABLE `find_people` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `title` varchar(255) COLLATE utf8mb4_bin DEFAULT NULL, `text` text COLLATE utf8mb4_bin, `picture` varchar(255) COLLATE utf8mb4_bin DEFAULT NULL, `publish_time` datetime DEFAULT NULL, `end_time` datetime DEFAULT NULL, `state` int(11) DEFAULT NULL, `user_id` bigint(20) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin; /*Data for the table `find_people` */ insert into `find_people`(`id`,`title`,`text`,`picture`,`publish_time`,`end_time`,`state`,`user_id`) values (3,'找小孩','大家觉得觉得就到家','6546207d-b97a-4347-ba68-6a938c193cd7.jpg','2019-06-07 16:39:12','2019-06-08 11:35:31',1,10000),(6,'找小孩','身穿红色短袖,黄色裤子,眉毛粗粗的,脸圆圆的,叫野原新之助。','95ca8572-12c9-4cfb-9ba8-416955ddd8bf.jpg','2019-06-08 15:23:03','2019-06-08 15:24:27',1,10000),(7,'找小孩','呵呵呵呵呵呵','74bbde2b-acf3-4584-8b23-a4cb18d59f2f.jpg','2019-06-08 15:30:30',NULL,0,10000),(8,'救救孩子吧!','啊啊啊啊啊啊啊啊孩子丢啦!!!','11561dfb-a5f0-4470-a58c-48e4d0d70d6c.jpg','2019-06-10 10:18:56',NULL,0,10000),(9,'救救孩子吧!!!','孩子丢啦!!!!啊啊啊啊啊啊啊啊!!!','5114c739-d04c-4ecc-b840-ce66f51116c4.jpg','2019-06-10 11:50:28',NULL,0,10000),(10,'救救孩子吧啊啊啊啊啊啊啊啊','啊啊啊啊啊啊啊啊孩子丢啦!!!','b4bbcdbc-88fc-4ce3-922f-d7a4f2b595e7.jpg','2019-06-10 11:54:44',NULL,0,10000),(11,'我妈妈走丢了','我妈妈走丢了,请好心人找找她,谢谢','f5e7932b-57f9-4576-b547-76004b379c87.jpg','2019-06-10 12:05:43','2019-06-10 12:06:04',1,10000); /*Table structure for table `hotel` */ DROP TABLE IF EXISTS `hotel`; CREATE TABLE `hotel` ( `id` int(11) NOT NULL AUTO_INCREMENT, `type` varchar(255) COLLATE utf8mb4_bin DEFAULT NULL, `text` varchar(255) COLLATE utf8mb4_bin DEFAULT NULL, `picture` varchar(255) COLLATE utf8mb4_bin DEFAULT NULL, `price` decimal(10,0) DEFAULT NULL, `name` varchar(255) COLLATE utf8mb4_bin DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin; /*Data for the table `hotel` */ insert into `hotel`(`id`,`type`,`text`,`picture`,`price`,`name`) values (1,'高档型','杏花岭区府东街87号','758de2bcd3c028217b5064a7c8824872.jpg','1000','太原铜锣湾广场和颐酒店'),(2,'三星级','桃园正街6号','87ccec81453f0f96c5121bfe34235541.jpg','800','山西农业大厦绿色主题酒店'),(3,'经济型','朝阳街2号,地处服装城','d2e69e8569e21cbe8330c74cb0fff2d7.jpg','900','7天连锁酒店(太原火车站店)'),(4,'豪华型','迎泽大街118号','4eb629066f37472ca2c85a6796f421fa.jpg','1500','太原并州饭店'),(5,'豪华型','小店区长风街115-1号','b11117e92091349e7574c67a662a8045.jpg','1200','太原凯宾斯基饭店'); /*Table structure for table `restaurant` */ DROP TABLE IF EXISTS `restaurant`; CREATE TABLE `restaurant` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) COLLATE utf8mb4_bin DEFAULT NULL, `foodname` varchar(255) COLLATE utf8mb4_bin DEFAULT NULL, `picture` varchar(255) COLLATE utf8mb4_bin DEFAULT NULL, `price` decimal(10,0) DEFAULT NULL, `text` varchar(255) COLLATE utf8mb4_bin DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin; /*Data for the table `restaurant` */ insert into `restaurant`(`id`,`name`,`foodname`,`picture`,`price`,`text`) values (1,'山西会馆(太原胜利东街店)','中餐, 亚洲料理 晚餐 预订, 服务员, 座位','bfd11f3a09c06ab70f963b3a14a6ff98.jpg','10','山西省太原市胜利东街甲3号'),(2,'河东颐祥阁','中餐','fcd241c5c3d647bd92c4d52b2ddeeae6.jpg','20','山西省太原市亲贤北街10号'),(3,'上品牛排','牛排馆','fcd241c5c3d647bd92c4d52b2ddeeae6.jpg','30','山西省太原市小店区长风街116号北美新天地5楼'),(4,'清和元饭店(并南店)','美式烹饪','d65014adc7241803235842448100b598.jpg','40','山西省太原市并州南路102号'),(5,'晋韵贵宾楼','中餐','e762a0f13a0615b950eb0bbe0c75c87b.jpg',NULL,'山西省太原市小店区长风街体育西路'); /*Table structure for table `store` */ DROP TABLE IF EXISTS `store`; CREATE TABLE `store` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) COLLATE utf8mb4_bin DEFAULT NULL, `text` varchar(255) COLLATE utf8mb4_bin DEFAULT NULL, `picture` varchar(255) COLLATE utf8mb4_bin DEFAULT NULL, `price` decimal(10,0) DEFAULT NULL, `storename` varchar(255) COLLATE utf8mb4_bin DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin; /*Data for the table `store` */ insert into `store`(`id`,`name`,`text`,`picture`,`price`,`storename`) values (1,'牛肉干','百草味 原切牛肉条50g/袋 肉干肉脯休闲零食特产美食小吃','5b50404fN21f72dc1.jpg','18','百草味自营店'),(2,'龙须酥','西安回民街小吃龙须酥糖糕点小吃零食地方特色美食','58e09337Naeb38c97.jpg','26','秦品轩食品店'),(3,'梅干菜','休闲小吃梅干菜特产零食点心美食 ','5af3e11aNf35942cd.jpg','24','百草味自营店'); /*Table structure for table `user` */ DROP TABLE IF EXISTS `user`; CREATE TABLE `user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(255) COLLATE utf8mb4_bin DEFAULT NULL, `password` varchar(255) COLLATE utf8mb4_bin DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin; /*Data for the table `user` */ insert into `user`(`id`,`username`,`password`) values (1,'dingding','123456'); /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
58.601563
1,182
0.72737
25a98c91dcf5e2243697f62fa0c529a25514388a
90
js
JavaScript
app/page/PageUnderConstruction.js
mrFlick72/mrFlick72.github.io
c984ff5494762cbbdef13694cf271801e7e6f7db
[ "Apache-2.0" ]
1
2018-02-13T15:21:58.000Z
2018-02-13T15:21:58.000Z
app/page/PageUnderConstruction.js
mrFlick72/mrFlick72.github.io
c984ff5494762cbbdef13694cf271801e7e6f7db
[ "Apache-2.0" ]
null
null
null
app/page/PageUnderConstruction.js
mrFlick72/mrFlick72.github.io
c984ff5494762cbbdef13694cf271801e7e6f7db
[ "Apache-2.0" ]
null
null
null
import React from 'react'; export default () => {return <h1>Page Under Construction</h1>}
30
62
0.711111
4d84c3c48b430a4f6065d86bdf90e18fbbb36531
421
cs
C#
OOPS.DTO/Employee/EducationDTO.cs
emrecakmak77/OOPS
c0da3d11aca1358762a8551fd9464d705053d66f
[ "MIT" ]
null
null
null
OOPS.DTO/Employee/EducationDTO.cs
emrecakmak77/OOPS
c0da3d11aca1358762a8551fd9464d705053d66f
[ "MIT" ]
null
null
null
OOPS.DTO/Employee/EducationDTO.cs
emrecakmak77/OOPS
c0da3d11aca1358762a8551fd9464d705053d66f
[ "MIT" ]
null
null
null
using System; using System.Collections.Generic; using System.Text; namespace OOPS.DTO.Employee { public class EducationDTO { public string Name { get; set; } public int EducationsTypeID { get; set; } public virtual EducationsTypeDTO EducationsType { get; set; } public DateTime DateCompleted { get; set; } public virtual List<EmployeeDTO> Employees { get; set; } } }
26.3125
69
0.667458
29c4a1027fb1776982a12f74e59d58af2cf27034
775
kt
Kotlin
src/coop/rchain/lang/psi/RhoElements.kt
AbnerZheng/rholang-idea
b862845796de041af0c123abe90b59a7493acfdf
[ "MIT" ]
11
2018-05-10T05:05:19.000Z
2021-12-02T11:41:19.000Z
src/coop/rchain/lang/psi/RhoElements.kt
AbnerZheng/rholang-idea
b862845796de041af0c123abe90b59a7493acfdf
[ "MIT" ]
8
2018-01-25T21:29:37.000Z
2019-02-26T05:56:53.000Z
src/coop/rchain/lang/psi/RhoElements.kt
tgrospic/rholang-idea
6ffab0cd453e1251c1ff161458862375c59fc676
[ "MIT" ]
4
2017-11-03T13:37:55.000Z
2018-09-15T06:34:12.000Z
package coop.rchain.lang.psi import com.intellij.extapi.psi.ASTWrapperPsiElement import com.intellij.lang.ASTNode import com.intellij.psi.PsiElement import com.intellij.psi.tree.IElementType import coop.rchain.lang.RhoLanguage import org.jetbrains.annotations.NonNls class RhoElementType(@NonNls debugName: String) : IElementType(debugName, RhoLanguage.INSTANCE) class RhoTokenType(@NonNls debugName: String) : IElementType(debugName, RhoLanguage.INSTANCE) // Named element interface RhoNamedElement : RhoCompositeElement abstract class RhoNamedElementImpl(node: ASTNode) : RhoCompositeElementImpl(node), RhoNamedElement interface RhoCompositeElement : PsiElement abstract class RhoCompositeElementImpl(node: ASTNode) : ASTWrapperPsiElement(node), RhoCompositeElement
35.227273
103
0.846452
f444ed7a8fea88e1d788b4fa3dd560abce4f276b
4,504
rs
Rust
identity-iota/src/chain/document_chain.rs
dancrossley/identity.rs
21b78841971443d0bf6537b38f3e3e076f29ffdb
[ "Apache-2.0" ]
null
null
null
identity-iota/src/chain/document_chain.rs
dancrossley/identity.rs
21b78841971443d0bf6537b38f3e3e076f29ffdb
[ "Apache-2.0" ]
null
null
null
identity-iota/src/chain/document_chain.rs
dancrossley/identity.rs
21b78841971443d0bf6537b38f3e3e076f29ffdb
[ "Apache-2.0" ]
null
null
null
// Copyright 2020-2021 IOTA Stiftung // SPDX-License-Identifier: Apache-2.0 use core::fmt::Display; use core::fmt::Error as FmtError; use core::fmt::Formatter; use core::fmt::Result as FmtResult; use identity_core::convert::ToJson; use crate::chain::DiffChain; use crate::chain::IntegrationChain; use crate::did::DocumentDiff; use crate::did::IotaDID; use crate::did::IotaDocument; use crate::error::Result; use iota_client::bee_message::MessageId; #[derive(Clone, Debug, Deserialize, Serialize)] pub struct DocumentChain { chain_d: DiffChain, chain_i: IntegrationChain, #[serde(skip_serializing_if = "Option::is_none")] document: Option<IotaDocument>, } impl DocumentChain { pub(crate) fn __diff_message_id<'a>(chain_i: &'a IntegrationChain, diff: &'a DiffChain) -> &'a MessageId { diff .current_message_id() .unwrap_or_else(|| chain_i.current_message_id()) } pub(crate) fn __fold(chain_i: &IntegrationChain, chain_d: &DiffChain) -> Result<IotaDocument> { let mut this: IotaDocument = chain_i.current.clone(); for diff in chain_d.iter() { this.merge(diff)?; } Ok(this) } /// Creates a new `DocumentChain` from given the `IntegrationChain`. pub fn new(chain_i: IntegrationChain) -> Self { Self { chain_i, chain_d: DiffChain::new(), document: None, } } /// Creates a new `DocumentChain` from given the `IntegrationChain` and `DiffChain`. pub fn with_diff_chain(chain_i: IntegrationChain, chain_d: DiffChain) -> Result<Self> { let document: Option<IotaDocument> = if chain_d.is_empty() { None } else { Some(Self::__fold(&chain_i, &chain_d)?) }; Ok(Self { chain_d, chain_i, document, }) } /// Returns a reference to the DID identifying the document chain. pub fn id(&self) -> &IotaDID { self.chain_i.current.id() } /// Returns a reference to the `IntegrationChain`. pub fn integration_chain(&self) -> &IntegrationChain { &self.chain_i } /// Returns a mutable reference to the `IntegrationChain`. pub fn integration_chain_mut(&mut self) -> &mut IntegrationChain { &mut self.chain_i } /// Returns a reference to the `DiffChain`. pub fn diff(&self) -> &DiffChain { &self.chain_d } /// Returns a mutable reference to the `DiffChain`. pub fn diff_mut(&mut self) -> &mut DiffChain { &mut self.chain_d } pub fn fold(mut self) -> Result<IotaDocument> { for diff in self.chain_d.iter() { self.chain_i.current.merge(diff)?; } Ok(self.chain_i.current) } /// Returns a reference to the latest document. pub fn current(&self) -> &IotaDocument { self.document.as_ref().unwrap_or_else(|| self.chain_i.current()) } /// Returns a mutable reference to the latest document. pub fn current_mut(&mut self) -> &mut IotaDocument { if let Some(document) = self.document.as_mut() { document } else { self.chain_i.current_mut() } } /// Returns the Tangle message Id of the latest integration document. pub fn integration_message_id(&self) -> &MessageId { self.chain_i.current_message_id() } /// Returns the Tangle message Id of the latest diff or integration document. pub fn diff_message_id(&self) -> &MessageId { Self::__diff_message_id(&self.chain_i, &self.chain_d) } /// Adds a new integration document to the chain. /// /// # Errors /// /// Fails if the document is not a valid integration document. pub fn try_push_integration(&mut self, document: IotaDocument) -> Result<()> { self.chain_i.try_push(document)?; self.chain_d.clear(); self.document = None; Ok(()) } /// Adds a new diff to the chain. /// /// # Errors /// /// Fails if the document diff is invalid. pub fn try_push_diff(&mut self, diff: DocumentDiff) -> Result<()> { self.chain_d.check_validity(&self.chain_i, &diff)?; let mut document: IotaDocument = self.document.take().unwrap_or_else(|| self.chain_i.current().clone()); document.merge(&diff)?; self.document = Some(document); // SAFETY: we performed the necessary validation in `DiffChain::check_validity`. unsafe { self.chain_d.push_unchecked(diff); } Ok(()) } } impl Display for DocumentChain { fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult { if f.alternate() { f.write_str(&self.to_json_pretty().map_err(|_| FmtError)?) } else { f.write_str(&self.to_json().map_err(|_| FmtError)?) } } }
26.494118
108
0.662744
4be5b84d637192d4d438a39df98924e60f78c843
437
rs
Rust
crates/nh_d2_internal/src/shape.rs
f32by/openizual
59e0a77a5bf5adae80b9f119daa348701f0d9ebd
[ "Apache-2.0", "MIT-0", "MIT" ]
null
null
null
crates/nh_d2_internal/src/shape.rs
f32by/openizual
59e0a77a5bf5adae80b9f119daa348701f0d9ebd
[ "Apache-2.0", "MIT-0", "MIT" ]
null
null
null
crates/nh_d2_internal/src/shape.rs
f32by/openizual
59e0a77a5bf5adae80b9f119daa348701f0d9ebd
[ "Apache-2.0", "MIT-0", "MIT" ]
null
null
null
// Copyright (c) 2021 The Lutino Projects // // Use of this source code is governed by an MIT-style // license that can be found in the LICENSE file or at // https://opensource.org/licenses/MIT. pub struct Rectangle { pub left: i32, pub top: i32, pub width: i32, pub height: i32, } impl Rectangle { pub fn bottom(&self) -> i32 { self.top + self.height } pub fn right(&self) -> i32 { self.left + self.width } }
23
58
0.649886
1a8acc3057f98a433a613510d41ab255b42d6479
1,434
py
Python
critiquebrainz/frontend/views/profile.py
code-master5/critiquebrainz
a231ef27923f54f8c3abb0c368e871215423546e
[ "Apache-2.0" ]
null
null
null
critiquebrainz/frontend/views/profile.py
code-master5/critiquebrainz
a231ef27923f54f8c3abb0c368e871215423546e
[ "Apache-2.0" ]
null
null
null
critiquebrainz/frontend/views/profile.py
code-master5/critiquebrainz
a231ef27923f54f8c3abb0c368e871215423546e
[ "Apache-2.0" ]
null
null
null
from flask import Blueprint, render_template, request, redirect, url_for from flask_babel import gettext from flask_login import login_required, current_user import critiquebrainz.db.users as db_users from critiquebrainz.frontend import flash from critiquebrainz.frontend.forms.profile import ProfileEditForm profile_bp = Blueprint('profile_details', __name__) @profile_bp.route('/edit', methods=['GET', 'POST']) @login_required def edit(): form = ProfileEditForm() if form.validate_on_submit(): db_users.update(current_user.id, user_new_info={ "display_name": form.display_name.data, "email": form.email.data, "show_gravatar": form.show_gravatar.data, "license_choice": form.license_choice.data, }) flash.success(gettext("Profile updated.")) return redirect(url_for('user.reviews', user_id=current_user.id)) form.display_name.data = current_user.display_name form.email.data = current_user.email form.show_gravatar.data = current_user.show_gravatar form.license_choice.data = current_user.license_choice return render_template('profile/edit.html', form=form) @profile_bp.route('/delete', methods=['GET', 'POST']) @login_required def delete(): if request.method == 'POST': db_users.delete(current_user.id) return redirect(url_for('frontend.index')) return render_template('profile/delete.html')
35.85
73
0.728033
07afe73775213fe378af21bc0cc434504c8d9c94
1,399
css
CSS
public/custom.css
gsduong/shopee
fb92660c0cf9acdf7fb600b03c8ae7872313bc62
[ "MIT" ]
null
null
null
public/custom.css
gsduong/shopee
fb92660c0cf9acdf7fb600b03c8ae7872313bc62
[ "MIT" ]
null
null
null
public/custom.css
gsduong/shopee
fb92660c0cf9acdf7fb600b03c8ae7872313bc62
[ "MIT" ]
null
null
null
.dropzone { border-style: dashed !important; } select#colors option[value="1"] { color: #fff; background: rgba(0, 0, 0, 1) !important; } select#colors option[value="2"] { color: #fff; background: rgba(0, 0, 255, 1) !important; } select#colors option[value="3"] { color: #fff; background: rgba(165, 42, 42, 1) !important; } select#colors option[value="4"] { color: #fff; background: rgba(128, 128, 128, 1) !important; } select#colors option[value="5"] { color: #fff; background: rgba(0, 128, 0, 1) !important; } select#colors option[value="6"] { color: #fff; background: rgba(255, 165, 0, 1) !important; } select#colors option[value="7"] { color: #fff; background: rgba(255, 192, 203, 1) !important; } select#colors option[value="8"] { color: #fff; background: rgba(128, 0, 128, 1) !important; } select#colors option[value="9"] { color: #fff; background: rgba(255, 0, 0, 1) !important; } select#colors option[value="10"] { color: #fff; background: rgba(255, 255, 255, 1) !important; } select#colors option[value="11"] { color: #fff; background: rgba(255, 255, 0, 1) !important; } .pagination { margin-top: 0 !important; } .shipping { background-color: #00c0ef !important; } .pending { background-color: #dd4b39 !important; } .delivered , .shipped { background-color: #00a65a !important; }
22.206349
50
0.625447
f427d280c1c75d43c2c9e7041d70ffa4f6f7ece5
2,887
cs
C#
Core.Mvvm/Navigation/ViewHandle.cs
toeb/core.common
2b84c02a0759afea87578763a267a5f0ec0c751f
[ "MIT" ]
1
2021-05-16T06:12:19.000Z
2021-05-16T06:12:19.000Z
Core.Mvvm/Navigation/ViewHandle.cs
toeb/core.common
2b84c02a0759afea87578763a267a5f0ec0c751f
[ "MIT" ]
null
null
null
Core.Mvvm/Navigation/ViewHandle.cs
toeb/core.common
2b84c02a0759afea87578763a267a5f0ec0c751f
[ "MIT" ]
1
2021-02-15T12:46:02.000Z
2021-02-15T12:46:02.000Z
using Core.Common.MVVM; using System; using System.Windows; using Core.Common.Reflect; using System.Threading.Tasks; using System.Windows.Input; using System.Windows.Controls.Primitives; using System.Diagnostics; namespace Core.Common.Wpf { [DebuggerDisplay("{DebugString}")] public class ViewHandle { public ViewHandle() { } public string DebugString { get { return ToString(); } } public override string ToString() { return string.Format("", Contract, Content, HostControl, Source); } public static ICommand GetCloseCommand(DependencyObject obj) { return (ICommand)obj.GetValue(CloseCommandProperty); } private static void SetCloseCommand(DependencyObject obj, ICommand value) { obj.SetValue(CloseCommandProperty, value); } public void SetCloseCommand(DependencyObject obj) { SetCloseCommand(obj, Command.CreateCommand(Close)); } // Using a DependencyProperty as the backing store for CloseCommand. This enables animation, styling, binding, etc... public static readonly DependencyProperty CloseCommandProperty = DependencyProperty.RegisterAttached("CloseCommand", typeof(ICommand), typeof(ViewHandle), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.Inherits)); public object Contract { get; set; } public object Content { get; set; } public object HostControl { get; set; } public void Close() { if (DoClose != null) { DoClose(); } } private Action _doClose; public Action DoClose { get { return _doClose; } set { _doClose = value; } } internal void NotifyComplete() { ViewTaskSource.SetResult(this); } internal void NotifyError(Exception exc) { ViewTaskSource.SetException(exc); } private TaskCompletionSource<ViewHandle> ViewTaskSource { get { if (_viewTaskSource == null) { _viewTaskSource = new TaskCompletionSource<ViewHandle>(); } return _viewTaskSource; } } private TaskCompletionSource<ViewHandle> _viewTaskSource; public Task<ViewHandle> ViewTask { get { return ViewTaskSource.Task; } } public DataTemplate Template { get; internal set; } public object Source { get; internal set; } } }
24.058333
182
0.551437
c6ed23295db049571f988398bb3cb2fe3d4d10d0
623
css
CSS
web/admin/footer.css
taviroquai/MapIgniter
20ba899ee4f19f73b698e41d5a72318ef300dd9e
[ "Apache-2.0" ]
5
2015-03-14T17:10:05.000Z
2017-06-19T19:02:53.000Z
web/admin/footer.css
taviroquai/MapIgniter
20ba899ee4f19f73b698e41d5a72318ef300dd9e
[ "Apache-2.0" ]
4
2015-02-27T02:07:40.000Z
2015-11-06T18:35:44.000Z
web/admin/footer.css
taviroquai/MapIgniter
20ba899ee4f19f73b698e41d5a72318ef300dd9e
[ "Apache-2.0" ]
11
2015-01-10T14:05:04.000Z
2019-02-12T18:42:41.000Z
/** * MapIgniter * * An open source GeoCMS application * * @package MapIgniter * @author Marco Afonso * @copyright Copyright (c) 2012, Marco Afonso * @license dual license, one of two: Apache v2 or GPL * @link http://mapigniter.com/ * @since Version 1.0 * @filesource */ /* ------------------------------------------------------------------------ */ #footer-logos { display: block; margin: 0 auto; text-align: center; background-color: #f0f0f0; } #footer-logos a { padding: 10px; text-decoration: none; } #footer-logos a img { vertical-align: middle; width: 16px; }
18.878788
78
0.553772
4853b6c45f89201a0b73ca47fab2d9071f7422a5
146
sql
SQL
docker-compose/sql/seed.sql
titagaki/peercast-yayp
de73faa24061123b0ff0b34f99596f6c303f855e
[ "MIT" ]
1
2021-06-22T11:21:08.000Z
2021-06-22T11:21:08.000Z
docker-compose/sql/seed.sql
titagaki/peercast-yayp
de73faa24061123b0ff0b34f99596f6c303f855e
[ "MIT" ]
null
null
null
docker-compose/sql/seed.sql
titagaki/peercast-yayp
de73faa24061123b0ff0b34f99596f6c303f855e
[ "MIT" ]
null
null
null
INSERT INTO information ( `name`, `description`, `created_at`, `updated_at`, `deleted_at` ) VALUES ( 'MP◆Status', '稼働中', NOW(), NOW(), null );
29.2
65
0.636986
6d2bd3665aad980c54895c6cb333c30136b75900
173
ts
TypeScript
.history/src/radar/dto/radar_20220303214445.ts
MiguelAngelBadi/droides
02ffd1a71c620799824790a49c6e46ceccea63be
[ "MIT" ]
null
null
null
.history/src/radar/dto/radar_20220303214445.ts
MiguelAngelBadi/droides
02ffd1a71c620799824790a49c6e46ceccea63be
[ "MIT" ]
null
null
null
.history/src/radar/dto/radar_20220303214445.ts
MiguelAngelBadi/droides
02ffd1a71c620799824790a49c6e46ceccea63be
[ "MIT" ]
null
null
null
export class radarDto{ readonly protocols : Array<String>; readonly scan: Array<Object>; // readonly coordinates // readonly enemies // readonly allies }
24.714286
39
0.682081
7cfe753ad2505203fd1195f5deb762869fba9b5e
4,354
lua
Lua
nvim/session.lua
LuaDist-testing/nvim-client
c0ff82c80d9bc3024b3ccaae7d96d89ee195a713
[ "Apache-2.0" ]
null
null
null
nvim/session.lua
LuaDist-testing/nvim-client
c0ff82c80d9bc3024b3ccaae7d96d89ee195a713
[ "Apache-2.0" ]
null
null
null
nvim/session.lua
LuaDist-testing/nvim-client
c0ff82c80d9bc3024b3ccaae7d96d89ee195a713
[ "Apache-2.0" ]
null
null
null
require('coxpcall') local uv = require('luv') local MsgpackRpcStream = require('nvim.msgpack_rpc_stream') local Session = {} Session.__index = Session local function resume(co, ...) local status, result = coroutine.resume(co, ...) if coroutine.status(co) == 'dead' then if not status then error(result) end return end assert(coroutine.status(co) == 'suspended') result(co) end local function coroutine_exec(func, ...) local args = {...} local on_complete if #args > 0 and type(args[#args]) == 'function' then -- completion callback on_complete = table.remove(args) end resume(coroutine.create(function() local status, result = copcall(func, unpack(args)) if on_complete then coroutine.yield(function() -- run the completion callback on the main thread on_complete(status, result) end) end end)) end function Session.new(stream) return setmetatable({ _msgpack_rpc_stream = MsgpackRpcStream.new(stream), _pending_messages = {}, _prepare = uv.new_prepare(), _timer = uv.new_timer(), _is_running = false }, Session) end function Session:next_message(timeout) local function on_request(method, args, response) table.insert(self._pending_messages, {'request', method, args, response}) uv.stop() end local function on_notification(method, args) table.insert(self._pending_messages, {'notification', method, args}) uv.stop() end if self._is_running then error('Event loop already running') end if #self._pending_messages > 0 then return table.remove(self._pending_messages, 1) end self:_run(on_request, on_notification, timeout) return table.remove(self._pending_messages, 1) end function Session:notify(method, ...) self._msgpack_rpc_stream:write(method, {...}) end function Session:request(method, ...) local args = {...} local err, result if self._is_running then err, result = self:_yielding_request(method, args) else err, result = self:_blocking_request(method, args) end if err then return false, err end return true, result end function Session:run(request_cb, notification_cb, setup_cb, timeout) local function on_request(method, args, response) coroutine_exec(request_cb, method, args, function(status, result) if status then response:send(result) else response:send(result, true) end end) end local function on_notification(method, args) coroutine_exec(notification_cb, method, args) end self._is_running = true if setup_cb then coroutine_exec(setup_cb) end while #self._pending_messages > 0 do local msg = table.remove(self._pending_messages, 1) if msg[1] == 'request' then on_request(msg[2], msg[3], msg[4]) else on_notification(msg[2], msg[3]) end end self:_run(on_request, on_notification, timeout) self._is_running = false end function Session:stop() uv.stop() end function Session:close(signal) if not self._timer:is_closing() then self._timer:close() end if not self._prepare:is_closing() then self._prepare:close() end self._msgpack_rpc_stream:close(signal) end function Session:_yielding_request(method, args) return coroutine.yield(function(co) self._msgpack_rpc_stream:write(method, args, function(err, result) resume(co, err, result) end) end) end function Session:_blocking_request(method, args) local err, result local function on_request(method, args, response) table.insert(self._pending_messages, {'request', method, args, response}) end local function on_notification(method, args) table.insert(self._pending_messages, {'notification', method, args}) end self._msgpack_rpc_stream:write(method, args, function(e, r) err = e result = r uv.stop() end) self:_run(on_request, on_notification) return err, result end function Session:_run(request_cb, notification_cb, timeout) if type(timeout) == 'number' then self._prepare:start(function() self._timer:start(timeout, 0, function() uv.stop() end) self._prepare:stop() end) end self._msgpack_rpc_stream:read_start(request_cb, notification_cb, uv.stop) uv.run() self._prepare:stop() self._timer:stop() self._msgpack_rpc_stream:read_stop() end return Session
23.408602
77
0.702343
cd19aa42ebe4810bd5dbd37bf3fcc3fba32fbbbd
2,447
rb
Ruby
factbook-importers/lib/factbook-importers/importer.rb
eUgEntOptIc44/factbook
5a3894a34ba5273d74282c9703536cab424a5d46
[ "CC0-1.0" ]
94
2016-11-05T15:51:50.000Z
2022-02-04T14:48:58.000Z
factbook-importers/lib/factbook-importers/importer.rb
eUgEntOptIc44/factbook
5a3894a34ba5273d74282c9703536cab424a5d46
[ "CC0-1.0" ]
5
2021-01-22T14:38:12.000Z
2022-03-25T16:50:23.000Z
factbook-importers/lib/factbook-importers/importer.rb
eUgEntOptIc44/factbook
5a3894a34ba5273d74282c9703536cab424a5d46
[ "CC0-1.0" ]
15
2016-12-14T21:08:42.000Z
2022-03-31T23:04:51.000Z
# encoding: utf-8 module Factbook class Importer def import( page ) ## note: assumes active connection code = page.info.country_code name = page.info.country_name attribs = { name: name, area: sq_km( page.area ), # e.g. 83,871 sq km area_land: sq_km( page.area_land ), # e.g. 82,445 sq km area_water: sq_km( page.area_water ), # e.g. 1,426 sq km population: num( page.population ), # e.g. 8,665,550 (July 2015 est.) population_growth: percent( page.population_growth ), # e.g. 0.55% (2015 est.) birth_rate: rate_per_thousand( page.birth_rate ), # e.g. 9.41 births/1,000 population (2015 est.) death_rate: rate_per_thousand( page.death_rate ), # e.g. 9.42 deaths/1,000 population (2015 est.) migration_rate: rate_per_thousand( page.migration_rate ), # e.g. 5.56 migrant(s)/1,000 population (2015 est.) } rec = Fact.find_by( code: code ) if rec.nil? ## create (new) record rec = Fact.new attribs[ :code ] = code puts "create fact record #{code}/#{name}:" else ## update (exisiting) record puts "update fact record #{code}/#{name}:" end puts " #{attribs.inspect}" rec.update_attributes!( attribs ) end def rate_per_thousand( text ) # e.g. 9.41 births/1,000 population (2015 est.) # 9.42 deaths/1,000 population (2015 est.) # 5.56 migrant(s)/1,000 population (2015 est.) if text =~/([0-9\.]+) [a-z\(\)]+\/1,000/ $1.to_f else puts "*** warn: unknown rate <name>/1,000 format (no match): >#{text}<" nil end end def num( text ) # e.g. 8,665,550 (July 2015 est.) if text =~/([0-9,\.]+)/ $1.gsub(',', '').to_i ## note: remove commas (,) if present else puts "*** warn: unknown number format (no match): >#{text}<" nil ## return nil end end def percent( text ) # e.g. 0.55% (2015 est.) if text =~/([0-9\.]+)%/ $1.to_f else puts "*** warn: unknown percent format (no match): >#{text}<" nil ## return nil end end def sq_km( text ) # e.g. 83,871 sq km ## todo - check vatican - uses float e.g. 0.44 ?? add support? if text =~/([0-9,\.]+) sq km/ $1.gsub(',', '').to_i ## note: remove commas (,) if present else puts "*** warn: unknown sq km format (no match): >#{text}<" nil ## return nil end end end # class Importer end # module Factbook
26.311828
117
0.575398
9e13388f5af684c1e31e4e197290c1070c029e33
422
cs
C#
ACTransit.Training/Web.Business/Infrastructure/Common.cs
actransitorg/ACTransit.Training
c425e2bbf6cb51c0936df37cb1e9cb217852468f
[ "MIT" ]
7
2016-09-16T21:10:42.000Z
2016-12-16T21:10:10.000Z
ACTransit.Training/Web.Business/Infrastructure/Common.cs
actransitorg/ACTransit.Training
c425e2bbf6cb51c0936df37cb1e9cb217852468f
[ "MIT" ]
null
null
null
ACTransit.Training/Web.Business/Infrastructure/Common.cs
actransitorg/ACTransit.Training
c425e2bbf6cb51c0936df37cb1e9cb217852468f
[ "MIT" ]
null
null
null
using ACTransit.Framework.Caching; namespace ACTransit.Training.Web.Business.Infrastructure { internal static class Common { private static ICache _cache; public static ICache Cache { get { if (_cache == null) _cache = new Cache("ACTransit.Training.Web.Business"); return _cache; } } } }
22.210526
74
0.528436
1a6e6884fcef9d2bbe1e15e3daeb48db874cf85d
7,584
py
Python
legacy_migration/fix-computes.py
gaurav-dalvi/deployment-support
9732bb7419897ca27572b55b203fb1b76ecb106b
[ "Apache-2.0" ]
null
null
null
legacy_migration/fix-computes.py
gaurav-dalvi/deployment-support
9732bb7419897ca27572b55b203fb1b76ecb106b
[ "Apache-2.0" ]
2
2019-05-10T19:13:43.000Z
2019-05-16T02:21:33.000Z
legacy_migration/fix-computes.py
gaurav-dalvi/deployment-support
9732bb7419897ca27572b55b203fb1b76ecb106b
[ "Apache-2.0" ]
1
2018-12-11T18:47:42.000Z
2018-12-11T18:47:42.000Z
#!/usr/bin/python import paramiko import subprocess default_username = 'root' default_password = 'noir0123' # for the first compute node: # 1) edit the /etc/neutron/dhcp-agent.ini configuration file to set "force_metadata = True" # 2) restart neutron-dhcp-agent # 3) scp the /etc/neutron/metadata_agent.ini file to all the other computes # for all the computes # 1) edit the /etc/opflex-agent-ovs/conf.d/opflex-agent-ovs.conf to set "encrypted" # 2) kill supervisord # 3) delete all the flows in br-fabric # 4) restart agent-ovs # 5) clear iptables rule created by installer CLEAR_IP_TABLES_RULE='iptables -D INPUT -j REJECT --reject-with icmp-host-prohibited' def update_dhcp_agent_cfg(ssh_client): """Fix the neutron-dhcp-agent configuration.. Our nauto installer has a bug where it fails to configure the DHCP agent to use force_metadata (needed because there is no reference implementation neutron router in the network). This sets the force_metadata option to True and restarts the neutron-dhcp-agent service. """ SED_FIND = '#force_metadata = false' SED_REPLACE = 'force_metadata = true' FILE = '/etc/neutron/dhcp_agent.ini' cmd = "sed -i 's/" + SED_FIND + "/" + SED_REPLACE + "/g' " + FILE print cmd ssh_stdin, ssh_stdout, ssh_stderr = ssh_client.exec_command(cmd) cmd = "service neutron-dhcp-agent restart" print cmd ssh_stdin, ssh_stdout, ssh_stderr = ssh_client.exec_command(cmd) def restart_metadata_agent(ssh_client): """Restart metdata agent. Our nauto installer has a bug where it fails to configure the metadata agent correctly on all compute hosts except the first. This function kills supervisord on the host, deletes all the flows on br-fabric, and restarts the neutron-opflex-agent, which will use create new metadata agents using the updated configuration file. """ cmd = "systemctl stop neutron-metadata-agent" print cmd ssh_stdin, ssh_stdout, ssh_stderr = ssh_client.exec_command(cmd) cmd = "kill `ps -ef | grep [s]upervisord | awk -F' ' '{print $2}'`" print cmd ssh_stdin, ssh_stdout, ssh_stderr = ssh_client.exec_command(cmd) cmd = "ovs-ofctl del-flows br-fabric" print cmd ssh_stdin, ssh_stdout, ssh_stderr = ssh_client.exec_command(cmd) cmd = "service neutron-opflex-agent restart" print cmd ssh_stdin, ssh_stdout, ssh_stderr = ssh_client.exec_command(cmd) def fix_br_fabric(ssh_client): cmd = "ovs-vsctl del-br br-tun" print cmd ssh_stdin, ssh_stdout, ssh_stderr = ssh_client.exec_command(cmd) cmd1 = "ovs-vsctl --may-exist add-port br-fabric br-fab_vxlan0 -- " cmd2 = "set Interface br-fab_vxlan0 type=vxlan options:remote_ip=flow " cmd3 = "options:key=flow options:dst_port=8472" cmd = cmd1 + cmd2 + cmd3 print cmd ssh_stdin, ssh_stdout, ssh_stderr = ssh_client.exec_command(cmd) def restart_agent_ovs(ssh_client): cmd = "service agent-ovs restart" print cmd ssh_stdin, ssh_stdout, ssh_stderr = ssh_client.exec_command(cmd) def clear_iptables_rule(ssh_client): cmd = CLEAR_IP_TABLES_RULE print cmd ssh_stdin, ssh_stdout, ssh_stderr = ssh_client.exec_command(cmd) def update_agent_ovs_cfg(ssh_client): """Fix the agent-ovs configuration.. Our nauto installer has a bug where it configures the SSL option as "enabled" in agent-ovs, which is an invalid value. This function replaces enabled with the correct value of "encrypted" """ SED_FIND = '"mode": "enabled"' SED_REPLACE = '"mode": "encrypted"' FILE = '/etc/opflex-agent-ovs/conf.d/opflex-agent-ovs.conf' cmd = "sed -i 's/" + SED_FIND + "/" + SED_REPLACE + "/g' " + FILE print cmd ssh_stdin, ssh_stdout, ssh_stderr = ssh_client.exec_command(cmd) def update_agent_neutron_cfg(ssh_client): SED_FIND = '# root_helper_daemon =.*' SED_REPLACE = 'root_helper_daemon = ' FILE = '/etc/neutron/neutron.conf' cmd = "sed -i 's/" + SED_FIND + "/" + SED_REPLACE + "/g' " + FILE print cmd ssh_stdin, ssh_stdout, ssh_stderr = ssh_client.exec_command(cmd) def get_dhcp_hosts(): """Return compute hosts running DHCP agent. Return all compute hosts running the DHCP agent. """ cmd = "neutron agent-list | grep dhcp | awk -F'|' '{print $4}'" print cmd hosts = subprocess.check_output(['bash','-c', cmd]) return [host.strip() for host in hosts.split("\n") if host] def get_compute_hosts(): """Return all the compute hosts in the deployment. """ #cmd = "neutron agent-list -F host -f value | sort | uniq" cmd = "nova service-list | grep nova-compute | awk -F'|' '{print $4}'" print cmd hosts = subprocess.check_output(['bash','-c', cmd]) return [host.strip() for host in hosts.split("\n") if host] def update_metadata_agent_cfg(hosts): """Fix the neutron-metaata-agent configuration. Our nauto installer has a bug where it fails to configure the metadata agent correctly on all compute hosts except the first. This scp's the configuration file from the first compute host to all the others """ # get the file from the first compute host PATH = '/etc/neutron/' FILE = 'metadata_agent.ini' cmd = ('scp root@%(host)s:%(path)s%(file)s .' % {'host': hosts[0], 'file': FILE, 'path': PATH}) print cmd subprocess.check_output(['bash','-c', cmd]) # now copy it back down to the other compute hosts for host in hosts[1:]: cmd = ("scp %(file)s root@%(host)s:%(path)s%(file)s" % {'host': host, 'file': FILE, 'path': PATH}) print cmd subprocess.check_output(['bash','-c', cmd]) def get_metadata_config(): """Get the metadata configuration from the. """ cmd = "neutron agent-list -F host -f value | sort | uniq" print cmd hosts = subprocess.check_output(['bash','-c', cmd]) return [host.strip() for host in hosts.split("\n") if host] def cleanup_dead_agents(): cmd = "for agent in `neutron agent-list | grep xxx | awk -F'|' '{print $2}'`; do neutron agent-delete $agent; done" print cmd subprocess.check_output(['bash','-c', cmd]) # Main code cleanup_dead_agents() dhcp_host = get_dhcp_hosts()[0] print "DHCP host is " + dhcp_host all_hosts = get_compute_hosts() update_metadata_agent_cfg(all_hosts) for host in all_hosts: print host ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.load_system_host_keys() print "connecting to " + host ssh.connect(host, username=default_username) if host == dhcp_host: update_dhcp_agent_cfg(ssh) #update_agent_ovs_cfg(ssh) #update_agent_neutron_cfg(ssh) if host != all_hosts[0]: restart_metadata_agent(ssh) fix_br_fabric(ssh) restart_agent_ovs(ssh) clear_iptables_rule(ssh) cmd1 = "openstack image create --public --disk-format qcow2 " cmd2 = "--container-format bare --file cirros-0.3.5-x86_64-disk.img cirros.new" cmd = cmd1 + cmd2 print cmd hosts = subprocess.check_output(['bash','-c', cmd]) cmd1 = "neutron net-create l3out-2 --router:external True --shared " cmd2 = "--provider:network_type opflex --provider:physical_network physnet1" cmd = cmd1 + cmd2 print cmd hosts = subprocess.check_output(['bash','-c', cmd]) cmd1 = "neutron subnet-create l3out-2 60.60.60.0/24 --name ext_subnet " cmd2 = "--gateway 60.60.60.1 --disable-dhcp" cmd = cmd1 + cmd2 print cmd hosts = subprocess.check_output(['bash','-c', cmd])
37.731343
119
0.68394
dba03307af7ac8be08c0d699cdd045e39269f222
8,774
php
PHP
controllers/SiteController.php
deahk94/Yii-AngularJS-Learning
dee7c475a4c5f202af5b6eedae53ccbd3d16d4c2
[ "BSD-3-Clause" ]
null
null
null
controllers/SiteController.php
deahk94/Yii-AngularJS-Learning
dee7c475a4c5f202af5b6eedae53ccbd3d16d4c2
[ "BSD-3-Clause" ]
null
null
null
controllers/SiteController.php
deahk94/Yii-AngularJS-Learning
dee7c475a4c5f202af5b6eedae53ccbd3d16d4c2
[ "BSD-3-Clause" ]
null
null
null
<?php namespace app\controllers; use Yii; use yii\filters\AccessControl; use yii\web\Controller; use yii\web\Response; use yii\filters\VerbFilter; use yii\BaseYii; use yii\data\ActiveDataProvider; use app\models\LoginForm; use app\models\ContactForm; use app\models\SearchForm; use app\models\Wallet; use app\models\Transaction; use app\models\TransactionAR; class SiteController extends Controller { /** * {@inheritdoc} */ public function behaviors() { return [ 'access' => [ 'class' => AccessControl::className(), 'only' => ['logout', 'member', 'transfer'], //'except' => ['index', 'error', 'captcha', 'login', 'about', 'contact'], 'rules' => [ [ 'actions' => ['logout', 'member', 'transfer'], 'allow' => true, 'roles' => ['@'], ], ], ], 'verbs' => [ 'class' => VerbFilter::className(), 'actions' => [ 'logout' => ['post'], ], ], ]; } /** * {@inheritdoc} */ public function actions() { return [ 'error' => [ 'class' => 'yii\web\ErrorAction', ], 'captcha' => [ 'class' => 'yii\captcha\CaptchaAction', 'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null, ], ]; } /** * Displays homepage. * * @return string */ public function actionIndex() { return $this->render('index'); } /** * Login action. * * @return Response|string */ public function actionLogin() { if (!Yii::$app->user->isGuest) { return $this->goHome(); } $model = new LoginForm(); if ($model->load(Yii::$app->request->post()) && $model->login()) { return $this->redirect(['product/index']); // $wallet = new Wallet(); // $walletData = $wallet->fetchData($model->username); // $walletA = 0; // $walletB = 0; // foreach ($walletData as $wallet) { // if ($wallet['type'] === "A") // { // $walletA = $wallet->amount; // } // else // { // $walletB = $wallet->amount; // } // } // return $this->render('member', ['model' => $model, 'walletA' => $walletA, 'walletB' => $walletB, 'data' => $walletData]); } $model->password = ''; return $this->render('login', [ 'model' => $model, ]); } public function actionMember() { $account = Yii::$app->user->identity; $walletList = ['ALL' => 'ALL', 'A' => 'A', 'B' => 'B']; $dataProvider = null; $search = new SearchForm(); if($search->load(Yii::$app->request->get()) && $search->validate()) { //throw new \Exception(var_export($search, true), 1); $query = TransactionAR::find(); $query->AndWhere(['userid'=> $account->id]); // when Wallet Type input is not empty if(!empty($search->walletType) && $search->walletType !== "ALL") { //Get wallet's id because transaction table only have out/in-walletid $walletid = Wallet::findOne(['type' => $search->walletType, 'userid' => $account->id])->id; $query->AndWhere(['outwalletid' => $walletid]); //NOT USED* Change to outwalletid only /*$query->AndWhere(['or', ['outwalletid' => $walletid], ['inwalletid' => $walletid] ]);*/ } // when min or max Amount is not empty if (!empty($search->minAmount) || !empty($search->maxAmount)){ if (empty($search->minAmount)) $search->minAmount = $search->maxAmount; if (empty($search->maxAmount)) $search->maxAmount = $search->minAmount; $query->andFilterWhere(['between', 'amount', $search->minAmount, $search->maxAmount ]); } $dataProvider = new ActiveDataProvider([ 'query' => $query, 'pagination' => [ 'pageSize' => 10, ], 'sort' => [ // 'enableMultiSort' => true, 'defaultOrder' => [ 'date' => SORT_DESC ], ], ]); } else { $dataProvider = new ActiveDataProvider([ 'query' => TransactionAR::find() ->AndWhere(['userid'=> $account->id]), 'pagination' => [ 'pageSize' => 10, ], 'sort' => [ // 'enableMultiSort' => true, 'defaultOrder' => [ 'date' => SORT_DESC ], ], ]); } // $dataProvider->setSort([ // 'attributes' => [ // 'amount' => [ // 'asc' => ['amount' => SORT_ASC], // 'desc' => ['amount' => SORT_DESC], // 'default' => SORT_ASC // ], // 'date' => [ // 'asc' => ['date' => SORT_ASC], // 'desc' => ['date' => SORT_DESC], // 'default' => SORT_ASC, // ], // 'outwalletid' => [ // 'asc' => ['outwalletid' => SORT_ASC], // 'desc' => ['outwalletid' => SORT_DESC], // 'default' => SORT_ASC, // ], // 'inwalletid' => [ // 'asc' => ['inwalletid' => SORT_ASC], // 'desc' => ['inwalletid' => SORT_DESC], // 'default' => SORT_ASC, // ], // ], // 'defaultOrder' => [ // 'date' => SORT_ASC // ] // ]); //throw new \Exception(var_export(Yii::$app->request->post(), true), 1); return $this->render('member', [ 'account' => $account, 'dataProvider' => $dataProvider, 'search' => $search, 'walletList' => $walletList, ]); } /** * Logout action. * * @return Response */ public function actionLogout() { Yii::$app->user->logout(); return $this->goHome(); } /** * Displays contact page. * * @return Response|string */ public function actionContact() { $model = new ContactForm(); if ($model->load(Yii::$app->request->post()) && $model->contact(Yii::$app->params['adminEmail'])) { Yii::$app->session->setFlash('contactFormSubmitted'); return $this->refresh(); } return $this->render('contact', [ 'model' => $model, ]); } /** * Displays about page. * * @return string */ public function actionAbout() { return $this->render('about'); } public function actionTransfer() { $account = Yii::$app->user->identity; //GET request can be replace with AR find() using $account->id //Kept for future reference $walletType = $_GET['walletType']; $username = $_GET['username']; $balance = Wallet::find()->AndWhere(['userid' => $account->id, 'type' => $walletType])->one()->amount; $transaction = new Transaction(); if($transaction->load(Yii::$app->request->post()) && $transaction->validate()) { $outWallet = $account->getWallet($transaction->type); $inWalletType = ($transaction->type === 'A') ? 'B' : 'A'; $inWallet = $account->getWallet($inWalletType); $outWallet->transfer($transaction->amount, $inWallet->id, [ 'remark' => 'test', ]); return $this->redirect('member'); } return $this->render('transfer', [ 'transaction' => $transaction, 'type' => $walletType, 'user' => $username, 'balance' => $balance, ]); } public function actionConfirm() { return $this->render('index'); } }
28.861842
136
0.422042
cce34812e86a81aa8917bdcf2f99e7fcf23eacbb
24,781
rb
Ruby
test/test_url.rb
pablitosanchez/wgit
0f557b1227877e787c8d2f4001e9c596218f45d1
[ "MIT" ]
null
null
null
test/test_url.rb
pablitosanchez/wgit
0f557b1227877e787c8d2f4001e9c596218f45d1
[ "MIT" ]
null
null
null
test/test_url.rb
pablitosanchez/wgit
0f557b1227877e787c8d2f4001e9c596218f45d1
[ "MIT" ]
null
null
null
# frozen_string_literal: true require_relative 'helpers/test_helper' # Test class for Url methods. class TestUrl < TestHelper # Run non DB tests in parallel for speed. parallelize_me! # Runs before every test. def setup @url_str = 'http://www.google.co.uk' @bad_url_str = 'my_server' @link = '/about.html' @url_str_link = "#{@url_str}#{@link}" @url_str_anchor = "#{@url_str_link}#about-us" @url_str_query = "#{@url_str_link}?foo=bar" @iri = 'https://www.über.com/about#top' @time_stamp = Time.new @mongo_doc_dup = { 'url' => @url_str, 'crawled' => true, 'date_crawled' => @time_stamp } end def test_initialize url = Wgit::Url.new @url_str assert_equal @url_str, url refute url.crawled assert_nil url.date_crawled end def test_initialize_from_url temp_url = Wgit::Url.new @url_str url = Wgit::Url.new temp_url assert_equal @url_str, url refute url.crawled assert_nil url.date_crawled end def test_initialize_from_iri url = Wgit::Url.new @iri assert_equal @iri, url refute url.crawled assert_nil url.date_crawled end def test_initialize_from_mongo_doc url = Wgit::Url.new @mongo_doc_dup assert_equal @url_str, url assert url.crawled assert_equal @time_stamp, url.date_crawled end def test_initialize_using_parse url = Wgit::Url.parse @url_str assert_equal @url_str, url refute url.crawled assert_nil url.date_crawled end def test_validate Wgit::Url.validate @url_str Wgit::Url.validate @iri assert_raises(RuntimeError) { Wgit::Url.validate @bad_url_str } assert_raises(RuntimeError) { Wgit::Url.validate '/über' } end def test_valid? assert Wgit::Url.valid? @url_str refute Wgit::Url.valid? @bad_url_str assert Wgit::Url.valid? @url_str_anchor assert Wgit::Url.valid? @iri refute Wgit::Url.valid? '/über' end def test_prefix_protocol assert_equal "https://#{@bad_url_str}", Wgit::Url.prefix_protocol( @bad_url_str.dup, true ) assert_equal "http://#{@bad_url_str}", Wgit::Url.prefix_protocol( @bad_url_str.dup ) end def test_replace__from_string url = Wgit::Url.new 'http://www.google.co.uk' new_url = url.replace '/about' assert_equal '/about', url assert_equal '/about', new_url assert_equal '/about', url.to_uri.to_s end def test_replace__from_url url = Wgit::Url.new 'http://www.google.co.uk' new_url = url.replace Wgit::Url.new('/about') assert_equal '/about', url assert_equal '/about', new_url assert_equal '/about', url.to_uri.to_s end def test_is_relative? # Common type URL's. assert Wgit::Url.new(@link).is_relative? refute Wgit::Url.new(@url_str).is_relative? # IRI's. assert Wgit::Url.new('/über').is_relative? refute Wgit::Url.new(@iri).is_relative? # Single slash URL's. assert Wgit::Url.new('/').is_relative? # Anchors/fragments. assert Wgit::Url.new('#about-us').is_relative? refute Wgit::Url.new(@url_str_anchor).is_relative? # Query string params. assert Wgit::Url.new('?foo=bar').is_relative? refute Wgit::Url.new(@url_str_query).is_relative? # Valid error scenarios. ex = assert_raises(RuntimeError) { Wgit::Url.new('').is_relative? } assert_equal "Invalid link: ''", ex.message end def test_is_relative__with_host # IRI's. assert Wgit::Url.new(@iri).is_relative? host: 'https://www.über.com' refute Wgit::Url.new(@iri).is_relative? host: 'https://www.überon.com' # URL's with paths (including slashes). assert Wgit::Url.new(@url_str_link).is_relative? host: @url_str assert Wgit::Url.new('https://www.google.co.uk').is_relative? host: @url_str # Diff protocol. refute Wgit::Url.new(@url_str_link).is_relative? host: 'http://bing.com' assert Wgit::Url.new(@url_str).is_relative? host: @url_str assert Wgit::Url.new(@url_str + '/').is_relative? host: @url_str assert Wgit::Url.new(@url_str + '/').is_relative? host: @url_str + '/' # Single slash URL's. assert Wgit::Url.new('/').is_relative? host: @url_str # Anchors/fragments. assert Wgit::Url.new('#about-us').is_relative? host: @url_str assert Wgit::Url.new(@url_str_anchor).is_relative? host: @url_str # Query string params. assert Wgit::Url.new('?foo=bar').is_relative? host: @url_str assert Wgit::Url.new(@url_str_query).is_relative? host: @url_str # URL specific. refute( Wgit::Url.new('http://www.example.com/search').is_relative?(host: 'https://ftp.example.com') ) refute( 'http://www.example.com/search'.to_url.is_relative?(host: 'https://ftp.example.com'.to_url) ) refute( 'http://www.example.com/search'.to_url.is_relative?(host: 'https://ftp.example.co.uk'.to_url) ) refute( 'https://server.example.com'.to_url.is_relative?(host: 'https://example.com/en'.to_url) ) # Valid error scenarios. ex = assert_raises(RuntimeError) do Wgit::Url.new(@url_str_link).is_relative? host: 'bing.com' end assert_equal( 'Invalid host, must be absolute and contain protocol: bing.com', ex.message ) ex = assert_raises(RuntimeError) { Wgit::Url.new('').is_relative? } assert_equal "Invalid link: ''", ex.message end def test_is_relative__with_domain # IRI's. assert Wgit::Url.new(@iri).is_relative? domain: 'https://www.über.com' refute Wgit::Url.new(@iri).is_relative? domain: 'https://www.überon.com' # URL's with paths (including slashes). assert Wgit::Url.new(@url_str_link).is_relative? domain: @url_str assert Wgit::Url.new('https://www.google.co.uk').is_relative? domain: @url_str # Diff protocol. refute Wgit::Url.new(@url_str_link).is_relative? domain: 'http://bing.com' assert Wgit::Url.new(@url_str).is_relative? domain: @url_str assert Wgit::Url.new(@url_str + '/').is_relative? domain: @url_str assert Wgit::Url.new(@url_str + '/').is_relative? domain: @url_str + '/' # Single slash URL's. assert Wgit::Url.new('/').is_relative? domain: @url_str # Anchors/fragments. assert Wgit::Url.new('#about-us').is_relative? domain: @url_str assert Wgit::Url.new(@url_str_anchor).is_relative? domain: @url_str # Query string params. assert Wgit::Url.new('?foo=bar').is_relative? domain: @url_str assert Wgit::Url.new(@url_str_query).is_relative? domain: @url_str # URL specific. assert( Wgit::Url.new('http://www.example.com/search').is_relative?(domain: 'https://ftp.example.com') ) assert( 'http://www.example.com/search'.to_url.is_relative?(domain: 'https://ftp.example.com'.to_url) ) refute( 'http://www.example.com/search'.to_url.is_relative?(domain: 'https://ftp.example.co.uk'.to_url) ) assert( 'https://server.example.com'.to_url.is_relative?(domain: 'https://example.com/en'.to_url) ) # Valid error scenarios. ex = assert_raises(RuntimeError) do Wgit::Url.new(@url_str_link).is_relative? domain: 'bing.com' end assert_equal( 'Invalid domain, must be absolute and contain protocol: bing.com', ex.message ) ex = assert_raises(RuntimeError) do Wgit::Url.new('/about').is_relative?(host: '1', domain: '2') end assert_equal 'Provide only one of: [:host, :domain, :brand]', ex.message ex = assert_raises(RuntimeError) { Wgit::Url.new('').is_relative? } assert_equal "Invalid link: ''", ex.message end def test_is_relative__with_brand # IRI's. assert Wgit::Url.new(@iri).is_relative? brand: 'https://www.über.com' assert Wgit::Url.new(@iri).is_relative? brand: 'https://www.über.co.uk' # URL's with paths (including slashes). assert Wgit::Url.new(@url_str_link).is_relative? brand: @url_str assert Wgit::Url.new('https://www.google.co.uk').is_relative? brand: @url_str # Diff protocol. assert Wgit::Url.new(@url_str_link).is_relative? brand: 'https://www.google.com' refute Wgit::Url.new(@url_str_link).is_relative? brand: 'http://bing.com' assert Wgit::Url.new(@url_str).is_relative? brand: @url_str assert Wgit::Url.new(@url_str + '/').is_relative? brand: @url_str assert Wgit::Url.new(@url_str + '/').is_relative? brand: @url_str + '/' # Single slash URL's. assert Wgit::Url.new('/').is_relative? brand: @url_str # Anchors/fragments. assert Wgit::Url.new('#about-us').is_relative? brand: @url_str assert Wgit::Url.new(@url_str_anchor).is_relative? brand: @url_str # Query string params. assert Wgit::Url.new('?foo=bar').is_relative? brand: @url_str assert Wgit::Url.new(@url_str_query).is_relative? brand: @url_str # URL specific. assert( Wgit::Url.new('http://www.example.com/search').is_relative?(brand: 'https://ftp.example.com') ) assert( Wgit::Url.new('http://www.example.co.uk/search').is_relative?(brand: 'https://ftp.example.com') ) assert( 'http://www.example.com/search'.to_url.is_relative?(brand: 'https://ftp.example.com'.to_url) ) assert( 'http://www.example.com/search'.to_url.is_relative?(brand: 'https://ftp.example.co.uk'.to_url) ) refute( 'https://server.example.com'.to_url.is_relative?(brand: 'https://example2.com/en'.to_url) ) # Valid error scenarios. ex = assert_raises(RuntimeError) do Wgit::Url.new(@url_str_link).is_relative? brand: 'bing.com' end assert_equal( 'Invalid brand, must be absolute and contain protocol: bing.com', ex.message ) ex = assert_raises(RuntimeError) do Wgit::Url.new('/about').is_relative?(host: '1', brand: '2') end assert_equal 'Provide only one of: [:host, :domain, :brand]', ex.message ex = assert_raises(RuntimeError) { Wgit::Url.new('').is_relative? } assert_equal "Invalid link: ''", ex.message end def test_concat assert_equal @url_str_link, Wgit::Url.concat(@url_str, @link) assert_equal @url_str_link, Wgit::Url.concat(@url_str, @link[1..-1]) assert_equal @url_str_anchor, Wgit::Url.concat(@url_str_link, '#about-us') assert_equal @url_str_query, Wgit::Url.concat(@url_str_link, '?foo=bar') assert_equal 'https://www.über?foo=bar', Wgit::Url.concat('https://www.über', '?foo=bar') end def test_crawled= url = Wgit::Url.new @url_str url.crawled = true assert url.crawled assert url.crawled? end def test_normalise # Normalise an IRI. url = Wgit::Url.new @iri normalised = url.normalise assert_instance_of Wgit::Url, normalised assert_equal 'https://www.xn--ber-goa.com/about#top', normalised # Already normalised URL's stay the same. url = Wgit::Url.new 'https://www.example.com/blah#top' normalised = url.normalise assert_instance_of Wgit::Url, normalised assert_equal 'https://www.example.com/blah#top', normalised end def test_to_uri assert_equal URI::HTTP, Wgit::Url.new(@url_str).to_uri.class assert_equal URI::HTTPS, Wgit::Url.new('https://blah.com').to_uri.class uri = Wgit::Url.new(@iri).to_uri assert_equal URI::HTTPS, uri.class assert_equal 'https://www.xn--ber-goa.com/about#top', uri.to_s end def test_to_url url = Wgit::Url.new @url_str assert_equal url.object_id, url.to_url.object_id assert_equal url, url.to_url assert_equal Wgit::Url, url.to_url.class url = Wgit::Url.new @iri assert_equal url.object_id, url.to_url.object_id assert_equal url, url.to_url assert_equal Wgit::Url, url.to_url.class end def test_to_scheme url = Wgit::Url.new @url_str assert_equal 'http', url.to_scheme assert_equal Wgit::Url, url.to_scheme.class assert_nil Wgit::Url.new(@link).to_scheme url = Wgit::Url.new @iri assert_equal 'https', url.to_scheme assert_equal Wgit::Url, url.to_scheme.class assert_nil Wgit::Url.new('über').to_scheme end def test_to_host assert_equal 'www.google.co.uk', Wgit::Url.new(@url_str_link).to_host assert_equal Wgit::Url, Wgit::Url.new(@url_str_link).to_host.class assert_nil Wgit::Url.new(@link).to_host assert_equal 'www.über.com', Wgit::Url.new(@iri).to_host assert_equal Wgit::Url, Wgit::Url.new(@iri).to_host.class assert_nil Wgit::Url.new('über').to_host end def test_to_domain assert_equal 'google.co.uk', Wgit::Url.new(@url_str_link).to_domain assert_equal Wgit::Url, Wgit::Url.new(@url_str_link).to_domain.class assert_nil Wgit::Url.new(@link).to_domain assert_equal 'über.com', Wgit::Url.new(@iri).to_domain assert_equal Wgit::Url, Wgit::Url.new(@iri).to_domain.class assert_nil Wgit::Url.new('über').to_domain assert_nil Wgit::Url.new('google.co.uk').to_domain assert_nil Wgit::Url.new('/about').to_domain assert_nil Wgit::Url.new('?q=hello').to_domain assert_nil Wgit::Url.new('#top').to_domain end def test_to_brand assert_equal 'google', Wgit::Url.new(@url_str_link).to_brand assert_equal Wgit::Url, Wgit::Url.new(@url_str_link).to_brand.class assert_nil Wgit::Url.new(@link).to_brand assert_equal 'über', Wgit::Url.new(@iri).to_brand assert_equal Wgit::Url, Wgit::Url.new(@iri).to_brand.class assert_nil Wgit::Url.new('über').to_brand assert_nil Wgit::Url.new('/').to_brand assert_nil Wgit::Url.new('').to_brand assert_nil Wgit::Url.new('/about').to_brand assert_nil Wgit::Url.new('?q=hello').to_brand assert_nil Wgit::Url.new('#top').to_brand end def test_to_base assert_equal @url_str, Wgit::Url.new(@url_str_link).to_base assert_equal Wgit::Url, Wgit::Url.new(@url_str_link).to_base.class assert_nil Wgit::Url.new(@link).to_base assert_equal 'https://www.über.com', Wgit::Url.new(@iri).to_base assert_equal Wgit::Url, Wgit::Url.new(@iri).to_base.class assert_nil Wgit::Url.new('über').to_base assert_equal 'https://www.über.com', 'https://www.über.com'.to_url.to_base assert_equal Wgit::Url, 'https://www.über.com'.to_url.to_base.class end def test_to_path url = Wgit::Url.new @url_str_link assert_equal 'about.html', url.to_path assert_equal Wgit::Url, url.to_path.class url = Wgit::Url.new '/about.html' assert_equal 'about.html', url.to_path assert_equal Wgit::Url, url.to_path.class url = Wgit::Url.new '/about.html/' assert_equal 'about.html', url.to_path assert_equal Wgit::Url, url.to_path.class url = Wgit::Url.new '/' assert_equal '/', url.to_path assert_equal Wgit::Url, url.to_path.class url = Wgit::Url.new 'about.html' assert_equal 'about.html', url.to_path assert_equal Wgit::Url, url.to_path.class url = Wgit::Url.new @url_str assert_nil url.to_path url = Wgit::Url.new @url_str_anchor assert_equal 'about.html', url.to_path assert_equal Wgit::Url, url.to_path.class url = Wgit::Url.new @url_str_query assert_equal 'about.html', url.to_path assert_equal Wgit::Url, url.to_path.class url = Wgit::Url.new @iri assert_equal 'about', url.to_path assert_equal Wgit::Url, url.to_path.class end def test_to_endpoint url = Wgit::Url.new @url_str_link assert_equal '/about.html', url.to_endpoint assert_equal Wgit::Url, url.to_endpoint.class url = Wgit::Url.new '/about.html' assert_equal '/about.html', url.to_endpoint assert_equal Wgit::Url, url.to_endpoint.class url = Wgit::Url.new @url_str_link + '/' assert_equal '/about.html/', url.to_endpoint assert_equal Wgit::Url, url.to_endpoint.class url = Wgit::Url.new '/' assert_equal '/', url.to_endpoint assert_equal Wgit::Url, url.to_endpoint.class url = Wgit::Url.new 'about.html' assert_equal '/about.html', url.to_endpoint assert_equal Wgit::Url, url.to_endpoint.class url = Wgit::Url.new @url_str assert_equal '/', url.to_endpoint assert_equal Wgit::Url, url.to_endpoint.class url = Wgit::Url.new @url_str_anchor assert_equal '/about.html', url.to_endpoint assert_equal Wgit::Url, url.to_endpoint.class url = Wgit::Url.new @url_str_query assert_equal '/about.html', url.to_endpoint assert_equal Wgit::Url, url.to_endpoint.class url = Wgit::Url.new @iri assert_equal '/about', url.to_endpoint assert_equal Wgit::Url, url.to_endpoint.class end def test_to_query_string url = Wgit::Url.new @url_str_link + '?q=ruby&page=2' assert_equal '?q=ruby&page=2', url.to_query_string assert_equal Wgit::Url, url.to_query_string.class url = Wgit::Url.new 'https://www.über.com/about?q=ruby&page=2' assert_equal '?q=ruby&page=2', url.to_query_string assert_equal Wgit::Url, url.to_query_string.class url = Wgit::Url.new @url_str assert_nil url.to_query_string end def test_to_anchor url = Wgit::Url.new @url_str_anchor assert_equal '#about-us', url.to_anchor assert_equal Wgit::Url, url.to_anchor.class url = Wgit::Url.new '#about-us' assert_equal '#about-us', url.to_anchor assert_equal Wgit::Url, url.to_anchor.class url = Wgit::Url.new @iri assert_equal '#top', url.to_anchor assert_equal Wgit::Url, url.to_anchor.class url = Wgit::Url.new @url_str assert_nil url.to_anchor end def test_to_extension url = Wgit::Url.new @url_str_link assert_equal 'html', url.to_extension assert_equal Wgit::Url, url.to_extension.class url = Wgit::Url.new '/img/icon/apple-touch-icon-76x76.png?v=kPgE9zo' assert_equal 'png', url.to_extension assert_equal Wgit::Url, url.to_extension.class url = Wgit::Url.new 'https://www.über.com/about.html' assert_equal 'html', url.to_extension assert_equal Wgit::Url, url.to_extension.class url = Wgit::Url.new @url_str assert_nil url.to_extension end def test_without_leading_slash url = Wgit::Url.new @url_str assert_equal @url_str, url.without_leading_slash assert_equal Wgit::Url, url.without_leading_slash.class url = Wgit::Url.new @link assert_equal 'about.html', url.without_leading_slash assert_equal Wgit::Url, url.without_leading_slash.class url = Wgit::Url.new '/über' assert_equal 'über', url.without_leading_slash assert_equal Wgit::Url, url.without_leading_slash.class end def test_without_trailing_slash url = Wgit::Url.new @url_str assert_equal @url_str, url.without_trailing_slash assert_equal Wgit::Url, url.without_trailing_slash.class url = Wgit::Url.new @url_str + '/' assert_equal @url_str, url.without_trailing_slash assert_equal Wgit::Url, url.without_trailing_slash.class url = Wgit::Url.new 'über/' assert_equal 'über', url.without_trailing_slash assert_equal Wgit::Url, url.without_trailing_slash.class end def test_without_slashes url = Wgit::Url.new 'link.html' assert_equal 'link.html', url.without_slashes assert_equal Wgit::Url, url.without_slashes.class url = Wgit::Url.new '/link.html/' assert_equal 'link.html', url.without_slashes assert_equal Wgit::Url, url.without_slashes.class url = Wgit::Url.new '/über/' assert_equal 'über', url.without_slashes assert_equal Wgit::Url, url.without_slashes.class end def test_without_base url = Wgit::Url.new 'http://google.com/search?q=foo#bar' assert_equal 'search?q=foo#bar', url.without_base assert_equal Wgit::Url, url.without_base.class url = Wgit::Url.new '/about.html' assert_equal 'about.html', url.without_base assert_equal Wgit::Url, url.without_base.class url = Wgit::Url.new '/about.html#hello/' assert_equal 'about.html#hello', url.without_base assert_equal Wgit::Url, url.without_base.class url = Wgit::Url.new '/about.html/hello?a=b&b=c#about' assert_equal 'about.html/hello?a=b&b=c#about', url.without_base assert_equal Wgit::Url, url.without_base.class url = Wgit::Url.new '/' assert_equal url, url.without_base assert_equal Wgit::Url, url.without_base.class url = Wgit::Url.new 'https://google.com/' assert_equal url, url.without_base assert_equal Wgit::Url, url.without_base.class url = Wgit::Url.new 'https://google.com' assert_equal url, url.without_base assert_equal Wgit::Url, url.without_base.class url = Wgit::Url.new @iri assert_equal 'about#top', url.without_base assert_equal Wgit::Url, url.without_base.class end def test_without_query_string url = Wgit::Url.new 'http://google.com/search?q=hello&foo=bar' assert_equal 'http://google.com/search', url.without_query_string assert_equal Wgit::Url, url.without_query_string.class url = Wgit::Url.new '/about.html' assert_equal '/about.html', url.without_query_string assert_equal Wgit::Url, url.without_query_string.class url = Wgit::Url.new '/about.html?q=hello&foo=bar' assert_equal '/about.html', url.without_query_string assert_equal Wgit::Url, url.without_query_string.class url = Wgit::Url.new '/about.html/hello?a=b&b=c#about' assert_equal '/about.html/hello#about', url.without_query_string assert_equal Wgit::Url, url.without_query_string.class url = Wgit::Url.new '/about.html/hello#about?a=b&b=c' # Invalid anchor. assert_equal '/about.html/hello#about?a=b&b=c', url.without_query_string assert_equal Wgit::Url, url.without_query_string.class url = Wgit::Url.new '/' assert_equal url, url.without_query_string assert_equal Wgit::Url, url.without_query_string.class url = Wgit::Url.new '?q=hello&foo=bar' assert_empty url.without_query_string assert_equal Wgit::Url, url.without_query_string.class url = Wgit::Url.new 'https://google.com/' assert_equal url, url.without_query_string assert_equal Wgit::Url, url.without_query_string.class url = Wgit::Url.new 'https://google.com' assert_equal url, url.without_query_string assert_equal Wgit::Url, url.without_query_string.class iri_without_anchor = 'https://www.über.com/about' url = Wgit::Url.new iri_without_anchor + '?q=hello' assert_equal iri_without_anchor, url.without_query_string assert_equal Wgit::Url, url.without_query_string.class end def test_without_anchor url = Wgit::Url.new 'http://google.com/search?q=foo#bar' assert_equal 'http://google.com/search?q=foo', url.without_anchor assert_equal Wgit::Url, url.without_anchor.class url = Wgit::Url.new '/about.html' assert_equal '/about.html', url.without_anchor assert_equal Wgit::Url, url.without_anchor.class url = Wgit::Url.new '/about.html#hello/' assert_equal '/about.html', url.without_anchor assert_equal Wgit::Url, url.without_anchor.class url = Wgit::Url.new '/about.html/hello?a=b&b=c#about' assert_equal '/about.html/hello?a=b&b=c', url.without_anchor assert_equal Wgit::Url, url.without_anchor.class url = Wgit::Url.new '/about.html/hello#about?a=b&b=c' # Invalid anchor. assert_equal '/about.html/hello', url.without_anchor assert_equal Wgit::Url, url.without_anchor.class url = Wgit::Url.new '/' assert_equal url, url.without_anchor assert_equal Wgit::Url, url.without_anchor.class url = Wgit::Url.new '#about' assert_empty url.without_anchor assert_equal Wgit::Url, url.without_anchor.class url = Wgit::Url.new '/about#' assert_equal '/about', url.without_anchor assert_equal Wgit::Url, url.without_anchor.class url = Wgit::Url.new 'https://google.com/' assert_equal url, url.without_anchor assert_equal Wgit::Url, url.without_anchor.class url = Wgit::Url.new 'https://google.com' assert_equal url, url.without_anchor assert_equal Wgit::Url, url.without_anchor.class url = Wgit::Url.new @iri assert_equal 'https://www.über.com/about', url.without_anchor assert_equal Wgit::Url, url.without_anchor.class end def test_is_query_string? url = Wgit::Url.new '?q=hello' assert url.is_query_string? url = Wgit::Url.new '?q=hello&z=world' assert url.is_query_string? url = Wgit::Url.new '#top' refute url.is_query_string? url = Wgit::Url.new '/about?q=hello' refute url.is_query_string? url = Wgit::Url.new 'http://example.com?q=hello' refute url.is_query_string? end def test_is_anchor? url = Wgit::Url.new '#' assert url.is_anchor? url = Wgit::Url.new '?q=hello' refute url.is_anchor? url = Wgit::Url.new '/public#top' refute url.is_anchor? url = Wgit::Url.new 'http://example.com#top' refute url.is_anchor? url = Wgit::Url.new 'http://example.com/home#top' refute url.is_anchor? end def test_to_h assert_equal @mongo_doc_dup, Wgit::Url.new(@mongo_doc_dup).to_h end end
33.487838
101
0.690085
20e7e03488835e9abb074f5ce10f003d92866888
12,366
cs
C#
nanoFramework.Graphics/Presentation/Media/SolidColorBrush.cs
josesimoes/nanoFramework.Graphics
0478bbc27136d7b562bb1d7f9cfbdf766e737308
[ "MIT" ]
3
2021-01-04T17:07:43.000Z
2021-01-21T12:03:43.000Z
nanoFramework.Graphics/Presentation/Media/SolidColorBrush.cs
josesimoes/nanoFramework.Graphics
0478bbc27136d7b562bb1d7f9cfbdf766e737308
[ "MIT" ]
10
2020-05-21T06:32:34.000Z
2020-12-22T09:27:52.000Z
nanoFramework.Graphics/Presentation/Media/SolidColorBrush.cs
josesimoes/nanoFramework.Graphics
0478bbc27136d7b562bb1d7f9cfbdf766e737308
[ "MIT" ]
6
2020-05-20T12:33:46.000Z
2020-10-16T19:20:51.000Z
// // Copyright (c) .NET Foundation and Contributors // Portions Copyright (c) Microsoft Corporation. All rights reserved. // See LICENSE file in the project root for full license information. // using System; using nanoFramework.UI; namespace nanoFramework.Presentation.Media { /// <summary> /// /// </summary> public sealed class SolidColorBrush : Brush { /// <summary> /// /// </summary> public Color Color; /// <summary> /// /// </summary> /// <param name="color"></param> public SolidColorBrush(Color color) { Color = color; } /// <summary> /// /// </summary> /// <param name="bmp"></param> /// <param name="pen"></param> /// <param name="x"></param> /// <param name="y"></param> /// <param name="width"></param> /// <param name="height"></param> protected internal override void RenderRectangle(Bitmap bmp, Pen pen, int x, int y, int width, int height) { Color outlineColor = (pen != null) ? pen.Color : (Color)0x0; ushort outlineThickness = (pen != null) ? pen.Thickness : (ushort)0; bmp.DrawRectangle(outlineColor, outlineThickness, x, y, width, height, 0, 0, Color, 0, 0, Color, 0, 0, Opacity); } /// <summary> /// /// </summary> /// <param name="bmp"></param> /// <param name="pen"></param> /// <param name="x"></param> /// <param name="y"></param> /// <param name="xRadius"></param> /// <param name="yRadius"></param> protected internal override void RenderEllipse(Bitmap bmp, Pen pen, int x, int y, int xRadius, int yRadius) { Color outlineColor = (pen != null) ? pen.Color : (Color)0x0; ushort outlineThickness = (pen != null) ? pen.Thickness : (ushort)0; bmp.DrawEllipse(outlineColor, outlineThickness, x, y, xRadius, yRadius, Color, 0, 0, Color, 0, 0, Opacity); } class LineSegment { public int x1; public int y1; public int x2; public int y2; /// <summary> /// We will use Bresenham alg for line calc. /// </summary> public int dx; public int dy; public int cx; public int e; public bool highSlope; public int ix; public int processedPts; } private void Swap(ref int a, ref int b) { int t = a; a = b; b = t; } private int Abs(int a) { if (a < 0) return -a; return a; } const int c_YMinBit = 0x40000000; const int c_XValueMask = 0x3FFFFFFF; /// <summary> /// Basic algorithm uses scan lines to fill the polygon. /// No multiplication or division is needed, neither is floating point calculation. /// </summary> /// <param name="bmp"></param> /// <param name="outline"></param> /// <param name="pts"></param> protected internal override void RenderPolygon(Bitmap bmp, Pen outline, int[] pts) { int n = pts.Length / 2; // This is number of points and number of lines (closed polygon). // Polygon to fill must have at least 3 points. if (n < 3) return; // Nothing to do if this is a transparent brush. if (Opacity == Bitmap.OpacityTransparent) return; int i = 0; int y = 0; int yLow = 0; int yHigh = 0; LineSegment[] lines = new LineSegment[n]; int []xPoints = new int[n]; // Initialize line segments. for (i = 0; i < n; i++) { lines[i] = new LineSegment(); lines[i].processedPts = 0; xPoints[i] = new int(); lines[i].x1 = pts[i * 2]; lines[i].y1 = pts[i * 2 + 1]; if (i < (n - 1)) { lines[i].x2 = pts[(i + 1) * 2]; lines[i].y2 = pts[(i + 1) * 2 + 1]; } else { lines[i].x2 = pts[0]; lines[i].y2 = pts[1]; } // Reverse the points to make sure y1 <= y2 always. if (lines[i].y2 < lines[i].y1) { Swap(ref lines[i].y2, ref lines[i].y1); Swap(ref lines[i].x2, ref lines[i].x1); } // Calculate slopes and increments. lines[i].dx = Abs(lines[i].x2 - lines[i].x1); lines[i].dy = Abs(lines[i].y2 - lines[i].y1); lines[i].cx = lines[i].x1; lines[i].e = 0; if (lines[i].dx < lines[i].dy) { // Angle is 45 degree or more. So y increases faster. lines[i].highSlope = true; } else { lines[i].highSlope = false; } // Actual increment direction. if (lines[i].x2 > lines[i].x1) lines[i].ix = 1; else lines[i].ix = -1; if (i == 0) { yLow = lines[i].y1; yHigh = lines[i].y2; } else { if (lines[i].y1 < yLow) yLow = lines[i].y1; if (lines[i].y2 > yHigh) yHigh = lines[i].y2; } } // Fill via scan lines between yLow and yHigh. for (y = yLow; y <= yHigh; y++) { int j = 0; for (i = 0; i < n; i++) { xPoints[i] = Int32.MaxValue; } // Find intersection points for given y. for (i = 0; i < n; i++) { if (y < lines[i].y1) continue; if (y > lines[i].y2) continue; lines[i].processedPts++; if (lines[i].dy != 0) { if (lines[i].highSlope) { // For this y find the x, which either the same pixel // in last iteration or next one. if (y == lines[i].y1) lines[i].cx = lines[i].x1; else if (y == lines[i].y2) lines[i].cx = lines[i].x2; else { lines[i].e += lines[i].dx; if ((lines[i].e << 1) >= lines[i].dy) { lines[i].cx += lines[i].ix; lines[i].e -= lines[i].dy; } } } else { // In this case for every y pixel inc, x increases more than 1 pixel. if (y == lines[i].y1) lines[i].cx = lines[i].x1; else if (y == lines[i].y2) lines[i].cx = lines[i].x2; else { for (; ; ) { lines[i].cx += lines[i].ix; lines[i].e += lines[i].dy; if ((lines[i].e << 1) >= lines[i].dx) { lines[i].e -= lines[i].dx; break; } } } } } // Insertion sort, do not insert back to back duplicates int x1; bool x1YMin; int x2 = int.MaxValue; bool x2YMin = false; // add both x endpoints if the line is horizontal if (lines[i].dy == 0) { x1 = lines[i].x1; x1YMin = true; x2 = lines[i].x2; x2YMin = true; if (x2 < 0) x2 = 0; } else { x1 = lines[i].cx; x1YMin = lines[i].processedPts == 1; } // We don't need to process negative values of x if (x1 < 0) x1 = 0; int idx1 = -1; int idx2 = x2 == int.MaxValue ? x2 : -1; int offset = 0; // First we search for the indexes of x1 and x2 (if neccessary) and then we will insert the // items, by shifting the elements in the array for (j = 0; j < n; j++) { int ix = (xPoints[j] & c_XValueMask); bool isYMin = (xPoints[j] & c_YMinBit) != 0; if (idx1 == -1) { // Only add duplicate x values if the intersection produces up (^) or down (v) angles // as opposed to right (<) or left (>) angles. if (ix == x1 && isYMin != x1YMin) { idx1 = int.MaxValue; } else if (ix > x1 ) { idx1 = j + offset; offset++; } } if (idx2 == -1) { // Only add duplicate x values if the intersection produces up (^) or down (v) angles // as opposed to right (<) or left (>) angles. if (ix == x2 && isYMin != x2YMin) { idx2 = int.MaxValue; } else if (ix > x2 ) { idx2 = j + offset; offset++; } } // don't break until we have found both indexes and then end of the list if(idx1 != -1 && idx2 != -1 && xPoints[j] == int.MaxValue) break; } int idxMin = (idx1 < idx2 ? idx1 : idx2); // Because we may have two values to insert, the index to the next item to be shifted // can either be n-1 or n-2. offset = (idx2 == int.MaxValue || idx1 == int.MaxValue ? 1 : 2); // j is already one element past the last valid data item, so increase it by one if we are // inserting two elements j += (offset - 1); // Make sure the index does not overflow if (j >= xPoints.Length) j = xPoints.Length-1; for (; j >= idxMin; j--) { if (j == idx1) { xPoints[j] = x1YMin ? x1 | c_YMinBit : x1; offset--; continue; } if (j == idx2) { xPoints[j] = x2YMin ? x2 | c_YMinBit : x2; offset--; continue; } if (j < offset) break; xPoints[j] = xPoints[j - offset]; } } // Finally draw the line segments to fill. for (i = 0; i < xPoints.Length - 1; i += 2) { int ix1 = (xPoints[i ] & c_XValueMask); int ix2 = (xPoints[i + 1] & c_XValueMask); if ((ix1 == c_XValueMask) || (ix2 == c_XValueMask)) break; bmp.DrawLine(Color, 1, ix1, y, ix2, y); } } } } }
35.331429
115
0.377406
663582017e45ebc25559ce63cde60fefc1b77662
5,588
py
Python
tests/key_params/test_dss.py
FloLie/openssh_key_parser
44cdc6c2085069e7c2612841de38f581f8ef226c
[ "MIT" ]
null
null
null
tests/key_params/test_dss.py
FloLie/openssh_key_parser
44cdc6c2085069e7c2612841de38f581f8ef226c
[ "MIT" ]
null
null
null
tests/key_params/test_dss.py
FloLie/openssh_key_parser
44cdc6c2085069e7c2612841de38f581f8ef226c
[ "MIT" ]
null
null
null
import pytest from cryptography.hazmat.primitives.asymmetric import dsa from openssh_key.key_params import DSSPrivateKeyParams, DSSPublicKeyParams from openssh_key.pascal_style_byte_stream import PascalStyleFormatInstruction PARAMS_TEST_CASES = [ { 'cls': DSSPublicKeyParams, 'format_instructions_dict': { 'p': PascalStyleFormatInstruction.MPINT, 'q': PascalStyleFormatInstruction.MPINT, 'g': PascalStyleFormatInstruction.MPINT, 'y': PascalStyleFormatInstruction.MPINT, }, 'valid_values': [{ 'p': 1, 'q': 2, 'g': 3, 'y': 4, }] }, { 'cls': DSSPrivateKeyParams, 'format_instructions_dict': { 'p': PascalStyleFormatInstruction.MPINT, 'q': PascalStyleFormatInstruction.MPINT, 'g': PascalStyleFormatInstruction.MPINT, 'y': PascalStyleFormatInstruction.MPINT, 'x': PascalStyleFormatInstruction.MPINT, }, 'valid_values': [{ 'p': 1, 'q': 2, 'g': 3, 'y': 4, 'x': 5, }] } ] def test_dss_public_convert_from_unknown(): with pytest.raises(NotImplementedError): DSSPublicKeyParams.convert_from('random') def test_dss_public_convert_from_cryptography_public(): private_key = dsa.generate_private_key( DSSPrivateKeyParams.KEY_SIZE ).public_key() public_numbers = private_key.public_numbers() parameter_numbers = public_numbers.parameter_numbers converted = DSSPublicKeyParams.convert_from(private_key) assert type(converted) == DSSPublicKeyParams assert converted == { 'p': parameter_numbers.p, 'q': parameter_numbers.q, 'g': parameter_numbers.g, 'y': public_numbers.y, } def test_dss_public_convert_from_cryptography_private(): private_key = dsa.generate_private_key( DSSPrivateKeyParams.KEY_SIZE ) private_numbers = private_key.private_numbers() public_numbers = private_numbers.public_numbers parameter_numbers = public_numbers.parameter_numbers converted = DSSPublicKeyParams.convert_from(private_key) assert type(converted) == DSSPublicKeyParams assert converted == { 'p': parameter_numbers.p, 'q': parameter_numbers.q, 'g': parameter_numbers.g, 'y': public_numbers.y, } def test_dss_public_convert_to_cryptography_public(): dss_private = DSSPrivateKeyParams.generate_private_params() dss_public = DSSPublicKeyParams({ 'p': dss_private['p'], 'q': dss_private['q'], 'g': dss_private['g'], 'y': dss_private['y'], }) converted = dss_public.convert_to(dsa.DSAPublicKey) assert isinstance(converted, dsa.DSAPublicKey) assert converted.public_numbers() == dsa.DSAPublicNumbers( dss_public['y'], dsa.DSAParameterNumbers( dss_public['p'], dss_public['q'], dss_public['g'] ) ) def test_dss_private_convert_from_unknown(): with pytest.raises(NotImplementedError): DSSPrivateKeyParams.convert_from('random') def test_dss_private_convert_from_cryptography_private(): private_key = dsa.generate_private_key( DSSPrivateKeyParams.KEY_SIZE ) private_numbers = private_key.private_numbers() public_numbers = private_numbers.public_numbers parameter_numbers = public_numbers.parameter_numbers converted = DSSPrivateKeyParams.convert_from(private_key) assert type(converted) == DSSPrivateKeyParams assert converted == { 'p': parameter_numbers.p, 'q': parameter_numbers.q, 'g': parameter_numbers.g, 'y': public_numbers.y, 'x': private_numbers.x, } def test_dss_private_convert_to_cryptography_private(): dss_private = DSSPrivateKeyParams.generate_private_params() converted = dss_private.convert_to(dsa.DSAPrivateKey) assert isinstance(converted, dsa.DSAPrivateKey) assert converted.private_numbers() == dsa.DSAPrivateNumbers( dss_private['x'], dsa.DSAPublicNumbers( dss_private['y'], dsa.DSAParameterNumbers( dss_private['p'], dss_private['q'], dss_private['g'] ) ) ) def test_dss_private_convert_to_cryptography_dssprivatekey(): dss_private = DSSPrivateKeyParams.generate_private_params() converted = dss_private.convert_to(dsa.DSAPrivateKey) assert isinstance(converted, dsa.DSAPrivateKey) assert converted.private_numbers() == dsa.DSAPrivateNumbers( dss_private['x'], dsa.DSAPublicNumbers( dss_private['y'], dsa.DSAParameterNumbers( dss_private['p'], dss_private['q'], dss_private['g'] ) ) ) def test_dss_private_convert_to_cryptography_public(): dss_private = DSSPrivateKeyParams.generate_private_params() converted = dss_private.convert_to(dsa.DSAPublicKey) assert isinstance(converted, dsa.DSAPublicKey) assert converted.public_numbers() == dsa.DSAPublicNumbers( dss_private['y'], dsa.DSAParameterNumbers( dss_private['p'], dss_private['q'], dss_private['g'] ) ) def test_dss_public_convert_to_not_implemented(): dss_private = DSSPrivateKeyParams.generate_private_params() with pytest.raises(NotImplementedError): assert dss_private.convert_to(type)
31.931429
77
0.656049
7be7e3a9791d159ff8ed1d8d403e49dc34097259
4,029
cc
C++
cc/test-settings-v1.cc
acorg/acmacs-base
a1a6e5b346ea3746f3fc1750ed4b7f29c7c0d049
[ "MIT" ]
null
null
null
cc/test-settings-v1.cc
acorg/acmacs-base
a1a6e5b346ea3746f3fc1750ed4b7f29c7c0d049
[ "MIT" ]
null
null
null
cc/test-settings-v1.cc
acorg/acmacs-base
a1a6e5b346ea3746f3fc1750ed4b7f29c7c0d049
[ "MIT" ]
null
null
null
#include <iostream> #include "acmacs-base/settings-v1.hh" // ---------------------------------------------------------------------- struct AAAtPos : public acmacs::settings::v1::object { acmacs::settings::v1::field<size_t> diverse_index_threshold{this, "diverse_index_threshold", 3}; acmacs::settings::v1::field<double> line_length{this, "line_length", 0.5}; acmacs::settings::v1::field<bool> report_most_diverse_positions{this, "report_most_diverse_positions", false}; acmacs::settings::v1::field<std::string> comment{this, "comment"}; using acmacs::settings::v1::object::object; }; struct Mod : public acmacs::settings::v1::object { acmacs::settings::v1::field<std::string> name{this, "N"}; acmacs::settings::v1::field<double> d1{this, "d1", 1.0/8.0}; using acmacs::settings::v1::object::object; }; struct Settings : public acmacs::settings::v1::toplevel { acmacs::settings::v1::field<std::string> version{this, " version", "signature-page-settings-v4"}; acmacs::settings::v1::field_object<AAAtPos> aa_at_pos{this, "aa_at_pos"}; acmacs::settings::v1::field_array<double> viewport{this, "viewport", {0.125, 0.25, 122}}; acmacs::settings::v1::field_array_of<Mod> mods{this, "mods"}; acmacs::settings::v1::field<acmacs::Size> size{this, "size", {7, 8}}; acmacs::settings::v1::field<acmacs::Offset> offset{this, "offset", {-1, 111}}; acmacs::settings::v1::field<Color> fill{this, "fill", "cornflowerblue"}; acmacs::settings::v1::field<acmacs::TextStyle> text_style{this, "text_style", "monospace"}; }; // ---------------------------------------------------------------------- int main() { int exit_code = 0; try { Settings s1; s1.inject_default(); std::cout << s1.pretty() << '\n'; std::cout << "report_most_diverse_positions: " << s1.aa_at_pos->report_most_diverse_positions << '\n'; s1.aa_at_pos->report_most_diverse_positions = true; std::cout << "report_most_diverse_positions: " << s1.aa_at_pos->report_most_diverse_positions << '\n'; std::cout << "line_length: " << s1.aa_at_pos->line_length << '\n'; s1.aa_at_pos->line_length = 1.2; std::cout << "line_length: " << s1.aa_at_pos->line_length << '\n'; std::cout << "size: " << acmacs::to_string(s1.size) << '\n'; s1.size = acmacs::Size{9, 10}; std::cout << "size: " << acmacs::to_string(s1.size) << '\n'; std::cout << "offset: " << s1.offset << '\n'; s1.offset = acmacs::Offset{12, -13.5}; std::cout << "offset: " << s1.offset << '\n'; std::cout << fmt::format("fill: \"{}\"\n", *s1.fill); s1.fill = Color("#123456"); std::cout << fmt::format("fill: \"{}\"\n", *s1.fill); std::cout << "text_style: " << s1.text_style << '\n'; s1.text_style = acmacs::TextStyle("serif"); std::cout << "text_style: " << s1.text_style << '\n'; std::cout << "aa_at_pos: " << s1.aa_at_pos << '\n'; std::cout << "viewport: " << s1.viewport << '\n'; s1.viewport.append(s1.viewport[2]); std::cout << "viewport: " << s1.viewport << '\n'; std::cout << '\n'; auto mod1 = s1.mods.append(); mod1->name = "first"; std::cout << "mod1->name: " << *mod1->name << '\n'; s1.mods.append()->name = "second"; std::cout << s1.pretty() << '\n'; if (auto found = s1.mods.find_if([](const Mod& mod) { AD_DEBUG("mod.name {}", *mod.name); return mod.name == "second"; }); found) std::cout << "found: " << *found << '\n'; else std::cout << "mod \"second\" not found!\n"; } catch (std::exception& err) { std::cerr << "ERROR: " << err.what() << '\n'; exit_code = 1; } return exit_code; } // ---------------------------------------------------------------------- /// Local Variables: /// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer)) /// End:
41.96875
137
0.542318
2c78ab5bfbd0e695ccc1569eb21c243db6398254
221
cpp
C++
filter_ultrasonic.cpp
lchappellet/SignalLamp
a72473e332ea1104d6a321088875e84772dd3cf5
[ "BSD-2-Clause" ]
null
null
null
filter_ultrasonic.cpp
lchappellet/SignalLamp
a72473e332ea1104d6a321088875e84772dd3cf5
[ "BSD-2-Clause" ]
null
null
null
filter_ultrasonic.cpp
lchappellet/SignalLamp
a72473e332ea1104d6a321088875e84772dd3cf5
[ "BSD-2-Clause" ]
null
null
null
#include "filter_ultrasonic.h" //Filter_ultrasonic::Filter_ultrasonic() {} double Filter_ultrasonic::average_ping_filter(double sonar_ping) { ping_value = 0.9 * ping_value + 0.1 * sonar_ping; return ping_value; }
20.090909
66
0.755656
2c64e014214c8480176c486927ffb9ecd7361629
7,558
py
Python
apps/business/models.py
aspic2/rendermaps
517905c5f970bbb8bba87e9599be874fc0fd250d
[ "MIT" ]
null
null
null
apps/business/models.py
aspic2/rendermaps
517905c5f970bbb8bba87e9599be874fc0fd250d
[ "MIT" ]
24
2018-02-21T22:51:24.000Z
2022-03-11T23:12:25.000Z
apps/business/models.py
aspic2/jobs-by-neighborhood
517905c5f970bbb8bba87e9599be874fc0fd250d
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models from django.core.exceptions import ObjectDoesNotExist from django.core.exceptions import ValidationError from django.core.validators import RegexValidator, EmailValidator, URLValidator from main.settings_deploy import DOMAIN_NAME from datetime import date, datetime, timedelta from django.contrib.auth.models import User # Imported filter was created to sort database queries ignoring letter case from ..app_filters import case_insensitive_criteria from industries import INDUSTRY_INDEX # Import Localflavor for US Geographic data # Reference documentation: http://django-localflavor.readthedocs.io/en/latest from localflavor.us.us_states import US_STATES from localflavor.us.models import USZipCodeField from main.settings import BASE_DIR import re import os import json INDUSTRY_KEY_FIELD = 'industries' INDUSTRY_CODE = 'industry_code' INDUSTRY_NAME = 'industry_title' SUBINDUSTRIES = 'sub_industries' JSON_FILE = os.path.join(BASE_DIR, 'static', 'base', 'json', 'naics_industries.json') INDUSTRY_INDEX_FILE = os.path.join(BASE_DIR, 'apps', 'business', 'industries.py') PHONE_REGEX = RegexValidator( regex=r'^\d{3}-\d{3}-\d{4}(\sext.\d{1,5})?$', message="Phone number must be entered in the format: '999-999-9999'.") STATUS_CODES = [ ('submitted', 'Submitted'), ('review', 'Under Review'), ('approved', 'Approved') ] def get_industry_choices(key_field=INDUSTRY_KEY_FIELD): # Return a tuple of field choices from a json file of industry categories # Import NAICS Industry categories from US Bureau of Labor Statistics JSON data with open(JSON_FILE) as f: json_data = json.load(f) choices_list = [] if key_field in json_data: industries = json_data[key_field] for industry in industries: choices_list.append((industry[INDUSTRY_CODE], industry[INDUSTRY_NAME][0])) choices_list = sort_list(choices_list) return tuple(choices_list) def index_industries(): # Generate an index of the industries in the JSON file # Index key = Industry Code; value = Industry Name index = {} with open(JSON_FILE) as f: json_data = json.load(f) if INDUSTRY_KEY_FIELD in json_data: industries = json_data[INDUSTRY_KEY_FIELD] for industry in industries: index[industry[INDUSTRY_CODE]] = industry[INDUSTRY_NAME][0] if SUBINDUSTRIES in industry: for sub in industry[SUBINDUSTRIES]: index[sub[INDUSTRY_CODE]] = sub[INDUSTRY_NAME] with open(INDUSTRY_INDEX_FILE, 'w') as fw: fw.write('INDUSTRY_INDEX = {}'.format(index)) return def get_industry_subchoices(parent_industry_code): # Return a tuple of field choices from a json file of industry categories # Import NAICS Industry categories from US Bureau of Labor Statistics JSON data with open(JSON_FILE) as f: json_data = json.load(f) choices_list = [] industries = json_data[INDUSTRY_KEY_FIELD] for industry in industries: if industry[INDUSTRY_CODE] == parent_industry_code: for sub in industry[SUBINDUSTRIES]: choices_list.append((sub[INDUSTRY_CODE], sub[INDUSTRY_NAME])) break choices_list = sort_list(choices_list) return tuple(choices_list) def sort_list(choices): return sorted(choices, key=lambda choice: choice[1]) class BusinessManager(models.Manager): def get_all(self, sort_field=None, default="name"): if sort_field == None: sort_field = default if "created_at" in sort_field or "updated_at" in sort_field: lower_field = sort_field order_field = sort_field else: lower_field, order_field = case_insensitive_criteria(sort_field) businesses = (Business.objects.all() .extra(select={'lower_field':lower_field}) .order_by(order_field)) for b in businesses: b.industry = INDUSTRY_INDEX[b.industry] return businesses def get_total(self): # totals = {} pass # totals['total'] = Contact.objects.all().count() # return totals def get_or_create_contact(self, first_name, last_name, email): # created = False pass # try: # contact = Contact.objects.get(email=email) # except Contact.DoesNotExist: # contact = Contact.objects.create( # first_name=first_name, # last_name=last_name, # email=email # ) # created = True # return contact, created def update_timestamp(self, email): pass # contact = Contact.objects.get(email=email) # contact.save() # return class Business(models.Model): name = models.CharField(max_length=100) industry = models.CharField( max_length=2, default="", choices=get_industry_choices(), validators=[ RegexValidator( regex='^[0-9]{2}$', message='Please select an industry from the list.' ) ] ) subindustry = models.CharField( max_length=3, default="", blank=True, choices=get_industry_subchoices('72') ) website = models.CharField( max_length=100, blank=True, validators=[URLValidator()] ) email = models.EmailField( max_length=100, blank=True, validators=[EmailValidator()] ) phone = models.CharField( max_length=20, blank=True, validators=[PHONE_REGEX] ) primary_poc = models.CharField( max_length=50, blank=True ) poc_role = models.CharField( max_length=30, blank=True ) created_by = models.ForeignKey( User, on_delete=models.PROTECT, related_name="businesses_created" ) created_at = models.DateTimeField(auto_now_add=True) status = models.CharField( max_length=10, default="submitted", choices=STATUS_CODES ) updated_at = models.DateTimeField(auto_now=True) objects = BusinessManager() class LocationManager(models.Manager): pass class Location(models.Model): name = models.CharField( max_length=50, default="Primary" ) business = models.ForeignKey( Business, on_delete=models.CASCADE, related_name="locations") is_primary = models.BooleanField(default=True) street = models.CharField( max_length=50, default="", blank=True, null=True ) city = models.CharField( max_length=50, default="" ) state = models.CharField( max_length=2, default="IL", choices=US_STATES ) zipcode = USZipCodeField( blank=True ) longitude = models.DecimalField( max_digits=12, decimal_places=8, default=0 ) latitude = models.DecimalField( max_digits=12, decimal_places=8, default=0 ) neighborhood = models.CharField( max_length=50, blank=True, default='' ) phone = models.CharField( max_length=20, blank=True, validators=[PHONE_REGEX] ) #objects = LocationManager()
29.755906
90
0.632442
80fcdc5e9bd67ad198e94fafad5d98aaa402af6d
8,544
lua
Lua
lua/mediaplayer/utils.lua
kevinhenschen/gm-mediaplayer
61636f52349b8ad08acec95f7e24bc69092d10b0
[ "MIT" ]
null
null
null
lua/mediaplayer/utils.lua
kevinhenschen/gm-mediaplayer
61636f52349b8ad08acec95f7e24bc69092d10b0
[ "MIT" ]
null
null
null
lua/mediaplayer/utils.lua
kevinhenschen/gm-mediaplayer
61636f52349b8ad08acec95f7e24bc69092d10b0
[ "MIT" ]
null
null
null
if SERVER then AddCSLuaFile() end local file = file local math = math local urllib = url local ceil = math.ceil local floor = math.floor local Round = math.Round local log = math.log local pow = math.pow local format = string.format local tostring = tostring local IsValid = IsValid local utils = {} --- -- Ceil the given number to the largest power of two. -- function utils.CeilPower2(n) return pow(2, ceil(log(n) / log(2))) end --- -- Method for easily grabbing a value from a table without checking that each -- fragment exists. -- -- @param tbl Table -- @param key e.g. "json.key.fragments" -- function utils.TableLookup( tbl, key ) local fragments = string.Split(key, '.') local value = tbl for _, fragment in ipairs(fragments) do value = value[fragment] if not value then return nil end end return value end --- -- Formats the number of seconds to a string. -- e.g. 3612 => 24:12 -- function utils.FormatSeconds(sec) sec = Round(sec) local hours = floor(sec / 3600) local minutes = floor((sec % 3600) / 60) local seconds = sec % 60 if minutes < 10 then minutes = "0" .. tostring(minutes) end if seconds < 10 then seconds = "0" .. tostring(seconds) end if hours > 0 then return format("%s:%s:%s", hours, minutes, seconds) else return format("%s:%s", minutes, seconds) end end -- https://github.com/xfbs/PiL3/blob/master/18MathLibrary/shuffle.lua function utils.Shuffle(list) -- make and fill array of indices local indices = {} for i = 1, #list do indices[#indices+1] = i end -- create shuffled list local shuffled = {} for i = 1, #list do -- get a random index local index = math.random(#indices) -- get the value local value = list[indices[index]] -- remove it from the list so it won't be used again table.remove(indices, index) -- insert into shuffled array shuffled[#shuffled+1] = value end return shuffled end function utils.Retry( func, success, error, maxAttempts ) maxAttempts = maxAttempts or 3 local attempts = 1 local function callback( value ) if value then success( value ) elseif attempts < maxAttempts then attempts = attempts + 1 func( callback ) else error() end end func( callback ) end local function setTimeout( func, wait ) local timerID = tostring( func ) timer.Create( timerID, wait, 1, func ) timer.Start( timerID ) return timerID end local function clearTimeout( timerID ) if timer.Exists( timerID ) then timer.Destroy( timerID ) end end -- based on underscore.js' _.throttle function function utils.Throttle( func, wait, options ) wait = wait or 1 options = options or {} local timeout, args, result local previous local function later() previous = (options.leading == false) and 0 or RealTime() timeout = nil result = func( unpack(args) ) if not timeout then args = nil end end local function throttled(...) local now = RealTime() if not previous then previous = now end local remaining = wait - (now - previous) args = {...} if remaining <= 0 or remaining > wait then if timeout then clearTimeout(timeout) timeout = nil end previous = now result = func( unpack(args) ) if not timeout then args = nil end elseif not timeout and options.trailing ~= false then timeout = setTimeout(later, remaining) end return result end return throttled end if CLIENT then local CeilPower2 = utils.CeilPower2 local SetDrawColor = surface.SetDrawColor local SetMaterial = surface.SetMaterial local DrawTexturedRect = surface.DrawTexturedRect local DrawRect = surface.DrawRect local color_white = color_white function utils.DrawHTMLPanel( panel, w, h ) if not (IsValid( panel ) and w and h) then return end panel:UpdateHTMLTexture() local pw, ph = panel:GetSize() -- Convert to scalar w = w / pw h = h / ph -- Fix for non-power-of-two html panel size pw = CeilPower2(pw) ph = CeilPower2(ph) SetDrawColor( color_white ) local mat = panel:GetHTMLMaterial() if mat then SetMaterial( mat ) DrawTexturedRect( 0, 0, w * pw, h * ph ) else DrawRect( 0, 0, w * pw, h * ph ) end end function utils.ParseHHMMSS( time ) local tbl = {} -- insert fragments in reverse for fragment, _ in string.gmatch(time, ":?(%d+)") do table.insert(tbl, 1, tonumber(fragment) or 0) end if #tbl == 0 then return nil end local seconds = 0 for i = 1, #tbl do seconds = seconds + tbl[i] * math.max(60 ^ (i-1), 1) end return seconds end --- -- Attempts to play uri from stream or local file and returns channel in -- callback. -- function utils.LoadStreamChannel(uri, options, callback) local isLocalFile = false -- Play uri from a local file if: -- 1. Windows OS and path contains drive letter -- 2. Linux or OS X and path starts with a single '/' -- -- We can't check this using file.Exists since GMod only allows checking -- within the GMod directory. However, sound.PlayFile will still load -- a file from any directory. if (system.IsWindows() and uri:find("^%w:/")) or (not system.IsWindows() and uri:find("^/[^/]")) then isLocalFile = true local success, decoded = pcall(urllib.unescape, uri) if success then uri = decoded end end local playFunc = isLocalFile and sound.PlayFile or sound.PlayURL playFunc(uri, options or "noplay", function(channel) if IsValid(channel) then local channel_ensured = utils.BassEnsurePlayback(channel) assert(IsValid(channel_ensured)) callback(channel_ensured) else callback(nil) end end) end local DEBUG = false local channels = utils.GetEnsuredPlayers and utils.GetEnsuredPlayers() or setmetatable({}, { __mode = 'k' }) function utils.GetEnsuredPlayers() return channels end if DEBUG then table.Empty(utils.GetEnsuredPlayers()) end local WRAPPERS = {} local MT = { __tostring = function(self) return "EnsureWrapped: " .. tostring(self.__channel__) end } local IGModAudioChannel = FindMetaTable"IGModAudioChannel" function MT:__index(k) local f = WRAPPERS[k] if f ~= nil then return f end local function wrapper(me, ...) return IGModAudioChannel[k](me.__channel__, ...) end WRAPPERS[k] = wrapper return wrapper end function WRAPPERS:Play(...) local channel = self.__channel__ channels[channel] = true return IGModAudioChannel.Play(channel, ...) end function WRAPPERS:Stop(...) local channel = self.__channel__ channels[channel] = nil return IGModAudioChannel.Stop(channel, ...) end function WRAPPERS:Pause(...) local channel = self.__channel__ channels[channel] = nil return IGModAudioChannel.Pause(channel, ...) end --MediaPlayer.Cvars.EnsurePlayback local EnsurePlayback = CreateClientConVar("mediaplayer_force_playback", '1', true, false) local function process() if not EnsurePlayback:GetBool() then return end if not next(channels) then timer.Exists"MP_BassEnsurePlayback" end for channel, inited in pairs(channels) do if channel:IsValid() then local stopped = channel:GetState() == GMOD_CHANNEL_STOPPED if DEBUG then print(channel, "inited=", inited, "stopped=", stopped) end if not inited and not stopped then channels[channel] = true elseif inited and stopped then channel:Play() print("Forcing playback for", channel) end else channels[channel] = nil end end end concommand.Add("stopsound_mediplayer_bass", function() for channel, inited in pairs(channels) do if channel:IsValid() then channels[channel] = nil channel:Stop() print("Stopped", channel) else channels[channel] = nil end end end) function utils.BassEnsurePlayback(channel, remove) if remove == true then channels[channel] = nil return end channels[channel] = false if DEBUG or not timer.Exists"MP_BassEnsurePlayback" then timer.Create("MP_BassEnsurePlayback", DEBUG and 3.123 or 0.351, 0, process) end local wrapped = setmetatable({ __channel__ = channel, channel = channel, __wrappers = WRAPPERS }, MT) if DEBUG then print("Wrapping to ensure playback", channel, "->", wrapped) end return wrapped end if DEBUG then sound.PlayURL("https://www.happyhardcore.com/livestreams/p/u9/", "noplay", function(a, ...) local asd = MediaPlayerUtils.BassEnsurePlayback(a) print(asd == nil, asd) _G.asd = asd end) end end _G.MediaPlayerUtils = utils
20.839024
103
0.683052
4461c66e66f845a8cf08dff5ed1aaa965d0c416a
1,466
py
Python
da_monitor.py
linjin1130/DA_monitor_websocket
d592559a95225d3d8f6d96055918d15162c26c9b
[ "MIT" ]
null
null
null
da_monitor.py
linjin1130/DA_monitor_websocket
d592559a95225d3d8f6d96055918d15162c26c9b
[ "MIT" ]
null
null
null
da_monitor.py
linjin1130/DA_monitor_websocket
d592559a95225d3d8f6d96055918d15162c26c9b
[ "MIT" ]
null
null
null
import time from socket import * # from config_util import * class DAbroaddata(object): dabroad_host='' dabroad_port=6789 bufsize = 1024 def __init__(self): # self.confobj = Config() # self.dabroad_host = self.confobj.dabroad_host # self.dabroad_port = self.confobj.dabroad_port self.bufsize = self.bufsize #与DA板建立连接 def connectDAboard(self): addr = (self.dabroad_host, self.dabroad_port) self.udpServer = socket(AF_INET, SOCK_DGRAM) # 创建一个服务器端UDP套接字 self.udpServer.bind(addr) # 开始监听 #得到DA板返回的数据 def dabroad_datareq(self): data, addr = self.udpServer.recvfrom(self.bufsize) # 接收数据和返回地址 return data,addr def udp_uncon(self): self.udpServer.close() return udp_rc = DAbroaddata() udp_rc.connectDAboard() # for i in range(10000): while(1): data, addr = udp_rc.dabroad_datareq() print(addr, data) # time.sleep(0.01) #!/usr/bin/python # encoding=utf-8 import time import websocket # 配置远程服务器的IP,帐号,密码,端口等,因我做了双机密钥信任,所以不需要密码 # websocket服务端地址 ws_server = "ws://127.0.0.1:8002/websocket/" def tailfLog(): """获取远程服务器实时日志,并发送到websocket服务端""" ws = websocket.WebSocket.create_connection(ws_server) # 创建websocket连接 while True: data, addr = udp_rc.dabroad_datareq() if addr[0]: ws.send(addr[0]) #把内容发送到websocket服务端 print(time.time()) if __name__ == '__main__': tailfLog()
23.269841
75
0.658254
dbe51a3fd23c76fb74a8f7270bb354971118b28c
2,909
php
PHP
backend/views/administrators/create.php
daifangyun/video
91ef22a78457af7b708207db8c8f196759f43c7c
[ "BSD-3-Clause" ]
null
null
null
backend/views/administrators/create.php
daifangyun/video
91ef22a78457af7b708207db8c8f196759f43c7c
[ "BSD-3-Clause" ]
null
null
null
backend/views/administrators/create.php
daifangyun/video
91ef22a78457af7b708207db8c8f196759f43c7c
[ "BSD-3-Clause" ]
null
null
null
<?php use yii\helpers\Html; use yii\helpers\Url; $this->title = '添加管理员账号 ...'; ?> <div class="site-index"> <div class="body-content"> <?= \backend\widget\FormAlertWidget::widget(); ?> <div class="row"> <div class="box-body"> <form role="form" action="<?= Url::to([Yii::$app->controller->id . '/' . Yii::$app->controller->action->id]) ?>" method="post"> <div class="form-group <?= ($usernameError = $model->getFirstError('username')) ? 'has-error' : '' ?>"> <label class="control-label" for="username"> <?= $usernameError ? '<i class="fa fa-times-circle-o"></i>' : '' ?> 账号 </label> <?= Html::activeTextInput($model, 'username', ['id' => 'username', 'class' => 'form-control', 'placeholder' => '账号 ...']); ?> <?= $usernameError ? '<span class="help-block m-b-none">' . $usernameError . '</span>' : '' ?> </div> <div class="form-group <?= ($passwordError = $model->getFirstError('password')) ? 'has-error' : '' ?>"> <label class="control-label" for="password"> <?= $passwordError ? '<i class="fa fa-times-circle-o"></i>' : '' ?> 密码 </label> <?= Html::activePasswordInput($model, 'password', ['id' => 'password', 'class' => 'form-control', 'placeholder' => '密码 ...']); ?> <?= $passwordError ? '<span class="help-block m-b-none">' . $passwordError . '</span>' : '' ?> </div> <div class="form-group <?= ($passwordConfrimError = $model->getFirstError('passwordConfim')) ? 'has-error' : '' ?>"> <label class="control-label" for="passwordConfim"> <?= $passwordConfrimError ? '<i class="fa fa-times-circle-o"></i>' : '' ?> 确认密码 </label> <?= Html::activePasswordInput($model, 'passwordConfim', ['id' => 'passwordConfim', 'class' => 'form-control', 'placeholder' => '确认密码 ...']); ?> <?= $passwordConfrimError ? '<span class="help-block m-b-none">' . $passwordConfrimError . '</span>' : '' ?> </div> <div class="form-group"> <?= Html::hiddenInput(Yii::$app->request->csrfParam, Yii::$app->request->csrfToken); ?> <?= Html::submitButton('保存内容', ['class' => 'btn btn-primary pull-right']); ?> </div> </form> </div> </div> </div> </div> <?php $this->beginBlock('myJs'); ?> <script> </script> <?php $this->endBlock(); ?>
49.305085
167
0.440358
934703af53e8e531c0c18021b53fca8ad0fee0d2
5,259
rs
Rust
src/responder.rs
sgasse/infercam_onnx
393dfae67276fe8cb0082014cf91ddb01af14611
[ "Apache-2.0" ]
1
2021-11-10T17:25:40.000Z
2021-11-10T17:25:40.000Z
src/responder.rs
sgasse/infercam_onnx
393dfae67276fe8cb0082014cf91ddb01af14611
[ "Apache-2.0" ]
null
null
null
src/responder.rs
sgasse/infercam_onnx
393dfae67276fe8cb0082014cf91ddb01af14611
[ "Apache-2.0" ]
null
null
null
//! Objects responding to endpoint calls. //! //! There are two main objects, both implement the `futures_core::Stream` trait: //! - `StreamableCamera` initializes the webcam and captures a new frame in its `poll_next` method. //! - `InferCamera` initializes both the webcam and a neural network model from an `.onnx` file. //! In the `poll_next` method, every frame is passed through the network, the output postprocessed //! and bounding boxes with confidences drawn onto the original frame. use actix_web::web::Bytes; use actix_web::Error; use futures_core::task::{Context, Poll}; use futures_core::Stream; use image::codecs::jpeg::JpegEncoder; use image::{ColorType, Rgb, RgbImage}; use imageproc::drawing::{draw_hollow_rect, draw_text}; use imageproc::rect::Rect; use rscam::Frame; use rusttype::{Font, Scale}; use std::io::Cursor; use std::pin::Pin; use tract_onnx::prelude::{tvec, Arc, TVec, Tensor, TractResult}; use super::nn::postproc_ultraface; /// Keep a handle to the capture function of an initialized camera. pub struct StreamableCamera { gen_frame: Box<dyn Fn() -> Frame>, } impl StreamableCamera { /// Create a new instance. pub fn new(gen_frame: Box<dyn Fn() -> Frame>) -> StreamableCamera { StreamableCamera { gen_frame } } } impl Stream for StreamableCamera { type Item = Result<Bytes, Error>; fn poll_next(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { let frame = (*self.gen_frame)(); let body: Bytes = Bytes::copy_from_slice( &[ "--frame\r\nContent-Type: image/jpeg\r\n\r\n".as_bytes(), &frame[..], "\r\n\r\n".as_bytes(), ] .concat(), ); log::debug!("Streaming..."); Poll::Ready(Some(Ok(body))) } } pub struct InferCamera { gen_frame: Box<dyn Fn() -> Frame>, infer_frame: Box<dyn Fn(TVec<Tensor>) -> TractResult<TVec<Arc<Tensor>>>>, preproc_frame: Box<dyn Fn(RgbImage) -> Tensor>, } impl InferCamera { /// Create a new instance. pub fn new( gen_frame: Box<dyn Fn() -> Frame>, infer_frame: Box<dyn Fn(TVec<Tensor>) -> TractResult<TVec<Arc<Tensor>>>>, preproc_frame: Box<dyn Fn(RgbImage) -> Tensor>, ) -> InferCamera { InferCamera { gen_frame, infer_frame, preproc_frame, } } } impl Stream for InferCamera { type Item = Result<Bytes, Error>; fn poll_next(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { log::debug!("Entering poll"); let frame = (*self.gen_frame)().to_vec(); let frame: RgbImage = RgbImage::from_raw(1280, 720, frame).unwrap(); log::debug!("Image read"); let (width, height) = frame.dimensions(); let infer_result = (*self.infer_frame)(tvec!((*self.preproc_frame)(frame.clone()))).unwrap(); log::debug!("Inference done"); let bboxes_with_conf = postproc_ultraface(infer_result); log::debug!("Found {} faces in image", bboxes_with_conf.len()); let frame = draw_bboxes_on_image(frame, bboxes_with_conf, width, height); let mut buf = Cursor::new(Vec::new()); JpegEncoder::new_with_quality(&mut buf, 70) .encode(&frame, width, height, ColorType::Rgb8) .unwrap(); let bytes = buf.into_inner(); log::debug!("Image encoded"); let body: Bytes = Bytes::copy_from_slice( &[ "--frame\r\nContent-Type: image/jpeg\r\n\r\n".as_bytes(), &bytes[..], "\r\n\r\n".as_bytes(), ] .concat(), ); Poll::Ready(Some(Ok(body))) } } /// Draw bounding boxes with confidence scores on the image. fn draw_bboxes_on_image( mut frame: RgbImage, bboxes_with_confidences: Vec<([f32; 4], f32)>, width: u32, height: u32, ) -> RgbImage { let (width, height) = (width as f32, height as f32); let font = load_font(); let color = Rgb::from([0, 255, 0]); for (bbox, confidence) in bboxes_with_confidences.iter() { // Coordinates of top-left and bottom-right points // Coordinate frame basis is on the top left corner let (x_tl, y_tl) = (bbox[0] * width, bbox[1] * height); let (x_br, y_br) = (bbox[2] * width, bbox[3] * height); let rect_width = x_br - x_tl; let rect_height = y_br - y_tl; let face_rect = Rect::at(x_tl as i32, y_tl as i32).of_size(rect_width as u32, rect_height as u32); frame = draw_hollow_rect(&frame, face_rect, Rgb::from([0, 255, 0])); frame = draw_text( &mut frame, color.clone(), x_tl as u32, y_tl as u32, Scale { x: 16.0, y: 16.0 }, &font, &format!("{:.2}%", confidence * 100.0), ); } frame } /// Load font. /// /// The font data is actually compiled into the binary with the `include_bytes!` macro. fn load_font() -> Font<'static> { let font_data: &[u8] = include_bytes!("../resources/DejaVuSansMono.ttf"); let font: Font<'static> = Font::try_from_bytes(font_data).unwrap(); return font; }
31.491018
100
0.596121
0d3a982fd0fb17f25575d0ad5b4189c25ca2facb
3,930
cs
C#
Source/DotSpatial.Data/ImageCoverage.cs
eapbokma/DotSpatial
2ddae0b2db98541771293838c37ba2f7bdcbbb96
[ "MIT" ]
null
null
null
Source/DotSpatial.Data/ImageCoverage.cs
eapbokma/DotSpatial
2ddae0b2db98541771293838c37ba2f7bdcbbb96
[ "MIT" ]
null
null
null
Source/DotSpatial.Data/ImageCoverage.cs
eapbokma/DotSpatial
2ddae0b2db98541771293838c37ba2f7bdcbbb96
[ "MIT" ]
null
null
null
// Copyright (c) DotSpatial Team. All rights reserved. // Licensed under the MIT license. See License.txt file in the project root for full license information. using System.Collections.Generic; using System.Drawing; namespace DotSpatial.Data { /// <summary> /// TiledImage is a class for actually controlling the data in several tiles. This does not supply /// direct accessors for modifying the bytes directly, and instead expects the user to edit the image on a tile-by-tile basis. However, /// the GetBitmap method will produce a representation of the envelope scaled to the specified window. /// </summary> public class ImageCoverage : DataSet, IImageCoverage { #region Fields private List<IImageData> _images; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="ImageCoverage"/> class. /// </summary> public ImageCoverage() { _images = new List<IImageData>(); } #endregion #region Properties /// <inheritdoc /> public int Count => _images.Count; /// <inheritdoc /> public override Extent Extent { get { Extent ext = new Extent(); foreach (IImageData tile in _images) { ext.ExpandToInclude(tile.Extent); } return ext; } } /// <inheritdoc /> public virtual List<IImageData> Images { get { return _images; } set { _images = value; } } #endregion #region Methods /// <summary> /// Gets the bitmap for the specified geographic envelope scaled to fit on a bitmap of the specified size in pixels. /// </summary> /// <param name="envelope">The envelope.</param> /// <param name="pixelSize">The pixel size.</param> /// <returns>The bitmap for the specified geographic envelope.</returns> public virtual Bitmap GetBitmap(Extent envelope, Size pixelSize) { Bitmap result = new Bitmap(pixelSize.Width, pixelSize.Height); Graphics g = Graphics.FromImage(result); foreach (var image in GetImages()) { Extent bounds = envelope.Intersection(image.Extent); Size ps = new Size((int)(pixelSize.Width * bounds.Width / envelope.Width), (int)(pixelSize.Height * bounds.Height / envelope.Height)); int x = pixelSize.Width * (int)((bounds.X - envelope.X) / envelope.Width); int y = pixelSize.Height * (int)((envelope.Y - bounds.Y) / envelope.Height); if (ps.Width > 0 && ps.Height > 0) { Bitmap tile = image.GetBitmap(bounds, ps); g.DrawImageUnscaled(tile, x, y); } } return result; } /// <inheritdoc /> public IEnumerable<IImageData> GetImages() { return _images; } /// <summary> /// Cycles through each of the images and calls the open method on each one. /// </summary> public virtual void Open() { // it seems that the images would already be open if they were instantiated. } /// <summary> /// Cycles through each of the images and calls the save method on each one. /// </summary> public void Save() { foreach (IImageData id in _images) { id.Save(); } } #endregion } }
31.190476
151
0.519847
82e808875da5d8cb965f413e3b1cbe7c08a3cfdb
2,649
rs
Rust
src/cargo-tizen/commands/config.rs
Palladinium/cargo-rutin-tizen
c51ee225104a44d797fdc8c60c9cd4aa97c5854b
[ "Apache-2.0" ]
2
2021-04-07T01:07:15.000Z
2021-05-05T13:57:09.000Z
src/cargo-tizen/commands/config.rs
Palladinium/cargo-rutin-tizen
c51ee225104a44d797fdc8c60c9cd4aa97c5854b
[ "Apache-2.0" ]
1
2021-05-05T14:52:44.000Z
2021-05-05T22:59:55.000Z
src/cargo-tizen/commands/config.rs
Palladinium/cargo-rutin-tizen
c51ee225104a44d797fdc8c60c9cd4aa97c5854b
[ "Apache-2.0" ]
1
2021-11-22T11:58:27.000Z
2021-11-22T11:58:27.000Z
use crate::error::TizenError; use crate::tizen_env::{ConfigFrom, TizenEnv}; use clap::ArgMatches; use cli_table::{print_stdout, Cell, Table}; use colored::*; pub fn run(tizen_env: &TizenEnv, args: &ArgMatches) -> Result<i32, TizenError> { match args.value_of("env_key") { Some(str_value) => show_detail(tizen_env, String::from(str_value)), None => list_configs(&tizen_env), } } fn show_detail(tizen_env: &TizenEnv, env_key: String) -> Result<i32, TizenError> { let config_value = tizen_env .raw_config_values .iter() .find(|v| v.env_key == env_key); match config_value { Some(config_value) => { let table = vec![ vec!["env key".cell(), config_value.env_key.clone().cell()], vec!["value".cell(), config_value.value.clone().cell()], vec!["from".cell(), from_to_s(&config_value.from).cell()], vec![ "cargo key".cell(), config_value .cargo_key .clone() .unwrap_or_else(|| "".to_string()) .cell(), ], vec![ "manifest key".cell(), config_value .manifest_key .clone() .unwrap_or_else(|| "".to_string()) .cell(), ], ] .table(); assert!(print_stdout(table).is_ok()); Ok(0) } None => Err(TizenError { message: format!("No config named {}", env_key), }), } } fn list_configs(tizen_env: &TizenEnv) -> Result<i32, TizenError> { println!("{}", "Configurable values:".green().bold()); for raw_value in tizen_env.raw_config_values.iter() { println!("{}={}", raw_value.env_key, raw_value.value); } println!( "{} {} {}", "Run".green(), "cargo tizen config NAME_OF_CONFIG".yellow().bold(), "to see more info".green() ); println!("\n{}", "Other env variables:".green().bold()); for (key, value) in tizen_env.get_additional_build_env() { println!("{}={}", &key, &value); } Ok(0) } fn from_to_s(config_from: &ConfigFrom) -> String { match config_from { ConfigFrom::Env => "env".to_string(), ConfigFrom::Arg => "cli args".to_string(), ConfigFrom::Cargo => "cargo file".to_string(), ConfigFrom::Manifest => "manifest".to_string(), ConfigFrom::Default => "default".to_string(), } }
30.448276
82
0.505851
a22bbf93e75358a1a275c2623a1573e1c697d61d
53
dart
Dart
lib/src/utils/firebase_product_type.dart
sanjeevbishnoi/flutter_firebase_chat_core
f04dd5c0d838b3cc7f320618dd1541af7346399f
[ "Apache-2.0" ]
null
null
null
lib/src/utils/firebase_product_type.dart
sanjeevbishnoi/flutter_firebase_chat_core
f04dd5c0d838b3cc7f320618dd1541af7346399f
[ "Apache-2.0" ]
null
null
null
lib/src/utils/firebase_product_type.dart
sanjeevbishnoi/flutter_firebase_chat_core
f04dd5c0d838b3cc7f320618dd1541af7346399f
[ "Apache-2.0" ]
null
null
null
enum FirebaseProductType { fireRealTime, fireStore }
26.5
52
0.830189
02776f948c5fa197561eef3d5f575f85a41e012e
4,281
cpp
C++
ModuleProgram.cpp
raulgonzalezupc/FirstAssigment
9193de31049922787da966695340253d84439bf3
[ "MIT" ]
null
null
null
ModuleProgram.cpp
raulgonzalezupc/FirstAssigment
9193de31049922787da966695340253d84439bf3
[ "MIT" ]
null
null
null
ModuleProgram.cpp
raulgonzalezupc/FirstAssigment
9193de31049922787da966695340253d84439bf3
[ "MIT" ]
null
null
null
#include "ModuleProgram.h" #include "Application.h" #include "ModuleImgui.h" #include "Globals.h" #include "MathGeoLib/include/Math/float4x4.h" #include "SDL.h" ModuleProgram::ModuleProgram() { } ModuleProgram::~ModuleProgram() { } bool ModuleProgram::Init() { App->imgui->AddLog("\nSHADERS.\n\n"); //init vertex shader vs = createVertexShader(VERTEX_SHADER_PATH); fs = createFragmentShader(FRAGMENT_SHADER_PATH); defaultProgram = CreateProgram(vs, fs); sceneProgram = CreateProgram(vs, fs); //init skybox shader skyboxVertexShader = App->program->createVertexShader("Game/Skybox.vs"); skyboxFragmentShader = App->program->createFragmentShader("Game/Skybox.fs"); skyboxProgram = CreateProgram(skyboxVertexShader, skyboxFragmentShader); //set up the uniforms setUniformsBuffer(); return true; } update_status ModuleProgram::PreUpdate() { return UPDATE_CONTINUE; } update_status ModuleProgram::Update() { return UPDATE_CONTINUE; } update_status ModuleProgram::PostUpdate() { return UPDATE_CONTINUE; } bool ModuleProgram::CleanUp() { App->imgui->AddLog("Deleting vertex shader\n"); glDeleteShader(vertex_shader); App->imgui->AddLog("Deleting fragment shader\n"); glDeleteShader(fragment_shader); return true; } GLuint ModuleProgram::CreateProgram(unsigned int vs, unsigned int fs) { //Creating shader program shader_program = glCreateProgram(); //Attaching vertex shader to shader program glAttachShader(shader_program, vertex_shader); //Attaching fragment shader to shader program glAttachShader(shader_program, fragment_shader); //Linking shader program glLinkProgram(shader_program); GLint statusP = NULL; char charP[512]; glGetProgramiv(shader_program, GL_LINK_STATUS, &statusP); if (!statusP) { glGetProgramInfoLog(shader_program, 512, NULL, charP); App->imgui->AddLog("Program created wrong, code: %s\n", charP); } return shader_program; } const char* ModuleProgram::loadFile(const char* file_name) { char* data = nullptr; FILE* file = nullptr; fopen_s(&file, file_name, "rb"); if (file) { fseek(file, 0, SEEK_END); int size = ftell(file); rewind(file); data = (char*)malloc(size + 1); fread(data, 1, size, file); data[size] = 0; fclose(file); } return data; } unsigned int ModuleProgram::createVertexShader(const char * filename) { assert(filename != NULL); const char *vertex_shader_file = loadFile(VERTEX_SHADER_PATH); vertex_shader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertex_shader, 1, &vertex_shader_file, NULL); delete vertex_shader_file; glCompileShader(vertex_shader); GLint statusV = NULL; char charV[512]; glGetShaderiv(vertex_shader, GL_COMPILE_STATUS, &statusV); if(!statusV) { glGetShaderInfoLog(vertex_shader, 512, NULL, charV); App->imgui->AddLog("Vertex shader created wrong, code: %s\n", charV); } else { App->imgui->AddLog("Vertex shader created correctly.\n"); } return vertex_shader; } unsigned int ModuleProgram::createFragmentShader(const char * filename) { assert(filename != NULL); const char *fragment_shader_file = loadFile(FRAGMENT_SHADER_PATH); fragment_shader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragment_shader, 1, &fragment_shader_file, NULL); delete fragment_shader_file; glCompileShader(fragment_shader); GLint statusF = NULL; char charF[512]; glGetShaderiv(fragment_shader, GL_COMPILE_STATUS, &statusF); if (!statusF) { glGetShaderInfoLog(fragment_shader, 512, NULL, charF); App->imgui->AddLog("Fragment shader created wrong, code: %s\n", charF); } else { App->imgui->AddLog("Fragment shader created correctly.\n"); } return fragment_shader; } void ModuleProgram::setUniformsBuffer() { unsigned int uniformBlockIndexDefault = glGetUniformBlockIndex(defaultProgram, "Matrices"); glUniformBlockBinding(defaultProgram, uniformBlockIndexDefault, 0); unsigned int uniformSkybox = glGetUniformBlockIndex(skyboxProgram, "Skybox"); glUniformBlockBinding(skyboxProgram, uniformSkybox, 0); glGenBuffers(1, &uniformsBuffer); glBindBuffer(GL_UNIFORM_BUFFER, uniformsBuffer); glBufferData(GL_UNIFORM_BUFFER, 2 * sizeof(float4x4), NULL, GL_STATIC_DRAW); glBindBuffer(GL_UNIFORM_BUFFER, 0); glBindBufferRange(GL_UNIFORM_BUFFER, 0, uniformsBuffer, 0, 2 * sizeof(float4x4)); }
24.186441
92
0.759402
75c09a500e272a0c32cd2baccd9a6e420ef7de36
430
css
CSS
src/components/Header/styles.css
Giancarl021/Ow-Scan
badba7c340e42cc227e0f1d75300e0fdfbef73b3
[ "MIT" ]
null
null
null
src/components/Header/styles.css
Giancarl021/Ow-Scan
badba7c340e42cc227e0f1d75300e0fdfbef73b3
[ "MIT" ]
null
null
null
src/components/Header/styles.css
Giancarl021/Ow-Scan
badba7c340e42cc227e0f1d75300e0fdfbef73b3
[ "MIT" ]
null
null
null
.header-nav { height: 4rem; box-shadow: 0 0 15px #0004; } .navbar-item img.logo { max-height: unset; height: 3rem; width: auto } .header-burger { height: 4rem; } .navbar-end.tagger { justify-content: center; align-items: center; } .navbar-item.tag.sponsor { display: flex; flex: 1; margin: 0.5rem 0.75rem; text-align: center; transition: width .14s; user-select: none; }
15.357143
31
0.606977
fac11caa286a6aff7db04d0231457d619d27cd0f
126
swift
Swift
Sources/App/Models/User.swift
GYLibrary/SwiftService
888721b52f0628ee35d11066851f697389359cb3
[ "Apache-2.0" ]
null
null
null
Sources/App/Models/User.swift
GYLibrary/SwiftService
888721b52f0628ee35d11066851f697389359cb3
[ "Apache-2.0" ]
null
null
null
Sources/App/Models/User.swift
GYLibrary/SwiftService
888721b52f0628ee35d11066851f697389359cb3
[ "Apache-2.0" ]
null
null
null
// // User.swift // App // // Created by zgy on 2019/4/12. // import Vapor struct User: Content { var name: String }
9.692308
32
0.587302
75b1490fc405d341a1da82c5ad28a30184054efb
585
css
CSS
public_html/style-carousel.css
IboRakhmonov-debug/laravel_blade_sciencesoft
31d63707597620da480571c22302f6f8bf8be656
[ "MIT" ]
null
null
null
public_html/style-carousel.css
IboRakhmonov-debug/laravel_blade_sciencesoft
31d63707597620da480571c22302f6f8bf8be656
[ "MIT" ]
null
null
null
public_html/style-carousel.css
IboRakhmonov-debug/laravel_blade_sciencesoft
31d63707597620da480571c22302f6f8bf8be656
[ "MIT" ]
null
null
null
.container { padding-top: 100px; } .slick-slide { margin: 0 20px; } .slick-slide img { width: 100%; } .slick-slider { position: relative; display: block; box-sizing: border-box; } .slick-list { position: relative; display: block; overflow: hidden; margin: 0; padding: 0; } .slick-track { position: relative; top: 0; left: 0; display: block; } .slick-slide { display: none; float: left; height: 100%; min-height: 1px; } .slick-slide img { display: block; } .slick-initialized .slick-slide { display: block; } .copy { padding-top: 250px; }
12.717391
33
0.630769
a35279f32c359103c2722df922d7e6b48cc5a764
1,175
java
Java
e2e-tests-activemq-artemis-tests/src/test/java/io/github/tlbueno/e2e_tests/activemq/artemis/tests/journal/retention/Producer.java
tlbueno/e2e-tests
3456fcce8232101c6a6b4ff5b1c9697a1a761a92
[ "Apache-2.0" ]
null
null
null
e2e-tests-activemq-artemis-tests/src/test/java/io/github/tlbueno/e2e_tests/activemq/artemis/tests/journal/retention/Producer.java
tlbueno/e2e-tests
3456fcce8232101c6a6b4ff5b1c9697a1a761a92
[ "Apache-2.0" ]
null
null
null
e2e-tests-activemq-artemis-tests/src/test/java/io/github/tlbueno/e2e_tests/activemq/artemis/tests/journal/retention/Producer.java
tlbueno/e2e-tests
3456fcce8232101c6a6b4ff5b1c9697a1a761a92
[ "Apache-2.0" ]
null
null
null
package io.github.tlbueno.e2e_tests.activemq.artemis.tests.journal.retention; import io.github.tlbueno.e2e_tests.framework.client.jms.JmsClient; import io.github.tlbueno.e2e_tests.framework.client.jms.producer.SingleQueueProducer; import io.github.tlbueno.e2e_tests.framework.client.jms.protocol.amqp.JmsClientAmqpBuilder; import org.apache.ignite.lang.IgniteRunnable; import javax.jms.Session; public class Producer implements IgniteRunnable { private String url; private String user; private String pass; public Producer(String url, String user, String pass) { this.url = url; this.user = user; this.pass = pass; } @Override public void run() { JmsClient client = new JmsClientAmqpBuilder(url). withUsername(user). withPassword(pass). withTransactedSession(false). withAckMode(Session.AUTO_ACKNOWLEDGE). build(); client.connect(); SingleQueueProducer.produceRandomMsgs(client.getSession(), "retentionTestQueue", 500); client.disconnect(); } }
32.638889
94
0.655319
e264712f09a451232a23a846a974cfab9d8b3ba0
350
py
Python
config.py
digigor/matchplicity-jobscrapper
f23a0b0fb803b72f98b95c249806a6da54af6153
[ "Apache-2.0" ]
null
null
null
config.py
digigor/matchplicity-jobscrapper
f23a0b0fb803b72f98b95c249806a6da54af6153
[ "Apache-2.0" ]
null
null
null
config.py
digigor/matchplicity-jobscrapper
f23a0b0fb803b72f98b95c249806a6da54af6153
[ "Apache-2.0" ]
null
null
null
# -*- coding: UTF-8 -*- PROXYSOCKET = '' RETRY_TIMES = 5 HEADERS = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36', 'Accept': 'application/json,application/xml' } INPUT_FILE = 'dependencies/input.xlsx' API_DEBUG = True API_PORT = 5678 POST_TIME = 60
19.444444
136
0.677143